🤯 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
⚡️ perf(server,agent-signal): improved skill intent detection (#14409)
Nekoa79cdd19f89d
diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.test.ts b/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.test.tsindex f6808a238d9..344125a8dc5 100644--- a/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.test.ts+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.test.ts@@ -21,15 +21,14 @@ describe('agent signal analyze-intent route prompt', () => {'Route to "skill", not "prompt"',);expect(AGENT_SIGNAL_ANALYZE_INTENT_ROUTE_SYSTEM_ROLE).toContain(- 'The PR review checklist and release-risk checklist overlap',- );- expect(AGENT_SIGNAL_ANALYZE_INTENT_ROUTE_SYSTEM_ROLE).toContain(- 'Create a reusable skill for future PR reviews',+ 'create, update, refine, merge, consolidate, deduplicate, or reorganize',);expect(AGENT_SIGNAL_ANALYZE_INTENT_FEEDBACK_SATISFACTION_SYSTEM_ROLE).toContain('Create a reusable skill for future PR reviews',);- expect(AGENT_SIGNAL_ANALYZE_INTENT_ROUTE_SYSTEM_ROLE).toContain('这个 review 流程挺好');+ expect(AGENT_SIGNAL_ANALYZE_INTENT_ROUTE_SYSTEM_ROLE).toContain(+ 'Route to "skill" for explicit requests',+ );expect(AGENT_SIGNAL_ANALYZE_INTENT_FEEDBACK_SATISFACTION_SYSTEM_ROLE).toContain('这个 review 流程挺好',);@@ -44,8 +43,8 @@ describe('agent signal analyze-intent route prompt', () => {*/it('includes serialized context and rules for implicit reusable workflow feedback', () => {const prompt = createAgentSignalAnalyzeIntentRoutePrompt({- evidence: [{ cue: '这种方式', excerpt: '以后都用这种方式做吧。' }],- message: '以后都用这种方式做吧。',+ evidence: [{ cue: 'this workflow', excerpt: 'Use this workflow next time.' }],+ message: 'Use this workflow next time.',reason: 'positive reusable workflow reinforcement',result: 'satisfied',serializedContext:@@ -61,4 +60,24 @@ describe('agent signal analyze-intent route prompt', () => {'recent context contains a reusable multi-step workflow',);});++ /**+ * @example+ * Future-scoped procedural reuse should route to skill, while personal style+ * and negative approach preferences remain memory candidates.+ */+ it('documents the memory versus skill boundary for future-scoped feedback', () => {+ expect(AGENT_SIGNAL_ANALYZE_INTENT_ROUTE_SYSTEM_ROLE).toContain(+ 'future-scoped reuse of a concrete procedure',+ );+ expect(AGENT_SIGNAL_ANALYZE_INTENT_ROUTE_SYSTEM_ROLE).toContain(+ 'Do not route to "memory" merely because the feedback contains future-oriented language',+ );+ expect(AGENT_SIGNAL_ANALYZE_INTENT_ROUTE_SYSTEM_ROLE).toContain(+ 'For future database migration reviews',+ );+ expect(AGENT_SIGNAL_ANALYZE_INTENT_ROUTE_SYSTEM_ROLE).toContain(+ 'This approach is not suitable',+ );+ });});diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.ts b/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.tsindex 5158a952a61..7aff8b34a26 100644--- a/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.ts+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.ts@@ -54,33 +54,28 @@ Rules:- "skill" can fan out with "memory" when the feedback contains both a personal preference and a reusable workflow/template insight.- Route to "skill", not "prompt", when the feedback asks to create, update, refine, merge, consolidate, deduplicate, or reorganize an existing reusable checklist, skill, template, workflow, playbook, or writing pattern.- Route to "skill" for explicit requests to create or preserve a reusable operational artifact, even when the message is phrased as an imperative instead of a complaint.-- If the feedback refers to "this way", "that workflow", "这种方式", "这个流程", or similar deictic phrasing, inspect serializedContext before deciding.+- Route to "skill" for future-scoped reuse of a concrete procedure, review checklist, troubleshooting sequence, migration-review order, deploy/rollback checklist, or repeatable working method.+- Treat "use this next time", "follow the previous order", "do it like that for this class of task", "reuse this procedure later", and similar phrasing as "skill" when recent context contains procedural steps.+- Do not route to "memory" merely because the feedback contains future-oriented language such as "future", "next time", "going forward", or "later". If the durable directive mainly preserves a repeatable procedure, checklist, or workflow, route to "skill" instead.+- Route to "memory" only when removing the procedural/checklist content still leaves a useful personal preference, such as brevity, tone, priority, tool choice, or do-not-do guidance.+- If the feedback refers to "this way", "that workflow", "this procedure", "that flow", or similar deictic phrasing, inspect serializedContext before deciding.- Route to "skill" when recent context contains a reusable multi-step workflow and the feedback asks to use that workflow for future similar tasks.- Route to "memory", not "skill", when recent context only supports a stable personal style, tool preference, or communication preference.- Never output duplicate targets.- Return "none" when no durable target is justified.-Examples:+Compact boundary 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:not_satisfied, message:"For future database migration reviews, follow the checklist from earlier."+Output: {"targets":[{"target":"skill","confidence":0.9,"reason":"future reuse of a database migration review checklist","evidence":[{"cue":"future database migration reviews","excerpt":"For future database migration reviews"},{"cue":"follow the checklist","excerpt":"follow the checklist from earlier"}]}]}-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."}]}]}--Input satisfaction=result:not_satisfied, message:"Create a reusable skill for future PR reviews: always check correctness, tests, security, rollout risk, and rollback risk."-Output: {"targets":[{"target":"skill","confidence":0.94,"reason":"explicit reusable skill creation request","evidence":[{"cue":"create reusable skill","excerpt":"Create a reusable skill for future PR reviews"},{"cue":"future PR reviews","excerpt":"future PR reviews"}]}]}--Input satisfaction=result:satisfied, message:"这个 review 流程挺好,下次也可以参考。"-Output: {"targets":[{"target":"skill","confidence":0.78,"reason":"positive reusable workflow signal","evidence":[{"cue":"review 流程","excerpt":"这个 review 流程挺好"},{"cue":"下次参考","excerpt":"下次也可以参考"}]}]}--Input satisfaction=result:not_satisfied, message:"The PR review checklist and release-risk checklist overlap; combine the repeated parts."-Output: {"targets":[{"target":"skill","confidence":0.88,"reason":"maintains existing reusable checklist artifacts","evidence":[{"cue":"checklist","excerpt":"The PR review checklist and release-risk checklist overlap; combine the repeated parts."},{"cue":"combine","excerpt":"combine the repeated parts"}]}]}+Input satisfaction=result:not_satisfied, message:"This approach is not suitable. Please do not do this again."+Output: {"targets":[{"target":"memory","confidence":0.82,"reason":"durable negative preference about future approach selection","evidence":[{"cue":"not suitable","excerpt":"This approach is not suitable"},{"cue":"do not do this again","excerpt":"Please do not do this again"}]}]}Return only the JSON object.`;diff --git a/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts b/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.tsindex 0faea45b093..87ebe492635 100644--- a/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts+++ b/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts@@ -648,6 +648,26 @@ describe('createServerAgentToolsEngine', () => {expect(result.enabledToolIds).not.toContain(LocalSystemManifest.identifier);});+ it('can suppress only LocalSystem while preserving the rest of tool discovery', () => {+ const context = createMockContext();+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: { plugins: [LocalSystemManifest.identifier, WebBrowsingManifest.identifier] },+ clientRuntime: 'desktop',+ disableLocalSystem: true,+ model: 'gpt-4',+ provider: 'openai',+ });++ const result = engine.generateToolsDetailed({+ model: 'gpt-4',+ provider: 'openai',+ toolIds: [LocalSystemManifest.identifier, WebBrowsingManifest.identifier],+ });++ expect(result.enabledToolIds).not.toContain(LocalSystemManifest.identifier);+ expect(result.enabledToolIds).toContain(WebBrowsingManifest.identifier);+ });+it('does not enable LocalSystem for web callers even when gateway is configured', () => {const context = createMockContext();const engine = createServerAgentToolsEngine(context, {diff --git a/src/server/modules/Mecha/AgentToolsEngine/index.ts b/src/server/modules/Mecha/AgentToolsEngine/index.tsindex d2c407e504b..d56e2d5f0e3 100644--- a/src/server/modules/Mecha/AgentToolsEngine/index.ts+++ b/src/server/modules/Mecha/AgentToolsEngine/index.ts@@ -97,6 +97,7 @@ export const createServerAgentToolsEngine = (agentConfig,clientRuntime,deviceContext,+ disableLocalSystem = false,globalMemoryEnabled = false,hasAgentDocuments = false,hasEnabledKnowledgeBases = false,@@ -173,6 +174,7 @@ export const createServerAgentToolsEngine = (// prerequisite needed;// - legacy device-proxy with an online & auto-activated device.[LocalSystemManifest.identifier]:+ !disableLocalSystem &&runtimeMode === 'local' &&(hasClientExecutor ||(hasDeviceProxy && !!deviceContext?.deviceOnline && !!deviceContext?.autoActivated)),diff --git a/src/server/modules/Mecha/AgentToolsEngine/types.ts b/src/server/modules/Mecha/AgentToolsEngine/types.tsindex 44843c90a8c..188a3046d04 100644--- a/src/server/modules/Mecha/AgentToolsEngine/types.ts+++ b/src/server/modules/Mecha/AgentToolsEngine/types.ts@@ -59,6 +59,8 @@ export interface ServerCreateAgentToolsEngineParams {deviceOnline?: boolean;gatewayConfigured: boolean;};+ /** Whether to suppress the local-system builtin while preserving other tools. */+ disableLocalSystem?: boolean;/** Whether the user's global memory setting is enabled */globalMemoryEnabled?: boolean;/** Whether agent has agent documents */diff --git a/src/server/services/agentSignal/observability/__tests__/traceEvents.test.ts b/src/server/services/agentSignal/observability/__tests__/traceEvents.test.tsindex 7582c6d7a2b..9cd731377c9 100644--- a/src/server/services/agentSignal/observability/__tests__/traceEvents.test.ts+++ b/src/server/services/agentSignal/observability/__tests__/traceEvents.test.ts@@ -149,4 +149,75 @@ describe('toAgentSignalTraceEvents', () => {}),);});++ /**+ * @example+ * skill domain signal trace includes compact route and classifier fields.+ */+ it('projects skill intent classifier fields on signal trace events', () => {+ const source = {+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },+ payload: { message: 'remember this', messageId: 'msg_1' },+ scopeKey: 'topic:t1',+ sourceId: 'source_1',+ sourceType: 'agent.user.message' as const,+ timestamp: 1,+ };+ const events = toAgentSignalTraceEvents({+ actions: [],+ results: [],+ signals: [+ {+ chain: { chainId: 'chain_1', parentNodeId: 'sig_parent', rootSourceId: 'source_1' },+ payload: {+ confidence: 0.9,+ evidence: [+ { cue: 'future reuse', excerpt: 'follow the review checklist from earlier' },+ ],+ message: 'For future database migration reviews, follow the checklist from earlier.',+ messageId: 'msg_1',+ reason: 'skill-domain target',+ satisfactionResult: 'satisfied',+ skillActionIntent: 'create',+ skillIntentError: {+ cause: 'HTTP 401 unauthorized',+ message: 'provider returned invalid key: [redacted-key]',+ name: 'Error',+ },+ skillIntentConfidence: 0.86,+ skillIntentExplicitness: 'implicit_strong_learning',+ skillIntentReason: 'future-scoped procedural reuse instruction',+ skillRoute: 'direct_decision',+ target: 'skill',+ },+ signalId: 'sig_skill',+ signalType: 'signal.feedback.domain.skill',+ source,+ timestamp: 102,+ },+ ],+ source,+ });++ expect(events[1]).toEqual(+ expect.objectContaining({+ data: expect.objectContaining({+ classifierConfidence: 0.86,+ classifierError: {+ cause: 'HTTP 401 unauthorized',+ message: 'provider returned invalid key: [redacted-key]',+ name: 'Error',+ },+ classifierReason: 'future-scoped procedural reuse instruction',+ satisfactionResult: 'satisfied',+ signalId: 'sig_skill',+ skillActionIntent: 'create',+ skillIntentExplicitness: 'implicit_strong_learning',+ skillRoute: 'direct_decision',+ target: 'skill',+ }),+ type: 'agent_signal.signal',+ }),+ );+ });});diff --git a/src/server/services/agentSignal/observability/traceEvents.ts b/src/server/services/agentSignal/observability/traceEvents.tsindex 01b21deb078..94590f45741 100644--- a/src/server/services/agentSignal/observability/traceEvents.ts+++ b/src/server/services/agentSignal/observability/traceEvents.ts@@ -46,13 +46,19 @@ export const toAgentSignalTraceEvents = (input: {return {data: {+ classifierConfidence: payload?.skillIntentConfidence,+ classifierError: payload?.skillIntentError,+ classifierReason: payload?.skillIntentReason,confidence: payload?.confidence,parentNodeId: signal.chain.parentNodeId,reason: payload?.reason,+ satisfactionResult: payload?.satisfactionResult ?? payload?.result,signalId: signal.signalId,signalType: signal.signalType,sourceId: signal.source.sourceId,- satisfactionResult: payload?.result,+ skillActionIntent: payload?.skillActionIntent,+ skillIntentExplicitness: payload?.skillIntentExplicitness,+ skillRoute: payload?.skillRoute,target: payload?.target,},timestamp: signal.timestamp,diff --git a/src/server/services/agentSignal/orchestrator.ts b/src/server/services/agentSignal/orchestrator.tsindex afe7f0961c7..f3ec8f2cd59 100644--- a/src/server/services/agentSignal/orchestrator.ts+++ b/src/server/services/agentSignal/orchestrator.ts@@ -136,6 +136,11 @@ const executeAgentSignalSourceEventCore = async <TSourceType extends AgentSignaloptions.policyOptions?.skillManagement?.selfIterationEnabled ?? false,userId: context.userId,},+ skillIntentClassifier: {+ db: context.db,+ ...options.policyOptions?.skillIntentClassifier,+ userId: context.userId,+ },}),});const runtimeResult = await runtime.emitNormalized(emission.source);diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.tsindex f5b5a80e149..2988049093b 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts@@ -51,6 +51,15 @@ type DomainSignalInput<TTarget extends SupportedTask4DomainTarget> = {message: string;messageId: string;satisfactionResult?: 'not_satisfied' | 'neutral' | 'satisfied';+ skillActionIntent?: 'consolidate' | 'create' | 'maintain' | 'noop' | 'refine';+ skillIntentConfidence?: number;+ skillIntentExplicitness?:+ | 'explicit_action'+ | 'implicit_strong_learning'+ | 'non_skill_preference'+ | 'weak_positive';+ skillIntentReason?: string;+ skillRoute?: 'accumulate' | 'direct_decision' | 'non_skill';signalId: string;sourceId: string;target: TTarget;@@ -154,6 +163,11 @@ function createDomainSignal(messageId: input.messageId,reason: 'test-domain-signal',satisfactionResult: input.satisfactionResult ?? 'not_satisfied',+ skillActionIntent: input.skillActionIntent,+ skillIntentConfidence: input.skillIntentConfidence,+ skillIntentExplicitness: input.skillIntentExplicitness,+ skillIntentReason: input.skillIntentReason,+ skillRoute: input.skillRoute,target: 'skill',},signalId: input.signalId,@@ -358,6 +372,125 @@ describe('feedbackActionPlanner', () => {expect(result).toBeUndefined();});+ /**+ * @example+ * satisfied explicit skill intent bypasses accumulator and dispatches skill management.+ */+ it('plans direct skill-management actions for satisfied explicit skill intent', async () => {+ const handler = createFeedbackActionPlannerSignalHandler();+ const result = await handler.handle(+ createDomainSignal({+ message:+ 'The SKILL.md draft from the chat agent is usable. Convert it into a real skills/bundle.',+ messageId: 'msg_skill_convert',+ satisfactionResult: 'satisfied',+ signalId: 'sig_skill_convert',+ skillActionIntent: 'create',+ skillIntentExplicitness: 'explicit_action',+ skillRoute: 'direct_decision',+ sourceId: 'source_skill_convert',+ target: 'skill',+ }),+ context,+ );++ expect(result).toEqual(+ expect.objectContaining({+ actions: [+ expect.objectContaining({+ actionType: 'action.skill-management.handle',+ payload: expect.objectContaining({+ feedbackHint: 'satisfied',+ idempotencyKey: 'source_skill_convert:skill:msg_skill_convert',+ }),+ }),+ ],+ status: 'dispatch',+ }),+ );+ });++ /**+ * @example+ * implicit strong learning also bypasses weak-positive accumulation.+ */+ it('plans direct skill-management actions for implicit strong learning intent', async () => {+ const handler = createFeedbackActionPlannerSignalHandler();+ const result = await handler.handle(+ createDomainSignal({+ message: 'For future database migration reviews, follow the checklist from earlier.',+ messageId: 'msg_skill_implicit',+ satisfactionResult: 'satisfied',+ signalId: 'sig_skill_implicit',+ skillActionIntent: 'create',+ skillIntentExplicitness: 'implicit_strong_learning',+ skillRoute: 'direct_decision',+ sourceId: 'source_skill_implicit',+ target: 'skill',+ }),+ context,+ );++ expect(result).toEqual(+ expect.objectContaining({+ actions: [+ expect.objectContaining({+ actionType: 'action.skill-management.handle',+ }),+ ],+ status: 'dispatch',+ }),+ );+ });++ /**+ * @example+ * weak positive skill intent remains accumulator-only.+ */+ it('keeps weak positive skill intent in accumulation', async () => {+ const handler = createFeedbackActionPlannerSignalHandler();+ const result = await handler.handle(+ createDomainSignal({+ message: 'This explanation was helpful.',+ messageId: 'msg_skill_weak_positive',+ satisfactionResult: 'satisfied',+ signalId: 'sig_skill_weak_positive',+ skillActionIntent: 'maintain',+ skillIntentExplicitness: 'weak_positive',+ skillRoute: 'accumulate',+ sourceId: 'source_skill_weak_positive',+ target: 'skill',+ }),+ context,+ );++ expect(result).toBeUndefined();+ });++ /**+ * @example+ * non-skill preference routed through skill domain does not dispatch skill action.+ */+ it('does not plan skill actions for non-skill preference route', async () => {+ const handler = createFeedbackActionPlannerSignalHandler();+ const result = await handler.handle(+ createDomainSignal({+ message: 'This approach is not suitable. Please do not do this again.',+ messageId: 'msg_skill_non_skill',+ satisfactionResult: 'satisfied',+ signalId: 'sig_skill_non_skill',+ skillActionIntent: 'noop',+ skillIntentExplicitness: 'non_skill_preference',+ skillRoute: 'non_skill',+ sourceId: 'source_skill_non_skill',+ target: 'skill',+ }),+ context,+ );++ expect(result).toBeUndefined();+ });+/*** @example* repeated satisfied skill feedback writes candidate records, then emits an accumulated marker.@@ -665,7 +798,7 @@ describe('procedure marker suppression', () => {markerReader: { shouldSuppress },});const signal = createDomainSignal({- message: '记住我喜欢简洁回答',+ message: 'Remember that I prefer concise replies.',messageId: 'msg_1',signalId: 'sig_procedure_1',sourceId: 'source_procedure_1',@@ -702,7 +835,7 @@ describe('procedure marker suppression', () => {markerReader: { shouldSuppress: vi.fn(async () => false) },});const signal = createDomainSignal({- message: '记住我喜欢简洁回答',+ message: 'Remember that I prefer concise replies.',messageId: 'msg_1',signalId: 'sig_procedure_2',sourceId: 'source_procedure_2',diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.tsindex 6dd6f063760..85b33d4ada3 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.ts@@ -1,7 +1,8 @@// @vitest-environment node-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import { createRuntimeProcessorContext } from '../../../runtime/context';+import type { SignalFeedbackSatisfaction } from '../../types';import { createFeedbackDomainJudgeSignalHandler } from '../feedbackDomain';const context = createRuntimeProcessorContext({@@ -16,6 +17,33 @@ const context = createRuntimeProcessorContext({scopeKey: 'topic:thread_1',});+const createSatisfactionSignal = (input: {+ message: string;+ result: 'not_satisfied' | 'satisfied';+ serializedContext?: string;+}): SignalFeedbackSatisfaction => ({+ chain: { chainId: 'chain:source_1', parentNodeId: 'source_1', rootSourceId: 'source_1' },+ payload: {+ agentId: 'agent_1',+ confidence: 0.9,+ evidence: [{ cue: 'feedback', excerpt: input.message }],+ message: input.message,+ messageId: 'msg_1',+ reason: 'test satisfaction',+ result: input.result,+ serializedContext: input.serializedContext,+ sourceHints: { intents: ['skill'] },+ topicId: 'topic_1',+ },+ signalId: 'source_1:signal:feedback-satisfaction',+ signalType: 'signal.feedback.satisfaction',+ source: {+ sourceId: 'source_1',+ sourceType: 'agent.user.message',+ },+ timestamp: 101,+});+describe('feedbackDomainJudge', () => {it('routes assistant phrasing corrections to the prompt lane', async () => {const handler = createFeedbackDomainJudgeSignalHandler({@@ -370,4 +398,100 @@ describe('feedbackDomainJudge', () => {}),);});++ /**+ * @example+ * skill-domain direct routing carries classifier metadata into the emitted signal.+ */+ it('enriches skill domain signals with direct skill intent classification', async () => {+ const handler = createFeedbackDomainJudgeSignalHandler({+ resolveDomains: vi.fn().mockResolvedValue([+ {+ confidence: 0.91,+ evidence: [{ cue: 'skill target', excerpt: 'follow the checklist from earlier' }],+ reason: 'skill-domain target',+ target: 'skill',+ },+ ]),+ skillIntentClassifier: {+ classify: vi.fn().mockResolvedValue({+ actionIntent: 'create',+ confidence: 0.86,+ explicitness: 'implicit_strong_learning',+ reason: 'future-scoped procedural reuse instruction',+ route: 'direct_decision',+ }),+ },+ });++ const result = await handler.handle(+ createSatisfactionSignal({+ message: 'For future database migration reviews, follow the checklist from earlier.',+ result: 'satisfied',+ serializedContext: 'topic=database-migration-review',+ }),+ context,+ );++ expect(result).toEqual(+ expect.objectContaining({+ signals: [+ expect.objectContaining({+ payload: expect.objectContaining({+ skillActionIntent: 'create',+ skillIntentConfidence: 0.86,+ skillIntentExplicitness: 'implicit_strong_learning',+ skillIntentReason: 'future-scoped procedural reuse instruction',+ skillRoute: 'direct_decision',+ target: 'skill',+ }),+ signalType: 'signal.feedback.domain.skill',+ }),+ ],+ status: 'dispatch',+ }),+ );+ });++ /**+ * @example+ * weak positive skill-domain feedback carries accumulation metadata.+ */+ it('enriches weak positive skill domain signals with accumulation route', async () => {+ const handler = createFeedbackDomainJudgeSignalHandler({+ resolveDomains: vi.fn().mockResolvedValue([+ {+ confidence: 0.8,+ evidence: [{ cue: 'skill target', excerpt: 'helpful' }],+ reason: 'skill-domain target',+ target: 'skill',+ },+ ]),+ });++ const result = await handler.handle(+ createSatisfactionSignal({+ message: 'This explanation was helpful.',+ result: 'satisfied',+ serializedContext: 'topic=debugging-help',+ }),+ context,+ );++ expect(result).toEqual(+ expect.objectContaining({+ signals: [+ expect.objectContaining({+ payload: expect.objectContaining({+ skillActionIntent: 'maintain',+ skillIntentExplicitness: 'weak_positive',+ skillIntentReason: 'generic positive feedback without durable future-use instruction',+ skillRoute: 'accumulate',+ target: 'skill',+ }),+ }),+ ],+ }),+ );+ });});diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.tsindex a398940edee..8dee959cfc8 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts@@ -175,9 +175,23 @@ describe('feedbackSatisfactionJudge', () => {);});- it('treats explicit skill merge requests as unsatisfied actionable feedback', async () => {+ /**+ * @example+ * explicit skill-management wording still uses the satisfaction judge; skill intent is resolved later.+ */+ it('keeps explicit skill-management wording in the satisfaction stage', async () => {const judge = {- judgeSatisfaction: vi.fn(),+ judgeSatisfaction: vi.fn().mockResolvedValue({+ confidence: 0.81,+ evidence: [+ {+ cue: 'accepted draft',+ excerpt: 'SKILL.md 草稿可以用',+ },+ ],+ reason: 'positive acceptance of the foreground draft',+ result: 'satisfied',+ }),};const ctx = createRuntimeProcessorContext({backend: {@@ -193,22 +207,25 @@ describe('feedbackSatisfactionJudge', () => {const processor = createFeedbackSatisfactionJudgeProcessor({ judge });const result = await processor.handle(createUserMessageSource(- 'source_skill_merge',- 'The PR review checklist and release-risk checklist overlap; combine the repeated parts.',+ 'source_skill_convert',+ '刚才 chat agent 写的 SKILL.md 草稿可以用,把它转成真正的 skills/bundle。','topic=repo-review',['skill'],),ctx,);- expect(judge.judgeSatisfaction).not.toHaveBeenCalled();+ expect(judge.judgeSatisfaction).toHaveBeenCalledWith({+ message: '刚才 chat agent 写的 SKILL.md 草稿可以用,把它转成真正的 skills/bundle。',+ serializedContext: 'topic=repo-review',+ });expect(result).toEqual(expect.objectContaining({signals: [expect.objectContaining({payload: expect.objectContaining({- reason: 'source hinted explicit skill-management change request',- result: 'not_satisfied',+ reason: 'positive acceptance of the foreground draft',+ result: 'satisfied',}),}),],@@ -216,9 +233,19 @@ describe('feedbackSatisfactionJudge', () => {);});- it('treats explicit Chinese skill conversion requests as unsatisfied actionable feedback', async () => {+ it('keeps explicit skill merge requests in the satisfaction judge', async () => {const judge = {- judgeSatisfaction: vi.fn(),+ judgeSatisfaction: vi.fn().mockResolvedValue({+ confidence: 0.84,+ evidence: [+ {+ cue: 'merge request',+ excerpt: 'combine the repeated parts',+ },+ ],+ reason: 'explicit request to change reusable workflow material',+ result: 'not_satisfied',+ }),};const ctx = createRuntimeProcessorContext({backend: {@@ -234,21 +261,25 @@ describe('feedbackSatisfactionJudge', () => {const processor = createFeedbackSatisfactionJudgeProcessor({ judge });const result = await processor.handle(createUserMessageSource(- 'source_skill_convert',- '刚才 chat agent 写的 SKILL.md 草稿可以用,把它转成真正的 skills/bundle。',+ 'source_skill_merge',+ 'The PR review checklist and release-risk checklist overlap; combine the repeated parts.','topic=repo-review',['skill'],),ctx,);- expect(judge.judgeSatisfaction).not.toHaveBeenCalled();+ expect(judge.judgeSatisfaction).toHaveBeenCalledWith({+ message:+ 'The PR review checklist and release-risk checklist overlap; combine the repeated parts.',+ serializedContext: 'topic=repo-review',+ });expect(result).toEqual(expect.objectContaining({signals: [expect.objectContaining({payload: expect.objectContaining({- reason: 'source hinted explicit skill-management change request',+ reason: 'explicit request to change reusable workflow material',result: 'not_satisfied',}),}),diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/skillIntent.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/skillIntent.test.tsnew file mode 100644index 00000000000..5d9346c4cf4--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/skillIntent.test.ts@@ -0,0 +1,268 @@+// @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 {+ classifySkillIntent,+ classifySkillIntentByRules,+ SkillIntentClassifierAgentService,+} from '../skillIntent';++vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));++describe('skillIntent classifier', () => {+ const mockGenerateObject = vi.fn();++ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({+ generateObject: mockGenerateObject,+ } as never);+ });++ /**+ * @example+ * explicit artifact conversion skips the fallback model and routes to direct decision.+ */+ it('classifies explicit SKILL.md conversion as direct create intent', () => {+ const result = classifySkillIntentByRules({+ message:+ 'The SKILL.md draft from the chat agent is usable. Convert it into a real skills/bundle.',+ serializedContext: 'topic=repo-review',+ });++ expect(result).toEqual({+ actionIntent: 'create',+ confidence: 0.92,+ explicitness: 'explicit_action',+ reason: 'explicit skill artifact conversion request',+ route: 'direct_decision',+ });+ });++ /**+ * @example+ * named skill edits are explicit refine requests.+ */+ it('classifies named skill edit requests as direct refine intent', () => {+ const result = classifySkillIntentByRules({+ message: 'Update review-skill to include security checks and rollback checks.',+ serializedContext: 'topic=repo-review',+ });++ expect(result).toEqual({+ actionIntent: 'refine',+ confidence: 0.9,+ explicitness: 'explicit_action',+ reason: 'explicit named skill refinement request',+ route: 'direct_decision',+ });+ });++ /**+ * @example+ * generic praise is weak positive and remains accumulator-only.+ */+ it('classifies generic helpful feedback as weak positive accumulation', () => {+ const result = classifySkillIntentByRules({+ message: 'This explanation was helpful.',+ serializedContext: 'topic=debugging-help',+ });++ expect(result).toEqual({+ actionIntent: 'maintain',+ confidence: 0.78,+ explicitness: 'weak_positive',+ reason: 'generic positive feedback without durable future-use instruction',+ route: 'accumulate',+ });+ });++ /**+ * @example+ * negative future preference is durable, but not skill-management.+ */+ it('classifies negative future preference as non-skill preference', () => {+ const result = classifySkillIntentByRules({+ message: 'This approach is not suitable. Please do not do this again.',+ serializedContext: 'topic=database-migration',+ });++ expect(result).toEqual({+ actionIntent: 'noop',+ confidence: 0.82,+ explicitness: 'non_skill_preference',+ reason: 'negative future preference belongs outside skill management',+ route: 'non_skill',+ });+ });++ /**+ * @example+ * implicit strong learning goes through the injected fallback classifier.+ */+ it('uses fallback classifier for implicit strong learning instructions', async () => {+ const fallback = {+ classify: vi.fn().mockResolvedValue({+ actionIntent: 'create',+ confidence: 0.86,+ explicitness: 'implicit_strong_learning',+ reason: 'future-scoped procedural reuse instruction',+ route: 'direct_decision',+ }),+ };++ const result = await classifySkillIntent(+ {+ message: 'For future database migration reviews, follow the checklist from earlier.',+ serializedContext: 'topic=database-migration-review',+ },+ { fallback },+ );++ expect(fallback.classify).toHaveBeenCalledWith({+ message: 'For future database migration reviews, follow the checklist from earlier.',+ serializedContext: 'topic=database-migration-review',+ topicLabel: 'database-migration-review',+ });+ expect(result).toEqual({+ actionIntent: 'create',+ confidence: 0.86,+ explicitness: 'implicit_strong_learning',+ reason: 'future-scoped procedural reuse instruction',+ route: 'direct_decision',+ });+ });++ /**+ * @example+ * injected fallback classifiers may omit actionIntent for non-skill routes.+ */+ it('accepts fallback classifier output without optional action intent', async () => {+ const fallback = {+ classify: vi.fn().mockResolvedValue({+ confidence: 0.84,+ explicitness: 'non_skill_preference',+ reason: 'durable preference outside skill management',+ route: 'non_skill',+ }),+ };++ const result = await classifySkillIntent(+ {+ message: 'For future code reviews, use shorter comments.',+ serializedContext: 'topic=code-review',+ },+ { fallback },+ );++ expect(result).toEqual({+ confidence: 0.84,+ explicitness: 'non_skill_preference',+ reason: 'durable preference outside skill management',+ route: 'non_skill',+ });+ });++ /**+ * @example+ * invalid fallback output falls back to safe accumulation instead of direct mutation.+ */+ it('falls back safely when fallback classifier throws a malformed output error', async () => {+ const diagnostics = {+ recordMalformedOutput: vi.fn().mockResolvedValue(undefined),+ };+ const classifierError = new Error('provider returned invalid key: sk-testsecret123456789');+ (classifierError as Error & { cause?: unknown }).cause = new Error('HTTP 401 unauthorized');+ const fallback = {+ classify: vi.fn().mockRejectedValue(classifierError),+ };++ const result = await classifySkillIntent(+ {+ message: 'For future database migration reviews, follow the checklist from earlier.',+ serializedContext: 'topic=database-migration-review',+ },+ {+ diagnostics,+ fallback,+ scopeKey: 'topic:thread_1',+ sourceId: 'source_1',+ },+ );++ expect(result).toEqual({+ actionIntent: 'maintain',+ classifierError: {+ cause: 'HTTP 401 unauthorized',+ message: 'provider returned invalid key: [redacted-key]',+ name: 'Error',+ },+ confidence: 0.35,+ explicitness: 'weak_positive',+ reason: 'classifier-fallback-failed',+ route: 'accumulate',+ });+ expect(diagnostics.recordMalformedOutput).toHaveBeenCalledWith({+ error: expect.any(Error),+ reason: 'malformed skill-intent classifier output',+ scopeKey: 'topic:thread_1',+ sourceId: 'source_1',+ stage: 'skill-intent',+ });+ });++ /**+ * @example+ * the model-backed fallback receives compact context only.+ */+ it('uses the model-backed fallback with compact structured schema', async () => {+ mockGenerateObject.mockResolvedValue({+ actionIntent: 'create',+ confidence: 0.88,+ explicitness: 'implicit_strong_learning',+ reason: 'stable future-use procedure instruction',+ route: 'direct_decision',+ });++ const service = new SkillIntentClassifierAgentService({} as LobeChatDatabase, 'user_1', {+ model: 'gpt-test',+ provider: 'openai',+ });+ const result = await service.classify({+ message: 'This troubleshooting procedure is stable. Use it for future login failures.',+ serializedContext: 'topic=login-debugging;tool_outcome=createDocument',+ topicLabel: 'login-debugging',+ });++ expect(initModelRuntimeFromDB).toHaveBeenCalledWith({} as LobeChatDatabase, 'user_1', 'openai');+ expect(mockGenerateObject).toHaveBeenCalledWith(+ expect.objectContaining({+ messages: [+ expect.objectContaining({+ content: expect.stringContaining('Classify skill intent for Agent Signal'),+ role: 'system',+ }),+ expect.objectContaining({+ content: expect.stringContaining('"topicLabel":"login-debugging"'),+ role: 'user',+ }),+ ],+ model: 'gpt-test',+ }),+ { metadata: { trigger: RequestTrigger.AgentSignal } },+ );+ expect(result).toEqual({+ actionIntent: 'create',+ confidence: 0.88,+ explicitness: 'implicit_strong_learning',+ reason: 'stable future-use procedure instruction',+ route: 'direct_decision',+ });+ });+});diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.tsindex 3421960abb3..669cdf7141c 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts@@ -23,14 +23,13 @@ import {} from '../../processors/procedure';import type { RuntimeProcessorContext } from '../../runtime/context';import { defineSignalHandler } from '../../runtime/middleware';-import type { AgentSignalActionServices } from '../../services/actionServices';+import type {+ AgentSignalActionServices,+ NonSatisfiedSkillActionServiceSignal,+} from '../../services/actionServices';import { createDefaultActionServices } from '../../services/actionServices';import type { ProcedureMarkerSuppressInput, ProcedureStateService } from '../../services/types';-import type {- AgentSignalFeedbackSatisfactionResult,- SignalFeedbackDomainMemory,- SignalFeedbackDomainSkill,-} from '../types';+import type { SignalFeedbackDomainMemory } from '../types';import { AGENT_SIGNAL_POLICY_SIGNAL_TYPES } from '../types';/**@@ -83,25 +82,30 @@ export interface FeedbackActionPlannerOptions {procedure?: FeedbackActionProcedureDeps;}-const isSatisfiedSkillSignal = (- signal: FeedbackDomainSignal,-): signal is SatisfiedSkillFeedbackDomainSignal => {- return signal.payload.target === 'skill' && signal.payload.satisfactionResult === 'satisfied';-};-const isMemorySignal = (signal: FeedbackDomainSignal): signal is SignalFeedbackDomainMemory => {return signal.payload.target === 'memory';};-const isNonSatisfiedSkillSignal = (+const isDirectSkillDecisionSignal = (signal: FeedbackDomainSignal,-): signal is SignalFeedbackDomainSkill & {- payload: SignalFeedbackDomainSkill['payload'] & {- satisfactionResult: Exclude<AgentSignalFeedbackSatisfactionResult, 'satisfied'>;- target: 'skill';- };-} => {- return signal.payload.target === 'skill' && signal.payload.satisfactionResult !== 'satisfied';+): signal is NonSatisfiedSkillActionServiceSignal => {+ if (signal.payload.target !== 'skill') return false;+ if (signal.payload.skillRoute === 'direct_decision') return true;++ return (+ signal.payload.satisfactionResult !== 'satisfied' && signal.payload.skillRoute !== 'non_skill'+ );+};++const isAccumulatingSkillSignal = (+ signal: FeedbackDomainSignal,+): signal is SatisfiedSkillFeedbackDomainSignal => {+ return (+ signal.payload.target === 'skill' &&+ signal.payload.satisfactionResult === 'satisfied' &&+ signal.payload.skillRoute !== 'direct_decision' &&+ signal.payload.skillRoute !== 'non_skill'+ );};const createPlannerProcedureState = (@@ -318,7 +322,7 @@ export const createFeedbackActionPlannerSignalHandler = (};}- if (isNonSatisfiedSkillSignal(signal)) {+ if (isDirectSkillDecisionSignal(signal)) {const plan = actionServices.skillActions.prepare(signal);return {@@ -327,7 +331,7 @@ export const createFeedbackActionPlannerSignalHandler = (};}- if (isSatisfiedSkillSignal(signal)) {+ if (isAccumulatingSkillSignal(signal)) {return handleSatisfiedSkillFeedback(signal, procedureContext, options, procedureState);}},diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomain.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomain.tsindex eb65bff9c91..546ae9deb4b 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomain.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomain.ts@@ -4,13 +4,18 @@ import type { LobeChatDatabase } from '@/database/type';import { classifyDomain, transitionToSignals } from '../../processors';import { defineSignalHandler } from '../../runtime/middleware';-import type { ClassifierDiagnosticsService, DomainClassifierService } from '../../services';+import type {+ ClassifierDiagnosticsService,+ DomainClassifierService,+ SkillIntentClassifierService,+} from '../../services';import { AGENT_SIGNAL_POLICY_SIGNAL_TYPES, type SignalFeedbackSatisfaction } from '../types';import {type FeedbackDomainJudgeAgentModelConfig,type FeedbackDomainJudgeAgentResult,FeedbackDomainJudgeAgentService,} from './feedbackDomainAgent';+import { classifySkillIntent, SkillIntentClassifierAgentService } from './skillIntent';interface FeedbackDomainJudgeResolverInput {chain: SignalFeedbackSatisfaction['chain'];@@ -32,6 +37,8 @@ export interface CreateFeedbackDomainJudgeSignalHandlerOptions {resolveDomains?: (input: FeedbackDomainJudgeResolverInput,) => Promise<FeedbackDomainJudgeAgentResult['targets']>;+ /** Optional skill-intent classifier used after skill-domain routing. */+ skillIntentClassifier?: SkillIntentClassifierService;}/**@@ -42,6 +49,10 @@ export interface CreateFeedbackDomainJudgePolicyOptions {db: LobeChatDatabase;userId: string;};+ skillIntentClassifier?: Partial<FeedbackDomainJudgeAgentModelConfig> & {+ db: LobeChatDatabase;+ userId: string;+ };}const createDomainResolver = (@@ -70,6 +81,16 @@ const createDomainResolver = (};};+export const createSkillIntentClassifier = (+ options: CreateFeedbackDomainJudgePolicyOptions = {},+): SkillIntentClassifierService | undefined => {+ const runtimeDeps = options.skillIntentClassifier;++ if (!runtimeDeps) return undefined;++ return new SkillIntentClassifierAgentService(runtimeDeps.db, runtimeDeps.userId, runtimeDeps);+};+/*** Creates the signal handler for routing satisfaction signals into domain signals.*@@ -92,11 +113,44 @@ export const createFeedbackDomainJudgeSignalHandler = (options: CreateFeedbackDomainJudgeSignalHandlerOptions = {},) => {const resolveDomains = options.resolveDomains;+ const skillIntentClassifier = options.skillIntentClassifier;return defineSignalHandler(AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackSatisfaction,'signal.feedback-domain-judge',async (signal, ctx): Promise<RuntimeProcessorResult | void> => {+ const enrichSkillTargets = async (+ targets: FeedbackDomainJudgeAgentResult['targets'],+ ): Promise<FeedbackDomainJudgeAgentResult['targets']> => {+ return Promise.all(+ targets.map(async (target) => {+ if (target.target !== 'skill') return target;++ const classification = await classifySkillIntent(+ {+ message: signal.payload.message,+ serializedContext: signal.payload.serializedContext,+ },+ {+ diagnostics: options.classifierDiagnostics,+ fallback: skillIntentClassifier,+ scopeKey: ctx.scopeKey,+ sourceId: signal.source?.sourceId,+ },+ );++ return {+ ...target,+ skillActionIntent: classification.actionIntent,+ skillIntentError: classification.classifierError,+ skillIntentConfidence: classification.confidence,+ skillIntentExplicitness: classification.explicitness,+ skillIntentReason: classification.reason,+ skillRoute: classification.route,+ };+ }),+ );+ };const classifier: DomainClassifierService | undefined = resolveDomains? {async classify(input) {@@ -116,7 +170,7 @@ export const createFeedbackDomainJudgeSignalHandler = (topicId: input.payload.topicId,});- return targets;+ return enrichSkillTargets(targets);},}: undefined;diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.tsindex d4e8c5e60ca..8e30f287745 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts@@ -1,8 +1,5 @@import type { RuntimeProcessorResult } from '@lobechat/agent-signal';-import {- AGENT_SIGNAL_SOURCE_TYPES,- type SourceAgentUserMessage,-} from '@lobechat/agent-signal/source';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';import type { GenerateObjectPayload, GenerateObjectSchema } from '@lobechat/model-runtime';import { chainAgentSignalAnalyzeIntentFeedbackSatisfaction } from '@lobechat/prompts';@@ -32,10 +29,6 @@ const FeedbackSatisfactionStagePayloadSchema = z.object({result: z.enum(['neutral', 'not_satisfied', 'satisfied']),});-type FeedbackSatisfactionStagePayloadResult = z.infer<- typeof FeedbackSatisfactionStagePayloadSchema->;-const FeedbackSatisfactionGenerateObjectSchema = {name: 'agent_signal_feedback_satisfaction',schema: {@@ -253,27 +246,6 @@ const resolveJudge = (});};-const explicitSkillChangePattern =- /create|update|refine|merge|consolidate|combine|deduplicate|reorganize|创建|更新|合并|去重|整理|变成|变为|转换|转成|做成|沉淀|固化/i;--const resolveSkillHintSatisfaction = (- source: SourceAgentUserMessage,-): FeedbackSatisfactionStagePayloadResult | undefined => {- if (!source.payload.intents?.includes('skill')) return undefined;-- const message = source.payload.message.trim();- const explicitChangeRequest = explicitSkillChangePattern.test(message);-- if (!explicitChangeRequest) return undefined;-- return {- confidence: 0.8,- evidence: [{ cue: 'skill source hint', excerpt: message }],- reason: 'source hinted explicit skill-management change request',- result: 'not_satisfied',- };-};-/*** Creates the source handler for the feedback satisfaction judge.*@@ -300,8 +272,7 @@ export const createFeedbackSatisfactionJudgeProcessor = (async (source, ctx): Promise<RuntimeProcessorResult | void> => {const classifier: SatisfactionClassifierService = {async classify(input) {- const payload =- resolveSkillHintSatisfaction(source) ?? (await judge.judgeSatisfaction(input));+ const payload = await judge.judgeSatisfaction(input);return FeedbackSatisfactionStagePayloadSchema.parse(payload);},diff --git a/src/server/services/agentSignal/policies/analyzeIntent/index.ts b/src/server/services/agentSignal/policies/analyzeIntent/index.tsindex 7f73d3fd226..84f20113516 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/index.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/index.ts@@ -13,6 +13,7 @@ import type { CreateFeedbackDomainJudgePolicyOptions } from './feedbackDomain';import {createFeedbackDomainJudgeSignalHandler,createFeedbackDomainResolver,+ createSkillIntentClassifier,} from './feedbackDomain';import type { CreateFeedbackSatisfactionJudgePolicyOptions } from './feedbackSatisfaction';import { createFeedbackSatisfactionJudgeProcessor } from './feedbackSatisfaction';@@ -45,6 +46,8 @@ export interface CreateAnalyzeIntentPolicyOptions {feedbackSatisfactionJudge?: CreateFeedbackSatisfactionJudgePolicyOptions;/** Optional procedure dependencies shared by tool-outcome projection and action planning. */procedure?: AnalyzeIntentProcedureOptions;+ /** Optional skill intent classifier dependencies used after skill-domain routing. */+ skillIntentClassifier?: CreateFeedbackDomainJudgePolicyOptions['skillIntentClassifier'];/** Optional skill-management action handler dependencies. */skillManagement?: SkillManagementActionHandlerOptions;/** Optional user-memory action handler dependencies. */@@ -55,6 +58,9 @@ export const createAnalyzeIntentPolicy = (options: CreateAnalyzeIntentPolicyOpticonst feedbackDomainResolver = createFeedbackDomainResolver({feedbackDomainJudge: options.feedbackDomainJudge,});+ const skillIntentClassifier = createSkillIntentClassifier({+ skillIntentClassifier: options.skillIntentClassifier,+ });return defineAgentSignalHandlers([...(options.procedure ? [createToolOutcomeSourceHandler(options.procedure)] : []),@@ -66,6 +72,7 @@ export const createAnalyzeIntentPolicy = (options: CreateAnalyzeIntentPolicyOpticreateFeedbackDomainJudgeSignalHandler({classifierDiagnostics: options.classifierDiagnostics,resolveDomains: feedbackDomainResolver,+ skillIntentClassifier,}),createFeedbackActionPlannerSignalHandler({markerReader: options.procedure?.markerReader,diff --git a/src/server/services/agentSignal/policies/analyzeIntent/skillIntent.ts b/src/server/services/agentSignal/policies/analyzeIntent/skillIntent.tsnew file mode 100644index 00000000000..69a8066e18b--- /dev/null+++ b/src/server/services/agentSignal/policies/analyzeIntent/skillIntent.ts@@ -0,0 +1,463 @@+import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';+import type { GenerateObjectPayload, GenerateObjectSchema } from '@lobechat/model-runtime';+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 type {+ ClassifierDiagnosticsService,+ SkillIntentClassifierInput,+ SkillIntentClassifierService,+} from '../../services';+import type {+ AgentSignalClassifierErrorSummary,+ AgentSignalSkillIntentClassification,+ AgentSignalSkillIntentExplicitness,+ AgentSignalSkillIntentRoute,+} from '../types';++const log = debug('lobe-server:agent-signal:skill-intent:agent');++const SkillIntentClassificationSchema = z+ .object({+ actionIntent: z+ .enum(['create', 'refine', 'consolidate', 'maintain', 'noop'])+ .optional()+ .nullable(),+ confidence: z.number().min(0).max(1),+ explicitness: z.enum([+ 'explicit_action',+ 'implicit_strong_learning',+ 'weak_positive',+ 'non_skill_preference',+ ]),+ reason: z.string(),+ route: z.enum(['direct_decision', 'accumulate', 'non_skill']),+ })+ .transform(({ actionIntent, ...value }) => ({+ ...value,+ ...(actionIntent ? { actionIntent } : {}),+ }));++const SkillIntentGenerateObjectSchema = {+ name: 'agent_signal_skill_intent',+ schema: {+ additionalProperties: false,+ properties: {+ actionIntent: {+ enum: ['create', 'refine', 'consolidate', 'maintain', 'noop', null],+ type: ['string', 'null'],+ },+ confidence: { maximum: 1, minimum: 0, type: 'number' },+ explicitness: {+ enum: [+ 'explicit_action',+ 'implicit_strong_learning',+ 'weak_positive',+ 'non_skill_preference',+ ],+ type: 'string',+ },+ reason: { type: 'string' },+ route: { enum: ['direct_decision', 'accumulate', 'non_skill'], type: 'string' },+ },+ required: ['actionIntent', 'confidence', 'explicitness', 'reason', 'route'],+ type: 'object',+ },+ strict: true,+} satisfies GenerateObjectSchema;++const generateObjectRoles = ['assistant', 'system', 'user'] as const;++const isGenerateObjectRole = (+ role: string,+): role is GenerateObjectPayload['messages'][number]['role'] => {+ return generateObjectRoles.includes(role as (typeof generateObjectRoles)[number]);+};++const compactText = (value: string | undefined, maxLength = 1800): string | undefined => {+ if (!value) return undefined;+ if (value.length <= maxLength) return value;++ return `${value.slice(0, maxLength)}...`;+};++const getTopicLabel = (serializedContext: string | undefined): string | undefined => {+ if (!serializedContext) return undefined;++ const topicMatch = /topic=([^;\n<]+)/i.exec(serializedContext);+ return topicMatch?.[1];+};++const readRecord = (value: unknown): Record<string, unknown> | undefined => {+ return value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined;+};++const redactErrorText = (value: string, maxLength = 480): string => {+ const redacted = value+ .replaceAll(/(bearer\s+)[\w.-]+/gi, '$1[redacted-token]')+ .replaceAll(/(api[-_ ]?key["'=: ]+)[\w.-]{8,}/gi, '$1[redacted-key]')+ .replaceAll(/(invalid key[: ]+)[\w.-]{8,}/gi, '$1[redacted-key]')+ .replaceAll(/\bsk-[\w-]{8,}\b/gi, '[redacted-key]');++ return redacted.length <= maxLength ? redacted : `${redacted.slice(0, maxLength)}...`;+};++const readErrorMessage = (error: unknown): string => {+ if (error instanceof Error) return error.message;+ if (typeof error === 'string') return error;++ const record = readRecord(error);+ const message = record?.message;+ if (typeof message === 'string') return message;++ try {+ return JSON.stringify(error);+ } catch {+ return String(error);+ }+};++const readErrorName = (error: unknown): string | undefined => {+ if (error instanceof Error) return error.name;++ const record = readRecord(error);+ const name = record?.name ?? record?.errorType ?? record?.code;+ return typeof name === 'string' ? name : undefined;+};++/**+ * Normalizes classifier fallback errors for trace-safe diagnostics.+ *+ * Before:+ * - `ProviderError: invalid key: sk-...`+ *+ * After:+ * - `{ name: "ProviderError", message: "invalid key: [redacted-key]" }`+ */+const normalizeClassifierError = (error: unknown): AgentSignalClassifierErrorSummary => {+ const record = readRecord(error);+ const cause = error instanceof Error ? error.cause : record?.cause;++ return {+ ...(cause === undefined ? {} : { cause: redactErrorText(readErrorMessage(cause)) }),+ message: redactErrorText(readErrorMessage(error)),+ ...(readErrorName(error) ? { name: readErrorName(error) } : {}),+ };+};++const hasSkillArtifactReference = (message: string) => {+ return /skill|技能|workflow|工作流|procedure|流程|checklist|检查清单/i.test(message);+};++const hasConversionVerb = (message: string) => {+ return /create|convert|turn into|make into|做成|变成|变为|转换|转成|沉淀|固化|整理成/i.test(+ message,+ );+};++const hasRefineVerb = (message: string) => {+ return /update|refine|补上|补充|加入|加上|更新|完善|改进|扩展/i.test(message);+};++const hasMergeVerb = (message: string) => {+ return /merge|consolidate|combine|deduplicate|合并|整合|去重/i.test(message);+};++const hasFutureProcedureReuse = (message: string) => {+ return /(?:以后|之后|下次|每次|遇到).*(?:[按照来]|沿用|复用|参考|执行)|(?:future|next time|going forward|later).*(?:follow|reuse|use|apply|run)/i.test(+ message,+ );+};++const hasGenericPositive = (message: string) => {+ return /有帮助|不错|挺好|清楚|works well|helpful|good/i.test(message);+};++const hasNegativePreference = (message: string) => {+ return /不适合|别这么做|不要.*做|以后.*别|以后.*不要|not suitable|do not do this|don't do this|avoid this/i.test(+ message,+ );+};++const createClassification = (+ explicitness: AgentSignalSkillIntentExplicitness,+ route: AgentSignalSkillIntentRoute,+ reason: string,+ confidence: number,+ actionIntent?: AgentSignalSkillIntentClassification['actionIntent'],+ classifierError?: AgentSignalClassifierErrorSummary,+): AgentSignalSkillIntentClassification => ({+ ...(actionIntent ? { actionIntent } : {}),+ ...(classifierError ? { classifierError } : {}),+ confidence,+ explicitness,+ reason,+ route,+});++/**+ * Classifies obvious skill intent with conservative deterministic rules.+ *+ * Before:+ * - "把 SKILL.md 草稿转成真正的 skills/bundle。"+ * - "这个解释挺有帮助的。"+ *+ * After:+ * - `{ explicitness: "explicit_action", route: "direct_decision" }`+ * - `{ explicitness: "weak_positive", route: "accumulate" }`+ */+export const classifySkillIntentByRules = (+ input: SkillIntentClassifierInput,+): AgentSignalSkillIntentClassification | undefined => {+ const message = input.message.trim();++ if (hasNegativePreference(message) && !hasSkillArtifactReference(message)) {+ return createClassification(+ 'non_skill_preference',+ 'non_skill',+ 'negative future preference belongs outside skill management',+ 0.82,+ 'noop',+ );+ }++ if (hasSkillArtifactReference(message) && hasMergeVerb(message)) {+ return createClassification(+ 'explicit_action',+ 'direct_decision',+ 'explicit skill consolidation request',+ 0.9,+ 'consolidate',+ );+ }++ if (/[\w-]+-skill/i.test(message) && hasRefineVerb(message)) {+ return createClassification(+ 'explicit_action',+ 'direct_decision',+ 'explicit named skill refinement request',+ 0.9,+ 'refine',+ );+ }++ if (hasSkillArtifactReference(message) && hasRefineVerb(message)) {+ return createClassification(+ 'explicit_action',+ 'direct_decision',+ 'explicit skill refinement request',+ 0.88,+ 'refine',+ );+ }++ if (hasSkillArtifactReference(message) && hasConversionVerb(message)) {+ return createClassification(+ 'explicit_action',+ 'direct_decision',+ 'explicit skill artifact conversion request',+ 0.92,+ 'create',+ );+ }++ if (hasGenericPositive(message) && !hasFutureProcedureReuse(message)) {+ return createClassification(+ 'weak_positive',+ 'accumulate',+ 'generic positive feedback without durable future-use instruction',+ 0.78,+ 'maintain',+ );+ }++ return undefined;+};++/**+ * Options for resolving skill intent after deterministic rules.+ */+export interface ClassifySkillIntentOptions {+ /** Diagnostics sink for fallback classifier failures. */+ diagnostics?: ClassifierDiagnosticsService;+ /** Optional classifier used when deterministic rules are intentionally inconclusive. */+ fallback?: SkillIntentClassifierService;+ /** Runtime scope key for diagnostics. */+ scopeKey?: string;+ /** Source id for diagnostics. */+ sourceId?: string;+}++/**+ * Resolves skill intent using rules first and a small fallback classifier second.+ *+ * Use when:+ * - Domain routing selected `skill`+ * - Action planning needs a direct, accumulation, or non-skill route+ *+ * Expects:+ * - `input.message` is the user feedback text+ * - `input.serializedContext` is compact same-turn evidence, not full documents+ *+ * Returns:+ * - A safe classification. Fallback failures become weak-positive accumulation.+ */+export const classifySkillIntent = async (+ input: SkillIntentClassifierInput,+ options: ClassifySkillIntentOptions = {},+): Promise<AgentSignalSkillIntentClassification> => {+ const ruleResult = classifySkillIntentByRules(input);+ if (ruleResult) return ruleResult;++ if (!options.fallback) {+ return createClassification(+ 'weak_positive',+ 'accumulate',+ 'insufficient-evidence',+ 0.35,+ 'maintain',+ );+ }++ try {+ return SkillIntentClassificationSchema.parse(+ await options.fallback.classify({+ message: input.message,+ serializedContext: input.serializedContext,+ topicLabel: input.topicLabel ?? getTopicLabel(input.serializedContext),+ }),+ );+ } catch (error) {+ const classifierError = normalizeClassifierError(error);++ await options.diagnostics?.recordMalformedOutput({+ error,+ reason: 'malformed skill-intent classifier output',+ scopeKey: options.scopeKey ?? 'unknown',+ sourceId: options.sourceId,+ stage: 'skill-intent',+ });++ return createClassification(+ 'weak_positive',+ 'accumulate',+ 'classifier-fallback-failed',+ 0.35,+ 'maintain',+ classifierError,+ );+ }+};++/**+ * Model configuration for the skill-intent classifier agent.+ */+export interface SkillIntentClassifierAgentModelConfig {+ model: string;+ provider: string;+}++const normalizeGenerateObjectMessages = (+ messages: GenerateObjectPayload['messages'],+): GenerateObjectPayload['messages'] => {+ return messages.map((message) => {+ if (!isGenerateObjectRole(message.role)) {+ throw new TypeError(`Unsupported skill-intent classifier message role: ${message.role}`);+ }++ return message;+ });+};++const createSkillIntentClassifierMessages = (+ input: SkillIntentClassifierInput,+): GenerateObjectPayload['messages'] => [+ {+ content:+ 'Classify skill intent for Agent Signal. Return direct_decision only for explicit skill actions or implicit strong future-use procedural learning. Return accumulate for generic praise or weak approval. Return non_skill for user preference that does not belong to skill management. Do not author skills.',+ role: 'system',+ },+ {+ content: JSON.stringify({+ message: input.message,+ serializedContext: compactText(input.serializedContext),+ topicLabel: input.topicLabel,+ }),+ role: 'user',+ },+];++/**+ * Model-backed skill-intent classifier for ambiguous skill-domain feedback.+ *+ * Use when:+ * - Deterministic rules cannot safely classify the skill-domain feedback+ * - A small no-document-content model decision is acceptable+ *+ * Expects:+ * - `db` and `userId` identify the current Agent Signal user context+ * - `serializedContext` is already compact+ *+ * Returns:+ * - One parsed skill-intent classification+ */+export class SkillIntentClassifierAgentService implements SkillIntentClassifierService {+ private readonly db: LobeChatDatabase;+ private readonly modelConfig: SkillIntentClassifierAgentModelConfig;+ private readonly userId: string;++ constructor(+ db: LobeChatDatabase,+ userId: string,+ modelConfig: Partial<SkillIntentClassifierAgentModelConfig> = {},+ ) {+ 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,+ };+ }++ /**+ * Classifies one ambiguous skill-domain feedback message.+ *+ * Use when:+ * - Rule classification returned no confident decision+ * - Runtime policy wiring provided model dependencies+ *+ * Expects:+ * - No full document content in the serialized context+ *+ * Returns:+ * - One Zod-validated skill-intent classification+ */+ async classify(input: SkillIntentClassifierInput): Promise<AgentSignalSkillIntentClassification> {+ const modelRuntime = await initModelRuntimeFromDB(+ this.db,+ this.userId,+ this.modelConfig.provider,+ );++ log(+ 'classifySkillIntent model=%s provider=%s',+ this.modelConfig.model,+ this.modelConfig.provider,+ );++ const result = await modelRuntime.generateObject(+ {+ messages: normalizeGenerateObjectMessages(createSkillIntentClassifierMessages(input)),+ model: this.modelConfig.model,+ schema: SkillIntentGenerateObjectSchema,+ },+ { metadata: { trigger: RequestTrigger.AgentSignal } },+ );++ return SkillIntentClassificationSchema.parse(result);+ }+}diff --git a/src/server/services/agentSignal/policies/index.ts b/src/server/services/agentSignal/policies/index.tsindex dbc2842c561..bcbc84bbc34 100644--- a/src/server/services/agentSignal/policies/index.ts+++ b/src/server/services/agentSignal/policies/index.ts@@ -21,6 +21,7 @@ export interface CreateDefaultAgentSignalPoliciesOptions extends CreateFeedbackDclassifierDiagnostics?: CreateAnalyzeIntentPolicyOptions['classifierDiagnostics'];feedbackSatisfactionJudge?: CreateFeedbackSatisfactionJudgePolicyOptions;procedure?: CreateAnalyzeIntentPolicyOptions['procedure'];+ skillIntentClassifier?: CreateAnalyzeIntentPolicyOptions['skillIntentClassifier'];skillManagement?: SkillManagementActionHandlerOptions;userMemory?: UserMemoryActionHandlerOptions;}diff --git a/src/server/services/agentSignal/policies/types.ts b/src/server/services/agentSignal/policies/types.tsindex c3c7c47bd26..0949387af8c 100644--- a/src/server/services/agentSignal/policies/types.ts+++ b/src/server/services/agentSignal/policies/types.ts@@ -52,6 +52,49 @@ export type AgentSignalFeedbackDomainTarget = 'memory' | 'none' | 'prompt' | 'skexport type AgentSignalFeedbackPhase1DomainTarget = 'memory' | 'prompt' | 'skill';+export type AgentSignalSkillIntentExplicitness =+ | 'explicit_action'+ | 'implicit_strong_learning'+ | 'non_skill_preference'+ | 'weak_positive';++export type AgentSignalSkillActionIntent =+ | 'consolidate'+ | 'create'+ | 'maintain'+ | 'noop'+ | 'refine';++export type AgentSignalSkillIntentRoute = 'accumulate' | 'direct_decision' | 'non_skill';++/** Sanitized classifier error details safe enough for traces and eval diagnostics. */+export interface AgentSignalClassifierErrorSummary {+ /** Sanitized one-hop cause summary when the runtime attached `error.cause`. */+ cause?: string;+ /** Error message with likely secrets redacted and length bounded. */+ message: string;+ /** Error class or runtime-provided error type. */+ name?: string;+}++/**+ * Compact routing decision for one skill-domain feedback signal.+ */+export interface AgentSignalSkillIntentClassification {+ /** Durable skill-management action hint selected before the decision agent runs. */+ actionIntent?: AgentSignalSkillActionIntent;+ /** Sanitized classifier failure details when fallback classification failed. */+ classifierError?: AgentSignalClassifierErrorSummary;+ /** Confidence of the rule or model classifier, from 0 to 1. */+ confidence: number;+ /** Whether the feedback is explicit, implicit strong learning, weak positive, or non-skill preference. */+ explicitness: AgentSignalSkillIntentExplicitness;+ /** Short private-safe reason suitable for traces and eval assertions. */+ reason: string;+ /** Runtime route used by action planning. */+ route: AgentSignalSkillIntentRoute;+}+export interface AgentSignalFeedbackEvidence {cue: string;excerpt: string;@@ -72,6 +115,12 @@ export interface AgentSignalFeedbackDomainStagePayload<confidence: number;evidence: AgentSignalFeedbackEvidence[];reason: string;+ skillActionIntent?: AgentSignalSkillActionIntent;+ skillIntentConfidence?: number;+ skillIntentError?: AgentSignalClassifierErrorSummary;+ skillIntentExplicitness?: AgentSignalSkillIntentExplicitness;+ skillIntentReason?: string;+ skillRoute?: AgentSignalSkillIntentRoute;target: TTarget;}@@ -144,6 +193,12 @@ export interface AgentSignalPolicySignalPayloadMap {reason: string;satisfactionResult: AgentSignalFeedbackSatisfactionResult;serializedContext?: string;+ skillActionIntent?: AgentSignalSkillActionIntent;+ skillIntentError?: AgentSignalClassifierErrorSummary;+ skillIntentConfidence?: number;+ skillIntentExplicitness?: AgentSignalSkillIntentExplicitness;+ skillIntentReason?: string;+ skillRoute?: AgentSignalSkillIntentRoute;sourceHints?: AgentSignalFeedbackSourceHints;target: 'skill';topicId?: string;diff --git a/src/server/services/agentSignal/processors/__tests__/actions.test.ts b/src/server/services/agentSignal/processors/__tests__/actions.test.tsindex 8ca976b3871..6931789041e 100644--- a/src/server/services/agentSignal/processors/__tests__/actions.test.ts+++ b/src/server/services/agentSignal/processors/__tests__/actions.test.ts@@ -4,7 +4,7 @@ import { describe, expect, expectTypeOf, it } from 'vitest';import type { SignalFeedbackDomainMemory, SignalFeedbackDomainSkill } from '../../policies/types';import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../../policies/types';import {- type NonSatisfiedSkillFeedbackDomainSignal,+ type DirectSkillFeedbackDomainSignal,planSkillManagement,planUserMemory,} from '../actions';@@ -116,7 +116,7 @@ const createSkillSignal = (const createNonSatisfiedSkillSignal = (input: Parameters<typeof createSkillSignal>[0] = {},-): NonSatisfiedSkillFeedbackDomainSignal => {+): DirectSkillFeedbackDomainSignal => {const signal = createSkillSignal({...input,satisfactionResult: input.satisfactionResult ?? 'not_satisfied',@@ -261,15 +261,15 @@ describe('action planning processors', () => {/*** @example- * Satisfied skill feedback cannot be passed to planSkillManagement.+ * Skill action planning accepts skill-domain signals after handler-level route narrowing.*/- it('narrows skill action planning to non-satisfied skill feedback signals', () => {+ it('narrows skill action planning to direct skill-domain signals', () => {const satisfiedSignal = createSatisfiedSkillSignal();expectTypeOf<Parameters<typeof planSkillManagement>[0]- >().toMatchTypeOf<NonSatisfiedSkillFeedbackDomainSignal>();- expectTypeOf<typeof satisfiedSignal>().not.toMatchTypeOf<+ >().toMatchTypeOf<DirectSkillFeedbackDomainSignal>();+ expectTypeOf<typeof satisfiedSignal>().toMatchTypeOf<Parameters<typeof planSkillManagement>[0]>();expect(satisfiedSignal.payload.satisfactionResult).toBe('satisfied');diff --git a/src/server/services/agentSignal/processors/actions.ts b/src/server/services/agentSignal/processors/actions.tsindex cbce354ff89..07b2dbd32b9 100644--- a/src/server/services/agentSignal/processors/actions.ts+++ b/src/server/services/agentSignal/processors/actions.ts@@ -17,9 +17,8 @@ interface SourcePayloadCarrier {/*** Skill-domain feedback signal that is eligible for direct skill-management action planning.*/-export type NonSatisfiedSkillFeedbackDomainSignal = SignalFeedbackDomainSkill & {+export type DirectSkillFeedbackDomainSignal = SignalFeedbackDomainSkill & {payload: SignalFeedbackDomainSkill['payload'] & {- satisfactionResult: 'neutral' | 'not_satisfied';target: 'skill';};};@@ -102,7 +101,7 @@ export const planUserMemory = (signal: SignalFeedbackDomainMemory): ActionUserMe* - A typed skill-management action node with stable chain, signal, source, and idempotency metadata*/export const planSkillManagement = (- signal: NonSatisfiedSkillFeedbackDomainSignal,+ signal: DirectSkillFeedbackDomainSignal,): ActionSkillManagementHandle => {const { payload } = signal;@@ -119,7 +118,7 @@ export const planSkillManagement = (agentId: payload.agentId,conflictPolicy: payload.conflictPolicy,evidence: payload.evidence,- feedbackHint: 'not_satisfied',+ feedbackHint: payload.satisfactionResult === 'satisfied' ? 'satisfied' : 'not_satisfied',idempotencyKey: `${signal.chain.rootSourceId}:skill:${payload.messageId}`,message: payload.message,messageId: payload.messageId,diff --git a/src/server/services/agentSignal/processors/classifiers.ts b/src/server/services/agentSignal/processors/classifiers.tsindex 7f4975f9b0b..7dbba82f1c9 100644--- a/src/server/services/agentSignal/processors/classifiers.ts+++ b/src/server/services/agentSignal/processors/classifiers.ts@@ -235,6 +235,12 @@ const buildDomainSignal = (messageId: signal.payload.messageId,reason: target.reason,satisfactionResult: signal.payload.result,+ skillActionIntent: target.skillActionIntent,+ skillIntentError: target.skillIntentError,+ skillIntentConfidence: target.skillIntentConfidence,+ skillIntentExplicitness: target.skillIntentExplicitness,+ skillIntentReason: target.skillIntentReason,+ skillRoute: target.skillRoute,sourceHints: signal.payload.sourceHints,target: 'skill',topicId: signal.payload.topicId,diff --git a/src/server/services/agentSignal/services/classifierServices.ts b/src/server/services/agentSignal/services/classifierServices.tsindex f2f3580c6d9..4127d96e7d8 100644--- a/src/server/services/agentSignal/services/classifierServices.ts+++ b/src/server/services/agentSignal/services/classifierServices.ts@@ -2,6 +2,7 @@ import type {AgentSignalFeedbackDomainStagePayload,AgentSignalFeedbackDomainTarget,AgentSignalFeedbackSatisfactionStagePayload,+ AgentSignalSkillIntentClassification,SignalFeedbackSatisfaction,} from '../policies/types';@@ -19,6 +20,24 @@ export interface SatisfactionClassifierInput {serializedContext?: string;}+/**+ * Input consumed by skill-intent routing classifiers.+ */+export interface SkillIntentClassifierInput {+ /**+ * Trimmed user feedback message to classify.+ */+ message: string;+ /**+ * Optional compact same-turn evidence or execution summary.+ */+ serializedContext?: string;+ /**+ * Optional compact topic/task label for model-backed classification.+ */+ topicLabel?: string;+}+/*** Input recorded when classifier structured output is malformed.*/@@ -34,7 +53,7 @@ export interface ClassifierMalformedOutputDiagnosticInput {/** Source id for the source or current signal root. */sourceId?: string;/** Classifier stage that produced malformed structured output. */- stage: 'domain' | 'satisfaction';+ stage: 'domain' | 'satisfaction' | 'skill-intent';}/**@@ -92,3 +111,24 @@ export interface DomainClassifierService {input: SignalFeedbackSatisfaction,) => Promise<Array<AgentSignalFeedbackDomainStagePayload<AgentSignalFeedbackDomainTarget>>>;}++/**+ * Classifies one skill-domain feedback signal into a direct, accumulation, or non-skill route.+ */+export interface SkillIntentClassifierService {+ /**+ * Classifies skill intent after domain routing.+ *+ * Use when:+ * - A feedback-domain signal target is `skill`+ * - Satisfaction alone is not enough to choose action planning or accumulation+ *+ * Expects:+ * - `input.message` is trimmed+ * - `input.serializedContext` is compact and may be omitted+ *+ * Returns:+ * - One compact routing classification with no document content leakage+ */+ classify: (input: SkillIntentClassifierInput) => Promise<AgentSignalSkillIntentClassification>;+}diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 42a7f02ecc7..09a763d29d1 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -144,6 +144,8 @@ interface InternalExecAgentParams extends ExecAgentParams {botPlatformContext?: any;/** Cron job ID that triggered this execution (if trigger is 'cron') */cronJobId?: string;+ /** Disable only local-system while preserving other tools. Useful for signal-only evals. */+ disableLocalSystem?: boolean;/** Disable all tools (no plugins, no system manifests). Useful for eval/benchmark scenarios. */disableTools?: boolean;/** Discord context for injecting channel/guild info into agent system message */@@ -308,6 +310,7 @@ export class AiAgentService {taskId,evalContext,maxSteps,+ disableLocalSystem,initialStepCount,signal,userInterventionConfig = { approvalMode: 'headless' },@@ -831,6 +834,7 @@ export class AiAgentService {gatewayConfigured: true,}: undefined,+ disableLocalSystem,globalMemoryEnabled,hasAgentDocuments,hasEnabledKnowledgeBases,@@ -843,7 +847,7 @@ export class AiAgentService {const pluginIds = [...new Set([...agentPlugins,- LocalSystemManifest.identifier,+ ...(disableLocalSystem ? [] : [LocalSystemManifest.identifier]),RemoteDeviceManifest.identifier,// Include LobeHub Skills and Klavis tools so they are passed to generateToolsDetailed...lobehubSkillManifests.map((m) => m.identifier),@@ -876,6 +880,10 @@ export class AiAgentService {// (e.g., lobe-creds, lobe-cron). Exclude discoverable:false tools to prevent// internal infrastructure tools from being surfaced to the activator.for (const tool of builtinTools) {+ if (disableLocalSystem && tool.identifier === LocalSystemManifest.identifier) {+ continue;+ }+if (tool.discoverable !== false && !toolManifestMap[tool.identifier]) {toolManifestMap[tool.identifier] = tool.manifest as LobeToolManifest;}