🤯 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
✨ feat(agent-signal,agent-signal/policies): added signal policy for receiving feedback dynamically, for memory (#14187)
Nekofd9b0531ec12
diff --git a/packages/prompts/src/chains/agentSignal/analyzeIntent/feedbackSatisfaction.ts b/packages/prompts/src/chains/agentSignal/analyzeIntent/feedbackSatisfaction.tsnew file mode 100644index 00000000000..c5ea41a75d0--- /dev/null+++ b/packages/prompts/src/chains/agentSignal/analyzeIntent/feedbackSatisfaction.ts@@ -0,0 +1,37 @@+import type { ChatStreamPayload } from '@lobechat/types';++import {+ AGENT_SIGNAL_ANALYZE_INTENT_FEEDBACK_SATISFACTION_SYSTEM_ROLE,+ createAgentSignalAnalyzeIntentFeedbackSatisfactionPrompt,+} from '../../../prompts';++/**+ * Builds the prompt chain for Agent Signal feedback-satisfaction judging.+ *+ * Use when:+ * - A caller needs a reusable `{ system, user }` contract for satisfaction-only analysis+ *+ * Expects:+ * - `message` is one normalized feedback message+ * - `serializedContext` is the optional serialized execution context for the same feedback event+ *+ * Returns:+ * - A two-message chat payload for the satisfaction step+ */+export const chainAgentSignalAnalyzeIntentFeedbackSatisfaction = (input: {+ message: string;+ serializedContext?: string;+}): Partial<ChatStreamPayload> => {+ return {+ messages: [+ {+ content: AGENT_SIGNAL_ANALYZE_INTENT_FEEDBACK_SATISFACTION_SYSTEM_ROLE,+ role: 'system',+ },+ {+ content: createAgentSignalAnalyzeIntentFeedbackSatisfactionPrompt(input),+ role: 'user',+ },+ ],+ };+};diff --git a/packages/prompts/src/chains/agentSignal/analyzeIntent/gate.ts b/packages/prompts/src/chains/agentSignal/analyzeIntent/gate.tsnew file mode 100644index 00000000000..0b92c738408--- /dev/null+++ b/packages/prompts/src/chains/agentSignal/analyzeIntent/gate.ts@@ -0,0 +1,33 @@+import type { ChatStreamPayload } from '@lobechat/types';++import {+ AGENT_SIGNAL_ANALYZE_INTENT_GATE_SYSTEM_ROLE,+ createAgentSignalAnalyzeIntentGatePrompt,+} from '../../../prompts';++/**+ * Builds the prompt chain for Agent Signal user-feedback gate decisions.+ *+ * Use when:+ * - A caller needs a reusable `{ system, user }` contract for gate-level filtering+ *+ * Expects:+ * - `message` is one normalized feedback message+ *+ * Returns:+ * - A two-message chat payload for the gate step+ */+export const chainAgentSignalAnalyzeIntentGate = (message: string): Partial<ChatStreamPayload> => {+ return {+ messages: [+ {+ content: AGENT_SIGNAL_ANALYZE_INTENT_GATE_SYSTEM_ROLE,+ role: 'system',+ },+ {+ content: createAgentSignalAnalyzeIntentGatePrompt(message),+ role: 'user',+ },+ ],+ };+};diff --git a/packages/prompts/src/chains/agentSignal/analyzeIntent/index.ts b/packages/prompts/src/chains/agentSignal/analyzeIntent/index.tsnew file mode 100644index 00000000000..5391949f7d2--- /dev/null+++ b/packages/prompts/src/chains/agentSignal/analyzeIntent/index.ts@@ -0,0 +1,4 @@+export * from './feedbackSatisfaction';+export * from './gate';+export * from './planMemory';+export * from './route';diff --git a/packages/prompts/src/chains/agentSignal/analyzeIntent/planMemory.ts b/packages/prompts/src/chains/agentSignal/analyzeIntent/planMemory.tsnew file mode 100644index 00000000000..f16b49ec825--- /dev/null+++ b/packages/prompts/src/chains/agentSignal/analyzeIntent/planMemory.ts@@ -0,0 +1,35 @@+import type { ChatStreamPayload } from '@lobechat/types';++import {+ AGENT_SIGNAL_ANALYZE_INTENT_PLAN_MEMORY_SYSTEM_ROLE,+ createAgentSignalAnalyzeIntentPlanMemoryPrompt,+} from '../../../prompts';++/**+ * Builds the prompt chain for Agent Signal user-feedback memory planning.+ *+ * Use when:+ * - A caller needs a reusable `{ system, user }` contract for memory-lane planning+ *+ * Expects:+ * - `message` is one normalized feedback message already routed to the memory lane+ *+ * Returns:+ * - A two-message chat payload for the plan-memory step+ */+export const chainAgentSignalAnalyzeIntentPlanMemory = (+ message: string,+): Partial<ChatStreamPayload> => {+ return {+ messages: [+ {+ content: AGENT_SIGNAL_ANALYZE_INTENT_PLAN_MEMORY_SYSTEM_ROLE,+ role: 'system',+ },+ {+ content: createAgentSignalAnalyzeIntentPlanMemoryPrompt(message),+ role: 'user',+ },+ ],+ };+};diff --git a/packages/prompts/src/chains/agentSignal/analyzeIntent/route.ts b/packages/prompts/src/chains/agentSignal/analyzeIntent/route.tsnew file mode 100644index 00000000000..4eb30cfb54a--- /dev/null+++ b/packages/prompts/src/chains/agentSignal/analyzeIntent/route.ts@@ -0,0 +1,42 @@+import type { ChatStreamPayload } from '@lobechat/types';++import {+ AGENT_SIGNAL_ANALYZE_INTENT_ROUTE_SYSTEM_ROLE,+ createAgentSignalAnalyzeIntentRoutePrompt,+} from '../../../prompts';++/**+ * Builds the prompt chain for Agent Signal user-feedback domain routing.+ *+ * Use when:+ * - A caller needs a reusable `{ system, user }` contract for domain routing+ *+ * Expects:+ * - `message` is one normalized feedback message+ * - `result`, `reason`, and `evidence` come from the upstream satisfaction stage+ *+ * Returns:+ * - A two-message chat payload for the route step+ */+export const chainAgentSignalAnalyzeIntentRoute = (input: {+ evidence: Array<{+ cue: string;+ excerpt: string;+ }>;+ message: string;+ reason: string;+ result: 'neutral' | 'not_satisfied' | 'satisfied';+}): Partial<ChatStreamPayload> => {+ return {+ messages: [+ {+ content: AGENT_SIGNAL_ANALYZE_INTENT_ROUTE_SYSTEM_ROLE,+ role: 'system',+ },+ {+ content: createAgentSignalAnalyzeIntentRoutePrompt(input),+ role: 'user',+ },+ ],+ };+};diff --git a/packages/prompts/src/chains/index.ts b/packages/prompts/src/chains/index.tsindex ec2380022d0..fabeb6185fe 100644--- a/packages/prompts/src/chains/index.ts+++ b/packages/prompts/src/chains/index.ts@@ -1,4 +1,5 @@export * from './abstractChunk';+export * from './agentSignal/analyzeIntent';export * from './answerWithContext';export * from './compressContext';export * from './inputCompletion';diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/feedbackSatisfaction.ts b/packages/prompts/src/prompts/agentSignal/analyzeIntent/feedbackSatisfaction.tsnew file mode 100644index 00000000000..6e6d05040e4--- /dev/null+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/feedbackSatisfaction.ts@@ -0,0 +1,90 @@+/**+ * System role for the Agent Signal feedback-satisfaction step.+ *+ * Use when:+ * - One user feedback message must be judged for overall satisfaction only+ * - The caller needs a strict JSON-only contract before any domain routing+ *+ * Expects:+ * - The paired user prompt includes only the feedback message and serialized context+ *+ * Returns:+ * - Instructions that constrain the model to emit one stage-local satisfaction result+ */+export const AGENT_SIGNAL_ANALYZE_INTENT_FEEDBACK_SATISFACTION_SYSTEM_ROLE = `You are the satisfaction-judging step in Agent Signal feedback analysis.++You are not chatting with the user.+You are not routing domains.+You are not planning actions.+You must output exactly one minified JSON object and nothing else.+Do not wrap the JSON in markdown fences.+Do not add explanations before or after the JSON.++Judge only the user's overall satisfaction with the assistant's prior behavior or output.++Return exactly:+{+ "result": "satisfied" | "neutral" | "not_satisfied",+ "confidence": 0.0,+ "reason": "short reason",+ "evidence": [+ {+ "cue": "short semantic cue",+ "excerpt": "supporting excerpt or empty string"+ }+ ]+}++Definitions:+- "satisfied": the user is clearly approving, reinforcing, or affirming the prior assistant behavior or output+- "not_satisfied": the user is clearly dissatisfied, correcting, rejecting, or asking for a behavior/output change+- "neutral": the message does not clearly indicate overall satisfaction, is mixed/ambiguous, or the available context is insufficient++Rules:+- Use only the provided feedback message and serialized context.+- Treat future-facing preference corrections as actionable satisfaction feedback, not neutral.+- If the user is steering future assistant behavior toward a new preference or format, prefer "not_satisfied" unless the message clearly reinforces something already working well.+- Do not infer domains such as memory, prompt, skill, or experience.+- Do not output action plans, routing targets, or hidden intermediate reasoning.+- Keep "reason" short and decision-specific.+- Put the strongest supporting snippets in "evidence".+- The output must be valid JSON parseable by JSON.parse.+- The output must start with "{" and end with "}".++Examples:+Input message: "This is much better. Keep this structure."+Output: {"result":"satisfied","confidence":0.95,"reason":"clear positive reinforcement for the new structure","evidence":[{"cue":"positive approval","excerpt":"This is much better. Keep this structure."}]}++Input message: "Stop padding the answer and get to the point."+Output: {"result":"not_satisfied","confidence":0.97,"reason":"explicit dissatisfaction with answer style","evidence":[{"cue":"requested correction","excerpt":"Stop padding the answer and get to the point."}]}++Input message: "Going forward, I usually want the conclusion first and the explanation after it."+Output: {"result":"not_satisfied","confidence":0.89,"reason":"future-facing preference correction for answer structure","evidence":[{"cue":"going forward","excerpt":"Going forward, I usually want the conclusion first and the explanation after it."},{"cue":"usually want","excerpt":"Going forward, I usually want the conclusion first and the explanation after it."}]}++Input message: "Thanks."+Output: {"result":"neutral","confidence":0.78,"reason":"acknowledgement without clear satisfaction judgment","evidence":[{"cue":"brief acknowledgement","excerpt":"Thanks."}]}++Input message: "Keep the final answer concise like before, but explain code changes a bit more."+Output: {"result":"neutral","confidence":0.71,"reason":"mixed feedback with both reinforcement and correction","evidence":[{"cue":"mixed guidance","excerpt":"Keep the final answer concise like before, but explain code changes a bit more."}]}++Return only the JSON object.`;++/**+ * Builds the user prompt for the Agent Signal feedback-satisfaction step.+ *+ * Use when:+ * - One feedback message must be wrapped into the satisfaction-only contract+ *+ * Expects:+ * - `message` is the raw feedback message+ * - `serializedContext` is the upstream serialized execution context, when available+ *+ * Returns:+ * - A compact prompt that passes only the allowed decision inputs+ */+export const createAgentSignalAnalyzeIntentFeedbackSatisfactionPrompt = (input: {+ message: string;+ serializedContext?: string;+}) => {+ return `Judge the user's overall satisfaction.\nmessage=${JSON.stringify(input.message)}\nserializedContext=${JSON.stringify(input.serializedContext ?? null)}`;+};diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/gate.ts b/packages/prompts/src/prompts/agentSignal/analyzeIntent/gate.tsnew file mode 100644index 00000000000..6441eb692e5--- /dev/null+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/gate.ts@@ -0,0 +1,51 @@+/**+ * System role for the Agent Signal user-feedback gate step.+ *+ * Use when:+ * - A lightweight model should quickly reject obvious noise before domain routing+ * - The caller only needs a `proceed` or `ignore` decision for one feedback message+ *+ * Expects:+ * - The paired user prompt contains exactly one raw feedback message+ *+ * Returns:+ * - Instructions that constrain the model to a tiny JSON gate contract+ */+export const AGENT_SIGNAL_ANALYZE_INTENT_GATE_SYSTEM_ROLE = `You are the first gate in Agent Signal user-feedback analysis.++You are not chatting with the user.+Return exactly one minified JSON object and nothing else.++Your only job is to decide whether this feedback is worth deeper analysis.++Return:+{"decision":"proceed","reason":"short reason"}++or:+{"decision":"ignore","reason":"short reason"}++Ignore messages that are:+- acknowledgement only+- pure praise or positive reinforcement+- task-local one-off instructions+- empty or too vague to analyze++Proceed only when the message may contain a durable correction, preference, prompt/document rule, or other reusable learning signal.++Return only the JSON object.`;++/**+ * Builds the user prompt for the Agent Signal user-feedback gate step.+ *+ * Use when:+ * - One feedback message must be wrapped in the gate contract+ *+ * Expects:+ * - `message` is the raw user feedback text+ *+ * Returns:+ * - A single-task user instruction that quotes the feedback verbatim+ */+export const createAgentSignalAnalyzeIntentGatePrompt = (message: string) => {+ return `Gate this feedback for deeper analysis: ${JSON.stringify(message)}`;+};diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/index.ts b/packages/prompts/src/prompts/agentSignal/analyzeIntent/index.tsnew file mode 100644index 00000000000..5391949f7d2--- /dev/null+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/index.ts@@ -0,0 +1,4 @@+export * from './feedbackSatisfaction';+export * from './gate';+export * from './planMemory';+export * from './route';diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/planMemory.ts b/packages/prompts/src/prompts/agentSignal/analyzeIntent/planMemory.tsnew file mode 100644index 00000000000..fac72c93375--- /dev/null+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/planMemory.ts@@ -0,0 +1,93 @@+/**+ * System role for the Agent Signal user-feedback memory planning step.+ *+ * Use when:+ * - One routed feedback message already belongs to the memory lane+ * - The caller wants a strict JSON-only contract aligned with `addPreferenceMemory`+ *+ * Expects:+ * - The paired user prompt contains exactly one feedback message that should be planned as preference memory+ *+ * Returns:+ * - Instructions that constrain the model to either `addPreferenceMemory` JSON or `none`+ */+export const AGENT_SIGNAL_ANALYZE_INTENT_PLAN_MEMORY_SYSTEM_ROLE = `You are the memory-planning step in Agent Signal user-feedback analysis.++You are not chatting with the user.+You are not summarizing for display.+You must output exactly one minified JSON object and nothing else.+Do not wrap the JSON in markdown fences.+Do not add explanations before or after the JSON.++Decide whether the user's message should become durable preference memory.++If the message expresses a durable user preference that should guide future interactions, return exactly:+{+ "function": "addPreferenceMemory",+ "arguments": {+ "title": "short title",+ "summary": "short summary",+ "details": "optional detail",+ "memoryCategory": "communication",+ "memoryType": "preference",+ "tags": ["response-style"],+ "withPreference": {+ "appContext": null,+ "conclusionDirectives": "direct instruction to the assistant",+ "extractedLabels": ["response-style"],+ "extractedScopes": ["{\\"surface\\":\\"chat\\"}"],+ "originContext": {+ "actor": "User",+ "applicableWhen": "future interactions",+ "notApplicableWhen": null,+ "scenario": "assistant responses",+ "trigger": "user feedback"+ },+ "scorePriority": 0.9,+ "suggestions": ["Keep answers aligned with the stored preference."],+ "type": "personal"+ }+ }+}++If the message should not become durable preference memory, return exactly:+{+ "function": "none",+ "reason": "short reason"+}++Rules:+- Use "addPreferenceMemory" only for durable future-facing user preferences.+- Use "none" for one-off instructions like "for this reply".+- Use "none" for acknowledgement like "thanks".+- Use "none" for assistant wording corrections like "stop saying X before every answer".+- The output must be valid JSON parseable by JSON.parse.+- The output must start with "{" and end with "}".++Examples:+User message: "Going forward, I usually want the conclusion first."+Output: {"function":"addPreferenceMemory","arguments":{"title":"Conclusion first preference","summary":"User prefers conclusion-first answers.","details":"The user usually wants the conclusion before the explanation.","memoryCategory":"communication","memoryType":"preference","tags":["response-style","concise"],"withPreference":{"appContext":null,"conclusionDirectives":"Lead with the conclusion before supporting detail.","extractedLabels":["response-style","conclusion-first"],"extractedScopes":["{\\"surface\\":\\"chat\\"}"],"originContext":{"actor":"User","applicableWhen":"future interactions","notApplicableWhen":null,"scenario":"assistant responses","trigger":"user feedback"},"scorePriority":0.9,"suggestions":["Lead with the conclusion before the explanation."],"type":"personal"}}}++User message: "For this reply, keep it to three bullets."+Output: {"function":"none","reason":"task-local instruction"}++User message: "Stop saying \\"Below is a detailed analysis\\" before every answer."+Output: {"function":"none","reason":"agent phrasing rule"}++Return only the JSON object.`;++/**+ * Builds the user prompt for the Agent Signal user-feedback memory planning step.+ *+ * Use when:+ * - One routed feedback message must be packaged into a stable preference-memory planning contract+ *+ * Expects:+ * - `message` is the raw user feedback text+ *+ * Returns:+ * - A single-task user instruction that quotes the feedback message verbatim+ */+export const createAgentSignalAnalyzeIntentPlanMemoryPrompt = (message: string) => {+ return `Plan durable preference memory for this feedback: ${JSON.stringify(message)}`;+};diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.ts b/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.tsnew file mode 100644index 00000000000..ac5c273dee8--- /dev/null+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.ts@@ -0,0 +1,100 @@+/**+ * System role for the Agent Signal user-feedback domain routing step.+ *+ * Use when:+ * - One satisfaction signal already exists for a normalized user-feedback message+ * - The caller needs domain targets rather than final action payloads+ *+ * Expects:+ * - The paired user prompt includes the upstream satisfaction summary and the original feedback message+ *+ * Returns:+ * - Instructions that constrain the model to emit strict JSON domain targets only+ */+export const AGENT_SIGNAL_ANALYZE_INTENT_ROUTE_SYSTEM_ROLE = `You are the domain-routing step in Agent Signal user-feedback analysis.++You are not chatting with the user.+You are not planning final actions.+You must output exactly one minified JSON object and nothing else.+Do not wrap the JSON in markdown fences.+Do not add explanations before or after the JSON.++Choose one or more durable routing targets for this feedback message.++Valid targets:+- "memory": durable user preference or personal working style that should guide future interactions+- "prompt": assistant behavior, wording, or prompt-level rule that should update the agent's own operating prompt+- "skill": reusable playbook, template, workflow, or writing pattern worth capturing as a reusable skill+- "none": no durable routing target++Return exactly:+{+ "targets": [+ {+ "target": "memory" | "prompt" | "skill" | "none",+ "confidence": 0.0,+ "reason": "short reason",+ "evidence": [+ {+ "cue": "short cue",+ "excerpt": "supporting excerpt or empty string"+ }+ ]+ }+ ]+}++Rules:+- The output must be valid JSON parseable by JSON.parse.+- The output must start with "{" and end with "}".+- The caller only invokes you for satisfaction results "satisfied" and "not_satisfied".+- Prefer "none" when the message is acknowledgement, vague, or task-local.+- "prompt" is exclusive with "memory" and "skill" when the feedback is clearly about the assistant's own wording or operating pattern.+- "memory" is for the user's future preference, not the assistant's self-style or prompt rule.+- "skill" can fan out with "memory" when the feedback contains both a personal preference and a reusable workflow/template insight.+- Never output duplicate targets.+- Return "none" when no durable target is justified.++Examples:+Input satisfaction=result:not_satisfied, message:"Going forward, I prefer concise file-specific review comments."+Output: {"targets":[{"target":"memory","confidence":0.92,"reason":"durable user preference for future code review replies","evidence":[{"cue":"going forward","excerpt":"Going forward, I prefer concise file-specific review comments."},{"cue":"i prefer","excerpt":"Going forward, I prefer concise file-specific review comments."}]}]}++Input satisfaction=result:not_satisfied, message:"Stop saying \\"Below is a detailed analysis\\" before every answer."+Output: {"targets":[{"target":"prompt","confidence":0.97,"reason":"assistant self-wording rule","evidence":[{"cue":"stop saying","excerpt":"Stop saying \\"Below is a detailed analysis\\" before every answer."}]}]}++Input satisfaction=result:not_satisfied, message:"In code review I prefer concise comments and a reusable checklist template."+Output: {"targets":[{"target":"memory","confidence":0.86,"reason":"future personal preference for code review","evidence":[{"cue":"i prefer","excerpt":"In code review I prefer concise comments and a reusable checklist template."}]},{"target":"skill","confidence":0.78,"reason":"reusable checklist template idea","evidence":[{"cue":"template","excerpt":"In code review I prefer concise comments and a reusable checklist template."}]}]}++Input satisfaction=result:satisfied, message:"This workflow is much better and should become our reusable template."+Output: {"targets":[{"target":"skill","confidence":0.83,"reason":"reusable workflow worth capturing for future reuse","evidence":[{"cue":"reusable template","excerpt":"This workflow is much better and should become our reusable template."}]}]}++Return only the JSON object.`;++/**+ * Builds the user prompt for the Agent Signal user-feedback domain routing step.+ *+ * Use when:+ * - One satisfaction signal must be routed into one or more durable domains+ *+ * Expects:+ * - `message` is the normalized user feedback text+ * - `result` is the previously judged satisfaction label+ *+ * Returns:+ * - A compact user instruction that packages the routing decision input+ */+export const createAgentSignalAnalyzeIntentRoutePrompt = (input: {+ evidence: Array<{+ cue: string;+ excerpt: string;+ }>;+ message: string;+ reason: string;+ result: 'neutral' | 'not_satisfied' | 'satisfied';+}) => {+ return `Route this feedback into durable domains.\nsatisfaction=${JSON.stringify({+ evidence: input.evidence,+ reason: input.reason,+ result: input.result,+ })}\nmessage=${JSON.stringify(input.message)}`;+};diff --git a/packages/prompts/src/prompts/agentSignal/index.ts b/packages/prompts/src/prompts/agentSignal/index.tsnew file mode 100644index 00000000000..41768e51471--- /dev/null+++ b/packages/prompts/src/prompts/agentSignal/index.ts@@ -0,0 +1 @@+export * from './analyzeIntent';diff --git a/packages/prompts/src/prompts/index.ts b/packages/prompts/src/prompts/index.tsindex 70ab1d1daac..0b044197989 100644--- a/packages/prompts/src/prompts/index.ts+++ b/packages/prompts/src/prompts/index.ts@@ -1,5 +1,6 @@export * from './agentBuilder';export * from './agentGroup';+export * from './agentSignal';export * from './botPlatformContext';export * from './chatMessages';export * from './compressContext';diff --git a/src/features/Conversation/Messages/User/components/CollapsibleContent.tsx b/src/features/Conversation/Messages/User/components/CollapsibleContent.tsxindex ef1c2a29ca4..a533a4e93b8 100644--- a/src/features/Conversation/Messages/User/components/CollapsibleContent.tsx+++ b/src/features/Conversation/Messages/User/components/CollapsibleContent.tsx@@ -26,6 +26,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,contentCollapsed: css`overflow: hidden;+mask-image: linear-gradient(to bottom, #000 calc(100% - 48px), transparent);`,contentExpanded: css`diff --git a/src/server/services/agentEvalRun/__tests__/agentEvalRunService.evaluate.test.ts b/src/server/services/agentEvalRun/__tests__/agentEvalRunService.evaluate.test.tsindex 4385c4d9931..a9bc084c98f 100644--- a/src/server/services/agentEvalRun/__tests__/agentEvalRunService.evaluate.test.ts+++ b/src/server/services/agentEvalRun/__tests__/agentEvalRunService.evaluate.test.ts@@ -4,6 +4,10 @@ import { AgentEvalRunService } from '@/server/services/agentEvalRun';import { cleanupDB, serverDB, userId } from './_setup';+vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));+vi.mock('@/server/services/agentRuntime/AgentRuntimeService', () => ({AgentRuntimeService: vi.fn().mockImplementation(() => ({interruptOperation: vi.fn().mockResolvedValue(true),diff --git a/src/server/services/agentEvalRun/__tests__/agentEvalRunService.timeout.test.ts b/src/server/services/agentEvalRun/__tests__/agentEvalRunService.timeout.test.tsindex 08f7f0e672f..4a283ff17c0 100644--- a/src/server/services/agentEvalRun/__tests__/agentEvalRunService.timeout.test.ts+++ b/src/server/services/agentEvalRun/__tests__/agentEvalRunService.timeout.test.ts@@ -8,6 +8,10 @@ import { AgentRuntimeService } from '@/server/services/agentRuntime/AgentRuntimeimport { cleanupDB, serverDB, setupMultiCaseRun, userId } from './_setup';+vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));+vi.mock('@/server/services/agentRuntime/AgentRuntimeService', () => ({AgentRuntimeService: vi.fn().mockImplementation(() => ({interruptOperation: vi.fn().mockResolvedValue(true),diff --git a/src/server/services/agentSignal/__tests__/index.integration.test.ts b/src/server/services/agentSignal/__tests__/index.integration.test.tsindex 7edf97fc239..10818b1b3e1 100644--- a/src/server/services/agentSignal/__tests__/index.integration.test.ts+++ b/src/server/services/agentSignal/__tests__/index.integration.test.ts@@ -5,6 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';interface LoadIndexIntegrationModuleOptions {featureGateEnabled?: boolean;mockEmitSourceEvent?: Mock;+ mockInitModelRuntimeFromDB?: Mock;mockProjectObservability?: Mock;mockRuntimeFactory?: Mock;}@@ -38,6 +39,7 @@ const loadIndexIntegrationModule = async (options: LoadIndexIntegrationModuleOptvi.doUnmock('../runtime/AgentSignalRuntime');vi.doUnmock('../sources');vi.doUnmock('@/server/services/agentDocuments');+ vi.doUnmock('@/server/modules/ModelRuntime');const persistAgentSignalObservability = vi.fn().mockResolvedValue(undefined);const isAgentSignalEnabledForUser = vi.fn().mockResolvedValue(options.featureGateEnabled ?? true);@@ -49,6 +51,12 @@ const loadIndexIntegrationModule = async (options: LoadIndexIntegrationModuleOptpersistAgentSignalObservability,}));+ if (options.mockInitModelRuntimeFromDB) {+ vi.doMock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: options.mockInitModelRuntimeFromDB,+ }));+ }+if (options.mockEmitSourceEvent) {vi.doMock('../sources', () => ({emitSourceEvent: options.mockEmitSourceEvent,@@ -201,8 +209,18 @@ describe('emitAgentSignalSourceEvent integration', () => {mockRedis.hgetall.mockResolvedValue({});mockRedis.hset.mockResolvedValue(1);mockRedis.expire.mockResolvedValue(1);+ const initModelRuntimeFromDB = vi.fn().mockResolvedValue({+ generateObject: vi.fn().mockResolvedValue({+ confidence: 0.91,+ evidence: [{ cue: 'no durable request', excerpt: 'remember this' }],+ reason: 'the message does not express satisfaction feedback',+ result: 'neutral',+ }),+ });- const { emitAgentSignalSourceEvent, mocks } = await loadIndexIntegrationModule();+ const { emitAgentSignalSourceEvent, mocks } = await loadIndexIntegrationModule({+ mockInitModelRuntimeFromDB: initModelRuntimeFromDB,+ });const result = await emitAgentSignalSourceEvent({@@ -230,6 +248,7 @@ describe('emitAgentSignalSourceEvent integration', () => {expect(result.orchestration.observability.record.sourceType).toBe('agent.user.message');expect(result.orchestration.observability.envelope.source.sourceId).toBe('source_1');+ expect(initModelRuntimeFromDB).toHaveBeenCalledTimes(1);expect(mocks.persistAgentSignalObservability).toHaveBeenCalledWith(expect.objectContaining({record: expect.objectContaining({ sourceId: 'source_1' }),diff --git a/src/server/services/agentSignal/emitter.ts b/src/server/services/agentSignal/emitter.tsnew file mode 100644index 00000000000..9e5ace7cb35--- /dev/null+++ b/src/server/services/agentSignal/emitter.ts@@ -0,0 +1,174 @@+import type { DedupedSourceEventResult } from '@lobechat/agent-signal';+import debug from 'debug';++import { getServerDB } from '@/database/server';+import type { LobeChatDatabase } from '@/database/type';+import { AgentSignalWorkflow } from '@/server/workflows/agentSignal';++import { isAgentSignalEnabledForUser } from './featureGate';+import type { GeneratedAgentSignalEmissionResult } from './orchestrator';+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');++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;+}++export type RuntimeAgentSignalSourceInput<TSourceType extends RuntimeProducerSourceType> =+ AgentSignalSourceEventInput<TSourceType>;++export type BotAgentSignalSourceInput = AgentSignalSourceEventInput<+ SourceBotMessageMerged['sourceType']+>;++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,+ });+};++/**+ * 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+ *+ * 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;+ }++ const { executeAgentSignalSourceEvent } = await import('./orchestrator');++ return executeAgentSignalSourceEvent(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,+ };+};diff --git a/src/server/services/agentSignal/index.ts b/src/server/services/agentSignal/index.tsindex 12fd7c085a1..4f735d6e5bb 100644--- a/src/server/services/agentSignal/index.ts+++ b/src/server/services/agentSignal/index.ts@@ -1,352 +1 @@-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 });-};+export * from './emitter';diff --git a/src/server/services/agentSignal/orchestrator.ts b/src/server/services/agentSignal/orchestrator.tsnew file mode 100644index 00000000000..234a730b207--- /dev/null+++ b/src/server/services/agentSignal/orchestrator.ts@@ -0,0 +1,196 @@+import type {+ AgentSignalSource,+ BaseAction,+ BaseSignal,+ DedupedSourceEventResult,+ ExecutorResult,+ GeneratedSourceEventResult,+ SignalPlan,+} from '@lobechat/agent-signal';++import {+ type AgentSignalEmitOptions,+ type AgentSignalExecutionContext,+ type AgentSignalSourceEnvelope,+ type AgentSignalSourceEventInput,+ resolveSourceScopeKey,+} from './emitter';+import { projectAgentSignalObservability } from './observability/projector';+import { persistAgentSignalObservability } from './observability/store';+import {+ createDefaultAgentSignalPolicies,+ type CreateDefaultAgentSignalPoliciesOptions,+} 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';++interface ExecuteAgentSignalSourceEventOptions extends AgentSignalEmitOptions {+ policyOptions?: Partial<CreateDefaultAgentSignalPoliciesOptions>;+ runtimeGuardBackend?: RuntimeGuardBackend;+ store?: AgentSignalSourceEventStore;+}++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 executeAgentSignalSourceEventCore = async <TSourceType extends AgentSignalSourceType>(+ input: AgentSignalSourceEventInput<TSourceType>,+ context: AgentSignalExecutionContext,+ options: 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 emission = await emitSourceEvent(+ sourceEvent,+ options.store ? { store: options.store } : undefined,+ );+ if (emission.deduped) return emission;++ const runtime = await createAgentSignalRuntime({+ guardBackend: options.runtimeGuardBackend,+ policies: createDefaultAgentSignalPolicies({+ feedbackDomainJudge: {+ db: context.db,+ ...options.policyOptions?.feedbackDomainJudge,+ userId: context.userId,+ },+ feedbackSatisfactionJudge: {+ db: context.db,+ ...options.policyOptions?.feedbackSatisfactionJudge,+ userId: context.userId,+ },+ userMemory: {+ db: context.db,+ ...options.policyOptions?.userMemory,+ 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;+ }+};++/**+ * 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> => {+ return executeAgentSignalSourceEventCore(input, context, options);+};++/**+ * 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+ *+ * Returns:+ * - The same result shape as {@link executeAgentSignalSourceEvent}+ */+export const emitAgentSignalSourceEventWithStore = async <+ TSourceType extends AgentSignalSourceType,+>(+ input: AgentSignalSourceEventInput<TSourceType>,+ context: AgentSignalExecutionContext,+ store: AgentSignalSourceEventStore,+ options: Pick<ExecuteAgentSignalSourceEventOptions, 'policyOptions'> = {},+): Promise<DedupedSourceEventResult | GeneratedAgentSignalEmissionResult | undefined> => {+ return executeAgentSignalSourceEventCore(input, context, {+ policyOptions: options.policyOptions,+ store,+ });+};diff --git a/src/server/services/agentSignal/policies/actionIdempotency.ts b/src/server/services/agentSignal/policies/actionIdempotency.tsnew file mode 100644index 00000000000..e8c943b9ea9--- /dev/null+++ b/src/server/services/agentSignal/policies/actionIdempotency.ts@@ -0,0 +1,62 @@+import type { RuntimeProcessorContext } from '../runtime/context';++const ACTION_IDEMPOTENCY_LANE_PREFIX = 'action-idempotency';++/**+ * Creates the scope-local guard lane for one planned action idempotency key.+ *+ * Before:+ * - `source_1:memory:msg_1`+ *+ * After:+ * - `action-idempotency::source_1:memory:msg_1`+ */+export const createActionIdempotencyLane = (idempotencyKey: string) => {+ return `${ACTION_IDEMPOTENCY_LANE_PREFIX}::${idempotencyKey}`;+};++/**+ * Checks whether one action idempotency key has already been applied in the current runtime scope.+ *+ * Use when:+ * - An action handler must avoid replaying the same durable side effect+ * - The planner already emitted a stable `idempotencyKey`+ *+ * Expects:+ * - The key is stable across retries for the same intended side effect+ *+ * Returns:+ * - `true` when the action was already marked as applied+ * - `false` when the action should still execute+ */+export const hasAppliedActionIdempotency = async (+ ctx: RuntimeProcessorContext,+ idempotencyKey: string | undefined,+) => {+ if (!idempotencyKey) return false;++ const state = await ctx.runtimeState.getGuardState(createActionIdempotencyLane(idempotencyKey));++ return typeof state.lastEventAt === 'number';+};++/**+ * Marks one action idempotency key as successfully applied in the current runtime scope.+ *+ * Use when:+ * - An action handler finished its durable write and wants future retries to skip+ *+ * Expects:+ * - Callers only invoke this after the durable side effect succeeded+ *+ * Returns:+ * - The persisted runtime guard state for the idempotency lane+ */+export const markAppliedActionIdempotency = async (+ ctx: RuntimeProcessorContext,+ idempotencyKey: string | undefined,+) => {+ if (!idempotencyKey) return;++ await ctx.runtimeState.touchGuardState(createActionIdempotencyLane(idempotencyKey), ctx.now());+};diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.tsnew file mode 100644index 00000000000..8e2aae5ae10--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts@@ -0,0 +1,259 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { createRuntimeProcessorContext } from '../../../runtime/context';+import type {+ SignalFeedbackDomainMemory,+ SignalFeedbackDomainNone,+ SignalFeedbackDomainPrompt,+ SignalFeedbackDomainSkill,+} from '../../types';+import { createFeedbackActionPlannerSignalHandler } from '../feedbackAction';++const context = createRuntimeProcessorContext({+ backend: {+ async getGuardState() {+ return {};+ },+ async touchGuardState() {+ return {};+ },+ },+ scopeKey: 'topic:thread_1',+});++type SupportedTask4DomainTarget = 'memory' | 'none' | 'prompt' | 'skill';++type DomainSignalVariantByTarget = {+ memory: SignalFeedbackDomainMemory;+ none: SignalFeedbackDomainNone;+ prompt: SignalFeedbackDomainPrompt;+ skill: SignalFeedbackDomainSkill;+};++type DomainSignalInput<TTarget extends SupportedTask4DomainTarget> = {+ message: string;+ messageId: string;+ signalId: string;+ sourceId: string;+ target: TTarget;+};++function createDomainSignal(input: DomainSignalInput<'memory'>): SignalFeedbackDomainMemory;+function createDomainSignal(input: DomainSignalInput<'none'>): SignalFeedbackDomainNone;+function createDomainSignal(input: DomainSignalInput<'prompt'>): SignalFeedbackDomainPrompt;+function createDomainSignal(input: DomainSignalInput<'skill'>): SignalFeedbackDomainSkill;+function createDomainSignal(+ input: DomainSignalInput<SupportedTask4DomainTarget>,+): DomainSignalVariantByTarget[SupportedTask4DomainTarget] {+ const base = {+ chain: {+ chainId: 'chain_1',+ parentNodeId: input.signalId,+ rootSourceId: input.sourceId,+ },+ source: {+ payload: {+ serializedContext:+ '<feedback_analysis_context><message>context</message></feedback_analysis_context>',+ },+ sourceId: input.sourceId,+ sourceType: 'agent.user.message' as const,+ },+ timestamp: 1,+ };++ switch (input.target) {+ case 'memory': {+ return {+ ...base,+ payload: {+ confidence: 0.9,+ conflictPolicy: { forbiddenWith: ['none'], mode: 'fanout', priority: 100 },+ evidence: [{ cue: 'test', excerpt: input.message }],+ message: input.message,+ messageId: input.messageId,+ reason: 'test-domain-signal',+ satisfactionResult: 'not_satisfied',+ target: 'memory',+ },+ signalId: input.signalId,+ signalType: 'signal.feedback.domain.memory',+ timestamp: 1,+ };+ }+ case 'none': {+ return {+ ...base,+ payload: {+ confidence: 0.9,+ conflictPolicy: {+ forbiddenWith: ['memory', 'prompt', 'skill'],+ mode: 'exclusive',+ priority: 0,+ },+ evidence: [{ cue: 'test', excerpt: input.message }],+ message: input.message,+ messageId: input.messageId,+ reason: 'test-domain-signal',+ satisfactionResult: 'not_satisfied',+ target: 'none',+ },+ signalId: input.signalId,+ signalType: 'signal.feedback.domain.none',+ timestamp: 1,+ };+ }+ case 'prompt': {+ return {+ ...base,+ payload: {+ confidence: 0.9,+ conflictPolicy: {+ forbiddenWith: ['memory', 'none', 'skill'],+ mode: 'exclusive',+ priority: 90,+ },+ evidence: [{ cue: 'test', excerpt: input.message }],+ message: input.message,+ messageId: input.messageId,+ reason: 'test-domain-signal',+ satisfactionResult: 'not_satisfied',+ target: 'prompt',+ },+ signalId: input.signalId,+ signalType: 'signal.feedback.domain.prompt',+ timestamp: 1,+ };+ }+ case 'skill': {+ return {+ ...base,+ payload: {+ confidence: 0.9,+ conflictPolicy: { forbiddenWith: ['none'], mode: 'fanout', priority: 80 },+ evidence: [{ cue: 'test', excerpt: input.message }],+ message: input.message,+ messageId: input.messageId,+ reason: 'test-domain-signal',+ satisfactionResult: 'not_satisfied',+ target: 'skill',+ },+ signalId: input.signalId,+ signalType: 'signal.feedback.domain.skill',+ timestamp: 1,+ };+ }+ }+}++describe('feedbackActionPlanner', () => {+ it('creates stable idempotency keys for memory actions', async () => {+ const handler = createFeedbackActionPlannerSignalHandler();+ const signal = createDomainSignal({+ message: 'Remember this preference.',+ messageId: 'msg_1',+ signalId: 'sig_1',+ sourceId: 'source_1',+ target: 'memory',+ });++ const first = await handler.handle(signal, context);+ const second = await handler.handle(signal, context);++ expect(first).toEqual(+ expect.objectContaining({+ actions: [+ expect.objectContaining({+ actionType: 'action.user-memory.handle',+ payload: expect.objectContaining({+ feedbackHint: 'not_satisfied',+ idempotencyKey: 'source_1:memory:msg_1',+ serializedContext:+ '<feedback_analysis_context><message>context</message></feedback_analysis_context>',+ }),+ }),+ ],+ }),+ );+ expect(second).toEqual(first);+ });++ it('does not plan actions for unsupported future domains yet', async () => {+ const handler = createFeedbackActionPlannerSignalHandler();+ const skillResult = await handler.handle(+ createDomainSignal({+ message: 'This successful workflow should become a reusable skill.',+ messageId: 'msg_2',+ signalId: 'sig_2',+ sourceId: 'source_2',+ target: 'skill',+ }),+ context,+ );++ const promptResult = await handler.handle(+ createDomainSignal({+ message: 'Stop saying "Below is a detailed analysis" before every answer.',+ messageId: 'msg_2_prompt',+ signalId: 'sig_2_prompt',+ sourceId: 'source_2_prompt',+ target: 'prompt',+ }),+ context,+ );++ expect(skillResult).toBeUndefined();+ expect(promptResult).toBeUndefined();+ });++ it('dispatches memory actions without requiring preplanned memory payloads', async () => {+ const handler = createFeedbackActionPlannerSignalHandler();+ const result = await handler.handle(+ createDomainSignal({+ message: 'Remember this preference.',+ messageId: 'msg_4',+ signalId: 'sig_4',+ sourceId: 'source_4',+ target: 'memory',+ }),+ context,+ );++ expect(result).toEqual(+ expect.objectContaining({+ actions: [+ expect.objectContaining({+ actionType: 'action.user-memory.handle',+ payload: expect.objectContaining({+ evidence: [{ cue: 'test', excerpt: 'Remember this preference.' }],+ feedbackHint: 'not_satisfied',+ idempotencyKey: 'source_4:memory:msg_4',+ message: 'Remember this preference.',+ reason: 'test-domain-signal',+ serializedContext:+ '<feedback_analysis_context><message>context</message></feedback_analysis_context>',+ }),+ }),+ ],+ status: 'dispatch',+ }),+ );+ });++ it('does not plan actions for explicit no-op domain signals', async () => {+ const handler = createFeedbackActionPlannerSignalHandler();+ const result = await handler.handle(+ createDomainSignal({+ message: 'Thanks.',+ messageId: 'msg_3',+ signalId: 'sig_3',+ sourceId: 'source_3',+ target: 'none',+ }),+ context,+ );++ expect(result).toBeUndefined();+ });+});diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.tsnew file mode 100644index 00000000000..187ccbd5dca--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.ts@@ -0,0 +1,316 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { createRuntimeProcessorContext } from '../../../runtime/context';+import { createFeedbackDomainJudgeSignalHandler } from '../feedbackDomain';++const context = createRuntimeProcessorContext({+ backend: {+ async getGuardState() {+ return {};+ },+ async touchGuardState() {+ return {};+ },+ },+ scopeKey: 'topic:thread_1',+});++describe('feedbackDomainJudge', () => {+ it('routes assistant phrasing corrections to the prompt lane', async () => {+ const handler = createFeedbackDomainJudgeSignalHandler({+ resolveDomains: async () => [+ {+ confidence: 0.97,+ evidence: [+ {+ cue: 'stop saying',+ excerpt: 'Stop saying "Below is a detailed analysis" before every answer.',+ },+ ],+ reason: 'assistant self-wording rule',+ target: 'prompt',+ },+ ],+ });+ const result = await handler.handle(+ {+ chain: { chainId: 'chain_1', parentNodeId: 'source_1', rootSourceId: 'source_1' },+ payload: {+ confidence: 0.9,+ evidence: [{ cue: 'wrong', excerpt: 'wrong' }],+ message: 'Stop saying "Below is a detailed analysis" before every answer.',+ messageId: 'msg_1',+ reason: 'corrective-feedback-cue',+ result: 'not_satisfied',+ serializedContext: '{"should":"not be forwarded to domain signals"}',+ sourceHints: { documentPayload: { patch: true } },+ },+ signalId: 'sig_1',+ signalType: 'signal.feedback.satisfaction',+ source: { sourceId: 'source_1', sourceType: 'agent.user.message' },+ timestamp: 1,+ },+ context,+ );++ expect(result).toEqual(+ expect.objectContaining({+ signals: [+ expect.objectContaining({+ payload: expect.objectContaining({+ sourceHints: { documentPayload: { patch: true } },+ target: 'prompt',+ }),+ signalType: 'signal.feedback.domain.prompt',+ }),+ ],+ }),+ );+ });++ it('allows multi-target fanout for memory plus skill signals', async () => {+ const handler = createFeedbackDomainJudgeSignalHandler({+ resolveDomains: async () => [+ {+ confidence: 0.86,+ evidence: [+ {+ cue: 'i prefer',+ excerpt:+ 'Going forward, in code review I prefer concise file-specific suggestions and a reusable template.',+ },+ ],+ reason: 'future personal preference for code review',+ target: 'memory',+ },+ {+ confidence: 0.78,+ evidence: [+ {+ cue: 'template',+ excerpt:+ 'Going forward, in code review I prefer concise file-specific suggestions and a reusable template.',+ },+ ],+ reason: 'reusable template idea',+ target: 'skill',+ },+ ],+ });+ const result = await handler.handle(+ {+ chain: { chainId: 'chain_2', parentNodeId: 'source_2', rootSourceId: 'source_2' },+ payload: {+ confidence: 0.9,+ evidence: [{ cue: 'prefer', excerpt: 'prefer' }],+ message:+ 'Going forward, in code review I prefer concise file-specific suggestions and a reusable template.',+ messageId: 'msg_2',+ reason: 'corrective-feedback-cue',+ result: 'not_satisfied',+ sourceHints: { memoryPayload: { saved: true } },+ },+ signalId: 'sig_2',+ signalType: 'signal.feedback.satisfaction',+ source: { sourceId: 'source_2', sourceType: 'agent.user.message' },+ timestamp: 1,+ },+ context,+ );++ expect(result).toEqual(+ expect.objectContaining({+ signals: expect.arrayContaining([+ expect.objectContaining({ signalType: 'signal.feedback.domain.memory' }),+ expect.objectContaining({ signalType: 'signal.feedback.domain.skill' }),+ ]),+ }),+ );+ });++ it('does not invoke domain routing for neutral satisfaction results', async () => {+ let invocationCount = 0;++ const handler = createFeedbackDomainJudgeSignalHandler({+ resolveDomains: async () => {+ invocationCount += 1;++ return [+ {+ confidence: 0.95,+ evidence: [{ cue: 'thanks', excerpt: 'Thanks.' }],+ reason: 'should not happen',+ target: 'none',+ },+ ];+ },+ });++ const result = await handler.handle(+ {+ chain: {+ chainId: 'chain_neutral',+ parentNodeId: 'source_neutral',+ rootSourceId: 'source_neutral',+ },+ payload: {+ confidence: 0.91,+ evidence: [{ cue: 'thanks', excerpt: 'Thanks.' }],+ message: 'Thanks.',+ messageId: 'msg_neutral',+ reason: 'acknowledgement-only',+ result: 'neutral',+ sourceHints: { intents: ['memory'] },+ },+ signalId: 'sig_neutral',+ signalType: 'signal.feedback.satisfaction',+ source: { sourceId: 'source_neutral', sourceType: 'agent.user.message' },+ timestamp: 1,+ },+ context,+ );++ expect(invocationCount).toBe(0);+ expect(result).toBeUndefined();+ });++ it('passes structured satisfaction output to the resolver without serialized context', async () => {+ let resolverInput:+ | Parameters<+ NonNullable<+ NonNullable<+ Parameters<typeof createFeedbackDomainJudgeSignalHandler>[0]+ >['resolveDomains']+ >+ >[0]+ | undefined;++ const handler = createFeedbackDomainJudgeSignalHandler({+ resolveDomains: async (input) => {+ resolverInput = input;++ return [+ {+ confidence: 0.86,+ evidence: [+ {+ cue: 'i prefer',+ excerpt: 'Going forward, I prefer concise file-specific review comments.',+ },+ ],+ reason: 'durable user preference',+ target: 'memory',+ },+ ];+ },+ });++ await handler.handle(+ {+ chain: {+ chainId: 'chain_structured',+ parentNodeId: 'source_structured',+ rootSourceId: 'source_structured',+ },+ payload: {+ confidence: 0.88,+ evidence: [+ {+ cue: 'prefer',+ excerpt: 'Going forward, I prefer concise file-specific review comments.',+ },+ ],+ message: 'Going forward, I prefer concise file-specific review comments.',+ messageId: 'msg_structured',+ reason: 'corrective-feedback-cue',+ result: 'not_satisfied',+ serializedContext: '{"large":"context"}',+ sourceHints: { intents: ['memory'] },+ topicId: 'topic_structured',+ },+ signalId: 'sig_structured',+ signalType: 'signal.feedback.satisfaction',+ source: { sourceId: 'source_structured', sourceType: 'agent.user.message' },+ timestamp: 1,+ },+ context,+ );++ expect(resolverInput).toEqual({+ chain: {+ chainId: 'chain_structured',+ parentNodeId: 'source_structured',+ rootSourceId: 'source_structured',+ },+ feedback: {+ confidence: 0.88,+ evidence: [+ {+ cue: 'prefer',+ excerpt: 'Going forward, I prefer concise file-specific review comments.',+ },+ ],+ message: 'Going forward, I prefer concise file-specific review comments.',+ messageId: 'msg_structured',+ reason: 'corrective-feedback-cue',+ result: 'not_satisfied',+ },+ source: { sourceId: 'source_structured', sourceType: 'agent.user.message' },+ sourceHints: { intents: ['memory'] },+ topicId: 'topic_structured',+ });+ });++ it('keeps satisfied reinforcement out of the memory lane when only non-memory domains are returned', async () => {+ const handler = createFeedbackDomainJudgeSignalHandler({+ resolveDomains: async () => [+ {+ confidence: 0.83,+ evidence: [+ {+ cue: 'reusable template',+ excerpt: 'This workflow is much better and should become our reusable template.',+ },+ ],+ reason: 'reusable template suggestion',+ target: 'skill',+ },+ ],+ });+ const result = await handler.handle(+ {+ chain: { chainId: 'chain_3', parentNodeId: 'source_3', rootSourceId: 'source_3' },+ payload: {+ confidence: 0.9,+ evidence: [{ cue: 'much better', excerpt: 'much better' }],+ message: 'This workflow is much better and should become our reusable template.',+ messageId: 'msg_3',+ reason: 'positive-reinforcement-cue',+ result: 'satisfied',+ sourceHints: { intents: ['memory'] },+ },+ signalId: 'sig_3',+ signalType: 'signal.feedback.satisfaction',+ source: { sourceId: 'source_3', sourceType: 'agent.user.message' },+ timestamp: 1,+ },+ context,+ );++ expect(result).toEqual(+ expect.objectContaining({+ signals: expect.arrayContaining([+ expect.objectContaining({ signalType: 'signal.feedback.domain.skill' }),+ ]),+ }),+ );+ expect(result).not.toEqual(+ expect.objectContaining({+ signals: expect.arrayContaining([+ expect.objectContaining({ signalType: 'signal.feedback.domain.memory' }),+ ]),+ }),+ );+ });+});diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.tsnew file mode 100644index 00000000000..8778fcccfe5--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts@@ -0,0 +1,176 @@+// @vitest-environment node+import { RequestTrigger } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++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', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));++const createUserMessageSource = (+ sourceId: string,+ message: string,+ serializedContext = 'topic=repo-review;assistant_behavior=verbose',+): SourceAgentUserMessage => ({+ chain: { chainId: `chain:${sourceId}`, rootSourceId: sourceId },+ payload: {+ agentId: 'agent_1',+ documentPayload: { section: 'answer-style' },+ intents: ['document', 'memory'],+ memoryPayload: { preplanned: true },+ message,+ messageId: `msg:${sourceId}`,+ serializedContext,+ topicId: 'topic_1',+ },+ scopeKey: 'topic:thread_1',+ sourceId,+ sourceType: 'agent.user.message',+ timestamp: 1_710_000_000_000,+});++describe('feedbackSatisfactionJudge', () => {+ const mockGenerateObject = vi.fn();++ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({+ generateObject: mockGenerateObject,+ } as never);+ });++ it('uses the injected judge, passes only message and serializedContext, and skips guards', async () => {+ const getGuardState = vi.fn().mockResolvedValue({});+ const touchGuardState = vi.fn().mockResolvedValue({});+ const judge = {+ judgeSatisfaction: vi.fn().mockResolvedValue({+ confidence: 0.94,+ evidence: [{ cue: 'requested correction', excerpt: 'Cut the padding.' }],+ reason: 'explicit dissatisfaction with answer style',+ result: 'not_satisfied',+ }),+ };+ const ctx = createRuntimeProcessorContext({+ backend: {+ getGuardState,+ touchGuardState,+ },+ scopeKey: 'topic:thread_1',+ });++ const processor = createFeedbackSatisfactionJudgeProcessor({ judge });+ const result = await processor.handle(+ createUserMessageSource('source_1', 'Cut the padding.'),+ ctx,+ );++ expect(judge.judgeSatisfaction).toHaveBeenCalledWith({+ message: 'Cut the padding.',+ serializedContext: 'topic=repo-review;assistant_behavior=verbose',+ });+ expect(getGuardState).not.toHaveBeenCalled();+ expect(touchGuardState).not.toHaveBeenCalled();+ expect(result).toEqual(+ expect.objectContaining({+ signals: [+ expect.objectContaining({+ payload: expect.objectContaining({+ agentId: 'agent_1',+ confidence: 0.94,+ evidence: [{ cue: 'requested correction', excerpt: 'Cut the padding.' }],+ message: 'Cut the padding.',+ messageId: 'msg:source_1',+ reason: 'explicit dissatisfaction with answer style',+ result: 'not_satisfied',+ serializedContext: 'topic=repo-review;assistant_behavior=verbose',+ sourceHints: {+ documentPayload: { section: 'answer-style' },+ intents: ['document', 'memory'],+ memoryPayload: { preplanned: true },+ },+ topicId: 'topic_1',+ }),+ signalType: 'signal.feedback.satisfaction',+ }),+ ],+ status: 'dispatch',+ }),+ );+ });++ it('uses the default model-backed judge when db and userId are provided', async () => {+ mockGenerateObject.mockResolvedValue({+ confidence: 0.88,+ evidence: [{ cue: 'positive approval', excerpt: 'This structure works.' }],+ reason: 'clear approval of the new structure',+ result: 'satisfied',+ });++ const ctx = createRuntimeProcessorContext({+ backend: {+ async getGuardState() {+ return {};+ },+ async touchGuardState() {+ return {};+ },+ },+ scopeKey: 'topic:thread_1',+ });++ const processor = createFeedbackSatisfactionJudgeProcessor({+ db: {} as LobeChatDatabase,+ model: 'gpt-test',+ provider: 'openai',+ userId: 'user_1',+ });+ const result = await processor.handle(+ createUserMessageSource('source_2', 'This structure works.'),+ ctx,+ );++ expect(initModelRuntimeFromDB).toHaveBeenCalledWith({} as LobeChatDatabase, 'user_1', 'openai');+ expect(mockGenerateObject).toHaveBeenCalledWith(+ expect.objectContaining({+ messages: [+ expect.objectContaining({+ content: expect.stringContaining('You are the satisfaction-judging step'),+ role: 'system',+ }),+ expect.objectContaining({+ content: expect.stringContaining(+ 'serializedContext="topic=repo-review;assistant_behavior=verbose"',+ ),+ role: 'user',+ }),+ ],+ model: 'gpt-test',+ }),+ { metadata: { trigger: RequestTrigger.Memory } },+ );+ expect(result).toEqual(+ expect.objectContaining({+ signals: [+ expect.objectContaining({+ payload: expect.objectContaining({+ result: 'satisfied',+ reason: 'clear approval of the new structure',+ }),+ }),+ ],+ }),+ );+ });++ it('fails fast when no judge or runtime context is configured', () => {+ expect(() => createFeedbackSatisfactionJudgeProcessor()).toThrow(+ 'Feedback satisfaction judge requires either an injected judge or both db and userId.',+ );+ });+});diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.tsnew file mode 100644index 00000000000..b41a0a18b42--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/userMemory.test.ts@@ -0,0 +1,243 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { RuntimeProcessorContext } from '../../../../runtime/context';+import { defineUserMemoryActionHandler } from '../userMemory';++const memoryActionRunner = vi.fn();++const context = {+ now: () => 1,+ runtimeState: {+ getGuardState: vi.fn().mockResolvedValue({}),+ touchGuardState: vi.fn().mockResolvedValue({}),+ },+ scopeKey: 'topic:topic-1',+} as const satisfies RuntimeProcessorContext;++describe('defineUserMemoryActionHandler', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('runs the memory action through the injected memory agent runner', async () => {+ memoryActionRunner.mockResolvedValue({+ status: 'applied',+ });++ const handler = defineUserMemoryActionHandler({+ db: {} as never,+ memoryActionRunner,+ userId: 'user_1',+ });++ const result = await handler.handle(+ {+ actionId: 'act_memory_agent',+ actionType: 'action.user-memory.handle',+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },+ payload: {+ agentId: 'agent_1',+ conflictPolicy: { forbiddenWith: ['none'], mode: 'fanout', priority: 100 },+ evidence: [{ cue: 'going forward', excerpt: 'Keep code review comments concise.' }],+ feedbackHint: 'not_satisfied',+ idempotencyKey: 'source_1:memory:msg_1',+ message: 'Going forward, keep code review comments concise and file-specific.',+ reason: 'durable future preference for code review',+ serializedContext: '{"surface":"chat"}',+ sourceHints: { intents: ['memory'] },+ topicId: 'topic_1',+ },+ signal: {+ signalId: 'sig_1',+ signalType: 'signal.feedback.domain.memory',+ },+ source: { sourceId: 'source_1', sourceType: 'agent.user.message' },+ timestamp: 1,+ },+ context,+ );++ expect(memoryActionRunner).toHaveBeenCalledWith({+ agentId: 'agent_1',+ conflictPolicy: { forbiddenWith: ['none'], mode: 'fanout', priority: 100 },+ evidence: [{ cue: 'going forward', excerpt: 'Keep code review comments concise.' }],+ feedbackHint: 'not_satisfied',+ message: 'Going forward, keep code review comments concise and file-specific.',+ reason: 'durable future preference for code review',+ serializedContext: '{"surface":"chat"}',+ sourceHints: { intents: ['memory'] },+ topicId: 'topic_1',+ });+ expect(result?.status).toBe('applied');+ expect(context.runtimeState.touchGuardState).toHaveBeenCalledTimes(1);+ });++ it('skips memory actions when the feedback message is missing', async () => {+ const handler = defineUserMemoryActionHandler({+ db: {} as never,+ memoryActionRunner,+ userId: 'user_1',+ });++ const result = await handler.handle(+ {+ actionId: 'act_missing_message',+ actionType: 'action.user-memory.handle',+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },+ payload: {+ idempotencyKey: 'source_1:memory:msg_missing',+ message: ' ',+ },+ signal: {+ signalId: 'sig_missing',+ signalType: 'signal.feedback.domain.memory',+ },+ source: { sourceId: 'source_1', sourceType: 'agent.user.message' },+ timestamp: 1,+ },+ context,+ );++ expect(memoryActionRunner).not.toHaveBeenCalled();+ expect(result).toMatchObject({+ detail: 'Missing memory action message.',+ status: 'skipped',+ });+ });++ it('skips repeated actions after the same idempotency key was already applied', async () => {+ memoryActionRunner.mockResolvedValue({+ status: 'applied',+ });++ const getGuardState = vi+ .fn()+ .mockResolvedValueOnce({})+ .mockResolvedValueOnce({ lastEventAt: 1 });+ const touchGuardState = vi.fn().mockResolvedValue({});+ const idempotentContext = {+ ...context,+ runtimeState: { getGuardState, touchGuardState },+ } as const satisfies RuntimeProcessorContext;+ const handler = defineUserMemoryActionHandler({+ db: {} as never,+ memoryActionRunner,+ userId: 'user_1',+ });++ const action = {+ actionId: 'act_idempotent',+ actionType: 'action.user-memory.handle',+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },+ payload: {+ agentId: 'agent_1',+ idempotencyKey: 'source_1:memory:msg_repeat',+ message: 'Remember that I prefer conclusion-first answers.',+ },+ signal: {+ signalId: 'sig_repeat',+ signalType: 'signal.feedback.domain.memory',+ },+ source: { sourceId: 'source_1', sourceType: 'agent.user.message' },+ timestamp: 1,+ } as const;++ const first = await handler.handle(action, idempotentContext);+ const second = await handler.handle(action, idempotentContext);++ expect(first?.status).toBe('applied');+ expect(second).toMatchObject({+ detail: 'Action idempotency key already applied.',+ status: 'skipped',+ });+ expect(memoryActionRunner).toHaveBeenCalledTimes(1);+ });++ it('surfaces memory agent failures without marking idempotency', async () => {+ memoryActionRunner.mockResolvedValue({+ detail: 'Memory action agent finished with an error.',+ status: 'failed',+ });++ const handler = defineUserMemoryActionHandler({+ db: {} as never,+ memoryActionRunner,+ userId: 'user_1',+ });++ const result = await handler.handle(+ {+ actionId: 'act_failed',+ actionType: 'action.user-memory.handle',+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },+ payload: {+ agentId: 'agent_1',+ idempotencyKey: 'source_1:memory:msg_failed',+ message: 'Remember the style I liked yesterday.',+ },+ signal: {+ signalId: 'sig_failed',+ signalType: 'signal.feedback.domain.memory',+ },+ source: { sourceId: 'source_1', sourceType: 'agent.user.message' },+ timestamp: 1,+ },+ context,+ );++ expect(result).toMatchObject({+ detail: 'Memory action agent finished with an error.',+ status: 'failed',+ });+ expect(context.runtimeState.touchGuardState).not.toHaveBeenCalled();+ });++ it('does not poison the idempotency lane when the first agent attempt fails', async () => {+ memoryActionRunner+ .mockResolvedValueOnce({+ detail: 'Memory action agent finished with an error.',+ status: 'failed',+ })+ .mockResolvedValueOnce({+ status: 'applied',+ });++ const getGuardState = vi.fn().mockResolvedValue({});+ const touchGuardState = vi.fn().mockResolvedValue({});+ const retryableContext = {+ ...context,+ runtimeState: { getGuardState, touchGuardState },+ } as const satisfies RuntimeProcessorContext;+ const handler = defineUserMemoryActionHandler({+ db: {} as never,+ memoryActionRunner,+ userId: 'user_1',+ });++ const action = {+ actionId: 'act_retryable',+ actionType: 'action.user-memory.handle',+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },+ payload: {+ agentId: 'agent_1',+ idempotencyKey: 'source_1:memory:msg_retry',+ message: 'Going forward, remember that I want concise answers.',+ },+ signal: {+ signalId: 'sig_retry',+ signalType: 'signal.feedback.domain.memory',+ },+ source: { sourceId: 'source_1', sourceType: 'agent.user.message' },+ timestamp: 1,+ } as const;++ const first = await handler.handle(action, retryableContext);+ const second = await handler.handle(action, retryableContext);++ expect(first?.status).toBe('failed');+ expect(second?.status).toBe('applied');+ expect(touchGuardState).toHaveBeenCalledTimes(1);+ expect(memoryActionRunner).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/index.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/index.tsnew file mode 100644index 00000000000..ce0f004e09f--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/index.ts@@ -0,0 +1 @@+export * from './userMemory';diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.tsnew file mode 100644index 00000000000..0831214ab3e--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts@@ -0,0 +1,453 @@+import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';+import type {+ AgenticAttempt,+ BaseAction,+ ExecutorResult,+ SignalAttempt,+} from '@lobechat/agent-signal';+import { MemoryApiName, MemoryIdentifier } from '@lobechat/builtin-tool-memory';+import type { LobeToolManifest, ToolExecutor, ToolSource } from '@lobechat/context-engine';+import { nanoid } from '@lobechat/utils';++import { PluginModel } from '@/database/models/plugin';+import type { LobeChatDatabase } from '@/database/type';+import {+ InMemoryAgentStateManager,+ InMemoryStreamEventManager,+} from '@/server/modules/AgentRuntime';+import {+ createServerAgentToolsEngine,+ type InstalledPlugin,+ type ServerAgentToolsContext,+} from '@/server/modules/Mecha';+import { AgentService } from '@/server/services/agent';++import type { RuntimeProcessorContext } from '../../../runtime/context';+import { defineActionHandler } from '../../../runtime/middleware';+import { hasAppliedActionIdempotency, markAppliedActionIdempotency } from '../../actionIdempotency';+import type {+ ActionUserMemoryHandle,+ AgentSignalFeedbackDomainConflictPolicy,+ AgentSignalFeedbackEvidence,+ AgentSignalFeedbackSourceHints,+} from '../../types';+import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../../types';++const MEMORY_AGENT_MAX_STEPS = 8;++const MEMORY_WRITE_TOOL_NAMES = new Set(+ [+ MemoryApiName.addActivityMemory,+ MemoryApiName.addContextMemory,+ MemoryApiName.addExperienceMemory,+ MemoryApiName.addIdentityMemory,+ MemoryApiName.addPreferenceMemory,+ MemoryApiName.removeIdentityMemory,+ MemoryApiName.updateIdentityMemory,+ ].map((apiName) => `${MemoryIdentifier}/${apiName}`),+);++const MEMORY_WRITER_SYSTEM_ROLE = `You are the Agent Signal memory writer.++You are not chatting with the user.+Your job is to decide whether the feedback should update durable user memory.++Use only the lobe-user-memory built-in tool when a durable memory write is justified.+Choose the correct memory API based on the feedback:+- addPreferenceMemory for stable future-facing preferences+- addIdentityMemory / updateIdentityMemory / removeIdentityMemory for enduring identity facts or corrections+- addContextMemory for ongoing situations, environments, or projects+- addExperienceMemory for reusable lessons from outcomes or workflows+- addActivityMemory for notable concrete events worth remembering++If the feedback should not become durable memory, do not call any tools and end briefly.+Do not invent your own JSON schema. Use the built-in tool exactly as exposed.`;++export interface MemoryAgentActionResult {+ detail?: string;+ status: 'applied' | 'failed' | 'skipped';+}++export interface UserMemoryActionHandlerOptions {+ agentService?: Pick<AgentService, 'getAgentConfig'>;+ db: LobeChatDatabase;+ memoryActionRunner?: (input: {+ agentId?: string;+ conflictPolicy?: AgentSignalFeedbackDomainConflictPolicy;+ evidence?: AgentSignalFeedbackEvidence[];+ feedbackHint?: 'not_satisfied' | 'satisfied';+ message: string;+ reason?: string;+ serializedContext?: string;+ sourceHints?: AgentSignalFeedbackSourceHints;+ topicId?: string;+ }) => Promise<MemoryAgentActionResult>;+ pluginModel?: Pick<PluginModel, 'query'>;+ userId: string;+}++const finalizeAttempt = (+ startedAt: number,+ status: SignalAttempt['status'],+): SignalAttempt | AgenticAttempt => ({+ completedAt: Date.now(),+ current: 1,+ startedAt,+ status,+});++const toExecutorError = (actionId: string, error: unknown, startedAt: number): ExecutorResult => {+ return {+ actionId,+ attempt: finalizeAttempt(startedAt, 'failed'),+ error: {+ cause: error,+ code: 'USER_MEMORY_EXECUTION_FAILED',+ message: error instanceof Error ? error.message : String(error),+ },+ status: 'failed',+ };+};++const isUserMemoryAction = (action: BaseAction): action is ActionUserMemoryHandle => {+ return action.actionType === AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle;+};++const toMemoryWriterPrompt = (input: {+ conflictPolicy?: AgentSignalFeedbackDomainConflictPolicy;+ evidence?: AgentSignalFeedbackEvidence[];+ feedbackHint?: 'not_satisfied' | 'satisfied';+ message: string;+ reason?: string;+ serializedContext?: string;+ sourceHints?: AgentSignalFeedbackSourceHints;+}) => {+ const feedbackHintBlock = input.feedbackHint+ ? `Feedback satisfaction hint: ${input.feedbackHint}`+ : undefined;+ const domainReasonBlock = input.reason ? `Domain routing reason: ${input.reason}` : undefined;+ const evidenceBlock =+ input.evidence && input.evidence.length > 0+ ? `Domain evidence:\n${JSON.stringify(input.evidence)}`+ : undefined;+ const sourceHintsBlock = input.sourceHints+ ? `Source hints:\n${JSON.stringify(input.sourceHints)}`+ : undefined;+ const conflictPolicyBlock = input.conflictPolicy+ ? `Conflict policy:\n${JSON.stringify(input.conflictPolicy)}`+ : undefined;+ const routingContextBlock = [+ feedbackHintBlock,+ domainReasonBlock,+ evidenceBlock,+ sourceHintsBlock,+ conflictPolicyBlock,+ ]+ .filter(Boolean)+ .join('\n\n');+ const contextBlock = input.serializedContext?.trim()+ ? `\n\nAdditional runtime context:\n${input.serializedContext}`+ : '';+ const hintBlock = routingContextBlock ? `\n\nRouting context:\n${routingContextBlock}` : '';++ return `User feedback to analyze for durable memory:\n${input.message}${hintBlock}${contextBlock}`;+};++const createInitialContext = (operationId: string): AgentRuntimeContext => {+ return {+ payload: { message: [] },+ phase: 'user_input',+ session: {+ messageCount: 1,+ sessionId: operationId,+ status: 'idle',+ stepCount: 0,+ },+ };+};++const toManifestRecord = (manifestMap: Map<string, LobeToolManifest>) => {+ return Object.fromEntries(manifestMap) as Record<string, LobeToolManifest>;+};++const createFunctionCallSupportChecker = async () => {+ const { LOBE_DEFAULT_MODEL_LIST } = await import('model-bank');++ return (model: string, provider: string) => {+ const info = LOBE_DEFAULT_MODEL_LIST.find(+ (item) => item.id === model && item.providerId === provider,+ );++ return info?.abilities?.functionCall ?? true;+ };+};++const hasSuccessfulMemoryWrite = (state: AgentState) => {+ const byTool = state.usage?.tools?.byTool ?? [];++ return byTool.some(+ (entry) => MEMORY_WRITE_TOOL_NAMES.has(entry.name) && entry.calls > entry.errors,+ );+};++const hasFailedMemoryWrite = (state: AgentState) => {+ const byTool = state.usage?.tools?.byTool ?? [];++ return byTool.some(+ (entry) =>+ MEMORY_WRITE_TOOL_NAMES.has(entry.name) && entry.calls > 0 && entry.calls === entry.errors,+ );+};++const runMemoryActionAgent = async (+ input: {+ agentId?: string;+ conflictPolicy?: AgentSignalFeedbackDomainConflictPolicy;+ evidence?: AgentSignalFeedbackEvidence[];+ feedbackHint?: 'not_satisfied' | 'satisfied';+ message: string;+ reason?: string;+ serializedContext?: string;+ sourceHints?: AgentSignalFeedbackSourceHints;+ topicId?: string;+ },+ options: UserMemoryActionHandlerOptions,+): Promise<MemoryAgentActionResult> => {+ if (!input.agentId) {+ return {+ detail: 'Missing agentId for memory action.',+ status: 'skipped',+ };+ }++ const agentService = options.agentService ?? new AgentService(options.db, options.userId);+ const pluginModel = options.pluginModel ?? new PluginModel(options.db, options.userId);+ const agentConfig = await agentService.getAgentConfig(input.agentId);++ if (!agentConfig?.model || !agentConfig?.provider) {+ return {+ detail: 'Missing runnable agent config for memory action.',+ status: 'failed',+ };+ }++ const installedPlugins = (await pluginModel.query()) as InstalledPlugin[];+ const isModelSupportToolUse = await createFunctionCallSupportChecker();+ const toolsContext: ServerAgentToolsContext = {+ installedPlugins,+ isModelSupportToolUse,+ };++ const memoryToolsAgentConfig = {+ chatConfig: {+ runtimeEnv: agentConfig.chatConfig?.runtimeEnv,+ searchMode: agentConfig.chatConfig?.searchMode,+ },+ plugins: [MemoryIdentifier],+ };++ const memoryRuntimeAgentConfig = {+ ...agentConfig,+ plugins: [MemoryIdentifier],+ systemRole: MEMORY_WRITER_SYSTEM_ROLE,+ };++ const toolsEngine = createServerAgentToolsEngine(toolsContext, {+ agentConfig: memoryToolsAgentConfig,+ globalMemoryEnabled: true,+ model: agentConfig.model,+ provider: agentConfig.provider,+ });++ const toolsResult = toolsEngine.generateToolsDetailed({+ model: agentConfig.model,+ provider: agentConfig.provider,+ skipDefaultTools: true,+ toolIds: [MemoryIdentifier],+ });++ if (!toolsResult.enabledToolIds.includes(MemoryIdentifier) || !toolsResult.tools?.length) {+ return {+ detail: 'Memory tool is not available for the memory action agent.',+ status: 'failed',+ };+ }++ const manifestMap = toolsEngine.getEnabledPluginManifests([MemoryIdentifier]);+ const operationId = `agent-signal-memory-${nanoid()}`;+ const initialContext = createInitialContext(operationId);+ const streamEventManager = new InMemoryStreamEventManager();+ const { AgentRuntimeService } =+ await import('@/server/services/agentRuntime/AgentRuntimeService');+ const runtimeService = new AgentRuntimeService(options.db, options.userId, {+ coordinatorOptions: {+ stateManager: new InMemoryAgentStateManager(),+ streamEventManager,+ },+ queueService: null,+ streamEventManager,+ });++ await runtimeService.createOperation({+ agentConfig: memoryRuntimeAgentConfig,+ appContext: {+ agentId: input.agentId,+ scope: 'chat',+ topicId: input.topicId ?? null,+ trigger: 'agent-signal',+ },+ autoStart: false,+ initialContext,+ initialMessages: [{ content: toMemoryWriterPrompt(input), role: 'user' }],+ modelRuntimeConfig: {+ model: agentConfig.model,+ provider: agentConfig.provider,+ },+ operationId,+ toolSet: {+ enabledToolIds: toolsResult.enabledToolIds,+ executorMap: {} as Record<string, ToolExecutor>,+ manifestMap: toManifestRecord(manifestMap),+ sourceMap: {} as Record<string, ToolSource>,+ tools: toolsResult.tools,+ },+ userId: options.userId,+ userInterventionConfig: { approvalMode: 'headless' },+ });++ const finalState = await runtimeService.executeSync(operationId, {+ initialContext,+ maxSteps: MEMORY_AGENT_MAX_STEPS,+ });++ if (finalState.status === 'error') {+ return {+ detail: 'Memory action agent finished with an error.',+ status: 'failed',+ };+ }++ if (hasSuccessfulMemoryWrite(finalState)) {+ return { status: 'applied' };+ }++ if (hasFailedMemoryWrite(finalState)) {+ return {+ detail: 'Memory tool call failed during memory action agent execution.',+ status: 'failed',+ };+ }++ return {+ detail: 'Memory action agent did not issue a durable memory write.',+ status: 'skipped',+ };+};++export const handleUserMemoryAction = async (+ action: BaseAction,+ options: UserMemoryActionHandlerOptions,+ context: RuntimeProcessorContext,+): Promise<ExecutorResult> => {+ const startedAt = Date.now();+ const idempotencyKey =+ 'idempotencyKey' in action.payload && typeof action.payload.idempotencyKey === 'string'+ ? action.payload.idempotencyKey+ : undefined;++ try {+ if (await hasAppliedActionIdempotency(context, idempotencyKey)) {+ return {+ actionId: action.actionId,+ attempt: finalizeAttempt(startedAt, 'skipped'),+ detail: 'Action idempotency key already applied.',+ status: 'skipped',+ };+ }++ if (!isUserMemoryAction(action)) {+ return {+ actionId: action.actionId,+ attempt: finalizeAttempt(startedAt, 'skipped'),+ detail: 'Unsupported memory action.',+ status: 'skipped',+ };+ }++ const message =+ typeof action.payload.message === 'string' ? action.payload.message.trim() : undefined;++ if (!message) {+ return {+ actionId: action.actionId,+ attempt: finalizeAttempt(startedAt, 'skipped'),+ detail: 'Missing memory action message.',+ status: 'skipped',+ };+ }++ const runner = options.memoryActionRunner ?? ((input) => runMemoryActionAgent(input, options));+ const result = await runner({+ agentId: typeof action.payload.agentId === 'string' ? action.payload.agentId : undefined,+ conflictPolicy:+ typeof action.payload.conflictPolicy === 'object' && action.payload.conflictPolicy+ ? action.payload.conflictPolicy+ : undefined,+ evidence: Array.isArray(action.payload.evidence) ? action.payload.evidence : undefined,+ feedbackHint:+ action.payload.feedbackHint === 'satisfied' ? 'satisfied' : action.payload.feedbackHint,+ message,+ reason: typeof action.payload.reason === 'string' ? action.payload.reason : undefined,+ serializedContext:+ typeof action.payload.serializedContext === 'string'+ ? action.payload.serializedContext+ : undefined,+ sourceHints:+ typeof action.payload.sourceHints === 'object' && action.payload.sourceHints+ ? action.payload.sourceHints+ : undefined,+ topicId: typeof action.payload.topicId === 'string' ? action.payload.topicId : undefined,+ });++ if (result.status === 'applied') {+ await markAppliedActionIdempotency(context, idempotencyKey);++ return {+ actionId: action.actionId,+ attempt: finalizeAttempt(startedAt, 'succeeded'),+ detail: result.detail,+ status: 'applied',+ };+ }++ if (result.status === 'failed') {+ return {+ ...toExecutorError(+ action.actionId,+ result.detail ?? 'Memory action agent failed.',+ startedAt,+ ),+ detail: result.detail,+ };+ }++ return {+ actionId: action.actionId,+ attempt: finalizeAttempt(startedAt, 'skipped'),+ detail: result.detail,+ status: 'skipped',+ };+ } catch (error) {+ return toExecutorError(action.actionId, error, startedAt);+ }+};++export const defineUserMemoryActionHandler = (options: UserMemoryActionHandlerOptions) => {+ return defineActionHandler(+ AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle,+ 'handler.user-memory.handle',+ async (action, context: RuntimeProcessorContext) => {+ return handleUserMemoryAction(action, options, context);+ },+ );+};diff --git a/src/server/services/agentSignal/policies/analyzeIntent/context/__tests__/feedbackContextAssembler.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/context/__tests__/feedbackContextAssembler.test.tsnew file mode 100644index 00000000000..d8fb4165ba7--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/context/__tests__/feedbackContextAssembler.test.ts@@ -0,0 +1,38 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import {+ assembleFeedbackContext,+ FEEDBACK_CONTEXT_RECENT_MESSAGE_LIMIT,+} from '../feedbackContextAssembler';++describe('assembleFeedbackContext', () => {+ it('returns rendered context and resolves the latest assistant reply from recent messages', () => {+ const messages = Array.from({ length: 12 }, (_, index) => ({+ content: `message-${index + 1}`,+ id: `message-${index + 1}`,+ role: index % 2 === 0 ? 'user' : 'assistant',+ }));++ const result = assembleFeedbackContext({+ feedbackMessage: {+ content: 'Use bullet points next time.',+ id: 'feedback-1',+ role: 'user',+ },+ messages,+ });++ expect(result.recentMessages).toHaveLength(FEEDBACK_CONTEXT_RECENT_MESSAGE_LIMIT);+ expect(result.recentMessages[0]?.id).toBe('message-3');+ expect(result.latestAssistantReply).toEqual(+ expect.objectContaining({+ id: 'message-12',+ role: 'assistant',+ }),+ );+ expect(result.serializedContext).toContain('<feedback_analysis_context>');+ expect(result.serializedContext).toContain('message-12');+ expect(result.serializedContext).toContain('Use bullet points next time.');+ });+});diff --git a/src/server/services/agentSignal/policies/analyzeIntent/context/__tests__/messageContextRenderer.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/context/__tests__/messageContextRenderer.test.tsnew file mode 100644index 00000000000..8d291a82574--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/context/__tests__/messageContextRenderer.test.ts@@ -0,0 +1,31 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { renderMessageContext } from '../messageContextRenderer';++describe('renderMessageContext', () => {+ it('renders stable xml sections for feedback analysis context', () => {+ const xml = renderMessageContext({+ feedbackMessage: {+ content: 'Please keep responses shorter.',+ id: 'feedback-1',+ role: 'user',+ },+ latestAssistantReply: {+ content: 'Here is a long explanation.',+ id: 'assistant-2',+ role: 'assistant',+ },+ recentMessages: [+ { content: 'Hi', id: 'user-1', role: 'user' },+ { content: 'Hello <there>', id: 'assistant-1', role: 'assistant' },+ ],+ });++ expect(xml).toContain('<feedback_analysis_context>');+ expect(xml).toContain('<conversation>');+ expect(xml).toContain('<latest_assistant_reply>');+ expect(xml).toContain('<feedback_message>');+ expect(xml).toContain('<there>');+ });+});diff --git a/src/server/services/agentSignal/policies/analyzeIntent/context/feedbackContextAssembler.ts b/src/server/services/agentSignal/policies/analyzeIntent/context/feedbackContextAssembler.tsnew file mode 100644index 00000000000..d57a07cccff--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/context/feedbackContextAssembler.ts@@ -0,0 +1,50 @@+import type { FeedbackContextMessage } from './messageContextRenderer';+import { renderMessageContext } from './messageContextRenderer';++export const FEEDBACK_CONTEXT_RECENT_MESSAGE_LIMIT = 10;++/** Inputs required to assemble message-only feedback context. */+export interface AssembleFeedbackContextParams {+ feedbackMessage: FeedbackContextMessage;+ messages: FeedbackContextMessage[];+}++/** Output bundle returned by the feedback context assembler. */+export interface FeedbackContextAssemblyResult {+ latestAssistantReply?: FeedbackContextMessage;+ recentMessages: FeedbackContextMessage[];+ serializedContext: string;+}++const isAssistantMessage = (message: FeedbackContextMessage) => message.role === 'assistant';++/**+ * Assembles the message-only feedback context for Phase 1 analysis.+ *+ * Use when:+ * - Workflow ingress has already queried conversation messages+ * - Later feedback stages need one rendered context string plus the selected message window+ *+ * Expects:+ * - `messages` is already ordered from oldest to newest+ * - `feedbackMessage` is the current user feedback turn, even if it is not part of `messages`+ *+ * Returns:+ * - The selected recent messages, the resolved latest assistant reply, and rendered XML context+ */+export const assembleFeedbackContext = (+ params: AssembleFeedbackContextParams,+): FeedbackContextAssemblyResult => {+ const recentMessages = params.messages.slice(-FEEDBACK_CONTEXT_RECENT_MESSAGE_LIMIT);+ const latestAssistantReply = [...recentMessages].reverse().find(isAssistantMessage);++ return {+ latestAssistantReply,+ recentMessages,+ serializedContext: renderMessageContext({+ feedbackMessage: params.feedbackMessage,+ latestAssistantReply,+ recentMessages,+ }),+ };+};diff --git a/src/server/services/agentSignal/policies/analyzeIntent/context/messageContextRenderer.ts b/src/server/services/agentSignal/policies/analyzeIntent/context/messageContextRenderer.tsnew file mode 100644index 00000000000..1ddf532c527--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/context/messageContextRenderer.ts@@ -0,0 +1,72 @@+/** Minimal message shape required for feedback-context rendering. */+export interface FeedbackContextMessage {+ content?: string | null;+ id?: string;+ role: string;+}++/** Inputs required to render one feedback-analysis XML document. */+export interface RenderMessageContextParams {+ feedbackMessage: FeedbackContextMessage;+ latestAssistantReply?: FeedbackContextMessage;+ recentMessages: FeedbackContextMessage[];+}++const escapeXml = (value: string) =>+ value+ .replaceAll('&', '&')+ .replaceAll('<', '<')+ .replaceAll('>', '>')+ .replaceAll('"', '"')+ .replaceAll("'", ''');++const toXmlAttribute = (name: string, value?: string) => {+ if (!value) return '';++ return ` ${name}="${escapeXml(value)}"`;+};++const toNormalizedContent = (value?: string | null) => value?.trim() ?? '';++const renderMessageElement = (message: FeedbackContextMessage) => {+ const content = escapeXml(toNormalizedContent(message.content));++ return [+ `<message${toXmlAttribute('id', message.id)}${toXmlAttribute('role', message.role)}>`,+ `<content>${content}</content>`,+ `</message>`,+ ].join('');+};++/**+ * Renders feedback-analysis context into a deterministic XML envelope.+ *+ * Use when:+ * - Later feedback stages need the recent conversation in one stable string+ * - Tests need a pure serializer without database dependencies+ *+ * Expects:+ * - `recentMessages` is already ordered from oldest to newest+ * - `latestAssistantReply`, when present, already reflects the most recent assistant turn+ *+ * Returns:+ * - One stable XML document containing conversation, assistant reply, and feedback sections+ */+export const renderMessageContext = (params: RenderMessageContextParams) => {+ const { feedbackMessage, latestAssistantReply, recentMessages } = params;++ // TODO: serialize recent tool calls / tool results into feedback analysis context when we finalize the context format.+ const conversationXml = recentMessages.map(renderMessageElement).join('');+ const latestAssistantReplyXml = latestAssistantReply+ ? renderMessageElement(latestAssistantReply)+ : '';+ const feedbackMessageXml = renderMessageElement(feedbackMessage);++ return [+ '<feedback_analysis_context>',+ `<conversation>${conversationXml}</conversation>`,+ `<latest_assistant_reply>${latestAssistantReplyXml}</latest_assistant_reply>`,+ `<feedback_message>${feedbackMessageXml}</feedback_message>`,+ '</feedback_analysis_context>',+ ].join('');+};diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.tsnew file mode 100644index 00000000000..50b08dca809--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts@@ -0,0 +1,125 @@+import type { BaseAction, BaseSignal, RuntimeProcessorResult } from '@lobechat/agent-signal';++import { defineSignalHandler } from '../../runtime/middleware';+import {+ AGENT_SIGNAL_POLICY_ACTION_TYPES,+ AGENT_SIGNAL_POLICY_SIGNAL_TYPES,+ type AgentSignalFeedbackDomainTarget,+ type AgentSignalFeedbackSourceHints,+} from '../types';++const createStableIdempotencyKey = (+ signal: BaseSignal,+ target: AgentSignalFeedbackDomainTarget,+ messageId: string,+) => {+ return `${signal.chain.rootSourceId}:${target}:${messageId}`;+};++const buildPlannedActions = (signal: BaseSignal): BaseAction[] => {+ const payload = signal.payload as {+ agentId?: string;+ conflictPolicy?: {+ forbiddenWith?: AgentSignalFeedbackDomainTarget[];+ mode: 'exclusive' | 'fanout';+ priority: number;+ };+ evidence?: Array<{+ cue: string;+ excerpt: string;+ }>;+ message: string;+ messageId: string;+ reason?: string;+ satisfactionResult?: 'not_satisfied' | 'neutral' | 'satisfied';+ sourceHints?: AgentSignalFeedbackSourceHints;+ target: AgentSignalFeedbackDomainTarget;+ topicId?: string;+ };+ const sourcePayload =+ signal.source && 'payload' in signal.source && signal.source.payload+ ? (signal.source.payload as Record<string, unknown>)+ : undefined;+ const serializedContext =+ typeof sourcePayload?.serializedContext === 'string'+ ? sourcePayload.serializedContext+ : undefined;++ const idempotencyKey = createStableIdempotencyKey(signal, payload.target, payload.messageId);++ if (payload.target === 'memory') {+ return [+ {+ actionId: `${signal.signalId}:action:memory`,+ actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle,+ chain: {+ chainId: signal.chain.chainId,+ parentNodeId: signal.signalId,+ parentSignalId: signal.signalId,+ rootSourceId: signal.chain.rootSourceId,+ },+ payload: {+ agentId: payload.agentId,+ conflictPolicy: payload.conflictPolicy,+ evidence: payload.evidence,+ feedbackHint: payload.satisfactionResult === 'satisfied' ? 'satisfied' : 'not_satisfied',+ idempotencyKey,+ message: payload.message,+ reason: payload.reason,+ serializedContext,+ sourceHints: payload.sourceHints,+ topicId: payload.topicId,+ },+ signal: {+ signalId: signal.signalId,+ signalType: signal.signalType,+ },+ source: signal.source,+ timestamp: Date.now(),+ },+ ];+ }++ return [];+};++/**+ * Creates the signal handler that turns domain signals into action lists.+ *+ * Triggering workflow:+ *+ * {@link createFeedbackDomainJudgeSignalHandler}+ * -> `signal.feedback.domain.*`+ * -> {@link createFeedbackActionPlannerSignalHandler}+ *+ * Upstream:+ * - {@link createFeedbackDomainJudgeSignalHandler}+ *+ * Downstream:+ * - `action.user-memory.handle`+ */+export const createFeedbackActionPlannerSignalHandler = () => {+ const listenedSignalTypes = [+ AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainMemory,+ AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainNone,+ AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainPrompt,+ AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainSkill,+ ] as const;++ return defineSignalHandler(+ listenedSignalTypes,+ 'signal.feedback-action-planner',+ async (signal): Promise<RuntimeProcessorResult | void> => {+ const actions = buildPlannedActions(signal);++ if (actions.length === 0) {+ return;+ }++ return {+ actions,+ status: 'dispatch',+ };+ },+ );+};diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomain.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomain.tsnew file mode 100644index 00000000000..fb1006783a3--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomain.ts@@ -0,0 +1,204 @@+import { type BaseSignal, type RuntimeProcessorResult } from '@lobechat/agent-signal';++import type { LobeChatDatabase } from '@/database/type';++import { defineSignalHandler } from '../../runtime/middleware';+import {+ AGENT_SIGNAL_POLICY_SIGNAL_TYPES,+ type AgentSignalFeedbackDomainConflictPolicy,+ type AgentSignalFeedbackEvidence,+ type SignalFeedbackSatisfaction,+} from '../types';+import {+ type FeedbackDomainJudgeAgentModelConfig,+ type FeedbackDomainJudgeAgentResult,+ FeedbackDomainJudgeAgentService,+} from './feedbackDomainAgent';++interface FeedbackDomainJudgeResolverInput {+ chain: SignalFeedbackSatisfaction['chain'];+ feedback: Pick<+ SignalFeedbackSatisfaction['payload'],+ 'confidence' | 'evidence' | 'message' | 'messageId' | 'reason' | 'result'+ >;+ source: SignalFeedbackSatisfaction['source'];+ sourceHints: SignalFeedbackSatisfaction['payload']['sourceHints'];+ topicId: SignalFeedbackSatisfaction['payload']['topicId'];+}++/**+ * Dependencies for the feedback-domain judge signal handler.+ */+export interface CreateFeedbackDomainJudgeSignalHandlerOptions {+ resolveDomains?: (+ input: FeedbackDomainJudgeResolverInput,+ ) => Promise<FeedbackDomainJudgeAgentResult['targets']>;+}++/**+ * Factory options for the feedback-domain task agent.+ */+export interface CreateFeedbackDomainJudgePolicyOptions {+ feedbackDomainJudge?: Partial<FeedbackDomainJudgeAgentModelConfig> & {+ db: LobeChatDatabase;+ userId: string;+ };+}++const toConflictPolicy = (+ target: FeedbackDomainJudgeAgentResult['targets'][number]['target'],+): AgentSignalFeedbackDomainConflictPolicy => {+ switch (target) {+ case 'memory': {+ return { forbiddenWith: ['none'], mode: 'fanout', priority: 100 };+ }+ case 'prompt': {+ return { forbiddenWith: ['memory', 'none', 'skill'], mode: 'exclusive', priority: 90 };+ }+ case 'skill': {+ return { forbiddenWith: ['none'], mode: 'fanout', priority: 80 };+ }+ default: {+ return {+ forbiddenWith: ['memory', 'prompt', 'skill'],+ mode: 'exclusive',+ priority: 0,+ };+ }+ }+};++const toSignalType = (target: FeedbackDomainJudgeAgentResult['targets'][number]['target']) => {+ switch (target) {+ case 'memory': {+ return AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainMemory;+ }+ case 'skill': {+ return AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainSkill;+ }+ case 'prompt': {+ return AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainPrompt;+ }+ default: {+ return AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainNone;+ }+ }+};++const buildDomainSignals = (+ signal: SignalFeedbackSatisfaction,+ targets: FeedbackDomainJudgeAgentResult['targets'],+): BaseSignal[] => {+ return targets.map((target) => ({+ chain: {+ chainId: signal.chain.chainId,+ parentNodeId: signal.signalId,+ rootSourceId: signal.chain.rootSourceId,+ },+ payload: {+ agentId: signal.payload.agentId,+ confidence: target.confidence,+ conflictPolicy: toConflictPolicy(target.target),+ evidence:+ target.evidence.length > 0+ ? (target.evidence as AgentSignalFeedbackEvidence[])+ : signal.payload.evidence,+ message: signal.payload.message,+ messageId: signal.payload.messageId,+ reason: target.reason,+ satisfactionResult: signal.payload.result,+ sourceHints: signal.payload.sourceHints,+ target: target.target,+ topicId: signal.payload.topicId,+ },+ signalId: `${signal.signalId}:domain:${target.target}`,+ signalType: toSignalType(target.target),+ source: signal.source,+ timestamp: Date.now(),+ }));+};++const createDomainResolver = (+ options: CreateFeedbackDomainJudgePolicyOptions = {},+): CreateFeedbackDomainJudgeSignalHandlerOptions['resolveDomains'] => {+ const runtimeDeps = options.feedbackDomainJudge;++ if (!runtimeDeps) return undefined;++ return async (signal) => {+ const agent = new FeedbackDomainJudgeAgentService(+ runtimeDeps.db,+ runtimeDeps.userId,+ runtimeDeps,+ );++ return (+ await agent.judgeDomains({+ evidence: signal.feedback.evidence,+ message: signal.feedback.message,+ reason: signal.feedback.reason,+ result: signal.feedback.result,+ })+ ).targets;+ };+};++/**+ * Creates the signal handler for routing satisfaction signals into domain signals.+ *+ * Triggering workflow:+ *+ * {@link createFeedbackSatisfactionJudgeProcessor}+ * -> `signal.feedback.satisfaction`+ * -> {@link createFeedbackDomainJudgeSignalHandler}+ *+ * Upstream:+ * - {@link createFeedbackSatisfactionJudgeProcessor}+ *+ * Downstream:+ * - `signal.feedback.domain.memory`+ * - `signal.feedback.domain.prompt`+ * - `signal.feedback.domain.skill`+ * - `signal.feedback.domain.none`+ */+export const createFeedbackDomainJudgeSignalHandler = (+ options: CreateFeedbackDomainJudgeSignalHandlerOptions = {},+) => {+ const resolveDomains = options.resolveDomains;++ return defineSignalHandler(+ AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackSatisfaction,+ 'signal.feedback-domain-judge',+ async (signal): Promise<RuntimeProcessorResult | void> => {+ if (!resolveDomains || signal.payload.result === 'neutral') {+ return;+ }++ const domainTargets = await resolveDomains({+ chain: signal.chain,+ feedback: {+ confidence: signal.payload.confidence,+ evidence: signal.payload.evidence,+ message: signal.payload.message,+ messageId: signal.payload.messageId,+ reason: signal.payload.reason,+ result: signal.payload.result,+ },+ source: signal.source,+ sourceHints: signal.payload.sourceHints,+ topicId: signal.payload.topicId,+ });++ return {+ signals: buildDomainSignals(signal, domainTargets),+ status: 'dispatch',+ };+ },+ );+};++export const createFeedbackDomainResolver = (+ options: CreateFeedbackDomainJudgePolicyOptions = {},+) => {+ return createDomainResolver(options);+};diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomainAgent.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomainAgent.tsnew file mode 100644index 00000000000..9a771e29744--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomainAgent.ts@@ -0,0 +1,142 @@+import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';+import { chainAgentSignalAnalyzeIntentRoute } from '@lobechat/prompts';+import { RequestTrigger } from '@lobechat/types';+import debug from 'debug';+import { z } from 'zod';++import type { LobeChatDatabase } from '@/database/type';+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';++import { buildGenerateObjectSchema } from '../../../../../../packages/memory-user-memory/src/utils/zod';+import type {+ AgentSignalFeedbackEvidence,+ AgentSignalFeedbackPhase1DomainTarget,+ AgentSignalFeedbackSatisfactionResult,+} from '../types';++const log = debug('lobe-server:agent-signal:feedback-domain:agent');++type FeedbackDomainJudgeTarget = AgentSignalFeedbackPhase1DomainTarget | 'none';++const DomainTargetSchema = z.object({+ confidence: z.number().min(0).max(1),+ evidence: z.array(+ z.object({+ cue: z.string(),+ excerpt: z.string(),+ }),+ ),+ reason: z.string(),+ target: z.enum(['memory', 'none', 'prompt', 'skill']),+});++const FeedbackDomainJudgeAgentResultSchema = z.object({+ targets: z.array(DomainTargetSchema).min(1).max(4),+});++export type FeedbackDomainJudgeAgentResult = z.infer<typeof FeedbackDomainJudgeAgentResultSchema>;++export interface FeedbackDomainJudgeAgentModelConfig {+ model: string;+ provider: string;+}++export interface JudgeFeedbackDomainsParams {+ evidence: AgentSignalFeedbackEvidence[];+ message: string;+ reason: string;+ result: AgentSignalFeedbackSatisfactionResult;+}++/**+ * Lightweight task-agent service for feedback domain routing.+ *+ * Use when:+ * - A satisfaction signal must be routed into one or more durable domains+ * - Agent Signal should use a model decision instead of cue-based heuristics+ *+ * Expects:+ * - `message` is one normalized user-feedback string+ * - `result`, `reason`, and `evidence` come from the upstream satisfaction stage+ *+ * Returns:+ * - One validated set of domain targets suitable for domain signal fan-out+ */+export class FeedbackDomainJudgeAgentService {+ private readonly db: LobeChatDatabase;+ private readonly modelConfig: FeedbackDomainJudgeAgentModelConfig;+ private readonly userId: string;++ constructor(+ db: LobeChatDatabase,+ userId: string,+ modelConfig: Partial<FeedbackDomainJudgeAgentModelConfig> = {},+ ) {+ this.db = db;+ this.userId = userId;+ this.modelConfig = {+ model: modelConfig.model ?? DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,+ provider: modelConfig.provider ?? DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,+ };+ }++ /**+ * Routes one feedback satisfaction input into durable domains.+ *+ * Use when:+ * - The domain judge needs model-backed routing without planning final actions+ *+ * Expects:+ * - `message` already reflects the normalized feedback text+ * - `result`, `reason`, and `evidence` already reflect the upstream satisfaction lane+ *+ * Returns:+ * - One validated set of unique domain targets with confidence and rationale+ */+ async judgeDomains(params: JudgeFeedbackDomainsParams): Promise<FeedbackDomainJudgeAgentResult> {+ const payload = chainAgentSignalAnalyzeIntentRoute(params);+ const modelRuntime = await initModelRuntimeFromDB(+ this.db,+ this.userId,+ this.modelConfig.provider,+ );++ log('judgeDomains model=%s provider=%s', this.modelConfig.model, this.modelConfig.provider);++ const result = await modelRuntime.generateObject(+ {+ messages: payload.messages as any[],+ model: this.modelConfig.model,+ schema: buildGenerateObjectSchema(FeedbackDomainJudgeAgentResultSchema, {+ name: 'agent_signal_feedback_domain_route',+ }),+ },+ { metadata: { trigger: RequestTrigger.Memory } },+ );++ return FeedbackDomainJudgeAgentResultSchema.parse({+ targets: dedupeTargets(FeedbackDomainJudgeAgentResultSchema.parse(result).targets),+ });+ }+}++const dedupeTargets = (+ targets: Array<{+ confidence: number;+ evidence: Array<{ cue: string; excerpt: string }>;+ reason: string;+ target: FeedbackDomainJudgeTarget;+ }>,+) => {+ const deduped = new Map<FeedbackDomainJudgeTarget, (typeof targets)[number]>();++ for (const target of targets) {+ const current = deduped.get(target.target);++ if (!current || target.confidence > current.confidence) {+ deduped.set(target.target, target);+ }+ }++ return [...deduped.values()];+};diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.tsnew file mode 100644index 00000000000..b40e9feae2d--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts@@ -0,0 +1,267 @@+import type { RuntimeProcessorResult } from '@lobechat/agent-signal';+import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';+import { chainAgentSignalAnalyzeIntentFeedbackSatisfaction } from '@lobechat/prompts';+import { RequestTrigger } from '@lobechat/types';+import debug from 'debug';+import { z } from 'zod';++import type { LobeChatDatabase } from '@/database/type';+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';++import { buildGenerateObjectSchema } from '../../../../../../packages/memory-user-memory/src/utils/zod';+import { defineSourceHandler } from '../../runtime/middleware';+import { AGENT_SIGNAL_SOURCE_TYPES, type SourceAgentUserMessage } from '../../sourceTypes';+import {+ AGENT_SIGNAL_POLICY_SIGNAL_TYPES,+ type AgentSignalFeedbackEvidence,+ type AgentSignalFeedbackSatisfactionStagePayload,+ type SignalFeedbackSatisfaction,+} from '../types';++const log = debug('lobe-server:agent-signal:feedback-satisfaction:agent');++const FeedbackEvidenceSchema = z.object({+ cue: z.string(),+ excerpt: z.string(),+});++const FeedbackSatisfactionStagePayloadSchema = z.object({+ confidence: z.number().min(0).max(1),+ evidence: z.array(FeedbackEvidenceSchema),+ reason: z.string(),+ result: z.enum(['neutral', 'not_satisfied', 'satisfied']),+});++type FeedbackSatisfactionStagePayloadResult = z.infer<+ typeof FeedbackSatisfactionStagePayloadSchema+>;++/**+ * One normalized satisfaction-judge input.+ */+export interface JudgeFeedbackSatisfactionParams {+ message: string;+ serializedContext?: string;+}++/**+ * Minimal interface for one satisfaction-judge agent.+ */+export interface FeedbackSatisfactionJudge {+ /**+ * Judges one feedback message for overall satisfaction only.+ *+ * Use when:+ * - One normalized feedback message needs a stage-local satisfaction result+ *+ * Expects:+ * - `message` is the raw feedback text+ * - `serializedContext` is the optional serialized execution context for the same event+ *+ * Returns:+ * - One semantic satisfaction result with confidence, evidence, and reason+ */+ judgeSatisfaction: (+ params: JudgeFeedbackSatisfactionParams,+ ) => Promise<AgentSignalFeedbackSatisfactionStagePayload>;+}++/**+ * Model configuration for the default satisfaction judge agent.+ */+export interface FeedbackSatisfactionJudgeAgentModelConfig {+ model: string;+ provider: string;+}++/**+ * Options for constructing the feedback satisfaction source handler.+ */+export interface CreateFeedbackSatisfactionJudgePolicyOptions {+ db?: LobeChatDatabase;+ judge?: FeedbackSatisfactionJudge;+ model?: string;+ provider?: string;+ userId?: string;+}++/**+ * Model-backed satisfaction judge for Agent Signal feedback analysis.+ *+ * Use when:+ * - The satisfaction stage should rely on one structured model decision+ * - The caller needs stage-local output without domain routing or action planning+ *+ * Expects:+ * - `db` and `userId` point at the same user context as the surrounding Agent Signal runtime+ *+ * Returns:+ * - One validated satisfaction result parsed from structured model output+ */+export class FeedbackSatisfactionJudgeAgentService implements FeedbackSatisfactionJudge {+ private readonly db: LobeChatDatabase;+ private readonly modelConfig: FeedbackSatisfactionJudgeAgentModelConfig;+ private readonly userId: string;++ constructor(+ db: LobeChatDatabase,+ userId: string,+ modelConfig: Partial<FeedbackSatisfactionJudgeAgentModelConfig> = {},+ ) {+ this.db = db;+ this.userId = userId;+ this.modelConfig = {+ model: modelConfig.model ?? DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,+ provider: modelConfig.provider ?? DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,+ };+ }++ /**+ * Judges one feedback message for overall satisfaction only.+ *+ * Use when:+ * - Agent Signal needs semantic satisfaction analysis before domain routing+ *+ * Expects:+ * - The payload contains only the feedback message and serialized context+ *+ * Returns:+ * - One validated semantic satisfaction result+ */+ async judgeSatisfaction(+ params: JudgeFeedbackSatisfactionParams,+ ): Promise<AgentSignalFeedbackSatisfactionStagePayload> {+ const payload = chainAgentSignalAnalyzeIntentFeedbackSatisfaction(params);+ const modelRuntime = await initModelRuntimeFromDB(+ this.db,+ this.userId,+ this.modelConfig.provider,+ );++ log(+ 'judgeSatisfaction model=%s provider=%s',+ this.modelConfig.model,+ this.modelConfig.provider,+ );++ const result = await modelRuntime.generateObject(+ {+ messages: payload.messages as any[],+ model: this.modelConfig.model,+ schema: buildGenerateObjectSchema(FeedbackSatisfactionStagePayloadSchema, {+ name: 'agent_signal_feedback_satisfaction',+ }),+ },+ { metadata: { trigger: RequestTrigger.Memory } },+ );++ return FeedbackSatisfactionStagePayloadSchema.parse(result);+ }+}++const resolveJudge = (+ options: CreateFeedbackSatisfactionJudgePolicyOptions = {},+): FeedbackSatisfactionJudge => {+ if (options.judge) {+ return options.judge;+ }++ if (!options.db || !options.userId) {+ throw new TypeError(+ 'Feedback satisfaction judge requires either an injected judge or both db and userId.',+ );+ }++ return new FeedbackSatisfactionJudgeAgentService(options.db, options.userId, {+ model: options.model,+ provider: options.provider,+ });+};++const normalizeEvidence = (+ evidence: FeedbackSatisfactionStagePayloadResult['evidence'],+): AgentSignalFeedbackEvidence[] => {+ return evidence.map((item) => ({+ cue: item.cue,+ excerpt: item.excerpt,+ }));+};++const buildSignal = (+ source: SourceAgentUserMessage,+ payload: FeedbackSatisfactionStagePayloadResult,+ timestamp: number,+): SignalFeedbackSatisfaction => {+ const normalizedMessage = source.payload.message.trim();++ return {+ chain: {+ chainId: source.chain.chainId,+ parentNodeId: source.sourceId,+ rootSourceId: source.chain.rootSourceId,+ },+ payload: {+ agentId: source.payload.agentId,+ confidence: payload.confidence,+ evidence: normalizeEvidence(payload.evidence),+ message: normalizedMessage,+ messageId: source.payload.messageId,+ reason: payload.reason,+ result: payload.result,+ serializedContext: source.payload.serializedContext,+ sourceHints: {+ documentPayload: source.payload.documentPayload,+ intents: source.payload.intents,+ memoryPayload: source.payload.memoryPayload,+ },+ topicId: source.payload.topicId,+ },+ signalId: `${source.sourceId}:signal:feedback-satisfaction`,+ signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackSatisfaction,+ source: {+ sourceId: source.sourceId,+ sourceType: source.sourceType,+ },+ timestamp,+ };+};++/**+ * Creates the source handler for the feedback satisfaction judge.+ *+ * Triggering workflow:+ *+ * `agent.user.message`+ * -> {@link createFeedbackSatisfactionJudgeProcessor}+ * -> `signal.feedback.satisfaction`+ *+ * Upstream:+ * - `agent.user.message`+ *+ * Downstream:+ * - configured {@link FeedbackSatisfactionJudge}+ */+export const createFeedbackSatisfactionJudgeProcessor = (+ options: CreateFeedbackSatisfactionJudgePolicyOptions = {},+) => {+ const judge = resolveJudge(options);++ return defineSourceHandler(+ AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,+ `${AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage}:feedback-satisfaction-judge`,+ async (source, ctx): Promise<RuntimeProcessorResult | void> => {+ const normalizedMessage = source.payload.message.trim();+ const payload = await judge.judgeSatisfaction({+ message: normalizedMessage,+ serializedContext: source.payload.serializedContext,+ });++ return {+ signals: [+ buildSignal(source, FeedbackSatisfactionStagePayloadSchema.parse(payload), ctx.now()),+ ],+ status: 'dispatch',+ };+ },+ );+};diff --git a/src/server/services/agentSignal/policies/analyzeIntent/index.ts b/src/server/services/agentSignal/policies/analyzeIntent/index.tsnew file mode 100644index 00000000000..a744a8c02e1--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/index.ts@@ -0,0 +1,34 @@+import { defineAgentSignalHandlers } from '../../runtime/middleware';+import type { UserMemoryActionHandlerOptions } from './actions';+import { defineUserMemoryActionHandler } from './actions';+import { createFeedbackActionPlannerSignalHandler } from './feedbackAction';+import type { CreateFeedbackDomainJudgePolicyOptions } from './feedbackDomain';+import {+ createFeedbackDomainJudgeSignalHandler,+ createFeedbackDomainResolver,+} from './feedbackDomain';+import type { CreateFeedbackSatisfactionJudgePolicyOptions } from './feedbackSatisfaction';+import { createFeedbackSatisfactionJudgeProcessor } from './feedbackSatisfaction';++export interface CreateAnalyzeIntentPolicyOptions {+ feedbackDomainJudge?: CreateFeedbackDomainJudgePolicyOptions['feedbackDomainJudge'];+ feedbackSatisfactionJudge?: CreateFeedbackSatisfactionJudgePolicyOptions;+ userMemory?: UserMemoryActionHandlerOptions;+}++export const createAnalyzeIntentPolicy = (options: CreateAnalyzeIntentPolicyOptions = {}) => {+ const feedbackDomainResolver = createFeedbackDomainResolver({+ feedbackDomainJudge: options.feedbackDomainJudge,+ });++ return defineAgentSignalHandlers([+ createFeedbackSatisfactionJudgeProcessor(options.feedbackSatisfactionJudge),+ createFeedbackDomainJudgeSignalHandler({+ resolveDomains: feedbackDomainResolver,+ }),+ createFeedbackActionPlannerSignalHandler(),+ ...(options.userMemory ? [defineUserMemoryActionHandler(options.userMemory)] : []),+ ]);+};++export default createAnalyzeIntentPolicy;diff --git a/src/server/services/agentSignal/policies/groups/default.ts b/src/server/services/agentSignal/policies/groups/default.tsdeleted file mode 100644index 8f167478999..00000000000--- a/src/server/services/agentSignal/policies/groups/default.ts+++ /dev/null@@ -1,18 +0,0 @@-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/policies/index.ts b/src/server/services/agentSignal/policies/index.tsnew file mode 100644index 00000000000..fc6719b1d5f--- /dev/null+++ b/src/server/services/agentSignal/policies/index.ts@@ -0,0 +1,25 @@+import type { AgentSignalMiddleware } from '../runtime/middleware';+import { createAnalyzeIntentPolicy } from './analyzeIntent';+import type { UserMemoryActionHandlerOptions } from './analyzeIntent/actions';+import type { CreateFeedbackDomainJudgePolicyOptions } from './analyzeIntent/feedbackDomain';+import type { CreateFeedbackSatisfactionJudgePolicyOptions } from './analyzeIntent/feedbackSatisfaction';++export * from './actionIdempotency';+export * from './analyzeIntent';+export * from './analyzeIntent/actions';+export * from './analyzeIntent/feedbackAction';+export * from './analyzeIntent/feedbackDomain';+export * from './analyzeIntent/feedbackDomainAgent';+export * from './analyzeIntent/feedbackSatisfaction';+export * from './types';++export interface CreateDefaultAgentSignalPoliciesOptions extends CreateFeedbackDomainJudgePolicyOptions {+ feedbackSatisfactionJudge?: CreateFeedbackSatisfactionJudgePolicyOptions;+ userMemory?: UserMemoryActionHandlerOptions;+}++export const createDefaultAgentSignalPolicies = (+ options: CreateDefaultAgentSignalPoliciesOptions = {},+): AgentSignalMiddleware[] => {+ return [createAnalyzeIntentPolicy(options)];+};diff --git a/src/server/services/agentSignal/policies/types.test.ts b/src/server/services/agentSignal/policies/types.test.tsnew file mode 100644index 00000000000..18b36c3ed58--- /dev/null+++ b/src/server/services/agentSignal/policies/types.test.ts@@ -0,0 +1,21 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++describe('agent signal policy ids', () => {+ it('co-locates runtime ids with the policy type definitions', async () => {+ const {+ AGENT_SIGNAL_POLICIES,+ AGENT_SIGNAL_POLICY_ACTION_TYPES,+ AGENT_SIGNAL_POLICY_SIGNAL_TYPES,+ } = await import('./types');++ expect(AGENT_SIGNAL_POLICIES.feedbackActionPlanner).toBe('feedback-action-planner');+ expect(AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainMemory).toBe(+ 'signal.feedback.domain.memory',+ );+ expect(AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainPrompt).toBe(+ 'signal.feedback.domain.prompt',+ );+ expect(AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle).toBe('action.user-memory.handle');+ });+});diff --git a/src/server/services/agentSignal/policies/types.ts b/src/server/services/agentSignal/policies/types.tsnew file mode 100644index 00000000000..f69305d3018--- /dev/null+++ b/src/server/services/agentSignal/policies/types.ts@@ -0,0 +1,303 @@+import type { BaseAction, BaseSignal } from '@lobechat/agent-signal';++import type {+ SourceAgentExecutionCompleted,+ SourceAgentExecutionFailed,+ SourceRuntimeAfterStep,+ SourceRuntimeBeforeStep,+} from '../sourceTypes';++/** Server-owned built-in AgentSignal policy identifiers. */+export const AGENT_SIGNAL_POLICIES = {+ feedbackActionPlanner: 'feedback-action-planner',+ feedbackDomainJudge: 'feedback-domain-judge',+ feedbackSatisfactionJudge: 'feedback-satisfaction-judge',+ nudgeMemory: 'nudge.memory',+ selfReflectionAnalysis: 'self-reflection-analysis',+} as const;++/** Server-owned built-in AgentSignal signal type identifiers. */+export const AGENT_SIGNAL_POLICY_SIGNAL_TYPES = {+ feedbackDomainMemory: 'signal.feedback.domain.memory',+ feedbackDomainNone: 'signal.feedback.domain.none',+ feedbackDomainPrompt: 'signal.feedback.domain.prompt',+ feedbackDomainSkill: 'signal.feedback.domain.skill',+ feedbackSatisfaction: 'signal.feedback.satisfaction',+ nudgeMemoryConditionMatched: 'signal.nudge.memory.condition-matched',+ nudgeMemoryConditionMismatched: 'signal.nudge.memory.condition-mismatched',+ selfReflectionNeeded: 'signal.self-reflection-analysis.reflect-needed',+ selfReflectionSkipped: 'signal.self-reflection-analysis.reflect-skipped',+} as const;++/** Server-owned built-in AgentSignal action type identifiers. */+export const AGENT_SIGNAL_POLICY_ACTION_TYPES = {+ nudgeHandle: 'action.nudge.handle',+ personaHandle: 'action.persona.handle',+ userMemoryHandle: 'action.user-memory.handle',+} as const;++type ValueOf<TValue> = TValue[keyof TValue];++/** Server-owned built-in AgentSignal signal type union. */+export type AgentSignalPolicySignalType = ValueOf<typeof AGENT_SIGNAL_POLICY_SIGNAL_TYPES>;++/** Server-owned built-in AgentSignal action type union. */+export type AgentSignalPolicyActionType = ValueOf<typeof AGENT_SIGNAL_POLICY_ACTION_TYPES>;++export type AgentSignalFeedbackSatisfactionResult = 'neutral' | 'not_satisfied' | 'satisfied';++export type AgentSignalFeedbackDomainTarget = 'memory' | 'none' | 'prompt' | 'skill';++export type AgentSignalFeedbackPhase1DomainTarget = 'memory' | 'prompt' | 'skill';++export interface AgentSignalFeedbackEvidence {+ cue: string;+ excerpt: string;+}++/** Future-facing slim payload for the satisfaction stage. */+export interface AgentSignalFeedbackSatisfactionStagePayload {+ confidence: number;+ evidence: AgentSignalFeedbackEvidence[];+ reason: string;+ result: AgentSignalFeedbackSatisfactionResult;+}++/** Future-facing slim payload for one domain stage result. */+export interface AgentSignalFeedbackDomainStagePayload<+ TTarget extends AgentSignalFeedbackPhase1DomainTarget,+> {+ confidence: number;+ evidence: AgentSignalFeedbackEvidence[];+ reason: string;+ target: TTarget;+}++/**+ * Structured source hints already attached to one feedback source event.+ */+export interface AgentSignalFeedbackSourceHints {+ documentPayload?: Record<string, unknown>;+ intents?: Array<'document' | 'memory' | 'persona' | 'prompt'>;+ memoryPayload?: Record<string, unknown>;+}++export interface AgentSignalFeedbackDomainConflictPolicy {+ forbiddenWith?: AgentSignalFeedbackDomainTarget[];+ mode: 'exclusive' | 'fanout';+ priority: number;+}++/** Server-owned built-in AgentSignal signal payloads keyed by signal type. */+export interface AgentSignalPolicySignalPayloadMap {+ [AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainMemory]: {+ agentId?: string;+ confidence: number;+ conflictPolicy: AgentSignalFeedbackDomainConflictPolicy;+ evidence: AgentSignalFeedbackEvidence[];+ message: string;+ messageId: string;+ reason: string;+ satisfactionResult: AgentSignalFeedbackSatisfactionResult;+ serializedContext?: string;+ sourceHints?: AgentSignalFeedbackSourceHints;+ target: 'memory';+ topicId?: string;+ };+ [AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainNone]: {+ agentId?: string;+ confidence: number;+ conflictPolicy: AgentSignalFeedbackDomainConflictPolicy;+ evidence: AgentSignalFeedbackEvidence[];+ message: string;+ messageId: string;+ reason: string;+ satisfactionResult: AgentSignalFeedbackSatisfactionResult;+ serializedContext?: string;+ sourceHints?: AgentSignalFeedbackSourceHints;+ target: 'none';+ topicId?: string;+ };+ [AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainPrompt]: {+ agentId?: string;+ confidence: number;+ conflictPolicy: AgentSignalFeedbackDomainConflictPolicy;+ evidence: AgentSignalFeedbackEvidence[];+ message: string;+ messageId: string;+ reason: string;+ satisfactionResult: AgentSignalFeedbackSatisfactionResult;+ serializedContext?: string;+ sourceHints?: AgentSignalFeedbackSourceHints;+ target: 'prompt';+ topicId?: string;+ };+ [AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainSkill]: {+ agentId?: string;+ confidence: number;+ conflictPolicy: AgentSignalFeedbackDomainConflictPolicy;+ evidence: AgentSignalFeedbackEvidence[];+ message: string;+ messageId: string;+ reason: string;+ satisfactionResult: AgentSignalFeedbackSatisfactionResult;+ serializedContext?: string;+ sourceHints?: AgentSignalFeedbackSourceHints;+ target: 'skill';+ topicId?: string;+ };+ [AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackSatisfaction]: {+ agentId?: string;+ confidence: number;+ evidence: AgentSignalFeedbackEvidence[];+ message: string;+ messageId: string;+ reason: string;+ result: AgentSignalFeedbackSatisfactionResult;+ serializedContext?: string;+ sourceHints?: AgentSignalFeedbackSourceHints;+ topicId?: string;+ };+ [AGENT_SIGNAL_POLICY_SIGNAL_TYPES.nudgeMemoryConditionMatched]: {+ agentId?: string;+ condition: 'memory-conflict-detected' | 'memory-refresh-needed' | 'memory-reinforcement-needed';+ operationId?: string;+ serializedContext?: string;+ topicId?: string;+ };+ [AGENT_SIGNAL_POLICY_SIGNAL_TYPES.nudgeMemoryConditionMismatched]: {+ agentId?: string;+ condition: 'memory-conflict-detected' | 'memory-refresh-needed' | 'memory-reinforcement-needed';+ operationId?: string;+ reason: 'cooldown-active' | 'no-relevant-memory' | 'policy-filtered' | 'threshold-not-reached';+ serializedContext?: string;+ topicId?: string;+ };+ [AGENT_SIGNAL_POLICY_SIGNAL_TYPES.selfReflectionNeeded]: {+ agentId?: string;+ operationId: string;+ outcome: 'failed' | 'resolved' | 'succeeded';+ reason:+ | 'execution-failed'+ | 'repeated-repair'+ | 'successful-resolution'+ | 'unexpected-tool-result';+ serializedContext?: string;+ topicId?: string;+ };+ [AGENT_SIGNAL_POLICY_SIGNAL_TYPES.selfReflectionSkipped]: {+ agentId?: string;+ operationId: string;+ outcome: 'failed' | 'resolved' | 'succeeded';+ reason: 'cooldown-active' | 'insufficient-context' | 'no-learning-value' | 'policy-filtered';+ serializedContext?: string;+ topicId?: string;+ };+}++/** Server-owned built-in AgentSignal action payloads keyed by action type. */+export interface AgentSignalPolicyActionPayloadMap {+ [AGENT_SIGNAL_POLICY_ACTION_TYPES.nudgeHandle]: {+ agentId?: string;+ condition: 'memory-conflict-detected' | 'memory-refresh-needed' | 'memory-reinforcement-needed';+ idempotencyKey?: string;+ operationId?: string;+ serializedContext?: string;+ topicId?: string;+ };+ [AGENT_SIGNAL_POLICY_ACTION_TYPES.personaHandle]: {+ agentId?: string;+ idempotencyKey: string;+ message: string;+ serializedContext?: string;+ topicId?: string;+ update?: Record<string, unknown>;+ };+ [AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle]: {+ agentId?: string;+ conflictPolicy?: AgentSignalFeedbackDomainConflictPolicy;+ evidence?: AgentSignalFeedbackEvidence[];+ feedbackHint?: Exclude<AgentSignalFeedbackSatisfactionResult, 'neutral'>;+ idempotencyKey: string;+ message: string;+ reason?: string;+ serializedContext?: string;+ sourceHints?: AgentSignalFeedbackSourceHints;+ topicId?: string;+ };+}++/** Server-owned built-in AgentSignal signal variant. */+export type AgentSignalPolicySignalVariant<+ TSignalType extends AgentSignalPolicySignalType = AgentSignalPolicySignalType,+> = BaseSignal & {+ payload: AgentSignalPolicySignalPayloadMap[TSignalType];+ signalType: TSignalType;+};++/** Server-owned built-in AgentSignal signal union. */+export type AgentSignalPolicySignal = {+ [TSignalType in AgentSignalPolicySignalType]: AgentSignalPolicySignalVariant<TSignalType>;+}[AgentSignalPolicySignalType];++/** Server-owned built-in AgentSignal action variant. */+export type AgentSignalPolicyActionVariant<+ TActionType extends AgentSignalPolicyActionType = AgentSignalPolicyActionType,+> = BaseAction & {+ actionType: TActionType;+ payload: AgentSignalPolicyActionPayloadMap[TActionType];+};++/** Server-owned built-in AgentSignal action union. */+export type AgentSignalPolicyAction = {+ [TActionType in AgentSignalPolicyActionType]: AgentSignalPolicyActionVariant<TActionType>;+}[AgentSignalPolicyActionType];++export type SignalFeedbackSatisfaction =+ AgentSignalPolicySignalVariant<'signal.feedback.satisfaction'>;++export type SignalFeedbackDomainMemory =+ AgentSignalPolicySignalVariant<'signal.feedback.domain.memory'>;++export type SignalFeedbackDomainSkill =+ AgentSignalPolicySignalVariant<'signal.feedback.domain.skill'>;++export type SignalFeedbackDomainPrompt =+ AgentSignalPolicySignalVariant<'signal.feedback.domain.prompt'>;++export type SignalFeedbackDomainNone =+ AgentSignalPolicySignalVariant<'signal.feedback.domain.none'>;++/** Server-owned alias for reflect-needed signals. */+export type SignalSelfReflectionNeeded =+ AgentSignalPolicySignalVariant<'signal.self-reflection-analysis.reflect-needed'>;++/** Server-owned alias for reflect-skipped signals. */+export type SignalSelfReflectionSkipped =+ AgentSignalPolicySignalVariant<'signal.self-reflection-analysis.reflect-skipped'>;++/** Server-owned alias for matched memory-nudge signals. */+export type SignalNudgeMemoryConditionMatched =+ AgentSignalPolicySignalVariant<'signal.nudge.memory.condition-matched'>;++/** Server-owned alias for mismatched memory-nudge signals. */+export type SignalNudgeMemoryConditionMismatched =+ AgentSignalPolicySignalVariant<'signal.nudge.memory.condition-mismatched'>;++/** Server-owned alias for memory updates. */+export type ActionUserMemoryHandle = AgentSignalPolicyActionVariant<'action.user-memory.handle'>;++/** Server-owned alias for persona updates. */+export type ActionPersonaHandle = AgentSignalPolicyActionVariant<'action.persona.handle'>;++/** Server-owned alias for memory-nudge actions. */+export type ActionNudgeHandle = AgentSignalPolicyActionVariant<'action.nudge.handle'>;++/** Sources that can trigger the memory-nudge policy. */+export type MemoryNudgePolicySource =+ | SourceAgentExecutionCompleted+ | SourceRuntimeAfterStep+ | SourceRuntimeBeforeStep;++/** Sources that can trigger self-reflection analysis. */+export type SelfReflectionPolicySource = SourceAgentExecutionCompleted | SourceAgentExecutionFailed;diff --git a/src/server/services/agentSignal/runtime/AgentSignalScheduler.ts b/src/server/services/agentSignal/runtime/AgentSignalScheduler.tsindex 31a6d4c4757..d0051af2aa7 100644--- a/src/server/services/agentSignal/runtime/AgentSignalScheduler.ts+++ b/src/server/services/agentSignal/runtime/AgentSignalScheduler.ts@@ -37,6 +37,9 @@ export interface AgentSignalSchedulerHandler<TNode extends RuntimeNode = Runtimeid: string;}+export type AgentSignalSchedulerHandle<TNode extends RuntimeNode = RuntimeNode> =+ AgentSignalSchedulerHandler<TNode>['handle'];+/** Handler results accepted by the generalized runtime host. */export type AgentSignalSchedulerHandlerResult = ExecutorResult | RuntimeProcessorResult;diff --git a/src/server/services/agentSignal/runtime/__tests__/createRuntime.test.ts b/src/server/services/agentSignal/runtime/__tests__/createRuntime.test.tsindex 368b381444a..2c49a065c9c 100644--- a/src/server/services/agentSignal/runtime/__tests__/createRuntime.test.ts+++ b/src/server/services/agentSignal/runtime/__tests__/createRuntime.test.ts@@ -41,8 +41,10 @@ describe('createAgentSignalRuntime', () => {const runtime = await createAgentSignalRuntime({policies: [defineAgentSignalHandlers([- defineSourceHandler('source.user.message', {- async handle(source, context) {+ defineSourceHandler(+ 'source.user.message',+ 'test-source-handler',+ async (source, context) => {handled.push(`source:${context.scopeKey}`);return {@@ -56,10 +58,11 @@ describe('createAgentSignalRuntime', () => {status: 'dispatch',} as const;},- id: 'test-source-handler',- }),- defineSignalHandler('signal.memory.request', {- async handle(signal, context) {+ ),+ defineSignalHandler(+ 'signal.memory.request',+ 'test-signal-handler',+ async (signal, context) => {handled.push(`signal:${context.scopeKey}`);return {@@ -73,10 +76,11 @@ describe('createAgentSignalRuntime', () => {status: 'dispatch',} as const;},- id: 'test-signal-handler',- }),- defineActionHandler('action.memory.persist', {- async handle(action, context) {+ ),+ defineActionHandler(+ 'action.memory.persist',+ 'test-action-handler',+ async (action, context) => {handled.push(`action:${context.scopeKey}`);return {@@ -86,8 +90,7 @@ describe('createAgentSignalRuntime', () => {status: 'applied',} as const;},- id: 'test-action-handler',- }),+ ),]),],});diff --git a/src/server/services/agentSignal/runtime/middleware.ts b/src/server/services/agentSignal/runtime/middleware.tsindex 38b44fe1162..b41f792797e 100644--- a/src/server/services/agentSignal/runtime/middleware.ts+++ b/src/server/services/agentSignal/runtime/middleware.ts@@ -1,25 +1,63 @@import type { AgentSignalSource, BaseAction, BaseSignal } from '@lobechat/agent-signal';import type {+ AgentSignalPolicyActionType,+ AgentSignalPolicyActionVariant,+ AgentSignalPolicySignalType,+ AgentSignalPolicySignalVariant,+} from '../policies/types';+import type { AgentSignalSourceType, AgentSignalSourceVariant } from '../sourceTypes';+import type {+ AgentSignalSchedulerHandle,AgentSignalSchedulerHandler,AgentSignalSchedulerRegistry,} from './AgentSignalScheduler';--export interface AgentSignalSourceHandlerDefinition {- handler: AgentSignalSchedulerHandler<AgentSignalSource>;- listen: string | string[];+import type { RuntimeNode } from './context';++type OneOrMany<TValue extends string> = TValue | readonly TValue[];++type ExtractListenType<TListen extends OneOrMany<string>> =+ TListen extends readonly (infer TValue)[] ? Extract<TValue, string> : TListen;++type ResolveSourceHandlerInput<TListen extends OneOrMany<string>> =+ ExtractListenType<TListen> extends infer TType extends string+ ? TType extends AgentSignalSourceType+ ? AgentSignalSourceVariant<TType>+ : AgentSignalSource+ : never;++type ResolveSignalHandlerInput<TListen extends OneOrMany<string>> =+ ExtractListenType<TListen> extends infer TType extends string+ ? TType extends AgentSignalPolicySignalType+ ? AgentSignalPolicySignalVariant<TType>+ : BaseSignal+ : never;++type ResolveActionHandlerInput<TListen extends OneOrMany<string>> =+ ExtractListenType<TListen> extends infer TType extends string+ ? TType extends AgentSignalPolicyActionType+ ? AgentSignalPolicyActionVariant<TType>+ : BaseAction+ : never;++export interface AgentSignalSourceHandlerDefinition<TListen extends OneOrMany<string> = string> {+ handle: AgentSignalSchedulerHandle<ResolveSourceHandlerInput<TListen>>;+ id: string;+ listen: TListen;type: 'source';}-export interface AgentSignalSignalHandlerDefinition {- handler: AgentSignalSchedulerHandler<BaseSignal>;- listen: string | string[];+export interface AgentSignalSignalHandlerDefinition<TListen extends OneOrMany<string> = string> {+ handle: AgentSignalSchedulerHandle<ResolveSignalHandlerInput<TListen>>;+ id: string;+ listen: TListen;type: 'signal';}-export interface AgentSignalActionHandlerDefinition {- handler: AgentSignalSchedulerHandler<BaseAction>;- listen: string | string[];+export interface AgentSignalActionHandlerDefinition<TListen extends OneOrMany<string> = string> {+ handle: AgentSignalSchedulerHandle<ResolveActionHandlerInput<TListen>>;+ id: string;+ listen: TListen;type: 'action';}@@ -28,6 +66,26 @@ export type AgentSignalHandlerDefinition =| AgentSignalSignalHandlerDefinition| AgentSignalSourceHandlerDefinition;+type AgentSignalInstallableHandlerDefinition =+ | {+ handle: unknown;+ id: string;+ listen: OneOrMany<string>;+ type: 'action';+ }+ | {+ handle: unknown;+ id: string;+ listen: OneOrMany<string>;+ type: 'signal';+ }+ | {+ handle: unknown;+ id: string;+ listen: OneOrMany<string>;+ type: 'source';+ };+export interface AgentSignalMiddlewareInstallContext {handleAction: (handler: AgentSignalActionHandlerDefinition) => void;handleSignal: (handler: AgentSignalSignalHandlerDefinition) => void;@@ -44,60 +102,90 @@ export interface AgentSignalMiddlewareRegistries {sourceRegistry: AgentSignalSchedulerRegistry<AgentSignalSource>;}-const toListenArray = (listen: string | string[]) => {+const toListenArray = (listen: OneOrMany<string>) => {return Array.isArray(listen) ? listen : [listen];};-export const defineSourceHandler = (- listen: string | string[],- handler: AgentSignalSchedulerHandler<AgentSignalSource>,-): AgentSignalSourceHandlerDefinition => {+const resolveSchedulerHandler = <TNode extends RuntimeNode>(+ idOrHandler: AgentSignalSchedulerHandler<TNode> | string,+ handle?: AgentSignalSchedulerHandle<TNode>,+): AgentSignalSchedulerHandler<TNode> => {+ if (typeof idOrHandler === 'string') {+ if (!handle) {+ throw new TypeError('Missing handler function for define*Handler call.');+ }++ return {+ handle,+ id: idOrHandler,+ };+ }++ return idOrHandler;+};++export const defineSourceHandler = <TListen extends OneOrMany<string>>(+ listen: TListen,+ idOrHandler: AgentSignalSchedulerHandler<ResolveSourceHandlerInput<TListen>> | string,+ handle?: AgentSignalSchedulerHandle<ResolveSourceHandlerInput<TListen>>,+): AgentSignalSourceHandlerDefinition<TListen> => {+ const handler = resolveSchedulerHandler(idOrHandler, handle);+return {- handler,+ handle: handler.handle,+ id: handler.id,listen,type: 'source',};};-export const defineSignalHandler = (- listen: string | string[],- handler: AgentSignalSchedulerHandler<BaseSignal>,-): AgentSignalSignalHandlerDefinition => {+export const defineSignalHandler = <TListen extends OneOrMany<string>>(+ listen: TListen,+ idOrHandler: AgentSignalSchedulerHandler<ResolveSignalHandlerInput<TListen>> | string,+ handle?: AgentSignalSchedulerHandle<ResolveSignalHandlerInput<TListen>>,+): AgentSignalSignalHandlerDefinition<TListen> => {+ const handler = resolveSchedulerHandler(idOrHandler, handle);+return {- handler,+ handle: handler.handle,+ id: handler.id,listen,type: 'signal',};};-export const defineActionHandler = (- listen: string | string[],- handler: AgentSignalSchedulerHandler<BaseAction>,-): AgentSignalActionHandlerDefinition => {+export const defineActionHandler = <TListen extends OneOrMany<string>>(+ listen: TListen,+ idOrHandler: AgentSignalSchedulerHandler<ResolveActionHandlerInput<TListen>> | string,+ handle?: AgentSignalSchedulerHandle<ResolveActionHandlerInput<TListen>>,+): AgentSignalActionHandlerDefinition<TListen> => {+ const handler = resolveSchedulerHandler(idOrHandler, handle);+return {- handler,+ handle: handler.handle,+ id: handler.id,listen,type: 'action',};};export const defineAgentSignalHandlers = (- handlers: AgentSignalHandlerDefinition[],+ handlers: readonly AgentSignalInstallableHandlerDefinition[],): AgentSignalMiddleware => {return {install(context) {for (const handler of handlers) {if (handler.type === 'source') {- context.handleSource(handler);+ context.handleSource(handler as AgentSignalSourceHandlerDefinition);continue;}if (handler.type === 'signal') {- context.handleSignal(handler);+ context.handleSignal(handler as AgentSignalSignalHandlerDefinition);continue;}- context.handleAction(handler);+ context.handleAction(handler as AgentSignalActionHandlerDefinition);}},};@@ -109,17 +197,26 @@ export const createAgentSignalMiddlewareInstallContext = (return {handleAction(handler) {for (const listen of toListenArray(handler.listen)) {- registries.actionRegistry.register(listen, handler.handler);+ registries.actionRegistry.register(listen, {+ handle: handler.handle,+ id: handler.id,+ } as AgentSignalSchedulerHandler<BaseAction>);}},handleSignal(handler) {for (const listen of toListenArray(handler.listen)) {- registries.signalRegistry.register(listen, handler.handler);+ registries.signalRegistry.register(listen, {+ handle: handler.handle,+ id: handler.id,+ } as AgentSignalSchedulerHandler<BaseSignal>);}},handleSource(handler) {for (const listen of toListenArray(handler.listen)) {- registries.sourceRegistry.register(listen, handler.handler);+ registries.sourceRegistry.register(listen, {+ handle: handler.handle,+ id: handler.id,+ } as AgentSignalSchedulerHandler<AgentSignalSource>);}},};diff --git a/src/server/services/aiAgent/__tests__/execAgent.disableTools.test.ts b/src/server/services/aiAgent/__tests__/execAgent.disableTools.test.tsindex 9d971021f43..c6b2285b905 100644--- a/src/server/services/aiAgent/__tests__/execAgent.disableTools.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.disableTools.test.ts@@ -1,3 +1,4 @@+import type * as ModelBankModule from 'model-bank';import { beforeEach, describe, expect, it, vi } from 'vitest';import { AiAgentService } from '../index';@@ -106,16 +107,24 @@ vi.mock('@/server/services/toolExecution/deviceProxy', () => ({},}));-vi.mock('model-bank', () => ({- LOBE_DEFAULT_MODEL_LIST: [- {- abilities: { functionCall: true },- id: 'gpt-4',- providerId: 'openai',- },- ],+vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),}));+vi.mock('model-bank', async (importOriginal) => {+ const actual = await importOriginal<typeof ModelBankModule>();+ return {+ ...actual,+ LOBE_DEFAULT_MODEL_LIST: [+ {+ abilities: { functionCall: true },+ id: 'gpt-4',+ providerId: 'openai',+ },+ ],+ };+});+describe('AiAgentService.execAgent - disableTools', () => {let service: AiAgentService;const mockDb = {} as any;diff --git a/src/server/services/aiAgent/__tests__/execAgent.files.test.ts b/src/server/services/aiAgent/__tests__/execAgent.files.test.tsindex be743204753..11202337755 100644--- a/src/server/services/aiAgent/__tests__/execAgent.files.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.files.test.ts@@ -139,6 +139,10 @@ vi.mock('@/server/services/toolExecution/deviceProxy', () => ({},}));+vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));+vi.mock('model-bank', async (importOriginal) => {const actual = await importOriginal<typeof ModelBankModule>();return {diff --git a/src/server/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts b/src/server/services/aiAgent/__tests__/execAgent.headlessDefault.test.tsindex ef6e560259e..4c4c4f5bee4 100644--- a/src/server/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts@@ -95,6 +95,10 @@ vi.mock('@/server/services/toolExecution/deviceProxy', () => ({},}));+vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));+vi.mock('model-bank', async (importOriginal) => {const actual = await importOriginal<typeof ModelBankModule>();return {diff --git a/src/server/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts b/src/server/services/aiAgent/__tests__/execAgent.resumeApproval.test.tsindex abca4e2db39..2c9ba1564b5 100644--- a/src/server/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts@@ -122,6 +122,10 @@ vi.mock('@/server/services/toolExecution/deviceProxy', () => ({deviceProxy: { isConfigured: false, queryDeviceList: vi.fn().mockResolvedValue([]) },}));+vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));+vi.mock('model-bank', async (importOriginal) => {const actual = await importOriginal<typeof ModelBankModule>();return {diff --git a/src/server/services/aiAgent/__tests__/execAgent.threadId.test.ts b/src/server/services/aiAgent/__tests__/execAgent.threadId.test.tsindex ea1ba8a1bc5..8c02f4d6aaa 100644--- a/src/server/services/aiAgent/__tests__/execAgent.threadId.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.threadId.test.ts@@ -131,6 +131,10 @@ vi.mock('@/server/services/toolExecution/deviceProxy', () => ({},}));+vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));+// Mock model-bankvi.mock('model-bank', async (importOriginal) => {const actual = await importOriginal<typeof ModelBankModule>();diff --git a/src/server/services/aiAgent/__tests__/execGroupSubAgentTask.test.ts b/src/server/services/aiAgent/__tests__/execGroupSubAgentTask.test.tsindex 5e21dc236f0..e198b33fa63 100644--- a/src/server/services/aiAgent/__tests__/execGroupSubAgentTask.test.ts+++ b/src/server/services/aiAgent/__tests__/execGroupSubAgentTask.test.ts@@ -88,6 +88,10 @@ vi.mock('@/server/services/klavis', () => ({})),}));+vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));+describe('AiAgentService.execSubAgentTask', () => {let service: AiAgentService;const mockDb = {} as any;diff --git a/src/server/workflows/agentSignal/__tests__/run.integration.test.ts b/src/server/workflows/agentSignal/__tests__/run.integration.test.tsdeleted file mode 100644index 6ccb2b3c25b..00000000000--- a/src/server/workflows/agentSignal/__tests__/run.integration.test.ts+++ /dev/null@@ -1,402 +0,0 @@-// @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/__tests__/run.test.ts b/src/server/workflows/agentSignal/__tests__/run.test.tsnew file mode 100644index 00000000000..7dec8cc094d--- /dev/null+++ b/src/server/workflows/agentSignal/__tests__/run.test.ts@@ -0,0 +1,421 @@+// @vitest-environment node+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,+} from '@/server/workflows/agentSignal/run';+import { uuid } from '@/utils/uuid';++const createWorkflowContext = <TPayload>(requestPayload: TPayload) => {+ return {+ requestPayload,+ run: async <TRunResult>(_stepId: string, handler: () => Promise<TRunResult>) => handler(),+ };+};++describe('runAgentSignalWorkflow', () => {+ it('bridges client.runtime.start into agent.user.message with serialized root-topic context', async () => {+ const db = await getTestDB();+ const userId = `eval_${uuid()}`;+ const topicId = `topic_${uuid()}`;+ const parentMessageId = `msg_${uuid()}`;+ const baseTimestamp = new Date('2026-01-01T00:00:00.000Z').getTime();+ let capturedSourceEvent: AgentSignalSourceEnvelope | undefined;++ 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();++ await db.insert(topics).values({+ id: topicId,+ title: 'Workflow Topic',+ userId,+ });++ await db.insert(messages).values([+ {+ agentId: agent.id,+ content: 'Old question that should be truncated from the serialized context.',+ createdAt: new Date(baseTimestamp + 1_000),+ id: `msg_${uuid()}`,+ role: 'user',+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Old assistant reply that should be truncated from the serialized context.',+ createdAt: new Date(baseTimestamp + 2_000),+ id: `msg_${uuid()}`,+ role: 'assistant',+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Need a summary of the discussion so far.',+ createdAt: new Date(baseTimestamp + 3_000),+ id: `msg_${uuid()}`,+ role: 'user',+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Summary draft with a lot of extra detail.',+ createdAt: new Date(baseTimestamp + 4_000),+ id: `msg_${uuid()}`,+ role: 'assistant',+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Can you make it shorter?',+ createdAt: new Date(baseTimestamp + 5_000),+ id: `msg_${uuid()}`,+ role: 'user',+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Here is a shorter version.',+ createdAt: new Date(baseTimestamp + 6_000),+ id: `msg_${uuid()}`,+ role: 'assistant',+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Still a bit dense.',+ createdAt: new Date(baseTimestamp + 7_000),+ id: `msg_${uuid()}`,+ role: 'user',+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'I can switch to bullet points.',+ createdAt: new Date(baseTimestamp + 8_000),+ id: `msg_${uuid()}`,+ role: 'assistant',+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'That would help.',+ createdAt: new Date(baseTimestamp + 9_000),+ id: `msg_${uuid()}`,+ role: 'user',+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Here is a bullet-first structure.',+ createdAt: new Date(baseTimestamp + 10_000),+ id: `msg_${uuid()}`,+ role: 'assistant',+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Latest assistant reply before the feedback message.',+ createdAt: new Date(baseTimestamp + 11_000),+ id: `msg_${uuid()}`,+ role: 'assistant',+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Going forward, I prefer concise answers with the conclusion first.',+ createdAt: new Date(baseTimestamp + 12_000),+ id: parentMessageId,+ role: 'user',+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Future assistant reply that should be excluded from the anchored root context.',+ createdAt: new Date(baseTimestamp + 13_000),+ id: `msg_${uuid()}`,+ role: 'assistant',+ topicId,+ userId,+ },+ ]);++ const now = Date.now();+ const executeSourceEvent: NonNullable<RunAgentSignalWorkflowDeps['executeSourceEvent']> = vi.fn(+ async (sourceEvent) => {+ capturedSourceEvent = sourceEvent as AgentSignalSourceEnvelope;+ return undefined;+ },+ );++ const result = await runAgentSignalWorkflow(+ createWorkflowContext({+ agentId: agent.id,+ sourceEvent: {+ payload: {+ agentId: agent.id,+ operationId: `op_${uuid()}`,+ parentMessageId,+ parentMessageType: 'user',+ topicId,+ },+ scopeKey: `topic:${topicId}`,+ sourceId: `client.runtime.start:${now}`,+ sourceType: 'client.runtime.start',+ timestamp: now,+ },+ userId,+ }),+ {+ executeSourceEvent,+ getDb: async () => db,+ },+ );++ expect(result).toEqual(+ expect.objectContaining({+ sourceId: parentMessageId,+ success: true,+ }),+ );+ expect(executeSourceEvent).toHaveBeenCalledTimes(1);+ expect(capturedSourceEvent?.sourceType).toBe('agent.user.message');+ expect(capturedSourceEvent?.payload.serializedContext).toContain('<feedback_analysis_context>');+ expect(capturedSourceEvent?.payload.serializedContext).not.toContain(+ 'Old question that should be truncated from the serialized context.',+ );+ expect(capturedSourceEvent?.payload.serializedContext).not.toContain(+ 'Old assistant reply that should be truncated from the serialized context.',+ );+ expect(capturedSourceEvent?.payload.serializedContext).toContain(+ 'Latest assistant reply before the feedback message.',+ );+ expect(capturedSourceEvent?.payload.serializedContext).toContain(+ 'Going forward, I prefer concise answers with the conclusion first.',+ );+ expect(capturedSourceEvent?.payload.serializedContext).not.toContain(+ 'Future assistant reply that should be excluded from the anchored root context.',+ );+ });++ it('assembles serializedContext from the matching thread before executing a threaded source event', async () => {+ const db = await getTestDB();+ const userId = `eval_${uuid()}`;+ const topicId = `topic_${uuid()}`;+ const threadId = `thread_${uuid()}`;+ const otherThreadId = `thread_${uuid()}`;+ const feedbackMessageId = `msg_${uuid()}`;+ const baseTimestamp = new Date('2026-01-02T00:00:00.000Z').getTime();+ let capturedSourceEvent: AgentSignalSourceEnvelope | undefined;++ await db.insert(users).values({ id: userId });++ const [agent] = await db+ .insert(agents)+ .values({+ model: 'gpt-4o-mini',+ plugins: [],+ provider: 'openai',+ systemRole: '',+ title: 'Threaded Workflow Scenario Agent',+ userId,+ })+ .returning();++ await db.insert(topics).values({+ id: topicId,+ title: 'Threaded Workflow Topic',+ userId,+ });++ await db.insert(threads).values([+ {+ agentId: agent.id,+ id: threadId,+ title: 'Target Thread',+ topicId,+ type: 'standalone',+ userId,+ },+ {+ agentId: agent.id,+ id: otherThreadId,+ title: 'Other Thread',+ topicId,+ type: 'standalone',+ userId,+ },+ ]);++ await db.insert(messages).values([+ {+ agentId: agent.id,+ content: 'Root topic message that should not appear in the threaded context.',+ createdAt: new Date(baseTimestamp + 1_000),+ id: `msg_${uuid()}`,+ role: 'user',+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Different thread message that should be excluded.',+ createdAt: new Date(baseTimestamp + 2_000),+ id: `msg_${uuid()}`,+ role: 'assistant',+ threadId: otherThreadId,+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Thread message one that should be included.',+ createdAt: new Date(baseTimestamp + 3_000),+ id: `msg_${uuid()}`,+ role: 'user',+ threadId,+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Thread message two that should be included.',+ createdAt: new Date(baseTimestamp + 4_000),+ id: `msg_${uuid()}`,+ role: 'assistant',+ threadId,+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Going forward, keep using this format in this thread.',+ createdAt: new Date(baseTimestamp + 5_000),+ id: feedbackMessageId,+ role: 'user',+ threadId,+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Later reply in the same thread that should be excluded by the anchor window.',+ createdAt: new Date(baseTimestamp + 6_000),+ id: `msg_${uuid()}`,+ role: 'assistant',+ threadId,+ topicId,+ userId,+ },+ {+ agentId: agent.id,+ content: 'Later root message that should still be excluded from the threaded context.',+ createdAt: new Date(baseTimestamp + 7_000),+ id: `msg_${uuid()}`,+ role: 'assistant',+ topicId,+ userId,+ },+ ]);++ const executeSourceEvent: NonNullable<RunAgentSignalWorkflowDeps['executeSourceEvent']> = vi.fn(+ async (sourceEvent) => {+ capturedSourceEvent = sourceEvent as AgentSignalSourceEnvelope;+ return undefined;+ },+ );++ const result = await runAgentSignalWorkflow(+ createWorkflowContext({+ agentId: agent.id,+ sourceEvent: {+ payload: {+ agentId: agent.id,+ message: 'Going forward, keep using this format in this thread.',+ messageId: feedbackMessageId,+ threadId,+ topicId,+ },+ scopeKey: `topic:${topicId}`,+ sourceId: `workflow-threaded:${threadId}`,+ sourceType: 'agent.user.message',+ timestamp: Date.now(),+ },+ userId,+ }),+ {+ executeSourceEvent,+ getDb: async () => db,+ },+ );++ expect(result).toEqual(+ expect.objectContaining({+ sourceId: `workflow-threaded:${threadId}`,+ success: true,+ }),+ );+ expect(executeSourceEvent).toHaveBeenCalledTimes(1);+ expect(capturedSourceEvent?.sourceType).toBe('agent.user.message');++ if (capturedSourceEvent?.sourceType !== AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage) {+ throw new Error('Expected captured source event to be an agent user message');+ }++ const userMessageSource = capturedSourceEvent as SourceAgentUserMessage;++ expect(userMessageSource.payload.threadId).toBe(threadId);+ expect(userMessageSource.payload.serializedContext).toContain('<feedback_analysis_context>');+ expect(userMessageSource.payload.serializedContext).toContain(+ 'Thread message one that should be included.',+ );+ expect(userMessageSource.payload.serializedContext).toContain(+ 'Thread message two that should be included.',+ );+ expect(userMessageSource.payload.serializedContext).toContain(+ 'Going forward, keep using this format in this thread.',+ );+ expect(userMessageSource.payload.serializedContext).not.toContain(+ 'Root topic message that should not appear in the threaded context.',+ );+ expect(userMessageSource.payload.serializedContext).not.toContain(+ 'Different thread message that should be excluded.',+ );+ expect(userMessageSource.payload.serializedContext).not.toContain(+ 'Later reply in the same thread that should be excluded by the anchor window.',+ );+ expect(userMessageSource.payload.serializedContext).not.toContain(+ 'Later root message that should still be excluded from the threaded context.',+ );+ });+});diff --git a/src/server/workflows/agentSignal/run.ts b/src/server/workflows/agentSignal/run.tsindex c954fac5724..4229ee190a2 100644--- a/src/server/workflows/agentSignal/run.ts+++ b/src/server/workflows/agentSignal/run.ts@@ -1,9 +1,22 @@+import type { ExecutionSnapshot, ISnapshotStore, StepSnapshot } from '@lobechat/agent-tracing';+import { messages } from '@lobechat/database/schemas';import debug from 'debug';+import { and, desc, eq, isNull, lte } from 'drizzle-orm';+import { MessageModel } from '@/database/models/message';import { getServerDB } from '@/database/server';-import type { GeneratedAgentSignalEmissionResult } from '@/server/services/agentSignal';-import { executeAgentSignalSourceEvent } from '@/server/services/agentSignal';+import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';+import type { GeneratedAgentSignalEmissionResult } from '@/server/services/agentSignal/orchestrator';+import { 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';@@ -28,10 +41,295 @@ export interface AgentSignalWorkflowContext<TPayload = AgentSignalWorkflowRunPay/** Dependencies for executing one Agent Signal workflow payload. */export interface RunAgentSignalWorkflowDeps {createRuntimeGuardBackend?: typeof createRedisRuntimeGuardBackend;+ createSnapshotStore?: () => ISnapshotStore | null;executeSourceEvent?: typeof executeAgentSignalSourceEvent;getDb?: typeof getServerDB;}+/**+ * One normalized workflow source event after ingress bridging.+ *+ * @param TSourceType - Concrete Agent Signal source type after normalization.+ */+interface NormalizedWorkflowSourceEventInput<+ TSourceType extends AgentSignalSourceType = AgentSignalSourceType,+> {+ payload: AgentSignalSourcePayloadMap[TSourceType];+ scopeKey: string;+ sourceId: string;+ sourceType: TSourceType;+ timestamp: number;+}++const createDefaultSnapshotStore = (): ISnapshotStore | null => {+ if (process.env.NODE_ENV !== 'development') return null;++ try {+ // NOTICE:+ // Workflow-triggered Agent Signal runs do not pass through AgentRuntimeService.executeStep(),+ // so they never hit the normal dev snapshot recorder path. We lazily require the file-backed+ // store here to bridge those workflow-only runs into `.agent-tracing/` for local debugging.+ // Removal condition:+ // - Safe to remove only if workflow executions share the same snapshot recorder as executeStep.+ // Source/context:+ // - `AgentRuntimeService` records `agent_signal.*` events into step snapshots.+ // - `runAgentSignalWorkflow` only persisted OTel observability before this bridge.+ // - `agent-tracing inspect -S` therefore showed zero events for workflow-triggered runs.++ const { FileSnapshotStore } = require('@lobechat/agent-tracing');+ return new FileSnapshotStore();+ } catch {+ return null;+ }+};++const resolveSnapshotOperationId = (result: GeneratedAgentSignalEmissionResult) => {+ const payloadOperationId =+ typeof result.source.payload === 'object' &&+ result.source.payload !== null &&+ 'operationId' in result.source.payload &&+ typeof result.source.payload.operationId === 'string'+ ? result.source.payload.operationId+ : undefined;++ return payloadOperationId ?? result.source.sourceId;+};++const toWorkflowStepSnapshot = (result: GeneratedAgentSignalEmissionResult): StepSnapshot => {+ const events = toAgentSignalTraceEvents({+ actions: result.orchestration.actions,+ results: result.orchestration.results,+ signals: result.orchestration.emittedSignals,+ source: result.source,+ });+ const startedAt = result.source.timestamp;+ const completedAt =+ Math.max(+ startedAt,+ ...events+ .map((event) => event.timestamp)+ .filter((timestamp): timestamp is number => typeof timestamp === 'number'),+ ) || startedAt;++ return {+ completedAt,+ context: {+ payload: {+ scopeKey: result.source.scopeKey,+ sourceId: result.source.sourceId,+ sourceType: result.source.sourceType,+ },+ phase: 'agent_signal_workflow',+ },+ events,+ executionTimeMs: Math.max(0, completedAt - startedAt),+ startedAt,+ stepIndex: 0,+ stepType: 'call_tool',+ totalCost: 0,+ totalTokens: 0,+ };+};++const persistWorkflowSnapshot = async (+ result: GeneratedAgentSignalEmissionResult,+ store: ISnapshotStore,+ userId: string,+) => {+ const operationId = resolveSnapshotOperationId(result);+ const step = toWorkflowStepSnapshot(result);+ const snapshot: ExecutionSnapshot = {+ agentId:+ typeof result.source.payload === 'object' &&+ result.source.payload !== null &&+ 'agentId' in result.source.payload &&+ typeof result.source.payload.agentId === 'string'+ ? result.source.payload.agentId+ : undefined,+ completedAt: step.completedAt,+ completionReason: 'done',+ operationId,+ startedAt: step.startedAt,+ steps: [step],+ topicId:+ typeof result.source.payload === 'object' &&+ result.source.payload !== null &&+ 'topicId' in result.source.payload &&+ typeof result.source.payload.topicId === 'string'+ ? result.source.payload.topicId+ : undefined,+ totalCost: 0,+ totalSteps: 1,+ totalTokens: 0,+ traceId: operationId,+ userId,+ };++ await store.save(snapshot);+};++const isClientRuntimeStartSource = (+ sourceEvent: AgentSignalWorkflowRunPayload['sourceEvent'],+): sourceEvent is NormalizedWorkflowSourceEventInput<SourceClientRuntimeStart['sourceType']> => {+ return sourceEvent.sourceType === AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart;+};++const isAgentUserMessageSource = (+ sourceEvent: AgentSignalWorkflowRunPayload['sourceEvent'],+): sourceEvent is NormalizedWorkflowSourceEventInput<SourceAgentUserMessage['sourceType']> => {+ return sourceEvent.sourceType === AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage;+};++/**+ * Rebuilds one `agent.user.message` source from the client runtime-start event.+ *+ * Use when:+ * - The browser only emits `client.runtime.start`+ * - Feedback policies still need the original user message content+ *+ * Expects:+ * - `sourceEvent.payload.parentMessageType === 'user'`+ * - `sourceEvent.payload.parentMessageId` belongs to the same `userId`+ *+ * Returns:+ * - One normalized `agent.user.message` source when the parent user message exists+ * - Otherwise returns `undefined` so the original client source can continue unchanged+ */+const bridgeClientRuntimeStartToAgentUserMessage = async (+ sourceEvent: NormalizedWorkflowSourceEventInput<SourceClientRuntimeStart['sourceType']>,+ input: { db: Awaited<ReturnType<typeof getServerDB>>; userId: string },+): Promise<+ NormalizedWorkflowSourceEventInput<SourceAgentUserMessage['sourceType']> | undefined+> => {+ if (sourceEvent.payload.parentMessageType !== 'user') return undefined;+ if (typeof sourceEvent.payload.parentMessageId !== 'string') return undefined;++ const messageModel = new MessageModel(input.db, input.userId);+ const parentMessage = await messageModel.findById(sourceEvent.payload.parentMessageId);++ if (!parentMessage?.content) return undefined;++ return {+ payload: {+ agentId:+ typeof sourceEvent.payload.agentId === 'string' ? sourceEvent.payload.agentId : undefined,+ message: parentMessage.content,+ messageId: parentMessage.id,+ serializedContext:+ typeof sourceEvent.payload.serializedContext === 'string'+ ? sourceEvent.payload.serializedContext+ : undefined,+ threadId:+ typeof sourceEvent.payload.threadId === 'string' ? sourceEvent.payload.threadId : undefined,+ topicId:+ typeof sourceEvent.payload.topicId === 'string' ? sourceEvent.payload.topicId : undefined,+ trigger: 'client.runtime.start',+ },+ scopeKey: sourceEvent.scopeKey,+ sourceId: parentMessage.id,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,+ timestamp: sourceEvent.timestamp,+ };+};++const buildFeedbackSourceSerializedContext = async (+ sourceEvent: NormalizedWorkflowSourceEventInput<SourceAgentUserMessage['sourceType']>,+ input: { db: Awaited<ReturnType<typeof getServerDB>>; userId: string },+): Promise<string | undefined> => {+ if (typeof sourceEvent.payload.serializedContext === 'string') {+ return sourceEvent.payload.serializedContext;+ }++ if (typeof sourceEvent.payload.topicId !== 'string') return undefined;++ const messageModel = new MessageModel(input.db, input.userId);+ const anchorMessage = await messageModel.findById(sourceEvent.payload.messageId);++ if (!anchorMessage?.createdAt) return undefined;++ const threadScopeFilter =+ typeof sourceEvent.payload.threadId === 'string'+ ? eq(messages.threadId, sourceEvent.payload.threadId)+ : isNull(messages.threadId);++ const recentMessages = await input.db.query.messages.findMany({+ limit: 10,+ orderBy: [desc(messages.createdAt)],+ where: and(+ eq(messages.userId, input.userId),+ eq(messages.topicId, sourceEvent.payload.topicId),+ lte(messages.createdAt, anchorMessage.createdAt),+ threadScopeFilter,+ ),+ });++ // TODO: serialize recent tool calls / tool results into feedback analysis context when we finalize the context format.+ return assembleFeedbackContext({+ feedbackMessage: {+ content: sourceEvent.payload.message,+ id: sourceEvent.payload.messageId,+ role: 'user',+ },+ messages: [...recentMessages]+ .reverse()+ .map((message) => ({ content: message.content, id: message.id, role: message.role })),+ }).serializedContext;+};++const enrichFeedbackSourceSerializedContext = async (+ sourceEvent: AgentSignalWorkflowRunPayload['sourceEvent'],+ input: { db: Awaited<ReturnType<typeof getServerDB>>; userId: string },+): Promise<AgentSignalWorkflowRunPayload['sourceEvent']> => {+ if (!isAgentUserMessageSource(sourceEvent)) return sourceEvent;++ const serializedContext = await buildFeedbackSourceSerializedContext(sourceEvent, input);++ if (typeof serializedContext !== 'string') return sourceEvent;++ return {+ ...sourceEvent,+ payload: {+ ...sourceEvent.payload,+ serializedContext,+ },+ };+};++/**+ * Normalizes one workflow source event into the runtime-facing source catalog.+ *+ * Use when:+ * - Workflow ingress receives browser lifecycle events+ * - Downstream policies expect richer server-owned sources such as `agent.user.message`+ *+ * Expects:+ * - `db` and `userId` point at the same message store used by the originating chat session+ *+ * Returns:+ * - The bridged source when one ingress adapter applies+ * - Otherwise the original workflow source event+ *+ * Call stack:+ *+ * {@link runAgentSignalWorkflow}+ * -> {@link normalizeWorkflowSourceEvent}+ * -> {@link bridgeClientRuntimeStartToAgentUserMessage}+ * -> {@link MessageModel.findById}+ */+const normalizeWorkflowSourceEvent = async (+ sourceEvent: AgentSignalWorkflowRunPayload['sourceEvent'],+ input: { db: Awaited<ReturnType<typeof getServerDB>>; userId: string },+): Promise<AgentSignalWorkflowRunPayload['sourceEvent']> => {+ if (isClientRuntimeStartSource(sourceEvent)) {+ const bridgedSourceEvent =+ (await bridgeClientRuntimeStartToAgentUserMessage(sourceEvent, input)) ?? sourceEvent;++ return enrichFeedbackSourceSerializedContext(bridgedSourceEvent, input);+ }++ return enrichFeedbackSourceSerializedContext(sourceEvent, input);+};+/*** Runs one normalized Agent Signal source event inside the workflow worker.*@@ -60,13 +358,18 @@ export const runAgentSignalWorkflow = async (const getDb = deps.getDb ?? getServerDB;const executeSourceEvent = deps.executeSourceEvent ?? executeAgentSignalSourceEvent;const createGuardBackend = deps.createRuntimeGuardBackend ?? createRedisRuntimeGuardBackend;+ const snapshotStore = (deps.createSnapshotStore ?? createDefaultSnapshotStore)();const db = await getDb();+ const normalizedSourceEvent = await normalizeWorkflowSourceEvent(payload.sourceEvent, {+ db,+ userId: payload.userId,+ });const result = await context.run(- `agent-signal:execute:${payload.sourceEvent.sourceType}:${payload.sourceEvent.sourceId}`,+ `agent-signal:execute:${normalizedSourceEvent.sourceType}:${normalizedSourceEvent.sourceId}`,() =>executeSourceEvent(- payload.sourceEvent,+ normalizedSourceEvent,{agentId: payload.agentId,db,@@ -93,15 +396,23 @@ export const runAgentSignalWorkflow = async (}: undefined,scopeKey: payload.sourceEvent.scopeKey,- sourceId: payload.sourceEvent.sourceId,- sourceType: payload.sourceEvent.sourceType,+ sourceId: normalizedSourceEvent.sourceId,+ sourceType: normalizedSourceEvent.sourceType,});+ if (snapshotStore && isGeneratedEmission(result)) {+ try {+ await persistWorkflowSnapshot(result, snapshotStore, payload.userId);+ } catch (error) {+ log('Persist workflow snapshot failed error=%O', error);+ }+ }+return {deduped: result?.deduped ?? true,emittedSignals: isGeneratedEmission(result) ? result.orchestration.emittedSignals.length : 0,- scopeKey: payload.sourceEvent.scopeKey,- sourceId: payload.sourceEvent.sourceId,+ scopeKey: normalizedSourceEvent.scopeKey,+ sourceId: normalizedSourceEvent.sourceId,success: true,} as const;};