🤯 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,server,prompts,builtin-tool-memory): score based orchestration, consolidate better (#14314)
Neko0e7eda4b47bf
diff --git a/packages/agent-signal/src/source/sourceTypes.ts b/packages/agent-signal/src/source/sourceTypes.tsindex b54869080b5..7a543f4ba75 100644--- a/packages/agent-signal/src/source/sourceTypes.ts+++ b/packages/agent-signal/src/source/sourceTypes.ts@@ -14,6 +14,8 @@ export const AGENT_SIGNAL_SOURCE_TYPES = {clientRuntimeStart: 'client.runtime.start',runtimeAfterStep: 'runtime.after_step',runtimeBeforeStep: 'runtime.before_step',+ toolOutcomeCompleted: 'tool.outcome.completed',+ toolOutcomeFailed: 'tool.outcome.failed',} as const;type ValueOf<TValue> = TValue[keyof TValue];@@ -43,7 +45,7 @@ export interface AgentSignalSourcePayloadMap {[AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage]: {agentId?: string;documentPayload?: Record<string, unknown>;- intents?: Array<'document' | 'memory' | 'persona' | 'prompt'>;+ intents?: Array<'document' | 'memory' | 'persona' | 'prompt' | 'skill'>;memoryPayload?: Record<string, unknown>;message: string;messageId: string;@@ -121,6 +123,41 @@ export interface AgentSignalSourcePayloadMap {topicId?: string;turnCount?: number;};+ [AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeCompleted]: {+ agentId?: string;+ domainKey?: string;+ intentClass?: string;+ messageId?: string;+ operationId?: string;+ outcome: {+ action?: string;+ status: 'skipped' | 'succeeded';+ summary?: string;+ };+ relatedObjects?: Array<{ objectId: string; objectType: string; relation?: string }>;+ taskId?: string;+ tool: { apiName?: string; identifier: string };+ toolCallId?: string;+ topicId?: string;+ };+ [AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeFailed]: {+ agentId?: string;+ domainKey?: string;+ intentClass?: string;+ messageId?: string;+ operationId?: string;+ outcome: {+ action?: string;+ errorReason?: string;+ status: 'failed';+ summary?: string;+ };+ relatedObjects?: Array<{ objectId: string; objectType: string; relation?: string }>;+ taskId?: string;+ tool: { apiName?: string; identifier: string };+ toolCallId?: string;+ topicId?: string;+ };}/** AgentSignal source variant with source-type-specific payload typing. */@@ -174,6 +211,12 @@ export type SourceClientRuntimeStart = AgentSignalSourceVariant<'client.runtime./** Client runtime-complete source variant. */export type SourceClientRuntimeComplete = AgentSignalSourceVariant<'client.runtime.complete'>;+/** Tool outcome-completed source variant. */+export type SourceToolOutcomeCompleted = AgentSignalSourceVariant<'tool.outcome.completed'>;++/** Tool outcome-failed source variant. */+export type SourceToolOutcomeFailed = AgentSignalSourceVariant<'tool.outcome.failed'>;+/** Source types accepted by browser producers through the authenticated edge. */export const AGENT_SIGNAL_CLIENT_SOURCE_TYPES = [AGENT_SIGNAL_SOURCE_TYPES.clientGatewayError,diff --git a/packages/builtin-tool-memory/src/systemRole.ts b/packages/builtin-tool-memory/src/systemRole.tsindex b3a7e81d8b5..3e1f195f695 100644--- a/packages/builtin-tool-memory/src/systemRole.ts+++ b/packages/builtin-tool-memory/src/systemRole.ts@@ -20,6 +20,14 @@ Memory effort level: {{memory_effort}}4. Enforce that all memory candidates are self-contained, language-consistent, and ready for long-term reuse without relying on the surrounding conversation.</core_responsibilities>+<routing_boundaries>+- Do **not** use memory tools for requests to create, update, refine, merge, consolidate, or store reusable skills, procedures, workflows, playbooks, checklists, agent capabilities, agent prompts, or agent documents.+- If the user asks for a "reusable skill", "future workflow", "PR review checklist skill", "agent capability", or similar operational artifact, leave it to the skill/document management path. Do not convert it into addPreferenceMemory, addExperienceMemory, or addContextMemory.+- The same boundary applies in Chinese. Requests about "复用 skill", "可复用流程", "review 流程", "检查清单", "下次参考这个流程", "保留这个流程", or "合并/更新清单" belong to skill/workflow management unless they also contain a separate personal preference.+- Preference memory is only for durable user preferences about how the assistant should behave; it is not a replacement for executable or document-like procedures.+- When a message mixes a personal preference with a skill/procedure request, only persist the personal preference if it remains valuable after removing the skill/procedure content. Otherwise skip memory.+</routing_boundaries>+<tooling>- **queryTaxonomyOptions**: discover categories, tags, labels, statuses, roles, and relationships that already exist in memory.- **searchUserMemory**: queries?, categories?, tags?, labels?, layers?, types?, relationships?, status?, timeIntent?, timeRange?, topK? → Returns structured memories plus per-layer totals and hasMore signals.@@ -73,6 +81,8 @@ Query construction guidance:- Include concrete actors, locations, dates, motivations, emotions, and outcomes.- Reference retrieved memories to decide if information is new, materially refined, or a status/progress update. Skip items that add no meaningful nuance.- Do not store transient instructions, tool parameters, or secrets meant only for the current task.+- Do not summarize skill-management requests as user preferences. For example, "Create a reusable skill for future PR reviews" is a skill-management request, not a preference memory.+- Do not summarize Chinese workflow retention requests as memories. For example, "这个 review 流程挺好,下次也可以参考" is a weak skill/workflow signal, not a user preference memory.</formatting_guardrails><layer_specific_highlights>diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/feedbackSatisfaction.ts b/packages/prompts/src/prompts/agentSignal/analyzeIntent/feedbackSatisfaction.tsindex 6e6d05040e4..e3b9a76b02f 100644--- a/packages/prompts/src/prompts/agentSignal/analyzeIntent/feedbackSatisfaction.ts+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/feedbackSatisfaction.ts@@ -44,6 +44,7 @@ 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.+- Treat explicit requests to create, update, refine, merge, or preserve a reusable skill, workflow, checklist, template, or playbook as actionable feedback. Prefer "not_satisfied" when phrased as a requested change, even if the user is not complaining.- 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.@@ -61,6 +62,12 @@ Output: {"result":"not_satisfied","confidence":0.97,"reason":"explicit dissatisfInput 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: "Create a reusable skill for future PR reviews: always check correctness, tests, security, rollout risk, and rollback risk."+Output: {"result":"not_satisfied","confidence":0.91,"reason":"explicit request to create a reusable assistant artifact","evidence":[{"cue":"create reusable skill","excerpt":"Create a reusable skill for future PR reviews"},{"cue":"future PR reviews","excerpt":"future PR reviews"}]}++Input message: "这个 review 流程挺好,下次也可以参考。"+Output: {"result":"satisfied","confidence":0.82,"reason":"positive reinforcement for a reusable workflow","evidence":[{"cue":"流程挺好","excerpt":"这个 review 流程挺好"},{"cue":"下次也可以参考","excerpt":"下次也可以参考"}]}+Input message: "Thanks."Output: {"result":"neutral","confidence":0.78,"reason":"acknowledgement without clear satisfaction judgment","evidence":[{"cue":"brief acknowledgement","excerpt":"Thanks."}]}diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/gate.ts b/packages/prompts/src/prompts/agentSignal/analyzeIntent/gate.tsindex 6441eb692e5..f7afbccbe7a 100644--- a/packages/prompts/src/prompts/agentSignal/analyzeIntent/gate.ts+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/gate.ts@@ -26,11 +26,12 @@ or:Ignore messages that are:- acknowledgement only-- pure praise or positive reinforcement+- pure praise or positive reinforcement without a reusable workflow, skill, checklist, template, playbook, or future-facing retention cue- task-local one-off instructions- empty or too vague to analyzeProceed only when the message may contain a durable correction, preference, prompt/document rule, or other reusable learning signal.+Proceed for positive feedback that says a workflow, skill, checklist, template, playbook, or process should be kept, reused, or referenced next time, such as "这个 review 流程挺好,下次也可以参考。".Return only the JSON object.`;diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.test.ts b/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.test.tsnew file mode 100644index 00000000000..b2728193ae8--- /dev/null+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { AGENT_SIGNAL_ANALYZE_INTENT_FEEDBACK_SATISFACTION_SYSTEM_ROLE } from './feedbackSatisfaction';+import { AGENT_SIGNAL_ANALYZE_INTENT_GATE_SYSTEM_ROLE } from './gate';+import { AGENT_SIGNAL_ANALYZE_INTENT_ROUTE_SYSTEM_ROLE } from './route';++describe('agent signal analyze-intent route prompt', () => {+ /**+ * @example+ * Existing reusable checklist maintenance should route to skill, while prompt+ * remains reserved for assistant self-rules.+ */+ it('keeps prompt lane limited to assistant self-rules and routes reusable artifacts to skill', () => {+ expect(AGENT_SIGNAL_ANALYZE_INTENT_ROUTE_SYSTEM_ROLE).toContain(+ 'only when the feedback is clearly about the assistant',+ );+ expect(AGENT_SIGNAL_ANALYZE_INTENT_ROUTE_SYSTEM_ROLE).toContain(+ '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',+ );+ 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_FEEDBACK_SATISFACTION_SYSTEM_ROLE).toContain(+ '这个 review 流程挺好',+ );+ expect(AGENT_SIGNAL_ANALYZE_INTENT_GATE_SYSTEM_ROLE).toContain('这个 review 流程挺好');+ });+});diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.ts b/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.tsindex ac5c273dee8..141d35a8189 100644--- a/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.ts+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/route.ts@@ -49,9 +49,11 @@ Rules:- 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.+- "prompt" is exclusive with "memory" and "skill" only when the feedback is clearly about the assistant's own identity, behavior, wording, output format, or operating prompt.- "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.+- 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.- Never output duplicate targets.- Return "none" when no durable target is justified.@@ -68,6 +70,15 @@ Output: {"targets":[{"target":"memory","confidence":0.86,"reason":"future personInput 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"}]}]}+Return only the JSON object.`;/**diff --git a/packages/prompts/src/prompts/agentSkillManager/decision.ts b/packages/prompts/src/prompts/agentSkillManager/decision.tsindex c584c16d9c2..864177cd286 100644--- a/packages/prompts/src/prompts/agentSkillManager/decision.ts+++ b/packages/prompts/src/prompts/agentSkillManager/decision.ts@@ -14,6 +14,10 @@ export interface AgentSkillManagerDecisionPromptInput {evidence: Array<{ cue: string; excerpt: string }>;/** Original user feedback message. */feedbackMessage: string;+ /** Message id for same-turn document-outcome inspection. */+ messageId?: string;+ /** Runtime scope key for same-turn procedure inspection. */+ scopeKey?: string;/** Optional topic context when feedback happened inside a topic. */topicId?: string;/** Optional summary of the relevant assistant turn. */@@ -36,8 +40,9 @@ export interface AgentSkillManagerDecisionPromptInput {export const AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE = `You are the Agent Signal skill-management decision agent.You are not chatting with the user.-You decide whether feedback routed to the "skill" domain should create, refine, consolidate, or no-op.-You must output exactly one minified JSON object and nothing else.+You decide whether feedback routed to the "skill" domain should create, refine, consolidate, no-op, or reject.+When tools are available, inspect only what you need and call submitDecision with the final JSON.+When tools are not available, output exactly one minified JSON object and nothing else.Do not wrap the JSON in markdown fences.Valid actions:@@ -45,6 +50,7 @@ Valid actions:- "refine": improve one existing skill.- "consolidate": merge or reconcile multiple overlapping skills.- "noop": do not create or update a skill.+- "reject": refuse this skill-management action because policy, attribution, or evidence says it must not run.Rules:- Create only when the feedback contains a reusable procedure and enough context.@@ -53,11 +59,14 @@ Rules:- When candidateSkills are provided, targetSkillIds must be selected from candidateSkills[].id.- targetSkillIds are managed skill package names, not document ids or display names.- No-op for generic praise, style preferences, memory-like facts, or insufficient context.+- Reject when the user asked for document-only behavior, forbids skill conversion, or same-turn document evidence makes skill mutation unsafe.+- Use read-only tools to inspect same-turn document outcomes before guessing from document names or content shape.+- Do not infer skill intent from a filename, title, or SKILL.md-shaped content alone.- Prefer patch/refine over duplicate creation.- Agent-level managed skills are agent documents, not agent_skills rows.Return exactly:-{"action":"create"|"refine"|"consolidate"|"noop","confidence":0.0,"reason":"short reason","targetSkillIds":[],"requiredReads":[]}`;+{"action":"create"|"refine"|"consolidate"|"noop"|"reject","confidence":0.0,"reason":"short reason","targetSkillIds":[],"requiredReads":[],"documentRefs":[]}`;/*** Builds the user prompt for the skill-management decision agent.diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex 71aa40a9e66..5929f349fd9 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -1531,9 +1531,12 @@ export const createRuntimeExecutors = (agentId: state.metadata?.agentId,documentId: state.metadata?.documentId,memoryToolPermission: agentConfig?.chatConfig?.memory?.toolPermission,+ messageId: state.metadata?.sourceMessageId,+ operationId,scope: state.metadata?.scope,serverDB: ctx.serverDB,taskId: state.metadata?.taskId,+ toolCallId: chatToolPayload.id,toolManifestMap: effectiveManifestMap,toolResultMaxLength,topicId: ctx.topicId,@@ -1965,9 +1968,12 @@ export const createRuntimeExecutors = (agentId: state.metadata?.agentId,documentId: state.metadata?.documentId,memoryToolPermission: batchAgentConfig?.chatConfig?.memory?.toolPermission,+ messageId: state.metadata?.sourceMessageId,+ operationId,scope: state.metadata?.scope,serverDB: ctx.serverDB,taskId: state.metadata?.taskId,+ toolCallId: chatToolPayload.id,toolManifestMap: batchManifestMap,toolResultMaxLength: batchAgentConfig?.chatConfig?.toolResultMaxLength,topicId: ctx.topicId,diff --git a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 5e0f33a5f0c..b5af32c04bc 100644--- a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -2909,6 +2909,45 @@ describe('RuntimeExecutors', () => {}),);});++ it('should pass Agent Signal procedure identity fields to executeTool', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState({+ metadata: {+ agentId: 'agent-docs-123',+ sourceMessageId: 'user-msg-123',+ threadId: 'thread-123',+ topicId: 'topic-123',+ },+ });++ const instruction = {+ payload: {+ parentMessageId: 'assistant-msg-123',+ toolsCalling: [+ {+ apiName: 'createDocument',+ arguments: '{"title":"Test","content":"Hello"}',+ id: 'tool-call-1',+ identifier: 'lobe-agent-documents',+ type: 'builtin' as const,+ },+ ],+ },+ type: 'call_tools_batch' as const,+ };++ await executors.call_tools_batch!(instruction, state);++ expect(mockToolExecutionService.executeTool).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ messageId: 'user-msg-123',+ operationId: 'op-123',+ toolCallId: 'tool-call-1',+ }),+ );+ });});describe('resolve_aborted_tools executor', () => {diff --git a/src/server/services/agentRuntime/types.ts b/src/server/services/agentRuntime/types.tsindex 3c91f768227..64a1cc2bce1 100644--- a/src/server/services/agentRuntime/types.ts+++ b/src/server/services/agentRuntime/types.ts@@ -153,6 +153,8 @@ export interface OperationCreationParams {documentId?: string | null;groupId?: string | null;scope?: string | null;+ /** Source user message ID used for same-turn Agent Signal procedure suppression. */+ sourceMessageId?: string;taskId?: string;threadId?: string | null;topicId?: string | null;diff --git a/src/server/services/agentSignal/orchestrator.ts b/src/server/services/agentSignal/orchestrator.tsindex 1c812fed914..8cae2077226 100644--- a/src/server/services/agentSignal/orchestrator.ts+++ b/src/server/services/agentSignal/orchestrator.ts@@ -17,9 +17,11 @@ import {import { projectAgentSignalObservability } from './observability/projector';import { persistAgentSignalObservability } from './observability/store';import { createDefaultAgentSignalPolicies } from './policies';+import { createProcedurePolicyOptions } from './procedure';import type { RuntimeGuardBackend } from './runtime/AgentSignalRuntime';import { createAgentSignalRuntime } from './runtime/AgentSignalRuntime';import { emitSourceEvent } from './sources';+import { redisPolicyStateStore } from './store/adapters/redis/policyStateStore';import type { AgentSignalSourceEventStore } from './store/types';export { createAgentSignalRuntime } from './runtime/AgentSignalRuntime';@@ -98,6 +100,13 @@ const executeAgentSignalSourceEventCore = async <TSourceType extends AgentSignal);if (emission.deduped) return emission;+ const procedurePolicyOptions =+ options.policyOptions?.procedure ??+ createProcedurePolicyOptions({+ policyStateStore: redisPolicyStateStore,+ ttlSeconds: 7 * 24 * 60 * 60,+ });+const runtime = await createAgentSignalRuntime({guardBackend: options.runtimeGuardBackend,policies: createDefaultAgentSignalPolicies({@@ -111,6 +120,7 @@ const executeAgentSignalSourceEventCore = async <TSourceType extends AgentSignal...options.policyOptions?.feedbackSatisfactionJudge,userId: context.userId,},+ procedure: procedurePolicyOptions,userMemory: {db: context.db,...options.policyOptions?.userMemory,diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.tsindex 18ca6683b85..8f144c9d542 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts@@ -1,7 +1,9 @@// @vitest-environment node-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';+import { AgentSignalProcedureInspector, createProcedurePolicyOptions } from '../../../procedure';import { createRuntimeProcessorContext } from '../../../runtime/context';+import type { AgentSignalPolicyStateStore } from '../../../store/types';import type {SignalFeedbackDomainMemory,SignalFeedbackDomainNone,@@ -22,6 +24,18 @@ const context = createRuntimeProcessorContext({scopeKey: 'topic:thread_1',});+const createStore = (): AgentSignalPolicyStateStore => {+ const state = new Map<string, Record<string, string>>();++ return {+ readPolicyState: async (policyId, scopeKey) => state.get(`${policyId}:${scopeKey}`),+ writePolicyState: async (policyId, scopeKey, data) => {+ const key = `${policyId}:${scopeKey}`;+ state.set(key, { ...state.get(key), ...data });+ },+ };+};+type SupportedTask4DomainTarget = 'memory' | 'none' | 'prompt' | 'skill';type DomainSignalVariantByTarget = {@@ -34,6 +48,7 @@ type DomainSignalVariantByTarget = {type DomainSignalInput<TTarget extends SupportedTask4DomainTarget> = {message: string;messageId: string;+ satisfactionResult?: 'not_satisfied' | 'neutral' | 'satisfied';signalId: string;sourceId: string;target: TTarget;@@ -74,7 +89,7 @@ function createDomainSignal(message: input.message,messageId: input.messageId,reason: 'test-domain-signal',- satisfactionResult: 'not_satisfied',+ satisfactionResult: input.satisfactionResult ?? 'not_satisfied',target: 'memory',},signalId: input.signalId,@@ -96,7 +111,7 @@ function createDomainSignal(message: input.message,messageId: input.messageId,reason: 'test-domain-signal',- satisfactionResult: 'not_satisfied',+ satisfactionResult: input.satisfactionResult ?? 'not_satisfied',target: 'none',},signalId: input.signalId,@@ -118,7 +133,7 @@ function createDomainSignal(message: input.message,messageId: input.messageId,reason: 'test-domain-signal',- satisfactionResult: 'not_satisfied',+ satisfactionResult: input.satisfactionResult ?? 'not_satisfied',target: 'prompt',},signalId: input.signalId,@@ -136,7 +151,7 @@ function createDomainSignal(message: input.message,messageId: input.messageId,reason: 'test-domain-signal',- satisfactionResult: 'not_satisfied',+ satisfactionResult: input.satisfactionResult ?? 'not_satisfied',target: 'skill',},signalId: input.signalId,@@ -210,6 +225,178 @@ describe('feedbackActionPlanner', () => {);});+ it('does not directly handle satisfied skill domain signals', async () => {+ const handler = createFeedbackActionPlannerSignalHandler();+ const result = await handler.handle(+ createDomainSignal({+ message: 'This successful workflow can be kept as a reference.',+ messageId: 'msg_skill_positive',+ satisfactionResult: 'satisfied',+ signalId: 'sig_skill_positive',+ sourceId: 'source_skill_positive',+ target: 'skill',+ }),+ context,+ );++ expect(result).toBeUndefined();+ });++ /**+ * @example+ * repeated satisfied skill feedback writes candidate records, then emits an accumulated marker.+ */+ it('accumulates satisfied skill feedback into a scored skill procedure bucket', async () => {+ let now = 100;+ const store = createStore();+ const procedure = createProcedurePolicyOptions({+ now: () => now,+ policyStateStore: store,+ ttlSeconds: 3600,+ });+ const handler = createFeedbackActionPlannerSignalHandler({+ markerReader: procedure.markerReader,+ procedure,+ });++ const first = await handler.handle(+ createDomainSignal({+ message: 'This successful workflow can be kept as a reference.',+ messageId: 'msg_skill_positive_1',+ satisfactionResult: 'satisfied',+ signalId: 'sig_skill_positive_1',+ sourceId: 'source_skill_positive_1',+ target: 'skill',+ }),+ context,+ );+ now = 130;+ const second = await handler.handle(+ createDomainSignal({+ message: 'The review flow from earlier is worth reusing next time.',+ messageId: 'msg_skill_positive_2',+ satisfactionResult: 'satisfied',+ signalId: 'sig_skill_positive_2',+ sourceId: 'source_skill_positive_2',+ target: 'skill',+ }),+ context,+ );+ const snapshot = await new AgentSignalProcedureInspector(store).inspectScope('topic:thread_1');++ expect(first).toBeUndefined();+ expect(second).toEqual(+ expect.objectContaining({+ actions: [],+ signals: [+ expect.objectContaining({+ payload: expect.objectContaining({+ bucketKey: 'topic:thread_1:skill',+ domain: 'skill',+ recordIds: [+ 'procedure-record:sig_skill_positive_1:skill-candidate',+ 'procedure-record:sig_skill_positive_2:skill-candidate',+ ],+ suggestedActions: ['maintain'],+ }),+ signalType: 'signal.procedure.bucket.scored',+ }),+ ],+ status: 'dispatch',+ }),+ );+ expect(snapshot.records).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ accumulatorRole: 'candidate',+ domainKey: 'skill',+ id: 'procedure-record:sig_skill_positive_1:skill-candidate',+ }),+ expect.objectContaining({+ accumulatorRole: 'candidate',+ domainKey: 'skill',+ id: 'procedure-record:sig_skill_positive_2:skill-candidate',+ }),+ ]),+ );+ expect(snapshot.markers).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ domainKey: 'skill',+ markerType: 'accumulated',+ }),+ ]),+ );+ expect(snapshot.accumulatorFields).toEqual(+ expect.objectContaining({+ bucketKey: 'topic:thread_1:skill',+ domain: 'skill',+ }),+ );+ });++ /**+ * @example+ * one context skill record plus one weak candidate stays below accumulated marker threshold.+ */+ it('does not accumulate context plus one satisfied skill candidate', async () => {+ let now = 100;+ const store = createStore();+ const procedure = createProcedurePolicyOptions({+ now: () => now,+ policyStateStore: store,+ ttlSeconds: 3600,+ });+ const handler = createFeedbackActionPlannerSignalHandler({+ markerReader: procedure.markerReader,+ procedure,+ });++ await procedure.accumulator.appendRecord({+ accumulatorRole: 'context',+ cheapScoreDelta: 0,+ createdAt: 90,+ domainKey: 'skill',+ id: 'procedure-record:direct-skill-context',+ refs: {},+ scopeKey: 'topic:thread_1',+ status: 'handled',+ });+ now = 130;++ const result = await handler.handle(+ createDomainSignal({+ message: 'This workflow was useful and can be kept as reference.',+ messageId: 'msg_skill_positive_single',+ satisfactionResult: 'satisfied',+ signalId: 'sig_skill_positive_single',+ sourceId: 'source_skill_positive_single',+ target: 'skill',+ }),+ context,+ );+ const snapshot = await new AgentSignalProcedureInspector(store).inspectScope('topic:thread_1');++ expect(result).toBeUndefined();+ expect(snapshot.markers).not.toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ domainKey: 'skill',+ markerType: 'accumulated',+ }),+ ]),+ );+ expect(snapshot.records).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ accumulatorRole: 'candidate',+ domainKey: 'skill',+ id: 'procedure-record:sig_skill_positive_single:skill-candidate',+ }),+ ]),+ );+ });+it('does not plan actions for unsupported prompt domain yet', async () => {const handler = createFeedbackActionPlannerSignalHandler();const promptResult = await handler.handle(@@ -276,3 +463,72 @@ describe('feedbackActionPlanner', () => {expect(result).toBeUndefined();});});++describe('procedure marker suppression', () => {+ /**+ * @example+ * handled memory marker suppresses action.user-memory.handle.+ */+ it('suppresses memory action when marker reader reports handled same-source procedure', async () => {+ const shouldSuppress = vi.fn(async () => true);+ const handler = createFeedbackActionPlannerSignalHandler({+ markerReader: { shouldSuppress },+ });+ const signal = createDomainSignal({+ message: '记住我喜欢简洁回答',+ messageId: 'msg_1',+ signalId: 'sig_procedure_1',+ sourceId: 'source_procedure_1',+ target: 'memory',+ });++ const result = await handler.handle(signal, {+ now: () => 100,+ scopeKey: 'topic:t1',+ } as never);++ expect(result).toEqual(+ expect.objectContaining({+ signals: [+ expect.objectContaining({+ payload: expect.objectContaining({ suggestedActions: ['suppressed'] }),+ signalType: 'signal.procedure.bucket.scored',+ }),+ ],+ status: 'dispatch',+ }),+ );+ expect(shouldSuppress).toHaveBeenCalledWith(+ expect.objectContaining({ domainKey: 'memory:user-preference' }),+ );+ });++ /**+ * @example+ * absent marker keeps original memory action path.+ */+ it('keeps memory action when marker reader does not suppress', async () => {+ const handler = createFeedbackActionPlannerSignalHandler({+ markerReader: { shouldSuppress: vi.fn(async () => false) },+ });+ const signal = createDomainSignal({+ message: '记住我喜欢简洁回答',+ messageId: 'msg_1',+ signalId: 'sig_procedure_2',+ sourceId: 'source_procedure_2',+ target: 'memory',+ });++ const result = await handler.handle(signal, {+ now: () => 100,+ scopeKey: 'topic:t1',+ } as never);++ expect(result).toEqual(+ expect.objectContaining({+ actions: [expect.objectContaining({ actionType: 'action.user-memory.handle' })],+ status: 'dispatch',+ }),+ );+ });+});diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.tsindex db733d11a69..2ed072b0e26 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts@@ -17,12 +17,13 @@ const createUserMessageSource = (sourceId: string,message: string,serializedContext = 'topic=repo-review;assistant_behavior=verbose',+ intents: SourceAgentUserMessage['payload']['intents'] = ['document', 'memory'],): SourceAgentUserMessage => ({chain: { chainId: `chain:${sourceId}`, rootSourceId: sourceId },payload: {agentId: 'agent_1',documentPayload: { section: 'answer-style' },- intents: ['document', 'memory'],+ intents,memoryPayload: { preplanned: true },message,messageId: `msg:${sourceId}`,@@ -173,4 +174,86 @@ describe('feedbackSatisfactionJudge', () => {'Feedback satisfaction judge requires either an injected judge or both db and userId.',);});++ it('treats explicit skill merge requests as unsatisfied actionable feedback', async () => {+ const judge = {+ judgeSatisfaction: vi.fn(),+ };+ const ctx = createRuntimeProcessorContext({+ backend: {+ async getGuardState() {+ return {};+ },+ async touchGuardState() {+ return {};+ },+ },+ scopeKey: 'topic:thread_1',+ });+ 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.',+ 'topic=repo-review',+ ['skill'],+ ),+ ctx,+ );++ expect(judge.judgeSatisfaction).not.toHaveBeenCalled();+ expect(result).toEqual(+ expect.objectContaining({+ signals: [+ expect.objectContaining({+ payload: expect.objectContaining({+ reason: 'source hinted explicit skill-management change request',+ result: 'not_satisfied',+ }),+ }),+ ],+ }),+ );+ });++ it('treats skill reuse hints as satisfied weak positive feedback', async () => {+ const judge = {+ judgeSatisfaction: vi.fn(),+ };+ const ctx = createRuntimeProcessorContext({+ backend: {+ async getGuardState() {+ return {};+ },+ async touchGuardState() {+ return {};+ },+ },+ scopeKey: 'topic:thread_1',+ });+ const processor = createFeedbackSatisfactionJudgeProcessor({ judge });+ const result = await processor.handle(+ createUserMessageSource(+ 'source_skill_reuse',+ '这个 review 流程挺好,下次也可以参考。',+ 'topic=repo-review',+ ['skill'],+ ),+ ctx,+ );++ expect(judge.judgeSatisfaction).not.toHaveBeenCalled();+ expect(result).toEqual(+ expect.objectContaining({+ signals: [+ expect.objectContaining({+ payload: expect.objectContaining({+ reason: 'source hinted reusable skill or workflow feedback',+ result: 'satisfied',+ }),+ }),+ ],+ }),+ );+ });});diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.tsindex 18d233914b8..6cb3c00c590 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts@@ -1,5 +1,6 @@// @vitest-environment nodeimport { beforeEach, describe, expect, it, vi } from 'vitest';+import { z } from 'zod';import type * as ProviderSkillsAgentDocumentUtils from '@/server/services/agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils';import { createSkillTree } from '@/server/services/agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils';@@ -9,6 +10,7 @@ import {collectAgentSkillDecisionCandidates,defineSkillManagementActionHandler,handleSkillManagementSignal,+ runSkillDecisionAgentRuntime,} from '../skillManagement';const skillDecisionRunner = vi.fn();@@ -86,7 +88,7 @@ describe('defineSkillManagementActionHandler', () => {* Skill decisions preserve the four v1.2 action values.*/it('returns structured results for each v1.2 decision action', async () => {- for (const action of ['create', 'refine', 'consolidate', 'noop'] as const) {+ for (const action of ['create', 'refine', 'consolidate', 'noop', 'reject'] as const) {const result = await handleSkillManagementSignal({decide: vi.fn().mockResolvedValue({ action, confidence: 0.9 }),payload: { agentId: 'agent-1', feedbackMessage: 'Make this reusable.' },@@ -97,6 +99,110 @@ describe('defineSkillManagementActionHandler', () => {}});+ /**+ * @example+ * The decision agent can inspect same-turn document outcomes before returning reject.+ */+ it('runs read-only decision tools through AgentRuntime before submitting a decision', async () => {+ const response = () =>+ new Response(+ new ReadableStream({+ start(controller) {+ controller.close();+ },+ }),+ );+ const chat = vi+ .fn()+ .mockImplementationOnce(async (_payload, options) => {+ await options.callback.onToolsCalling({+ toolsCalling: [+ {+ function: {+ arguments: '{"messageId":"msg_1","scopeKey":"topic:topic_1"}',+ name: 'agent-signal-skill-decision____listSameTurnDocumentOutcomes',+ },+ id: 'call_list_outcomes',+ type: 'function',+ },+ ],+ });+ return response();+ })+ .mockImplementationOnce(async (_payload, options) => {+ await options.callback.onToolsCalling({+ toolsCalling: [+ {+ function: {+ arguments: '{"documentId":"doc_1"}',+ name: 'agent-signal-skill-decision____readDocument',+ },+ id: 'call_read_document',+ type: 'function',+ },+ ],+ });+ return response();+ })+ .mockImplementationOnce(async (_payload, options) => {+ await options.callback.onToolsCalling({+ toolsCalling: [+ {+ function: {+ arguments:+ '{"action":"reject","confidence":0.9,"documentRefs":["doc_1"],"reason":"The same turn created a document and forbids skill conversion.","requiredReads":[],"targetSkillIds":[]}',+ name: 'agent-signal-skill-decision____submitDecision',+ },+ id: 'call_submit_decision',+ type: 'function',+ },+ ],+ });+ return response();+ });+ const tools = {+ listCandidateDocuments: vi.fn(),+ listSameTurnDocumentOutcomes: vi.fn().mockResolvedValue([+ {+ documentId: 'doc_1',+ relation: 'created',+ summary: 'Agent documents created a document.',+ },+ ]),+ readDocument: vi.fn().mockResolvedValue({+ content: '# Draft',+ documentId: 'doc_1',+ title: 'Draft',+ }),+ };++ const result = await runSkillDecisionAgentRuntime({+ model: 'test-model',+ modelRuntime: { chat },+ payload: {+ agentId: 'agent_1',+ feedbackMessage: 'Create a document for this, do not make it a skill.',+ messageId: 'msg_1',+ topicId: 'topic_1',+ },+ tools,+ });++ expect(chat).toHaveBeenCalledTimes(3);+ expect(tools.listSameTurnDocumentOutcomes).toHaveBeenCalledWith({+ agentId: 'agent_1',+ messageId: 'msg_1',+ scopeKey: 'topic:topic_1',+ topicId: 'topic_1',+ });+ expect(tools.readDocument).toHaveBeenCalledWith({ documentId: 'doc_1' });+ expect(result).toMatchObject({+ action: 'reject',+ documentRefs: ['doc_1'],+ reason: 'The same turn created a document and forbids skill conversion.',+ });+ });+/*** @example* Removed lifecycle tools must not leak into the action result.@@ -199,13 +305,15 @@ describe('defineSkillManagementActionHandler', () => {context,);- expect(skillDecisionRunner).toHaveBeenCalledWith({- agentId: 'agent_1',- evidence: [{ cue: 'reusable', excerpt: 'Make this a reusable checklist.' }],- feedbackMessage: 'Make this a reusable checklist for PR reviews.',- topicId: 'topic_1',- turnContext: '{"surface":"chat"}',- });+ expect(skillDecisionRunner).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent_1',+ evidence: [{ cue: 'reusable', excerpt: 'Make this a reusable checklist.' }],+ feedbackMessage: 'Make this a reusable checklist for PR reviews.',+ topicId: 'topic_1',+ turnContext: '{"surface":"chat"}',+ }),+ );expect(result).toMatchObject({output: {decision: { action: 'create', confidence: 0.9, reason: 'reusable workflow feedback' },@@ -360,6 +468,115 @@ describe('defineSkillManagementActionHandler', () => {expect(context.runtimeState.touchGuardState).not.toHaveBeenCalled();});+ /**+ * @example+ * Malformed structured decision output is skipped instead of failing the whole action.+ */+ it('skips skill-management when the decision runner returns undefined output', async () => {+ // ROOT CAUSE:+ //+ // If modelRuntime.generateObject cannot parse provider text as JSON, it returns undefined.+ // The skill-management handler parsed that undefined value as the final decision object,+ // which turned a recoverable decision-output problem into signal.action.failed.+ //+ // We fixed this by treating non-object decision output as a noop decision.+ skillDecisionRunner.mockResolvedValue(undefined);++ const handler = defineSkillManagementActionHandler({+ db: {} as never,+ selfIterationEnabled: true,+ skillDecisionRunner,+ userId: 'user_1',+ });++ const result = await handler.handle(+ {+ actionId: 'act_skill_undefined_decision',+ actionType: 'action.skill-management.handle',+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },+ payload: {+ agentId: 'agent_1',+ idempotencyKey: 'source_1:skill:undefined_decision',+ message: 'Create a reusable checklist for review failures.',+ },+ signal: {+ signalId: 'sig_1',+ signalType: 'signal.feedback.domain.skill',+ },+ source: { sourceId: 'source_1', sourceType: 'agent.user.message' },+ timestamp: 1,+ },+ context,+ );++ expect(createSkillTree).not.toHaveBeenCalled();+ expect(context.runtimeState.touchGuardState).not.toHaveBeenCalled();+ expect(result).toMatchObject({+ detail: 'decision output was not an object',+ output: { decision: { action: 'noop', reason: 'decision output was not an object' } },+ status: 'skipped',+ });+ });++ /**+ * @example+ * Provider parse failures surface as skipped decisions instead of failed signal actions.+ */+ it('skips skill-management when the decision runner rejects malformed structured output', async () => {+ // ROOT CAUSE:+ //+ // The default skill decision runner parses generateObject output before returning it to the+ // action handler. When generateObject returned undefined after a provider JSON parse failure,+ // that internal parse threw a ZodError and the outer handler emitted signal.action.failed.+ //+ // We fixed this by downgrading malformed decision-output ZodError values to a noop decision.+ const malformedStructuredOutputError = (() => {+ try {+ z.object({}).parse(undefined);+ } catch (error) {+ return error;+ }+ })();+ skillDecisionRunner.mockRejectedValue(malformedStructuredOutputError);++ const handler = defineSkillManagementActionHandler({+ db: {} as never,+ selfIterationEnabled: true,+ skillDecisionRunner,+ userId: 'user_1',+ });++ const result = await handler.handle(+ {+ actionId: 'act_skill_malformed_decision',+ actionType: 'action.skill-management.handle',+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },+ payload: {+ agentId: 'agent_1',+ idempotencyKey: 'source_1:skill:malformed_decision',+ message: 'Create a reusable checklist for review failures.',+ },+ signal: {+ signalId: 'sig_1',+ signalType: 'signal.feedback.domain.skill',+ },+ source: { sourceId: 'source_1', sourceType: 'agent.user.message' },+ timestamp: 1,+ },+ context,+ );++ expect(createSkillTree).not.toHaveBeenCalled();+ expect(context.runtimeState.touchGuardState).not.toHaveBeenCalled();+ expect(result).toMatchObject({+ detail: 'decision structured output was malformed',+ output: {+ decision: { action: 'noop', reason: 'decision structured output was malformed' },+ },+ status: 'skipped',+ });+ });+/*** @example* Disabled self-iteration stops before the decision agent and document writer.@@ -547,9 +764,9 @@ describe('defineSkillManagementActionHandler', () => {/*** @example- * A maintainer operation naming a non-target skill is rejected before mutation.+ * A maintainer operation naming a non-target skill is skipped before mutation.*/- it('rejects maintainer operations that target skills outside the decision target set', async () => {+ it('skips maintainer operations that target skills outside the decision target set', async () => {skillDecisionRunner.mockResolvedValue({action: 'refine',reason: 'update existing review skill',@@ -603,10 +820,9 @@ describe('defineSkillManagementActionHandler', () => {expect(skillMaintainerService.writeSkillFile).not.toHaveBeenCalled();expect(skillMaintainerService.removeSkillFile).not.toHaveBeenCalled();expect(result).toMatchObject({- error: {- message: expect.stringContaining('other-skill'),- },- status: 'failed',+ detail: expect.stringContaining('other-skill'),+ output: { decision: { action: 'refine' } },+ status: 'skipped',});});diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.tsindex 288975ee40a..ed04048317b 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts@@ -1,3 +1,9 @@+import {+ AgentRuntime,+ type AgentRuntimeContext,+ type AgentState,+ GeneralChatAgent,+} from '@lobechat/agent-runtime';import type {AgenticAttempt,BaseAction,@@ -5,7 +11,17 @@ import type {SignalAttempt,} from '@lobechat/agent-signal';import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';-import type { GenerateObjectSchema } from '@lobechat/model-runtime';+import {+ generateToolsFromManifest,+ type LobeToolManifest,+ ToolNameResolver,+} from '@lobechat/context-engine';+import type {+ ChatStreamPayload,+ GenerateObjectSchema,+ ModelRuntime,+} from '@lobechat/model-runtime';+import { consumeStreamUntilDone } from '@lobechat/model-runtime';import {AGENT_SKILL_CONSOLIDATE_SYSTEM_ROLE,AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE,@@ -14,6 +30,7 @@ import {createAgentSkillManagerDecisionPrompt,createAgentSkillRefinePrompt,} from '@lobechat/prompts';+import type { ChatToolPayload, MessageToolCall, ModelUsage } from '@lobechat/types';import { RequestTrigger } from '@lobechat/types';import { z } from 'zod';@@ -21,12 +38,15 @@ import type { AgentDocument } from '@/database/models/agentDocuments';import { AgentDocumentModel } from '@/database/models/agentDocuments';import type { LobeChatDatabase } from '@/database/type';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import { AgentDocumentsService } from '@/server/services/agentDocuments';import { createMarkdownEditorSnapshot } from '@/server/services/agentDocuments/headlessEditor';import { AgentDocumentVfsService } from '@/server/services/agentDocumentVfs';import {createSkillTree,getSkillFolder,} from '@/server/services/agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils';+import { AgentSignalProcedureInspector } from '@/server/services/agentSignal/procedure';+import { redisPolicyStateStore } from '@/server/services/agentSignal/store/adapters/redis/policyStateStore';import { SkillMaintainerService } from '@/server/services/skillMaintainer/SkillMaintainerService';import { SkillReferenceResolver } from '@/server/services/skillMaintainer/SkillReferenceResolver';import { VfsSkillPackageAdapter } from '@/server/services/skillMaintainer/VfsSkillPackageAdapter';@@ -58,13 +78,17 @@ export interface SkillManagementSignalPayload {evidence?: Array<{ cue: string; excerpt: string }>;/** Original feedback message that motivated the signal. */feedbackMessage: string;+ /** Message that originated this same-turn feedback action. */+ messageId?: string;+ /** Runtime scope used to inspect same-turn procedure state. */+ scopeKey?: string;/** Optional topic where the feedback happened. */topicId?: string;/** Optional relevant turn summary. */turnContext?: string;}-export type SkillManagementDecisionAction = 'consolidate' | 'create' | 'noop' | 'refine';+export type SkillManagementDecisionAction = 'consolidate' | 'create' | 'noop' | 'refine' | 'reject';/*** Normalized result returned by the skill-management decision step.@@ -74,6 +98,8 @@ export interface SkillManagementDecision {action: SkillManagementDecisionAction;/** Optional confidence score from the decision model. */confidence?: number;+ /** Optional document ids inspected while deciding. */+ documentRefs?: string[];/** Optional short explanation for observability. */reason?: string;/** Optional file paths that should be read before refinement or consolidation. */@@ -94,6 +120,7 @@ export interface SkillManagementActionInput {evidence?: AgentSignalFeedbackEvidence[];feedbackHint?: 'not_satisfied' | 'satisfied';message: string;+ messageId?: string;reason?: string;serializedContext?: string;topicId?: string;@@ -114,6 +141,39 @@ export interface SkillManagementActionHandlerOptions {userId: string;}+export interface SkillDecisionDocumentOutcome {+ documentId: string;+ relation?: string;+ summary?: string;+}++export interface SkillDecisionCandidateDocument {+ documentId: string;+ filename?: string;+ title?: string;+}++export interface SkillDecisionDocumentSnapshot {+ content?: string;+ documentId: string;+ filename?: string;+ title?: string;+}++export interface SkillDecisionToolset {+ listCandidateDocuments: (input: {+ agentId: string;+ topicId?: string;+ }) => Promise<SkillDecisionCandidateDocument[]>;+ listSameTurnDocumentOutcomes: (input: {+ agentId: string;+ messageId?: string;+ scopeKey?: string;+ topicId?: string;+ }) => Promise<SkillDecisionDocumentOutcome[]>;+ readDocument: (input: { documentId: string }) => Promise<SkillDecisionDocumentSnapshot>;+}+export interface SkillManagementAgentModelConfig {model: string;provider: string;@@ -150,8 +210,9 @@ export interface SkillMaintainerFileOperationService {}const SkillManagementDecisionSchema = z.object({- action: z.enum(['create', 'refine', 'consolidate', 'noop']),+ action: z.enum(['create', 'refine', 'consolidate', 'noop', 'reject']),confidence: z.number().min(0).max(1).nullable(),+ documentRefs: z.array(z.string()).default([]),reason: z.string().nullable(),requiredReads: z.array(z.string()),targetSkillIds: z.array(z.string()),@@ -174,15 +235,16 @@ const SkillManagementDecisionGenerateObjectSchema = {schema: {additionalProperties: false,properties: {- action: { enum: ['create', 'refine', 'consolidate', 'noop'], type: 'string' },+ action: { enum: ['create', 'refine', 'consolidate', 'noop', 'reject'], type: 'string' },confidence: {anyOf: [{ maximum: 1, minimum: 0, type: 'number' }, { type: 'null' }],},+ documentRefs: { items: { type: 'string' }, type: 'array' },reason: { type: ['string', 'null'] },requiredReads: { items: { type: 'string' }, type: 'array' },targetSkillIds: { items: { type: 'string' }, type: 'array' },},- required: ['action', 'confidence', 'reason', 'requiredReads', 'targetSkillIds'],+ required: ['action', 'confidence', 'documentRefs', 'reason', 'requiredReads', 'targetSkillIds'],type: 'object',},strict: true,@@ -199,7 +261,16 @@ const SkillMaintainerWorkflowResultBaseGenerateObjectSchema = {items: {additionalProperties: false,properties: {- arguments: { additionalProperties: {}, type: 'object' },+ arguments: {+ additionalProperties: false,+ properties: {+ content: { type: ['string', 'null'] },+ path: { type: 'string' },+ skillRef: { type: 'string' },+ },+ required: ['skillRef', 'path', 'content'],+ type: 'object',+ },name: {enum: ['updateSkill', 'writeSkillFile', 'removeSkillFile'],type: 'string',@@ -211,7 +282,15 @@ const SkillMaintainerWorkflowResultBaseGenerateObjectSchema = {type: 'array',},proposedLifecycleActions: {- items: { additionalProperties: {}, type: 'object' },+ items: {+ additionalProperties: false,+ properties: {+ reason: { type: ['string', 'null'] },+ type: { type: 'string' },+ },+ required: ['type', 'reason'],+ type: 'object',+ },type: 'array',},reason: { type: ['string', 'null'] },@@ -223,7 +302,11 @@ const SkillMaintainerWorkflowResultBaseGenerateObjectSchema = {} satisfies Omit<GenerateObjectSchema, 'name'>;const isSkillManagementDecisionAction = (value: unknown): value is SkillManagementDecisionAction =>- value === 'create' || value === 'refine' || value === 'consolidate' || value === 'noop';+ value === 'create' ||+ value === 'refine' ||+ value === 'consolidate' ||+ value === 'noop' ||+ value === 'reject';const getStringArray = (value: unknown) => {if (!Array.isArray(value)) return undefined;@@ -241,6 +324,7 @@ const normalizeSkillManagementDecision = (decision: unknown): SkillManagementDecconst record = decision as Record<string, unknown>;const action = isSkillManagementDecisionAction(record.action) ? record.action : 'noop';const confidence = typeof record.confidence === 'number' ? record.confidence : undefined;+ const documentRefs = getStringArray(record.documentRefs);const reason = typeof record.reason === 'string' ? record.reason : undefined;const requiredReads = getStringArray(record.requiredReads);const targetSkillIds = getStringArray(record.targetSkillIds);@@ -248,12 +332,396 @@ const normalizeSkillManagementDecision = (decision: unknown): SkillManagementDecreturn {action,...(confidence === undefined ? {} : { confidence }),+ ...(documentRefs === undefined ? {} : { documentRefs }),...(reason === undefined ? {} : { reason }),...(requiredReads === undefined ? {} : { requiredReads }),...(targetSkillIds === undefined ? {} : { targetSkillIds }),};};+const malformedDecisionOutputReason = 'decision structured output was malformed';++const skillDecisionToolIdentifier = 'agent-signal-skill-decision';++const skillDecisionManifest = {+ api: [+ {+ description: 'List document tool outcomes from the same Agent Signal turn.',+ name: 'listSameTurnDocumentOutcomes',+ parameters: {+ additionalProperties: false,+ properties: {+ messageId: { type: ['string', 'null'] },+ scopeKey: { type: ['string', 'null'] },+ },+ required: ['messageId', 'scopeKey'],+ type: 'object',+ },+ },+ {+ description: 'List candidate agent documents when same-turn outcomes are insufficient.',+ name: 'listCandidateDocuments',+ parameters: {+ additionalProperties: false,+ properties: {+ agentId: { type: 'string' },+ topicId: { type: ['string', 'null'] },+ },+ required: ['agentId', 'topicId'],+ type: 'object',+ },+ },+ {+ description: 'Read one agent document by document id for attribution before deciding.',+ name: 'readDocument',+ parameters: {+ additionalProperties: false,+ properties: {+ documentId: { type: 'string' },+ },+ required: ['documentId'],+ type: 'object',+ },+ },+ {+ description:+ 'Submit the final skill-management decision after optional read-only inspection.',+ name: 'submitDecision',+ parameters: SkillManagementDecisionGenerateObjectSchema.schema,+ },+ ],+ identifier: skillDecisionToolIdentifier,+ meta: {+ description: 'Read same-turn evidence and submit one skill-management decision.',+ title: 'Agent Signal Skill Decision',+ },+ systemRole: 'Use read-only evidence tools before submitting a skill-management decision.',+ type: 'builtin',+} satisfies LobeToolManifest;++interface SkillDecisionAgentRuntimeInput {+ model: string;+ modelRuntime: Pick<ModelRuntime, 'chat'>;+ payload: SkillManagementSignalPayload;+ tools: SkillDecisionToolset;+}++const toNullableString = (value: unknown) => (typeof value === 'string' ? value : undefined);++const parseToolArguments = (value: string | undefined): Record<string, unknown> => {+ if (!value) return {};++ try {+ const parsed = JSON.parse(value) as unknown;+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)+ ? (parsed as Record<string, unknown>)+ : {};+ } catch {+ return {};+ }+};++const executeSkillDecisionRuntimeTool = async (+ toolCall: ChatToolPayload,+ input: Pick<SkillDecisionAgentRuntimeInput, 'payload' | 'tools'>,+) => {+ const args = parseToolArguments(toolCall.arguments);++ if (toolCall.apiName === 'listSameTurnDocumentOutcomes') {+ return input.tools.listSameTurnDocumentOutcomes({+ agentId: input.payload.agentId,+ messageId: toNullableString(args.messageId) ?? input.payload.messageId,+ scopeKey: toNullableString(args.scopeKey) ?? input.payload.scopeKey,+ topicId: input.payload.topicId,+ });+ }++ if (toolCall.apiName === 'listCandidateDocuments') {+ return input.tools.listCandidateDocuments({+ agentId: input.payload.agentId,+ topicId: toNullableString(args.topicId) ?? input.payload.topicId,+ });+ }++ if (toolCall.apiName === 'readDocument') {+ const documentId = toNullableString(args.documentId);+ if (!documentId) return { error: 'documentId is required' };++ return input.tools.readDocument({ documentId });+ }++ return { error: `Unsupported skill decision tool: ${toolCall.apiName}` };+};++/**+ * Runs the skill-management decision agent with the standard Agent Runtime state machine.+ *+ * Use when:+ * - The decision step must inspect same-turn document outcomes before deciding+ * - Tool use should follow the same LLM -> tool -> LLM control flow as normal agents+ *+ * Expects:+ * - Tool implementations are read-only and scoped by agent/message/scope+ * - `submitDecision` is the only terminal tool+ *+ * Returns:+ * - Final normalized skill-management decision+ *+ * Call stack:+ *+ * createSkillDecisionRunner+ * -> SkillManagementDecisionAgentService.decide+ * -> {@link runSkillDecisionAgentRuntime}+ * -> AgentRuntime.step+ */+export const runSkillDecisionAgentRuntime = async (input: SkillDecisionAgentRuntimeInput) => {+ let submittedDecision: SkillManagementDecision | undefined;+ const toolNameResolver = new ToolNameResolver();+ const manifestMap = { [skillDecisionToolIdentifier]: skillDecisionManifest };+ const tools = generateToolsFromManifest(skillDecisionManifest);+ const messages: Array<{ content: string; role: 'system' | 'user' }> = [+ { content: AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE, role: 'system' },+ {+ content: createAgentSkillManagerDecisionPrompt({+ agentId: input.payload.agentId,+ ...(input.payload.candidateSkills?.length+ ? { candidateSkills: input.payload.candidateSkills }+ : {}),+ evidence: input.payload.evidence ?? [],+ feedbackMessage: input.payload.feedbackMessage,+ messageId: input.payload.messageId,+ scopeKey: input.payload.scopeKey,+ topicId: input.payload.topicId,+ turnContext: input.payload.turnContext,+ }),+ role: 'user',+ },+ ];++ const runtime = new AgentRuntime(+ new GeneralChatAgent({+ compressionConfig: { enabled: false },+ modelRuntimeConfig: {+ model: input.model,+ provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,+ },+ operationId: `agent-signal-skill-decision:${input.payload.messageId ?? 'message'}`,+ }),+ {+ executors: {+ call_llm: async (instruction, state) => {+ const payload = (instruction as { payload: { messages: ChatStreamPayload['messages'] } })+ .payload;+ let content = '';+ let modelUsage: ModelUsage | undefined;+ let rawToolCalls: MessageToolCall[] = [];++ const response = await input.modelRuntime.chat(+ {+ messages: payload.messages,+ model: input.model,+ stream: true,+ tools,+ },+ {+ callback: {+ onCompletion: (data) => {+ modelUsage = data.usage;+ },+ onText: (text) => {+ content += text;+ },+ onToolsCalling: ({ toolsCalling }) => {+ rawToolCalls = toolsCalling;+ },+ },+ metadata: { trigger: RequestTrigger.Memory },+ },+ );+ await consumeStreamUntilDone(response);++ const assistantMessageId = `skill-decision-assistant-${state.stepCount}`;+ const resolvedToolCalls = toolNameResolver.resolve(rawToolCalls, manifestMap);+ const newState = structuredClone(state);++ newState.messages.push({+ content,+ id: assistantMessageId,+ role: 'assistant',+ ...(rawToolCalls.length > 0 ? { tool_calls: rawToolCalls } : {}),+ });++ return {+ events: [+ {+ result: { content, tool_calls: rawToolCalls, usage: modelUsage },+ type: 'llm_result',+ },+ ],+ newState,+ nextContext: {+ payload: {+ hasToolsCalling: resolvedToolCalls.length > 0,+ parentMessageId: assistantMessageId,+ result: { content, tool_calls: rawToolCalls },+ toolsCalling: resolvedToolCalls,+ },+ phase: 'llm_result',+ session: {+ messageCount: newState.messages.length,+ sessionId: newState.operationId,+ status: newState.status,+ stepCount: newState.stepCount,+ },+ stepUsage: modelUsage,+ } satisfies AgentRuntimeContext,+ };+ },+ call_tool: async (instruction, state) => {+ const payload = (+ instruction as {+ payload: {+ parentMessageId: string;+ toolCalling: ChatToolPayload;+ };+ }+ ).payload;+ const startedAt = Date.now();+ const args = parseToolArguments(payload.toolCalling.arguments);+ const data =+ payload.toolCalling.apiName === 'submitDecision'+ ? normalizeSkillManagementDecision(args)+ : await executeSkillDecisionRuntimeTool(payload.toolCalling, input);++ if (payload.toolCalling.apiName === 'submitDecision') {+ submittedDecision = data as SkillManagementDecision;+ }++ const content = JSON.stringify(data);+ const newState = structuredClone(state);+ newState.messages.push({+ content,+ role: 'tool',+ tool_call_id: payload.toolCalling.id,+ });++ return {+ events: [+ {+ id: payload.toolCalling.id,+ result: { content, success: true },+ type: 'tool_result',+ },+ ],+ newState,+ nextContext: {+ payload: {+ data,+ executionTime: Date.now() - startedAt,+ isSuccess: true,+ parentMessageId: payload.parentMessageId,+ toolCall: payload.toolCalling,+ toolCallId: payload.toolCalling.id,+ },+ phase: 'tool_result',+ session: {+ messageCount: newState.messages.length,+ sessionId: newState.operationId,+ status: newState.status,+ stepCount: newState.stepCount,+ },+ } satisfies AgentRuntimeContext,+ };+ },+ },+ },+ );++ const createdAt = new Date().toISOString();+ let state: AgentState = {+ cost: {+ calculatedAt: createdAt,+ currency: 'USD',+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ total: 0,+ },+ createdAt,+ lastModified: createdAt,+ messages,+ metadata: {+ agentId: input.payload.agentId,+ sourceMessageId: input.payload.messageId,+ topicId: input.payload.topicId,+ trigger: RequestTrigger.Memory,+ },+ modelRuntimeConfig: {+ model: input.model,+ provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,+ },+ operationId: `agent-signal-skill-decision:${input.payload.messageId ?? 'message'}`,+ operationToolSet: {+ enabledToolIds: [skillDecisionToolIdentifier],+ manifestMap,+ sourceMap: { [skillDecisionToolIdentifier]: 'builtin' },+ tools,+ },+ status: 'idle',+ stepCount: 0,+ toolManifestMap: manifestMap,+ toolSourceMap: { [skillDecisionToolIdentifier]: 'builtin' },+ tools,+ usage: {+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ llm: {+ apiCalls: 0,+ processingTimeMs: 0,+ tokens: { input: 0, output: 0, total: 0 },+ },+ tools: {+ byTool: [],+ totalCalls: 0,+ totalTimeMs: 0,+ },+ },+ userInterventionConfig: { approvalMode: 'headless' },+ };+ let context: AgentRuntimeContext = {+ payload: {+ model: input.model,+ provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,+ tools,+ },+ phase: 'user_input',+ session: {+ messageCount: messages.length,+ sessionId: state.operationId,+ status: state.status,+ stepCount: state.stepCount,+ },+ };++ for (let step = 0; step < 14; step += 1) {+ if (submittedDecision) break;+ if (state.status === 'done' || state.status === 'error' || state.status === 'interrupted') {+ break;+ }++ const result = await runtime.step(state, context);+ state = result.newState;++ if (!result.nextContext) break;+ context = result.nextContext;+ }++ return submittedDecision ?? createNoopDecision('decision agent did not submit a decision');+};+/*** Handles one skill-domain Agent Signal payload.*@@ -276,7 +744,19 @@ export const handleSkillManagementSignal = async (input: {return { reason: 'self iteration is disabled', status: 'skipped' as const };}- const decision = normalizeSkillManagementDecision(await input.decide(input.payload));+ let decisionOutput: unknown;++ try {+ decisionOutput = await input.decide(input.payload);+ } catch (error) {+ if (error instanceof z.ZodError) {+ return { reason: malformedDecisionOutputReason, status: 'skipped' as const };+ }++ throw error;+ }++ const decision = normalizeSkillManagementDecision(decisionOutput);return { decision, status: 'decided' as const };};@@ -286,6 +766,7 @@ const toSkillManagementDecision = (): SkillManagementDecision => ({action: value.action,...(value.confidence === null ? {} : { confidence: value.confidence }),+ ...(value.documentRefs.length === 0 ? {} : { documentRefs: value.documentRefs }),...(value.reason === null ? {} : { reason: value.reason }),...(value.requiredReads.length === 0 ? {} : { requiredReads: value.requiredReads }),...(value.targetSkillIds.length === 0 ? {} : { targetSkillIds: value.targetSkillIds }),@@ -327,6 +808,58 @@ export const collectAgentSkillDecisionCandidates = (return candidates.sort((left, right) => left.id.localeCompare(right.id));};+const createDefaultSkillDecisionToolset = (+ db: LobeChatDatabase,+ userId: string,+): SkillDecisionToolset => {+ const agentDocumentModel = new AgentDocumentModel(db, userId);+ const agentDocumentsService = new AgentDocumentsService(db, userId);+ const inspector = new AgentSignalProcedureInspector(redisPolicyStateStore);++ return {+ listCandidateDocuments: async ({ agentId, topicId }) => {+ const documents = topicId+ ? await agentDocumentsService.listDocumentsForTopic(agentId, topicId)+ : await agentDocumentModel.findByAgent(agentId);++ return documents.map((document) => ({+ documentId: document.documentId,+ filename: document.filename,+ title: document.title,+ }));+ },+ listSameTurnDocumentOutcomes: async ({ messageId, scopeKey }) => {+ if (!scopeKey) return [];++ const snapshot = await inspector.inspectScope(scopeKey);++ return snapshot.receipts+ .filter((receipt) => receipt.domainKey.startsWith('document:'))+ .filter((receipt) => !messageId || receipt.messageId === messageId)+ .flatMap((receipt) =>+ (receipt.relatedObjects ?? [])+ .filter((object) => object.objectType === 'document')+ .map((object) => ({+ documentId: object.objectId,+ relation: object.relation,+ summary: receipt.summary,+ })),+ );+ },+ readDocument: async ({ documentId }) => {+ const snapshot = await agentDocumentsService.getDocumentSnapshotById(documentId);+ if (!snapshot) return { documentId };++ return {+ content: snapshot.content,+ documentId,+ filename: snapshot.filename,+ title: snapshot.title,+ };+ },+ };+};+const toSkillMaintainerWorkflowResult = (value: z.infer<typeof SkillMaintainerWorkflowResultSchema>,): SkillMaintainerWorkflowResult => ({@@ -364,29 +897,26 @@ class SkillManagementDecisionAgentService {await new AgentDocumentModel(this.db, this.userId).findByAgent(input.agentId),);- const result = await modelRuntime.generateObject(- {- messages: [- { content: AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE, role: 'system' },- {- content: createAgentSkillManagerDecisionPrompt({- agentId: input.agentId,- ...(candidateSkills.length > 0 ? { candidateSkills } : {}),- evidence: input.evidence ?? [],- feedbackMessage: input.feedbackMessage,- topicId: input.topicId,- turnContext: input.turnContext,- }),- role: 'user',- },- ] as never[],- model: this.modelConfig.model,- schema: SkillManagementDecisionGenerateObjectSchema,+ const result = await runSkillDecisionAgentRuntime({+ model: this.modelConfig.model,+ modelRuntime,+ payload: {+ ...input,+ ...(candidateSkills.length > 0 ? { candidateSkills } : {}),},- { metadata: { trigger: RequestTrigger.Memory } },- );+ tools: createDefaultSkillDecisionToolset(this.db, this.userId),+ });- return toSkillManagementDecision(SkillManagementDecisionSchema.parse(result));+ return toSkillManagementDecision(+ SkillManagementDecisionSchema.parse({+ confidence: result.confidence ?? null,+ documentRefs: result.documentRefs ?? [],+ reason: result.reason ?? null,+ requiredReads: result.requiredReads ?? [],+ targetSkillIds: result.targetSkillIds ?? [],+ action: result.action,+ }),+ );}}@@ -747,7 +1277,15 @@ const runMaintainerWorkflow = async (),);- await applyMaintainerOperations(service, workflowResult.operations, targetSkillIds);+ try {+ await applyMaintainerOperations(service, workflowResult.operations, targetSkillIds);+ } catch (error) {+ return {+ decision,+ detail: error instanceof Error ? error.message : String(error),+ status: 'skipped',+ };+ }return {decision,@@ -761,6 +1299,14 @@ export const runSkillManagementAction = async (options: SkillManagementActionHandlerOptions,decision: SkillManagementDecision,): Promise<SkillManagementActionResult> => {+ if (decision.action === 'reject') {+ return {+ decision,+ detail: decision.reason ?? 'Skill-management decision was rejected.',+ status: 'skipped',+ };+ }+if (decision.action === 'noop') {return {decision,@@ -872,6 +1418,7 @@ export const handleSkillManagementAction = async (evidence: action.payload.evidence,feedbackHint: action.payload.feedbackHint,message,+ messageId: action.payload.messageId,reason: action.payload.reason,serializedContext: action.payload.serializedContext,topicId: action.payload.topicId,@@ -883,6 +1430,8 @@ export const handleSkillManagementAction = async (...(candidateSkills.length > 0 ? { candidateSkills } : {}),evidence: action.payload.evidence,feedbackMessage: message,+ messageId: action.payload.messageId,+ scopeKey: context.scopeKey,topicId: action.payload.topicId,turnContext: action.payload.serializedContext,},diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.tsindex 0831214ab3e..0748aa8eb8b 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts@@ -60,6 +60,11 @@ Choose the correct memory API based on the feedback:- addExperienceMemory for reusable lessons from outcomes or workflows- addActivityMemory for notable concrete events worth remembering+Do not use memory tools for requests to create, update, refine, merge, consolidate, or store reusable skills, procedures, workflows, playbooks, checklists, agent capabilities, agent prompts, or agent documents.+If the feedback asks for a "reusable skill", "future workflow", "PR review checklist skill", "agent capability", or similar operational artifact, skip memory and leave it to the skill/document management path.+Apply the same boundary to Chinese feedback such as "复用 skill", "可复用流程", "review 流程", "检查清单", "下次参考这个流程", "保留这个流程", or "合并/更新清单".+Do not summarize skill-management requests as preferences.+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.`;diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.tsindex 248aaff2f8f..88120b62b96 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts@@ -1,5 +1,12 @@import type { BaseAction, BaseSignal, RuntimeProcessorResult } from '@lobechat/agent-signal';+import type {+ AgentSignalProcedureMarker,+ AgentSignalProcedureRecord,+ ProcedureAccumulatorScoreResult,+} from '../../procedure';+import { createProcedureKey, createProcedureMarker, createProcedureRecord } from '../../procedure';+import type { RuntimeProcessorContext } from '../../runtime/context';import { defineSignalHandler } from '../../runtime/middleware';import {AGENT_SIGNAL_POLICY_ACTION_TYPES,@@ -29,7 +36,73 @@ const createStableIdempotencyKey = (return `${signal.chain.rootSourceId}:${target}:${messageId}`;};-const buildPlannedActions = (signal: BaseSignal): BaseAction[] => {+/**+ * Weak positive skill feedback needs repeated observations before the accumulator emits.+ */+const SATISFIED_SKILL_CHEAP_SCORE_DELTA = 0.6;++/**+ * Procedure dependencies used by the feedback action planner.+ */+export interface FeedbackActionProcedureDeps {+ /** Appends candidate records and optionally scores accumulated buckets. */+ accumulator?: {+ appendAndScore?: (+ record: AgentSignalProcedureRecord,+ ) => Promise<ProcedureAccumulatorScoreResult | undefined>;+ appendRecord: (record: AgentSignalProcedureRecord) => Promise<void>;+ };+ /** Writes accumulated markers after a bucket score is emitted. */+ markerStore?: { write: (marker: AgentSignalProcedureMarker) => Promise<void> };+ /** Provides a consistent millisecond timestamp for procedure writes. */+ now?: () => number;+ /** Writes candidate procedure records. */+ recordStore?: { write: (record: AgentSignalProcedureRecord) => Promise<void> };+ /** TTL used for marker expiration. */+ ttlSeconds?: number;+}++/**+ * Options for feedback action planning.+ */+export interface FeedbackActionPlannerOptions {+ /** Optional procedure marker reader used to suppress same-source duplicate actions. */+ markerReader?: {+ shouldSuppress: (input: {+ domainKey: string;+ intentClass?: string;+ intentClassCandidates?: string[];+ procedureKey: string;+ scopeKey: string;+ }) => Promise<boolean>;+ };+ /** Optional procedure dependencies used for weak-signal accumulation. */+ procedure?: FeedbackActionProcedureDeps;+}++const toDomainKey = (target: AgentSignalFeedbackDomainTarget) => {+ if (target === 'memory') return 'memory:user-preference';+ if (target === 'skill') return 'skill';+ return target;+};++const toPlannerIntentClass = (+ result?: 'not_satisfied' | 'neutral' | 'satisfied',+): 'implicit_positive' | 'unknown' => {+ return result === 'satisfied' ? 'implicit_positive' : 'unknown';+};++const toPlannerIntentClassCandidates = (+ target: AgentSignalFeedbackDomainTarget,+ result?: 'not_satisfied' | 'neutral' | 'satisfied',+) => {+ const primary = toPlannerIntentClass(result);+ if (target === 'memory') return [primary, 'explicit_persistence', 'unknown'];+ if (target === 'skill') return [primary, 'tool_command', 'explicit_persistence', 'unknown'];+ return [primary, 'unknown'];+};++const buildActionNodes = (signal: BaseSignal): BaseAction[] => {const payload = signal.payload as {agentId?: string;conflictPolicy?: {@@ -78,6 +151,7 @@ const buildPlannedActions = (signal: BaseSignal): BaseAction[] => {feedbackHint: payload.satisfactionResult === 'satisfied' ? 'satisfied' : 'not_satisfied',idempotencyKey,message: payload.message,+ messageId: payload.messageId,reason: payload.reason,serializedContext,sourceHints: payload.sourceHints,@@ -94,6 +168,8 @@ const buildPlannedActions = (signal: BaseSignal): BaseAction[] => {}if (payload.target === 'skill') {+ if (payload.satisfactionResult === 'satisfied') return [];+return [{actionId: `${signal.signalId}:action:skill-management`,@@ -108,9 +184,10 @@ const buildPlannedActions = (signal: BaseSignal): BaseAction[] => {agentId: payload.agentId,conflictPolicy: payload.conflictPolicy,evidence: payload.evidence,- feedbackHint: payload.satisfactionResult === 'satisfied' ? 'satisfied' : 'not_satisfied',+ feedbackHint: 'not_satisfied',idempotencyKey,message: payload.message,+ messageId: payload.messageId,reason: payload.reason,serializedContext,sourceHints: payload.sourceHints,@@ -129,6 +206,191 @@ const buildPlannedActions = (signal: BaseSignal): BaseAction[] => {return [];};+const buildSuppressedProcedureSignal = (signal: BaseSignal, context: RuntimeProcessorContext) => {+ const payload = signal.payload as {+ messageId: string;+ target: AgentSignalFeedbackDomainTarget;+ };+ const domain = toDomainKey(payload.target);++ return {+ chain: {+ chainId: signal.chain.chainId,+ parentNodeId: signal.signalId,+ parentSignalId: signal.signalId,+ rootSourceId: signal.chain.rootSourceId,+ },+ payload: {+ aggregateScore: 0,+ bucketKey: `${context.scopeKey}:${domain}`,+ confidence: 1,+ domain,+ itemScores: [],+ recordIds: [],+ suggestedActions: ['suppressed'],+ },+ signalId: `${signal.signalId}:signal:procedure-suppressed`,+ signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.procedureBucketScored,+ source: signal.source,+ timestamp: context.now(),+ } satisfies BaseSignal;+};++const buildScoredProcedureSignal = (signal: BaseSignal, scored: ProcedureAccumulatorScoreResult) =>+ ({+ chain: {+ chainId: signal.chain.chainId,+ parentNodeId: signal.signalId,+ parentSignalId: signal.signalId,+ rootSourceId: signal.chain.rootSourceId,+ },+ payload: {+ aggregateScore: scored.score.aggregateScore,+ bucketKey: scored.bucket.bucketKey,+ confidence: scored.score.confidence,+ domain: scored.bucket.domain,+ itemScores: scored.score.itemScores,+ recordIds: scored.bucket.recordIds,+ suggestedActions: scored.score.suggestedActions,+ },+ signalId: `${signal.signalId}:signal:procedure-accumulated`,+ signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.procedureBucketScored,+ source: signal.source,+ timestamp: scored.score.scoredAt,+ }) satisfies BaseSignal;++const createSatisfiedSkillCandidateRecord = (+ signal: BaseSignal,+ context: RuntimeProcessorContext,+ now: number,+) => {+ const payload = signal.payload as {+ message: string;+ messageId: string;+ reason?: string;+ satisfactionResult?: 'not_satisfied' | 'neutral' | 'satisfied';+ target: AgentSignalFeedbackDomainTarget;+ };++ return createProcedureRecord({+ accumulatorRole: 'candidate',+ cheapScoreDelta: SATISFIED_SKILL_CHEAP_SCORE_DELTA,+ createdAt: now,+ domainKey: 'skill',+ id: `procedure-record:${signal.signalId}:skill-candidate`,+ intentClass: toPlannerIntentClass(payload.satisfactionResult),+ refs: {+ signalIds: [signal.signalId],+ sourceIds: signal.source ? [signal.source.sourceId] : undefined,+ },+ scopeKey: context.scopeKey,+ status: 'observed',+ summary: payload.reason ?? payload.message,+ });+};++const maybeAccumulateSatisfiedSkillFeedback = async (+ signal: BaseSignal,+ context: RuntimeProcessorContext,+ options: FeedbackActionPlannerOptions,+) => {+ const payload = signal.payload as {+ messageId: string;+ satisfactionResult?: 'not_satisfied' | 'neutral' | 'satisfied';+ target: AgentSignalFeedbackDomainTarget;+ };++ if (payload.target !== 'skill' || payload.satisfactionResult !== 'satisfied') return undefined;++ const procedure = options.procedure;+ if (!procedure?.recordStore || !procedure.accumulator) return undefined;++ const now = procedure.now?.() ?? context.now();+ const record = createSatisfiedSkillCandidateRecord(signal, context, now);++ await procedure.recordStore.write(record);++ if (!procedure.accumulator.appendAndScore) {+ await procedure.accumulator.appendRecord(record);+ return undefined;+ }++ const scored = await procedure.accumulator.appendAndScore(record);+ if (!scored) return undefined;+ if (scored.score.aggregateScore < 1 && !scored.score.suggestedActions.includes('maintain')) {+ return undefined;+ }++ const scoredSignal = buildScoredProcedureSignal(signal, scored);++ if (procedure.markerStore && procedure.ttlSeconds) {+ await procedure.markerStore.write(+ createProcedureMarker({+ createdAt: now,+ domainKey: 'skill',+ expiresAt: now + procedure.ttlSeconds * 1000,+ intentClass: toPlannerIntentClass(payload.satisfactionResult),+ markerType: 'accumulated',+ procedureKey: createProcedureKey({+ messageId: payload.messageId,+ rootSourceId: signal.chain.rootSourceId,+ }),+ recordId: record.id,+ scopeKey: context.scopeKey,+ signalId: scoredSignal.signalId,+ sourceId: signal.source?.sourceId,+ }),+ );+ }++ return scoredSignal;+};++/**+ * Builds planned action nodes unless procedure markers suppress the same-source work.+ *+ * Use when:+ * - Feedback domain signals may overlap with direct tool outcomes+ * - Planner suppression must read marker state only+ *+ * Expects:+ * - `messageId` is present on feedback domain signals+ *+ * Returns:+ * - Planned actions and whether they were suppressed+ */+const buildPlannedActions = async (+ signal: BaseSignal,+ context: RuntimeProcessorContext,+ options: FeedbackActionPlannerOptions,+) => {+ const payload = signal.payload as {+ messageId: string;+ satisfactionResult?: 'not_satisfied' | 'neutral' | 'satisfied';+ target: AgentSignalFeedbackDomainTarget;+ };+ const suppressed = await options.markerReader?.shouldSuppress({+ domainKey: toDomainKey(payload.target),+ intentClass: toPlannerIntentClass(payload.satisfactionResult),+ intentClassCandidates: toPlannerIntentClassCandidates(+ payload.target,+ payload.satisfactionResult,+ ),+ procedureKey: `message:${payload.messageId}`,+ scopeKey: context.scopeKey,+ });++ if (suppressed) return { actions: [], suppressed: true };++ const scoredSignal = await maybeAccumulateSatisfiedSkillFeedback(signal, context, options);++ return {+ actions: buildActionNodes(signal),+ signals: scoredSignal ? [scoredSignal] : [],+ suppressed: false,+ };+};+/*** Creates the signal handler that turns domain signals into action lists.*@@ -145,7 +407,9 @@ const buildPlannedActions = (signal: BaseSignal): BaseAction[] => {* - `action.user-memory.handle`* - `action.skill-management.handle`*/-export const createFeedbackActionPlannerSignalHandler = () => {+export const createFeedbackActionPlannerSignalHandler = (+ options: FeedbackActionPlannerOptions = {},+) => {const listenedSignalTypes = [AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainMemory,AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainNone,@@ -156,15 +420,27 @@ export const createFeedbackActionPlannerSignalHandler = () => {return defineSignalHandler(listenedSignalTypes,'signal.feedback-action-planner',- async (signal): Promise<RuntimeProcessorResult | void> => {- const actions = buildPlannedActions(signal);+ async (signal, context): Promise<RuntimeProcessorResult | void> => {+ const {+ actions,+ signals = [],+ suppressed,+ } = await buildPlannedActions(signal, context, options);++ if (suppressed) {+ return {+ signals: [buildSuppressedProcedureSignal(signal, context)],+ status: 'dispatch',+ };+ }- if (actions.length === 0) {+ if (actions.length === 0 && signals.length === 0) {return;}return {actions,+ signals,status: 'dispatch',};},diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.tsindex d3225ed8fa7..7159a3fd9d2 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts@@ -254,6 +254,35 @@ const buildSignal = (};};+const explicitSkillChangePattern =+ /create|update|refine|merge|consolidate|combine|deduplicate|reorganize|创建|更新|合并|去重|整理/i;++const weakPositiveSkillPattern = /keep|reuse|reference|保留|复用|参考/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);+ const result =+ !explicitChangeRequest && weakPositiveSkillPattern.test(message)+ ? 'satisfied'+ : 'not_satisfied';++ return {+ confidence: 0.8,+ evidence: [{ cue: 'skill source hint', excerpt: message }],+ reason: explicitChangeRequest+ ? 'source hinted explicit skill-management change request'+ : result === 'satisfied'+ ? 'source hinted reusable skill or workflow feedback'+ : 'source hinted skill-management feedback',+ result,+ };+};+/*** Creates the source handler for the feedback satisfaction judge.*@@ -279,10 +308,12 @@ export const createFeedbackSatisfactionJudgeProcessor = (`${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,- });+ const payload =+ resolveSkillHintSatisfaction(source) ??+ (await judge.judgeSatisfaction({+ message: normalizedMessage,+ serializedContext: source.payload.serializedContext,+ }));return {signals: [diff --git a/src/server/services/agentSignal/policies/analyzeIntent/index.ts b/src/server/services/agentSignal/policies/analyzeIntent/index.tsindex e6c8bb76afc..ff6858963da 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/index.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/index.ts@@ -1,3 +1,5 @@+import type { ToolOutcomeProcedureDeps } from '../../procedure/toolOutcome';+import { createToolOutcomeSourceHandler } from '../../procedure/toolOutcome';import { defineAgentSignalHandlers } from '../../runtime/middleware';import type {SkillManagementActionHandlerOptions,@@ -16,6 +18,17 @@ import { createFeedbackSatisfactionJudgeProcessor } from './feedbackSatisfactionexport interface CreateAnalyzeIntentPolicyOptions {feedbackDomainJudge?: CreateFeedbackDomainJudgePolicyOptions['feedbackDomainJudge'];feedbackSatisfactionJudge?: CreateFeedbackSatisfactionJudgePolicyOptions;+ procedure?: ToolOutcomeProcedureDeps & {+ markerReader: {+ shouldSuppress: (input: {+ domainKey: string;+ intentClass?: string;+ intentClassCandidates?: string[];+ procedureKey: string;+ scopeKey: string;+ }) => Promise<boolean>;+ };+ };skillManagement?: SkillManagementActionHandlerOptions;userMemory?: UserMemoryActionHandlerOptions;}@@ -26,11 +39,15 @@ export const createAnalyzeIntentPolicy = (options: CreateAnalyzeIntentPolicyOpti});return defineAgentSignalHandlers([+ ...(options.procedure ? [createToolOutcomeSourceHandler(options.procedure)] : []),createFeedbackSatisfactionJudgeProcessor(options.feedbackSatisfactionJudge),createFeedbackDomainJudgeSignalHandler({resolveDomains: feedbackDomainResolver,}),- createFeedbackActionPlannerSignalHandler(),+ createFeedbackActionPlannerSignalHandler({+ markerReader: options.procedure?.markerReader,+ procedure: options.procedure,+ }),...(options.skillManagement? [defineSkillManagementActionHandler(options.skillManagement)]: []),diff --git a/src/server/services/agentSignal/policies/index.ts b/src/server/services/agentSignal/policies/index.tsindex 32546fdf768..82360c30eb5 100644--- a/src/server/services/agentSignal/policies/index.ts+++ b/src/server/services/agentSignal/policies/index.ts@@ -1,4 +1,5 @@import type { AgentSignalMiddleware } from '../runtime/middleware';+import type { CreateAnalyzeIntentPolicyOptions } from './analyzeIntent';import { createAnalyzeIntentPolicy } from './analyzeIntent';import type {SkillManagementActionHandlerOptions,@@ -18,6 +19,7 @@ export * from './types';export interface CreateDefaultAgentSignalPoliciesOptions extends CreateFeedbackDomainJudgePolicyOptions {feedbackSatisfactionJudge?: CreateFeedbackSatisfactionJudgePolicyOptions;+ procedure?: CreateAnalyzeIntentPolicyOptions['procedure'];skillManagement?: SkillManagementActionHandlerOptions;userMemory?: UserMemoryActionHandlerOptions;}diff --git a/src/server/services/agentSignal/policies/types.test.ts b/src/server/services/agentSignal/policies/types.test.tsindex 18b36c3ed58..38d33395930 100644--- a/src/server/services/agentSignal/policies/types.test.ts+++ b/src/server/services/agentSignal/policies/types.test.ts@@ -1,6 +1,9 @@// @vitest-environment node+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';import { describe, expect, it } from 'vitest';+import { AGENT_SIGNAL_POLICY_SIGNAL_TYPES } from './types';+describe('agent signal policy ids', () => {it('co-locates runtime ids with the policy type definitions', async () => {const {@@ -19,3 +22,25 @@ describe('agent signal policy ids', () => {expect(AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle).toBe('action.user-memory.handle');});});++describe('agent signal procedure type catalog', () => {+ /**+ * @example+ * expect(AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeCompleted).toBe('tool.outcome.completed');+ */+ it('exposes generic direct tool outcome source types', () => {+ expect(AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeCompleted).toBe('tool.outcome.completed');+ expect(AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeFailed).toBe('tool.outcome.failed');+ });++ /**+ * @example+ * expect(AGENT_SIGNAL_POLICY_SIGNAL_TYPES.toolOutcome).toBe('signal.tool.outcome');+ */+ it('exposes procedure policy signal types', () => {+ expect(AGENT_SIGNAL_POLICY_SIGNAL_TYPES.toolOutcome).toBe('signal.tool.outcome');+ expect(AGENT_SIGNAL_POLICY_SIGNAL_TYPES.procedureBucketScored).toBe(+ 'signal.procedure.bucket.scored',+ );+ });+});diff --git a/src/server/services/agentSignal/policies/types.ts b/src/server/services/agentSignal/policies/types.tsindex c3101d6013d..997532ca9c1 100644--- a/src/server/services/agentSignal/policies/types.ts+++ b/src/server/services/agentSignal/policies/types.ts@@ -24,8 +24,10 @@ export const AGENT_SIGNAL_POLICY_SIGNAL_TYPES = {feedbackSatisfaction: 'signal.feedback.satisfaction',nudgeMemoryConditionMatched: 'signal.nudge.memory.condition-matched',nudgeMemoryConditionMismatched: 'signal.nudge.memory.condition-mismatched',+ procedureBucketScored: 'signal.procedure.bucket.scored',selfReflectionNeeded: 'signal.self-reflection-analysis.reflect-needed',selfReflectionSkipped: 'signal.self-reflection-analysis.reflect-skipped',+ toolOutcome: 'signal.tool.outcome',} as const;/** Server-owned built-in AgentSignal action type identifiers. */@@ -78,7 +80,7 @@ export interface AgentSignalFeedbackDomainStagePayload<*/export interface AgentSignalFeedbackSourceHints {documentPayload?: Record<string, unknown>;- intents?: Array<'document' | 'memory' | 'persona' | 'prompt'>;+ intents?: Array<'document' | 'memory' | 'persona' | 'prompt' | 'skill'>;memoryPayload?: Record<string, unknown>;}@@ -173,6 +175,20 @@ export interface AgentSignalPolicySignalPayloadMap {serializedContext?: string;topicId?: string;};+ [AGENT_SIGNAL_POLICY_SIGNAL_TYPES.procedureBucketScored]: {+ aggregateScore: number;+ bucketKey: string;+ confidence: number;+ domain: string;+ itemScores: Array<{+ reasons: string[];+ recordId: string;+ score: number;+ suggestedAction?: 'handle' | 'ignore' | 'maintain' | 'review' | 'summarize';+ }>;+ recordIds: string[];+ suggestedActions: string[];+ };[AGENT_SIGNAL_POLICY_SIGNAL_TYPES.selfReflectionNeeded]: {agentId?: string;operationId: string;@@ -193,6 +209,24 @@ export interface AgentSignalPolicySignalPayloadMap {serializedContext?: string;topicId?: string;};+ [AGENT_SIGNAL_POLICY_SIGNAL_TYPES.toolOutcome]: {+ agentId?: string;+ domainKey?: string;+ intentClass?: string;+ messageId?: string;+ operationId?: string;+ outcome: {+ action?: string;+ errorReason?: string;+ status: 'failed' | 'skipped' | 'succeeded';+ summary?: string;+ };+ relatedObjects?: Array<{ objectId: string; objectType: string; relation?: string }>;+ taskId?: string;+ tool: { apiName?: string; identifier: string };+ toolCallId?: string;+ topicId?: string;+ };}/** Server-owned built-in AgentSignal action payloads keyed by action type. */@@ -220,6 +254,7 @@ export interface AgentSignalPolicyActionPayloadMap {feedbackHint?: Exclude<AgentSignalFeedbackSatisfactionResult, 'neutral'>;idempotencyKey: string;message: string;+ messageId?: string;reason?: string;serializedContext?: string;sourceHints?: AgentSignalFeedbackSourceHints;@@ -232,6 +267,7 @@ export interface AgentSignalPolicyActionPayloadMap {feedbackHint?: Exclude<AgentSignalFeedbackSatisfactionResult, 'neutral'>;idempotencyKey: string;message: string;+ messageId?: string;reason?: string;serializedContext?: string;sourceHints?: AgentSignalFeedbackSourceHints;diff --git a/src/server/services/agentSignal/procedure/__tests__/accumulator.test.ts b/src/server/services/agentSignal/procedure/__tests__/accumulator.test.tsnew file mode 100644index 00000000000..8120f68485f--- /dev/null+++ b/src/server/services/agentSignal/procedure/__tests__/accumulator.test.ts@@ -0,0 +1,191 @@+import type { AgentSignalPolicyStateStore } from '../../store/types';+import {+ appendAndScoreProcedureAccumulatorRecord,+ appendDomainProcedureRecord,+ shouldScoreAccumulator,+} from '../accumulator';+import { PROCEDURE_ACCUMULATOR_POLICY_ID } from '../keys';++const createStore = (): AgentSignalPolicyStateStore => {+ const state = new Map<string, Record<string, string>>();++ return {+ readPolicyState: async (policyId, scopeKey) => state.get(`${policyId}:${scopeKey}`),+ writePolicyState: async (policyId, scopeKey, data) => {+ const key = `${policyId}:${scopeKey}`;+ state.set(key, { ...state.get(key), ...data });+ },+ };+};++describe('DomainProcedureAccumulator', () => {+ /**+ * @example+ * appendDomainProcedureRecord(undefined, record).bucketKey === 'topic:t1:memory'+ */+ it('puts records into coarse domain buckets', () => {+ const state = appendDomainProcedureRecord(undefined, {+ createdAt: 100,+ domainKey: 'memory:user-preference',+ id: 'record_1',+ refs: {},+ scopeKey: 'topic:t1',+ status: 'observed',+ });++ expect(state.bucketKey).toBe('topic:t1:memory');+ expect(state.recordIds).toEqual(['record_1']);+ });++ /**+ * @example+ * context records keep cheapScore at zero.+ */+ it('does not add cheap score for direct tool context records', () => {+ const state = appendDomainProcedureRecord(undefined, {+ accumulatorRole: 'context',+ cheapScoreDelta: 9,+ createdAt: 100,+ domainKey: 'skill:managed-skill',+ id: 'record_1',+ refs: {},+ scopeKey: 'topic:t1',+ status: 'handled',+ });++ expect(state.cheapScore).toBe(0);+ expect(shouldScoreAccumulator(state, { cheapScoreThreshold: 1, minRecords: 2, now: 100 })).toBe(+ false,+ );+ });++ /**+ * @example+ * malformed record fields are ignored while valid bucket records still score.+ */+ it('ignores malformed and cross-bucket fields while scoring persisted records', async () => {+ const store = createStore();+ const bucketKey = 'topic:t1:skill';++ await store.writePolicyState(+ PROCEDURE_ACCUMULATOR_POLICY_ID,+ bucketKey,+ {+ 'record:bad-json': '{bad',+ 'record:missing-shape': JSON.stringify({ id: 'missing-shape' }),+ 'record:other-domain': JSON.stringify({+ accumulatorRole: 'candidate',+ cheapScoreDelta: 9,+ createdAt: 100,+ domainKey: 'memory:user-preference',+ id: 'other-domain',+ refs: {},+ scopeKey: 'topic:t1',+ status: 'observed',+ }),+ 'record:other-scope': JSON.stringify({+ accumulatorRole: 'candidate',+ cheapScoreDelta: 9,+ createdAt: 110,+ domainKey: 'skill',+ id: 'other-scope',+ refs: {},+ scopeKey: 'topic:other',+ status: 'observed',+ }),+ 'record:string-score': JSON.stringify({+ accumulatorRole: 'candidate',+ cheapScoreDelta: '0.6',+ createdAt: 115,+ domainKey: 'skill',+ id: 'string-score',+ refs: {},+ scopeKey: 'topic:t1',+ status: 'observed',+ }),+ 'record:valid-existing': JSON.stringify({+ accumulatorRole: 'candidate',+ cheapScoreDelta: 0.6,+ createdAt: 120,+ domainKey: 'skill',+ id: 'valid-existing',+ refs: {},+ scopeKey: 'topic:t1',+ status: 'observed',+ }),+ },+ 60,+ );++ const result = await appendAndScoreProcedureAccumulatorRecord(+ store,+ {+ accumulatorRole: 'candidate',+ cheapScoreDelta: 0.6,+ createdAt: 130,+ domainKey: 'skill',+ id: 'valid-new',+ refs: {},+ scopeKey: 'topic:t1',+ status: 'observed',+ },+ 60,+ { now: 140 },+ );++ expect(result).toEqual(+ expect.objectContaining({+ bucket: expect.objectContaining({+ cheapScore: 1.2,+ recordIds: ['valid-existing', 'valid-new'],+ }),+ score: expect.objectContaining({+ aggregateScore: 1.2,+ suggestedActions: ['maintain'],+ }),+ }),+ );+ expect(result?.records.map((record) => record.id)).toEqual(['valid-existing', 'valid-new']);+ });++ /**+ * @example+ * re-appending an already scored record set does not emit a duplicate score.+ */+ it('does not score the same persisted record set twice', async () => {+ const store = createStore();+ const existingRecord = {+ accumulatorRole: 'candidate' as const,+ cheapScoreDelta: 0.6,+ createdAt: 90,+ domainKey: 'skill',+ id: 'record_0',+ refs: {},+ scopeKey: 'topic:t1',+ status: 'observed' as const,+ };+ const record = {+ accumulatorRole: 'candidate' as const,+ cheapScoreDelta: 0.6,+ createdAt: 100,+ domainKey: 'skill',+ id: 'record_1',+ refs: {},+ scopeKey: 'topic:t1',+ status: 'observed' as const,+ };++ await appendAndScoreProcedureAccumulatorRecord(store, existingRecord, 60, { now: 100 });+ const first = await appendAndScoreProcedureAccumulatorRecord(store, record, 60, { now: 110 });+ await store.writePolicyState(+ PROCEDURE_ACCUMULATOR_POLICY_ID,+ 'topic:t1:skill',+ { recordIds: JSON.stringify(['record_1', 'record_0']) },+ 60,+ );+ const second = await appendAndScoreProcedureAccumulatorRecord(store, record, 60, { now: 120 });++ expect(first?.score.suggestedActions).toEqual(['maintain']);+ expect(second).toBeUndefined();+ });+});diff --git a/src/server/services/agentSignal/procedure/__tests__/batchScorer.test.ts b/src/server/services/agentSignal/procedure/__tests__/batchScorer.test.tsnew file mode 100644index 00000000000..50764e44137--- /dev/null+++ b/src/server/services/agentSignal/procedure/__tests__/batchScorer.test.ts@@ -0,0 +1,84 @@+import { scoreDomainProcedureBatch } from '../batchScorer';++describe('Domain procedure batch scorer', () => {+ /**+ * @example+ * context-only direct tool records receive zero handling pressure.+ */+ it('keeps context-only direct tool records below handling threshold', () => {+ const result = scoreDomainProcedureBatch({+ bucket: {+ bucketKey: 'topic:t1:memory',+ cheapScore: 0,+ domain: 'memory',+ firstSeenAt: 100,+ lastSeenAt: 100,+ recordCount: 1,+ recordIds: ['record_1'],+ scopeKey: 'topic:t1',+ version: '1',+ },+ now: 120,+ records: [+ {+ accumulatorRole: 'context',+ createdAt: 100,+ domainKey: 'memory:user-preference',+ id: 'record_1',+ refs: {},+ scopeKey: 'topic:t1',+ status: 'handled',+ },+ ],+ });++ expect(result.aggregateScore).toBe(0);+ expect(result.suggestedActions).toEqual([]);+ });++ /**+ * @example+ * candidate weak records can cross a domain bucket threshold.+ */+ it('scores candidate weak records into maintain suggestions', () => {+ const result = scoreDomainProcedureBatch({+ bucket: {+ bucketKey: 'topic:t1:skill',+ cheapScore: 1.2,+ domain: 'skill',+ firstSeenAt: 100,+ lastSeenAt: 130,+ recordCount: 2,+ recordIds: ['a', 'b'],+ scopeKey: 'topic:t1',+ version: '1',+ },+ now: 140,+ records: [+ {+ accumulatorRole: 'candidate',+ cheapScoreDelta: 0.6,+ createdAt: 100,+ domainKey: 'skill',+ id: 'a',+ refs: {},+ scopeKey: 'topic:t1',+ status: 'observed',+ },+ {+ accumulatorRole: 'candidate',+ cheapScoreDelta: 0.6,+ createdAt: 130,+ domainKey: 'skill',+ id: 'b',+ refs: {},+ scopeKey: 'topic:t1',+ status: 'observed',+ },+ ],+ });++ expect(result.aggregateScore).toBeGreaterThanOrEqual(1);+ expect(result.suggestedActions).toContain('maintain');+ });+});diff --git a/src/server/services/agentSignal/procedure/__tests__/emitToolOutcome.test.ts b/src/server/services/agentSignal/procedure/__tests__/emitToolOutcome.test.tsnew file mode 100644index 00000000000..3feef8b17a0--- /dev/null+++ b/src/server/services/agentSignal/procedure/__tests__/emitToolOutcome.test.ts@@ -0,0 +1,107 @@+import type { AgentSignalPolicyStateStore } from '../../store/types';+import { emitToolOutcomeSafely, recordToolOutcome } from '../emitToolOutcome';+import {+ buildProcedureMarkerKey,+ PROCEDURE_MARKER_POLICY_ID,+ PROCEDURE_RECEIPTS_POLICY_ID,+ PROCEDURE_RECORDS_POLICY_ID,+} from '../keys';++const createStore = (): AgentSignalPolicyStateStore => {+ const state = new Map<string, Record<string, string>>();++ return {+ readPolicyState: async (policyId, scopeKey) => state.get(`${policyId}:${scopeKey}`),+ writePolicyState: async (policyId, scopeKey, data) => {+ state.set(`${policyId}:${scopeKey}`, {+ ...state.get(`${policyId}:${scopeKey}`),+ ...data,+ });+ },+ };+};++describe('recordToolOutcome', () => {+ /**+ * @example+ * recordToolOutcome({ status: 'succeeded' }) writes projection state without enqueueing workflow.+ */+ it('writes direct tool procedure projection synchronously', async () => {+ const store = createStore();++ await recordToolOutcome({+ apiName: 'addPreferenceMemory',+ context: { userId: 'u1' },+ domainKey: 'memory:user-preference',+ identifier: 'lobe-user-memory',+ intentClass: 'explicit_persistence',+ messageId: 'm1',+ policyStateStore: store,+ scope: { topicId: 't1', userId: 'u1' },+ scopeKey: 'topic:t1',+ status: 'succeeded',+ summary: 'Saved preference.',+ toolAction: 'create',+ ttlSeconds: 3600,+ });++ const markerKey = buildProcedureMarkerKey({+ domainKey: 'memory:user-preference',+ intentClass: 'explicit_persistence',+ procedureKey: 'message:m1',+ scopeKey: 'topic:t1',+ });++ await expect(store.readPolicyState(PROCEDURE_MARKER_POLICY_ID, markerKey)).resolves.toEqual({+ marker: expect.stringContaining('memory:user-preference'),+ });+ await expect(store.readPolicyState(PROCEDURE_RECORDS_POLICY_ID, 'topic:t1')).resolves.toEqual(+ expect.objectContaining({+ 'record:procedure-record:tool-outcome:lobe-user-memory:addPreferenceMemory:succeeded:m1':+ expect.stringContaining('Saved preference.'),+ }),+ );+ await expect(store.readPolicyState(PROCEDURE_RECEIPTS_POLICY_ID, 'topic:t1')).resolves.toEqual(+ expect.objectContaining({+ 'receipt:procedure-receipt:procedure-record:tool-outcome:lobe-user-memory:addPreferenceMemory:succeeded:m1':+ expect.stringContaining('handled'),+ }),+ );+ });++ /**+ * @example+ * emitToolOutcomeSafely(input) logs but does not reject when procedure storage fails.+ */+ it('does not reject when procedure projection fails after a tool side effect', async () => {+ const error = new Error('redis unavailable');+ const store: AgentSignalPolicyStateStore = {+ readPolicyState: async () => undefined,+ writePolicyState: async () => {+ throw error;+ },+ };+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ await expect(+ emitToolOutcomeSafely({+ apiName: 'addPreferenceMemory',+ context: { userId: 'u1' },+ domainKey: 'memory:user-preference',+ identifier: 'lobe-user-memory',+ intentClass: 'explicit_persistence',+ messageId: 'm1',+ policyStateStore: store,+ scope: { topicId: 't1', userId: 'u1' },+ scopeKey: 'topic:t1',+ status: 'succeeded',+ summary: 'Saved preference.',+ toolAction: 'create',+ ttlSeconds: 3600,+ }),+ ).resolves.toBeUndefined();++ expect(consoleError).toHaveBeenCalledWith('[AgentSignal] Failed to emit tool outcome:', error);+ consoleError.mockRestore();+ });+});diff --git a/src/server/services/agentSignal/procedure/__tests__/inspector.test.ts b/src/server/services/agentSignal/procedure/__tests__/inspector.test.tsnew file mode 100644index 00000000000..741a0381782--- /dev/null+++ b/src/server/services/agentSignal/procedure/__tests__/inspector.test.ts@@ -0,0 +1,97 @@+import type { AgentSignalPolicyStateStore } from '../../store/types';+import { AgentSignalProcedureInspector } from '../inspector';+import {+ PROCEDURE_ACCUMULATOR_POLICY_ID,+ PROCEDURE_MARKER_INDEX_POLICY_ID,+ PROCEDURE_MARKER_POLICY_ID,+ PROCEDURE_RECEIPTS_POLICY_ID,+ PROCEDURE_RECORDS_POLICY_ID,+} from '../keys';++const createStore = (): AgentSignalPolicyStateStore => {+ const state = new Map<string, Record<string, string>>();++ return {+ readPolicyState: async (policyId, scopeKey) => state.get(`${policyId}:${scopeKey}`),+ writePolicyState: async (policyId, scopeKey, data) => {+ const key = `${policyId}:${scopeKey}`;+ state.set(key, { ...state.get(key), ...data });+ },+ };+};++describe('AgentSignalProcedureInspector', () => {+ /**+ * @example+ * inspector.inspectScope('topic:t1') returns records, markers, receipts, and accumulator fields.+ */+ it('reads procedure projections from an injected policy state store', async () => {+ const store = createStore();+ const marker = {+ createdAt: 100,+ domainKey: 'memory:user-preference',+ expiresAt: 200,+ key: 'marker_1',+ markerType: 'handled',+ scopeKey: 'topic:t1',+ };+ const receipt = {+ createdAt: 100,+ domainKey: 'memory:user-preference',+ id: 'receipt_1',+ scopeKey: 'topic:t1',+ status: 'handled',+ summary: 'Saved preference.',+ updatedAt: 100,+ };+ const record = {+ createdAt: 100,+ domainKey: 'memory:user-preference',+ id: 'record_1',+ refs: {},+ scopeKey: 'topic:t1',+ status: 'handled',+ };++ await store.writePolicyState(+ PROCEDURE_RECORDS_POLICY_ID,+ 'topic:t1',+ { 'record:record_1': JSON.stringify(record) },+ 60,+ );+ await store.writePolicyState(+ PROCEDURE_MARKER_INDEX_POLICY_ID,+ 'topic:t1',+ { 'marker:marker_1': JSON.stringify(marker) },+ 60,+ );+ await store.writePolicyState(+ PROCEDURE_MARKER_POLICY_ID,+ 'marker_1',+ { marker: JSON.stringify(marker) },+ 60,+ );+ await store.writePolicyState(+ PROCEDURE_RECEIPTS_POLICY_ID,+ 'topic:t1',+ { 'receipt:receipt_1': JSON.stringify(receipt) },+ 60,+ );+ await store.writePolicyState(+ PROCEDURE_ACCUMULATOR_POLICY_ID,+ 'topic:t1:memory',+ { bucketKey: 'topic:t1:memory' },+ 60,+ );++ const inspector = new AgentSignalProcedureInspector(store);++ await expect(inspector.inspectScope('topic:t1')).resolves.toEqual({+ accumulatorFields: { bucketKey: 'topic:t1:memory' },+ markers: [marker],+ receipts: [receipt],+ records: [record],+ });+ await expect(inspector.inspectMarkerKeys(['marker_1'])).resolves.toEqual([marker]);+ });+});diff --git a/src/server/services/agentSignal/procedure/__tests__/keys.test.ts b/src/server/services/agentSignal/procedure/__tests__/keys.test.tsnew file mode 100644index 00000000000..08cf4f645ea--- /dev/null+++ b/src/server/services/agentSignal/procedure/__tests__/keys.test.ts@@ -0,0 +1,45 @@+import { buildProcedureMarkerKey, createProcedureKey, getCoarseProcedureDomain } from '../keys';++describe('Agent Signal procedure keys', () => {+ /**+ * @example+ * createProcedureKey({ messageId: 'm1' }) === 'message:m1'+ */+ it('uses structured ids before fallback root source id', () => {+ expect(createProcedureKey({ messageId: 'm1', rootSourceId: 'source_1' })).toBe('message:m1');+ expect(createProcedureKey({ operationId: 'op1', rootSourceId: 'source_1' })).toBe(+ 'operation:op1',+ );+ expect(createProcedureKey({ rootSourceId: 'source_1', toolCallId: 'tool1' })).toBe(+ 'tool-call:tool1',+ );+ expect(createProcedureKey({ rootSourceId: 'source_1' })).toBe('root-source:source_1');+ });++ /**+ * @example+ * getCoarseProcedureDomain('memory:user-preference') === 'memory'+ */+ it('groups domain buckets by coarse domain', () => {+ expect(getCoarseProcedureDomain('memory:user-preference')).toBe('memory');+ expect(getCoarseProcedureDomain('skill:managed-skill')).toBe('skill');+ expect(getCoarseProcedureDomain('document:agent-document')).toBe('document');+ });++ /**+ * @example+ * buildProcedureMarkerKey(...) returns the Redis policy marker key string.+ */+ it('builds marker keys from scope domain intent and structured procedure key', () => {+ expect(+ buildProcedureMarkerKey({+ domainKey: 'memory:user-preference',+ intentClass: 'explicit_persistence',+ procedureKey: 'message:m1',+ scopeKey: 'topic:t1',+ }),+ ).toBe(+ 'agent-signal:policy:procedure-marker:topic:t1:memory:user-preference:explicit_persistence:message:m1',+ );+ });+});diff --git a/src/server/services/agentSignal/procedure/__tests__/marker.test.ts b/src/server/services/agentSignal/procedure/__tests__/marker.test.tsnew file mode 100644index 00000000000..77cddd4e1d6--- /dev/null+++ b/src/server/services/agentSignal/procedure/__tests__/marker.test.ts@@ -0,0 +1,51 @@+import { createProcedureMarker, shouldSuppressByMarker } from '../marker';++describe('AgentSignalProcedureMarker', () => {+ /**+ * @example+ * shouldSuppressByMarker(marker, 150) === false+ */+ it('does not suppress when marker is missing, expired, accumulated, or suppressed-only', () => {+ const base = {+ createdAt: 100,+ domainKey: 'memory:user-preference',+ expiresAt: 120,+ procedureKey: 'message:m1',+ scopeKey: 'topic:t1',+ };++ expect(shouldSuppressByMarker(undefined, 150)).toBe(false);+ expect(+ shouldSuppressByMarker(createProcedureMarker({ ...base, markerType: 'handled' }), 150),+ ).toBe(false);+ expect(+ shouldSuppressByMarker(+ createProcedureMarker({ ...base, expiresAt: 200, markerType: 'accumulated' }),+ 150,+ ),+ ).toBe(false);+ expect(+ shouldSuppressByMarker(+ createProcedureMarker({ ...base, expiresAt: 200, markerType: 'suppressed' }),+ 150,+ ),+ ).toBe(false);+ });++ /**+ * @example+ * shouldSuppressByMarker(activeHandledMarker, 150) === true+ */+ it('suppresses only active handled markers', () => {+ const marker = createProcedureMarker({+ createdAt: 100,+ domainKey: 'memory:user-preference',+ expiresAt: 200,+ markerType: 'handled',+ procedureKey: 'message:m1',+ scopeKey: 'topic:t1',+ });++ expect(shouldSuppressByMarker(marker, 150)).toBe(true);+ });+});diff --git a/src/server/services/agentSignal/procedure/__tests__/receipt.test.ts b/src/server/services/agentSignal/procedure/__tests__/receipt.test.tsnew file mode 100644index 00000000000..c32a6dbd364--- /dev/null+++ b/src/server/services/agentSignal/procedure/__tests__/receipt.test.ts@@ -0,0 +1,54 @@+import { mergeMessageReceiptEnvelope, renderProcedureReceiptContext } from '../receipt';++describe('AgentSignalProcedureReceipt', () => {+ /**+ * @example+ * mergeMessageReceiptEnvelope({ existing: true }, envelope).existing === true+ */+ it('merges message metadata without overwriting unrelated fields', () => {+ expect(+ mergeMessageReceiptEnvelope(+ { agentSignalReceipts: [{ domainKey: 'memory', id: 'old' }], existing: true },+ {+ domainKey: 'memory',+ id: 'new',+ status: 'handled',+ summary: 'Saved preference.',+ updatedAt: 200,+ },+ ),+ ).toEqual({+ agentSignalReceipts: [+ { domainKey: 'memory', id: 'old' },+ {+ domainKey: 'memory',+ id: 'new',+ status: 'handled',+ summary: 'Saved preference.',+ updatedAt: 200,+ },+ ],+ existing: true,+ });+ });++ /**+ * @example+ * renderProcedureReceiptContext(receipts).includes('memory')+ */+ it('renders compact context without exposing internal receipt ids', () => {+ expect(+ renderProcedureReceiptContext([+ {+ createdAt: 100,+ domainKey: 'memory:user-preference',+ id: 'receipt_internal',+ scopeKey: 'topic:t1',+ status: 'handled',+ summary: '已记录偏好:默认简洁回答。',+ updatedAt: 100,+ },+ ]),+ ).toBe('Recent Agent Signal updates:\n- memory: 已记录偏好:默认简洁回答。');+ });+});diff --git a/src/server/services/agentSignal/procedure/__tests__/toolOutcome.test.ts b/src/server/services/agentSignal/procedure/__tests__/toolOutcome.test.tsnew file mode 100644index 00000000000..85030d4ad01--- /dev/null+++ b/src/server/services/agentSignal/procedure/__tests__/toolOutcome.test.ts@@ -0,0 +1,108 @@+import { createSource } from '@lobechat/agent-signal';+import type {+ SourceToolOutcomeCompleted,+ SourceToolOutcomeFailed,+} from '@lobechat/agent-signal/source';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';++import { createToolOutcomeSourceHandler } from '../toolOutcome';++describe('tool outcome procedure handler', () => {+ /**+ * @example+ * completed explicit memory outcome writes one handled marker.+ */+ it('writes record marker receipt and context accumulator for completed memory outcomes', async () => {+ const records: unknown[] = [];+ const markers: unknown[] = [];+ const receipts: unknown[] = [];+ const accumulatorRecords: unknown[] = [];+ const handler = createToolOutcomeSourceHandler({+ accumulator: {+ appendRecord: async (record) => {+ accumulatorRecords.push(record);+ },+ },+ markerStore: {+ write: async (marker) => {+ markers.push(marker);+ },+ },+ now: () => 100,+ receiptStore: {+ append: async (receipt) => {+ receipts.push(receipt);+ },+ },+ recordStore: {+ write: async (record) => {+ records.push(record);+ },+ },+ ttlSeconds: 3600,+ });+ const source = createSource({+ payload: {+ domainKey: 'memory:user-preference',+ intentClass: 'explicit_persistence',+ messageId: 'm1',+ outcome: { action: 'create', status: 'succeeded', summary: 'Saved preference.' },+ tool: { apiName: 'addPreferenceMemory', identifier: 'lobe-user-memory' },+ },+ scope: { topicId: 't1', userId: 'u1' },+ scopeKey: 'topic:t1',+ sourceId: 'source_1',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeCompleted,+ }) as SourceToolOutcomeCompleted;++ const result = await handler.handle(source, { now: () => 100, scopeKey: 'topic:t1' } as never);++ expect(result).toEqual(+ expect.objectContaining({+ signals: [expect.objectContaining({ signalType: 'signal.tool.outcome' })],+ status: 'dispatch',+ }),+ );+ expect(records).toHaveLength(1);+ expect(markers).toHaveLength(1);+ expect(receipts).toHaveLength(1);+ expect(accumulatorRecords).toHaveLength(1);+ });++ /**+ * @example+ * failed direct tool outcomes never suppress future actions by default.+ */+ it('records failed outcomes without handled markers', async () => {+ const markers: unknown[] = [];+ const handler = createToolOutcomeSourceHandler({+ accumulator: { appendRecord: async () => {} },+ markerStore: {+ write: async (marker) => {+ markers.push(marker);+ },+ },+ now: () => 100,+ receiptStore: { append: async () => {} },+ recordStore: { write: async () => {} },+ ttlSeconds: 3600,+ });+ const source = createSource({+ payload: {+ domainKey: 'skill:market-skill',+ intentClass: 'tool_command',+ messageId: 'm1',+ outcome: { action: 'import', errorReason: 'network', status: 'failed' },+ tool: { apiName: 'importFromMarket', identifier: 'lobe-skill-store' },+ },+ scope: { topicId: 't1', userId: 'u1' },+ scopeKey: 'topic:t1',+ sourceId: 'source_2',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeFailed,+ }) as SourceToolOutcomeFailed;++ await handler.handle(source, { now: () => 100, scopeKey: 'topic:t1' } as never);++ expect(markers).toHaveLength(0);+ });+});diff --git a/src/server/services/agentSignal/procedure/accumulator.ts b/src/server/services/agentSignal/procedure/accumulator.tsnew file mode 100644index 00000000000..c07d7885aff--- /dev/null+++ b/src/server/services/agentSignal/procedure/accumulator.ts@@ -0,0 +1,391 @@+import type { AgentSignalPolicyStateStore } from '../store/types';+import { scoreDomainProcedureBatch } from './batchScorer';+import { getCoarseProcedureDomain, PROCEDURE_ACCUMULATOR_POLICY_ID } from './keys';+import type {+ AgentSignalProcedureRecord,+ DomainProcedureAccumulatorState,+ DomainProcedureBatchScore,+} from './types';++/**+ * Default deterministic P0 scoring thresholds for weak procedure candidates.+ */+export interface ProcedureAccumulatorScoringDefaults {+ /** Cheap score threshold that represents repeated weak positive evidence. */+ cheapScoreThreshold: number;+ /** Minimum record count that can force scoring even when score is low. */+ minRecords: number;+}++const DEFAULT_SCORING_OPTIONS = {+ cheapScoreThreshold: 1,+ minRecords: 2,+} satisfies ProcedureAccumulatorScoringDefaults;++/**+ * Scoring gate options for accumulated procedure buckets.+ */+export interface ScoreAccumulatorOptions {+ /** Cheap score threshold that triggers batch scoring. */+ cheapScoreThreshold: number;+ /** Minimum number of records that triggers batch scoring. */+ minRecords: number;+ /** Current millisecond timestamp. */+ now: number;+ /** Optional quiet window in milliseconds after the last record. */+ quietWindowMs?: number;+}++/**+ * Appends one procedure record into a domain accumulator state.+ *+ * Use when:+ * - Domain facts need to be bucketed by scope and coarse domain+ * - Direct tool outcomes should enter as zero-pressure context+ *+ * Expects:+ * - `record.scopeKey` is the runtime scope used by planner suppression+ *+ * Returns:+ * - Updated accumulator state+ */+export const appendDomainProcedureRecord = (+ current: DomainProcedureAccumulatorState | undefined,+ record: AgentSignalProcedureRecord,+): DomainProcedureAccumulatorState => {+ const domain = getCoarseProcedureDomain(record.domainKey);+ const bucketKey = `${record.scopeKey}:${domain}`;+ const cheapScoreDelta = record.accumulatorRole === 'context' ? 0 : (record.cheapScoreDelta ?? 0);++ if (!current) {+ return {+ bucketKey,+ cheapScore: cheapScoreDelta,+ domain,+ firstSeenAt: record.createdAt,+ lastSeenAt: record.createdAt,+ recordCount: 1,+ recordIds: [record.id],+ scopeKey: record.scopeKey,+ version: '1',+ };+ }++ return {+ ...current,+ cheapScore: current.cheapScore + cheapScoreDelta,+ lastSeenAt: record.createdAt,+ recordCount: current.recordCount + 1,+ recordIds: current.recordIds.includes(record.id)+ ? current.recordIds+ : [...current.recordIds, record.id],+ };+};++/**+ * Determines whether an accumulator bucket should be scored.+ *+ * Use when:+ * - Deciding whether weak signals have enough pressure for batch scoring+ * - Quiet-window scoring should flush low-volume buckets+ *+ * Expects:+ * - `now` and bucket timestamps are milliseconds+ *+ * Returns:+ * - Whether scoring should run+ */+export const shouldScoreAccumulator = (+ state: DomainProcedureAccumulatorState,+ options: ScoreAccumulatorOptions,+) => {+ if (state.recordCount >= options.minRecords) return true;+ if (state.cheapScore >= options.cheapScoreThreshold) return true;+ if (options.quietWindowMs && options.now - state.lastSeenAt >= options.quietWindowMs) return true;+ return false;+};++/**+ * Writes one procedure record into the policy-state accumulator bucket.+ *+ * Use when:+ * - Direct or async procedure records should feed domain accumulation+ * - Inspector and evals need bucket-level visibility+ *+ * Expects:+ * - Store writes merge hash fields+ *+ * Returns:+ * - Resolves after the bucket field is persisted+ */+export const appendProcedureAccumulatorRecord = async (+ store: AgentSignalPolicyStateStore,+ record: AgentSignalProcedureRecord,+ ttlSeconds: number,+) => {+ const domain = getCoarseProcedureDomain(record.domainKey);+ const bucketKey = `${record.scopeKey}:${domain}`;++ await store.writePolicyState(+ PROCEDURE_ACCUMULATOR_POLICY_ID,+ bucketKey,+ {+ [`record:${record.id}`]: JSON.stringify(record),+ bucketKey,+ domain,+ lastSeenAt: String(record.createdAt),+ scopeKey: record.scopeKey,+ version: '1',+ },+ ttlSeconds,+ );+};++/**+ * Result returned when a procedure accumulator bucket crosses a scoring gate.+ */+export interface ProcedureAccumulatorScoreResult {+ /** Bucket state reconstructed from stored records. */+ bucket: DomainProcedureAccumulatorState;+ /** Records included in the scored bucket. */+ records: AgentSignalProcedureRecord[];+ /** Batch score produced for the reconstructed bucket. */+ score: DomainProcedureBatchScore;+}++/**+ * Options for appending and scoring one procedure record.+ */+export interface AppendAndScoreProcedureAccumulatorOptions {+ /** Optional cheap score threshold override. */+ cheapScoreThreshold?: number;+ /** Optional minimum record count override. */+ minRecords?: number;+ /** Current millisecond timestamp for scoring. */+ now: number;+ /** Optional quiet window in milliseconds after the last record. */+ quietWindowMs?: number;+}++const parseAccumulatorBucketKey = (bucketKey: string) => {+ const separatorIndex = bucketKey.lastIndexOf(':');++ if (separatorIndex < 0) {+ return undefined;+ }++ return {+ domain: bucketKey.slice(separatorIndex + 1),+ scopeKey: bucketKey.slice(0, separatorIndex),+ };+};++const isProcedureRecordShape = (value: unknown): value is AgentSignalProcedureRecord => {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;++ const record = value as Partial<AgentSignalProcedureRecord>;+ const refs = record.refs as Record<string, unknown> | undefined;+ const hasStringArray = (items: unknown) =>+ items === undefined ||+ (Array.isArray(items) && items.every((item) => typeof item === 'string'));+ const hasRelatedObjectsShape = (items: unknown) =>+ items === undefined ||+ (Array.isArray(items) &&+ items.every((item) => {+ if (!item || typeof item !== 'object' || Array.isArray(item)) return false;++ const relatedObject = item as Record<string, unknown>;++ return (+ typeof relatedObject.objectId === 'string' &&+ typeof relatedObject.objectType === 'string' &&+ (relatedObject.relation === undefined || typeof relatedObject.relation === 'string')+ );+ }));++ return (+ (record.accumulatorRole === undefined ||+ record.accumulatorRole === 'candidate' ||+ record.accumulatorRole === 'context' ||+ record.accumulatorRole === 'ignored') &&+ (record.cheapScoreDelta === undefined || typeof record.cheapScoreDelta === 'number') &&+ typeof record.createdAt === 'number' &&+ Number.isFinite(record.createdAt) &&+ typeof record.domainKey === 'string' &&+ typeof record.id === 'string' &&+ (record.intentClass === undefined || typeof record.intentClass === 'string') &&+ typeof record.refs === 'object' &&+ record.refs !== null &&+ !Array.isArray(record.refs) &&+ hasStringArray(refs?.actionIds) &&+ hasStringArray(refs?.resultIds) &&+ hasStringArray(refs?.signalIds) &&+ hasStringArray(refs?.sourceIds) &&+ hasRelatedObjectsShape(record.relatedObjects) &&+ typeof record.scopeKey === 'string' &&+ (record.status === 'failed' ||+ record.status === 'handled' ||+ record.status === 'observed' ||+ record.status === 'suppressed') &&+ (record.summary === undefined || typeof record.summary === 'string')+ );+};++const parseAccumulatorRecord = (value: string) => {+ try {+ const parsed = JSON.parse(value) as unknown;+ return isProcedureRecordShape(parsed) ? parsed : undefined;+ } catch {+ return undefined;+ }+};++const parseStoredRecordIds = (value: string | undefined) => {+ if (!value) return undefined;++ try {+ const parsed = JSON.parse(value) as unknown;+ if (!Array.isArray(parsed)) return undefined;++ return parsed.filter((item): item is string => typeof item === 'string');+ } catch {+ return undefined;+ }+};++const hasSameRecordIds = (left: string[] | undefined, right: string[]) => {+ if (!left || left.length !== right.length) return false;++ const rightIds = new Set(right);++ return left.every((id) => rightIds.has(id));+};++const readProcedureAccumulatorRecords = async (+ store: Pick<AgentSignalPolicyStateStore, 'readPolicyState'>,+ bucketKey: string,+) => {+ const state = await store.readPolicyState(PROCEDURE_ACCUMULATOR_POLICY_ID, bucketKey);+ const bucket = parseAccumulatorBucketKey(bucketKey);++ return Object.entries(state ?? {})+ .filter(([key]) => key.startsWith('record:'))+ .map(([, value]) => parseAccumulatorRecord(value))+ .filter((record): record is AgentSignalProcedureRecord => {+ if (!record || !bucket) return false;++ return (+ record.scopeKey === bucket.scopeKey &&+ getCoarseProcedureDomain(record.domainKey) === bucket.domain+ );+ })+ .sort((a, b) => a.createdAt - b.createdAt);+};++/**+ * Reconstructs a deterministic accumulator bucket from persisted records.+ *+ * Use when:+ * - Policy state stores raw record fields and runtime needs the current bucket score+ * - Weak feedback should accumulate across multiple source events in the same scope+ *+ * Expects:+ * - Records belong to the same coarse domain and runtime scope+ *+ * Returns:+ * - A reconstructed bucket or undefined when no records exist+ */+export const composeProcedureAccumulatorBucket = (records: AgentSignalProcedureRecord[]) => {+ let bucket: DomainProcedureAccumulatorState | undefined;++ for (const record of records) {+ bucket = appendDomainProcedureRecord(bucket, record);+ }++ return bucket;+};++/**+ * Appends one record and scores the bucket when deterministic gates are met.+ *+ * Use when:+ * - Weak signal records should become an accumulated procedure signal+ * - The caller needs both persisted accumulator fields and a scored batch payload+ *+ * Expects:+ * - `record.scopeKey` is the runtime scope shared with marker writes+ *+ * Returns:+ * - Score result when the bucket crosses a gate, otherwise undefined+ */+export const appendAndScoreProcedureAccumulatorRecord = async (+ store: AgentSignalPolicyStateStore,+ record: AgentSignalProcedureRecord,+ ttlSeconds: number,+ options: AppendAndScoreProcedureAccumulatorOptions,+): Promise<ProcedureAccumulatorScoreResult | undefined> => {+ // Each incoming signal record is first stored, then the bucket is rebuilt from stored records.+ // This means the visible numeric state is always derived from persisted facts:+ // `recordCount` increments by one, `recordIds` gains the new id, `lastSeenAt` moves forward, and+ // `cheapScore` changes by the record's effective delta. Scoring runs only when the rebuilt bucket+ // crosses one of the configured gates.+ //+ // Current tunable gates are `cheapScoreThreshold`, `minRecords`, and `quietWindowMs`.+ await appendProcedureAccumulatorRecord(store, record, ttlSeconds);++ const domain = getCoarseProcedureDomain(record.domainKey);+ const bucketKey = `${record.scopeKey}:${domain}`;+ const accumulatorState = await store.readPolicyState(PROCEDURE_ACCUMULATOR_POLICY_ID, bucketKey);+ const records = await readProcedureAccumulatorRecords(store, bucketKey);+ const bucket = composeProcedureAccumulatorBucket(records);++ if (!bucket) return undefined;+ if (+ accumulatorState?.lastScoredAt &&+ hasSameRecordIds(parseStoredRecordIds(accumulatorState.recordIds), bucket.recordIds)+ ) {+ return undefined;+ }++ if (+ !shouldScoreAccumulator(bucket, {+ cheapScoreThreshold:+ options.cheapScoreThreshold ?? DEFAULT_SCORING_OPTIONS.cheapScoreThreshold,+ minRecords: options.minRecords ?? DEFAULT_SCORING_OPTIONS.minRecords,+ now: options.now,+ quietWindowMs: options.quietWindowMs,+ })+ ) {+ return undefined;+ }++ const score = scoreDomainProcedureBatch({ bucket, now: options.now, records });+ const scoredBucket = {+ ...bucket,+ lastBatch: score,+ lastEmittedAt: options.now,+ lastScoredAt: options.now,+ };++ await store.writePolicyState(+ PROCEDURE_ACCUMULATOR_POLICY_ID,+ bucketKey,+ {+ bucketKey,+ cheapScore: String(scoredBucket.cheapScore),+ domain: scoredBucket.domain,+ firstSeenAt: String(scoredBucket.firstSeenAt),+ lastBatch: JSON.stringify(score),+ lastEmittedAt: String(options.now),+ lastScoredAt: String(options.now),+ lastSeenAt: String(scoredBucket.lastSeenAt),+ recordCount: String(scoredBucket.recordCount),+ recordIds: JSON.stringify(scoredBucket.recordIds),+ scopeKey: scoredBucket.scopeKey,+ version: scoredBucket.version,+ },+ ttlSeconds,+ );++ return { bucket: scoredBucket, records, score };+};diff --git a/src/server/services/agentSignal/procedure/batchScorer.ts b/src/server/services/agentSignal/procedure/batchScorer.tsnew file mode 100644index 00000000000..ebd6e93f48a--- /dev/null+++ b/src/server/services/agentSignal/procedure/batchScorer.ts@@ -0,0 +1,62 @@+import type {+ AgentSignalProcedureRecord,+ DomainProcedureAccumulatorState,+ DomainProcedureBatchScore,+} from './types';++/**+ * Input for deterministic domain procedure batch scoring.+ */+export interface ScoreDomainProcedureBatchInput {+ /** Accumulator bucket being scored. */+ bucket: DomainProcedureAccumulatorState;+ /** Current millisecond timestamp. */+ now: number;+ /** Records contained in the accumulator bucket. */+ records: AgentSignalProcedureRecord[];+}++/**+ * Scores accumulated procedure records with deterministic P0 rules.+ *+ * Use when:+ * - Weak signals need a compact domain-level score+ * - Direct tool context records should remain zero-pressure+ *+ * Expects:+ * - Candidate records may carry `cheapScoreDelta`+ * - Context records do not create positive handling pressure+ *+ * Returns:+ * - Batch score with per-record reasons and aggregate suggestions+ */+export const scoreDomainProcedureBatch = (+ input: ScoreDomainProcedureBatchInput,+): DomainProcedureBatchScore => {+ // Scoring is additive per incoming signal record:+ // - context records add 0, so direct tool outcomes are remembered without triggering actions;+ // - candidate records add `cheapScoreDelta`, so repeated weak feedback can cross the threshold;+ // - suggested actions are derived from the aggregate score.+ //+ // Current tunable values are the per-record `cheapScoreDelta`, the aggregate action threshold,+ // the per-record role weights, confidence, and the suggested action mapping.+ const itemScores = input.records.map((record) => {+ const score = record.accumulatorRole === 'candidate' ? (record.cheapScoreDelta ?? 0) : 0;++ return {+ reasons: score > 0 ? ['candidate-record'] : ['context-record'],+ recordId: record.id,+ score,+ suggestedAction: score > 0 ? ('maintain' as const) : undefined,+ };+ });+ const aggregateScore = itemScores.reduce((sum, item) => sum + item.score, 0);++ return {+ aggregateScore,+ confidence: input.records.length > 0 ? 0.7 : 0,+ itemScores,+ scoredAt: input.now,+ suggestedActions: aggregateScore >= 1 ? ['maintain'] : [],+ };+};diff --git a/src/server/services/agentSignal/procedure/emitToolOutcome.ts b/src/server/services/agentSignal/procedure/emitToolOutcome.tsnew file mode 100644index 00000000000..fd3453a9a52--- /dev/null+++ b/src/server/services/agentSignal/procedure/emitToolOutcome.ts@@ -0,0 +1,314 @@+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';++import type { AgentSignalExecutionContext } from '../emitter';+import { enqueueAgentSignalSourceEvent } from '../emitter';+import type { AgentSignalPolicyStateStore } from '../store/types';+import { appendProcedureAccumulatorRecord } from './accumulator';+import { createProcedureKey } from './keys';+import { createProcedureMarker, writeProcedureMarker } from './marker';+import { appendProcedureReceipt } from './receipt';+import { createProcedureRecord, writeProcedureRecordField } from './record';++/**+ * Direct tool outcome emission input.+ */+export interface EmitToolOutcomeInput {+ /** Tool API method name. */+ apiName?: string;+ /** Agent Signal execution context used by async source enqueue. */+ context: Pick<AgentSignalExecutionContext, 'agentId' | 'userId'>;+ /** Fine-grained procedure domain key. */+ domainKey?: string;+ /** Compact failure reason for failed outcomes. */+ errorReason?: string;+ /** Tool identifier. */+ identifier: string;+ /** Intent class associated with the direct tool outcome. */+ intentClass?: string;+ /** Message id when known. */+ messageId?: string;+ /** Operation id when known. */+ operationId?: string;+ /** Related domain objects changed or observed by the tool. */+ relatedObjects?: Array<{ objectId: string; objectType: string; relation?: string }>;+ /** Runtime scope fields used to match planner suppression. */+ scope: {+ agentId?: string;+ botScopeKey?: string;+ taskId?: string;+ topicId?: string;+ userId: string;+ };+ /** Resolved runtime scope key. */+ scopeKey: string;+ /** Tool outcome status. */+ status: 'failed' | 'skipped' | 'succeeded';+ /** Compact outcome summary. */+ summary?: string;+ /** Tool action such as create, update, import, or activate. */+ toolAction?: string;+ /** Tool call id when known. */+ toolCallId?: string;+}++/**+ * Creates a stable source id for one direct tool outcome.+ *+ * Use when:+ * - Direct tool execution writes procedure state before async enqueue+ * - Idempotent source identity should prefer structured ids+ *+ * Expects:+ * - Natural-language text is not used for identity+ *+ * Returns:+ * - Stable tool outcome source id+ */+export const createToolOutcomeSourceId = (input: EmitToolOutcomeInput) => {+ const stableId =+ input.operationId ??+ input.toolCallId ??+ input.messageId ??+ `${input.scopeKey}:${input.identifier}:${input.apiName ?? 'unknown'}:${input.toolAction ?? 'unknown'}`;++ return `tool-outcome:${input.identifier}:${input.apiName ?? 'unknown'}:${input.status}:${stableId}`;+};++/**+ * Resolves direct tool outcome scope from request context fields.+ *+ * Use when:+ * - Tool runtimes need the same scope priority as planner suppression+ * - Topic or task context should win over broader agent/user fallback+ *+ * Expects:+ * - `userId` is always present+ *+ * Returns:+ * - Scope object and scope key using topic, task, agent+user, then user fallback+ */+export const resolveToolOutcomeScope = (input: {+ agentId?: string;+ taskId?: string;+ topicId?: string;+ userId: string;+}) => {+ const scope = {+ agentId: input.agentId,+ taskId: input.taskId,+ topicId: input.topicId,+ userId: input.userId,+ };+ const scopeKey = input.topicId+ ? `topic:${input.topicId}`+ : input.taskId+ ? `task:${input.taskId}`+ : input.agentId+ ? `agent:${input.agentId}:user:${input.userId}`+ : `user:${input.userId}`;++ return { scope, scopeKey };+};++const shouldWriteDirectHandledMarker = (input: EmitToolOutcomeInput) => {+ if (input.status !== 'succeeded' && input.status !== 'skipped') return false;+ if (input.domainKey?.startsWith('memory:')) return input.intentClass === 'explicit_persistence';+ if (input.domainKey?.startsWith('skill:')) {+ return input.intentClass === 'tool_command' || input.intentClass === 'explicit_persistence';+ }++ return false;+};++/**+ * Records a direct tool outcome as synchronous procedure policy state.+ *+ * Use when:+ * - Tool execution needs to leave a same-turn causal fact+ * - Planner suppression must read marker state before async workflow processing+ *+ * Expects:+ * - `scopeKey` matches the later planner runtime scope+ * - Caller provides structured ids rather than text-derived identity+ *+ * Returns:+ * - Source id used by the corresponding async tool outcome event+ */+export const recordToolOutcome = async (+ input: EmitToolOutcomeInput & {+ policyStateStore: AgentSignalPolicyStateStore;+ ttlSeconds: number;+ },+) => {+ const sourceId = createToolOutcomeSourceId(input);+ const procedureKey = createProcedureKey({+ messageId: input.messageId,+ operationId: input.operationId,+ rootSourceId: sourceId,+ toolCallId: input.toolCallId,+ });+ const now = Date.now();++ if (input.domainKey) {+ const record = createProcedureRecord({+ accumulatorRole: 'context',+ cheapScoreDelta: 0,+ createdAt: now,+ domainKey: input.domainKey,+ id: `procedure-record:${sourceId}`,+ intentClass: input.intentClass,+ refs: { sourceIds: [sourceId] },+ relatedObjects: input.relatedObjects,+ scopeKey: input.scopeKey,+ status: input.status === 'failed' ? 'failed' : 'handled',+ summary: input.summary,+ });++ await writeProcedureRecordField(input.policyStateStore, record, input.ttlSeconds);+ await appendProcedureAccumulatorRecord(input.policyStateStore, record, input.ttlSeconds);++ if (shouldWriteDirectHandledMarker(input)) {+ await writeProcedureMarker(+ input.policyStateStore,+ createProcedureMarker({+ createdAt: now,+ domainKey: input.domainKey,+ expiresAt: now + input.ttlSeconds * 1000,+ intentClass: input.intentClass,+ markerType: 'handled',+ procedureKey,+ recordId: record.id,+ scopeKey: input.scopeKey,+ sourceId,+ }),+ input.ttlSeconds,+ );+ }++ await appendProcedureReceipt(+ input.policyStateStore,+ {+ createdAt: now,+ domainKey: input.domainKey,+ id: `procedure-receipt:${record.id}`,+ intentClass: input.intentClass,+ messageId: input.messageId,+ recordIds: [record.id],+ relatedObjects: input.relatedObjects,+ scopeKey: input.scopeKey,+ sourceId,+ status: input.status === 'failed' ? 'failed' : 'handled',+ summary: input.summary ?? `${input.domainKey} tool outcome handled.`,+ updatedAt: now,+ },+ { maxItems: 8, ttlSeconds: input.ttlSeconds },+ );+ }++ return { sourceId };+};++/**+ * Emits a direct tool outcome and writes its synchronous procedure projection.+ *+ * Use when:+ * - Direct tool success or failure should suppress same-source duplicate planner actions+ * - Procedure records, receipts, and accumulators must exist before async source processing+ *+ * Expects:+ * - `scopeKey` matches the later planner runtime scope+ * - `policyStateStore` is available for synchronous procedure writes+ *+ * Returns:+ * - Resolves after procedure writes and source enqueue finish+ */+export const emitToolOutcome = async (+ input: EmitToolOutcomeInput & {+ policyStateStore: AgentSignalPolicyStateStore;+ ttlSeconds: number;+ },+) => {+ const { sourceId } = await recordToolOutcome(input);++ if (input.status === 'failed') {+ await enqueueAgentSignalSourceEvent(+ {+ payload: {+ agentId: input.scope.agentId,+ domainKey: input.domainKey,+ intentClass: input.intentClass,+ messageId: input.messageId,+ operationId: input.operationId,+ outcome: {+ action: input.toolAction,+ errorReason: input.errorReason,+ status: input.status,+ summary: input.summary,+ },+ relatedObjects: input.relatedObjects,+ taskId: input.scope.taskId,+ tool: { apiName: input.apiName, identifier: input.identifier },+ toolCallId: input.toolCallId,+ topicId: input.scope.topicId,+ },+ scopeKey: input.scopeKey,+ sourceId,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeFailed,+ },+ input.context,+ );+ return;+ }++ await enqueueAgentSignalSourceEvent(+ {+ payload: {+ agentId: input.scope.agentId,+ domainKey: input.domainKey,+ intentClass: input.intentClass,+ messageId: input.messageId,+ operationId: input.operationId,+ outcome: {+ action: input.toolAction,+ status: input.status,+ summary: input.summary,+ },+ relatedObjects: input.relatedObjects,+ taskId: input.scope.taskId,+ tool: { apiName: input.apiName, identifier: input.identifier },+ toolCallId: input.toolCallId,+ topicId: input.scope.topicId,+ },+ scopeKey: input.scopeKey,+ sourceId,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeCompleted,+ },+ input.context,+ );+};++/**+ * Emits a direct tool outcome without letting projection failures change tool results.+ *+ * Use when:+ * - A tool side effect has already succeeded or failed independently+ * - Procedure storage or async source enqueue should be best-effort observability+ *+ * Expects:+ * - Callers still pass structured ids so successful writes can suppress duplicates+ *+ * Returns:+ * - Resolves after best-effort emission attempt+ */+export const emitToolOutcomeSafely = async (+ input: EmitToolOutcomeInput & {+ policyStateStore: AgentSignalPolicyStateStore;+ ttlSeconds: number;+ },+) => {+ try {+ await emitToolOutcome(input);+ } catch (error) {+ console.error('[AgentSignal] Failed to emit tool outcome:', error);+ }+};diff --git a/src/server/services/agentSignal/procedure/index.ts b/src/server/services/agentSignal/procedure/index.tsnew file mode 100644index 00000000000..ae198cb9156--- /dev/null+++ b/src/server/services/agentSignal/procedure/index.ts@@ -0,0 +1,97 @@+import type { AgentSignalPolicyStateStore } from '../store/types';+import {+ appendAndScoreProcedureAccumulatorRecord,+ appendProcedureAccumulatorRecord,+} from './accumulator';+import { createProcedureMarkerKeysForRead } from './keys';+import { readFirstActiveHandledProcedureMarker, writeProcedureMarker } from './marker';+import { appendProcedureReceipt } from './receipt';+import { writeProcedureRecordField } from './record';+import type { AgentSignalProcedureRecord } from './types';++export * from './accumulator';+export * from './batchScorer';+export * from './emitToolOutcome';+export * from './inspector';+export * from './keys';+export * from './marker';+export * from './receipt';+export * from './record';+export * from './toolOutcome';+export * from './types';++/**+ * Input for composing procedure policy dependencies from one policy-state store.+ */+export interface CreateProcedurePolicyOptionsInput {+ /** Optional current-time provider for deterministic tests and eval runs. */+ now?: () => number;+ /** Policy-state store shared by records, markers, receipts, and accumulators. */+ policyStateStore: AgentSignalPolicyStateStore;+ /** TTL in seconds for procedure policy-state fields. */+ ttlSeconds: number;+}++/**+ * Composes procedure policy dependencies from a policy-state store.+ *+ * Use when:+ * - Default Agent Signal policies need procedure projections+ * - Tests or evals need isolated in-memory policy state+ *+ * Expects:+ * - One policy-state store backs all procedure projections for a runtime+ *+ * Returns:+ * - Dependency bag consumed by procedure-aware policy handlers+ */+export const createProcedurePolicyOptions = (input: CreateProcedurePolicyOptionsInput) => {+ const now = input.now ?? (() => Date.now());+ const appendRecord = async (record: AgentSignalProcedureRecord) => {+ await appendProcedureAccumulatorRecord(input.policyStateStore, record, input.ttlSeconds);+ };++ return {+ accumulator: {+ appendAndScore: (record: AgentSignalProcedureRecord) =>+ appendAndScoreProcedureAccumulatorRecord(input.policyStateStore, record, input.ttlSeconds, {+ now: now(),+ }),+ appendRecord,+ },+ markerReader: {+ shouldSuppress: async (markerInput: {+ domainKey: string;+ intentClass?: string;+ intentClassCandidates?: string[];+ procedureKey: string;+ scopeKey: string;+ }) => {+ const marker = await readFirstActiveHandledProcedureMarker(+ input.policyStateStore,+ createProcedureMarkerKeysForRead(markerInput),+ now(),+ );++ return Boolean(marker);+ },+ },+ markerStore: {+ write: (marker: Parameters<typeof writeProcedureMarker>[1]) =>+ writeProcedureMarker(input.policyStateStore, marker, input.ttlSeconds),+ },+ now,+ receiptStore: {+ append: (receipt: Parameters<typeof appendProcedureReceipt>[1]) =>+ appendProcedureReceipt(input.policyStateStore, receipt, {+ maxItems: 8,+ ttlSeconds: input.ttlSeconds,+ }),+ },+ recordStore: {+ write: (record: AgentSignalProcedureRecord) =>+ writeProcedureRecordField(input.policyStateStore, record, input.ttlSeconds),+ },+ ttlSeconds: input.ttlSeconds,+ };+};diff --git a/src/server/services/agentSignal/procedure/inspector.ts b/src/server/services/agentSignal/procedure/inspector.tsnew file mode 100644index 00000000000..c681002e1a0--- /dev/null+++ b/src/server/services/agentSignal/procedure/inspector.ts@@ -0,0 +1,110 @@+import type { AgentSignalPolicyStateStore } from '../store/types';+import {+ PROCEDURE_ACCUMULATOR_POLICY_ID,+ PROCEDURE_MARKER_INDEX_POLICY_ID,+ PROCEDURE_MARKER_POLICY_ID,+ PROCEDURE_RECEIPTS_POLICY_ID,+ PROCEDURE_RECORDS_POLICY_ID,+} from './keys';+import type {+ AgentSignalProcedureMarker,+ AgentSignalProcedureReceipt,+ AgentSignalProcedureRecord,+} from './types';++/**+ * Procedure projection snapshot for one runtime scope.+ */+export interface AgentSignalProcedureInspectionSnapshot {+ /** Raw accumulator fields merged from known coarse domain buckets. */+ accumulatorFields: Record<string, string>;+ /** Scope-indexed procedure markers. */+ markers: AgentSignalProcedureMarker[];+ /** Scope-local procedure receipts. */+ receipts: AgentSignalProcedureReceipt[];+ /** Scope-local procedure records. */+ records: AgentSignalProcedureRecord[];+}++/**+ * Reads compact Agent Signal procedure projections for devtools and evals.+ *+ * Use when:+ * - Eval assertions need procedure state written by the runtime+ * - Devtools need compact records, markers, receipts, and accumulator fields+ *+ * Expects:+ * - Store values are JSON fields written by procedure helpers+ *+ * Returns:+ * - Inspection snapshots without exposing a production route+ */+export class AgentSignalProcedureInspector {+ constructor(private readonly store: Pick<AgentSignalPolicyStateStore, 'readPolicyState'>) {}++ /**+ * Inspects records, markers, receipts, and known accumulator buckets for one scope.+ *+ * Use when:+ * - Eval assertions need a scope-local procedure snapshot+ * - Devtools need compact state without querying Redis keys directly+ *+ * Expects:+ * - `scopeKey` uses the same scope as runtime execution+ *+ * Returns:+ * - Parsed procedure inspection snapshot+ */+ async inspectScope(scopeKey: string): Promise<AgentSignalProcedureInspectionSnapshot> {+ const recordsState = await this.store.readPolicyState(PROCEDURE_RECORDS_POLICY_ID, scopeKey);+ const markerIndexState = await this.store.readPolicyState(+ PROCEDURE_MARKER_INDEX_POLICY_ID,+ scopeKey,+ );+ const receiptsState = await this.store.readPolicyState(PROCEDURE_RECEIPTS_POLICY_ID, scopeKey);+ const accumulatorStates = await Promise.all(+ ['memory', 'document', 'skill'].map((domain) =>+ this.store.readPolicyState(PROCEDURE_ACCUMULATOR_POLICY_ID, `${scopeKey}:${domain}`),+ ),+ );+ const accumulatorFields = Object.assign({}, ...accumulatorStates);++ return {+ accumulatorFields,+ markers: Object.entries(markerIndexState ?? {})+ .filter(([key]) => key.startsWith('marker:'))+ .map(([, value]) => value)+ .map((value) => JSON.parse(value) as AgentSignalProcedureMarker),+ receipts: Object.entries(receiptsState ?? {})+ .filter(([key]) => key.startsWith('receipt:'))+ .map(([, value]) => JSON.parse(value) as AgentSignalProcedureReceipt),+ records: Object.entries(recordsState ?? {})+ .filter(([key]) => key.startsWith('record:'))+ .map(([, value]) => JSON.parse(value) as AgentSignalProcedureRecord),+ };+ }++ /**+ * Reads explicit marker keys.+ *+ * Use when:+ * - Tests need to inspect marker keys that may not be in a scope index+ * - Debugging exact suppression candidates+ *+ * Expects:+ * - Marker keys are fully qualified policy marker keys+ *+ * Returns:+ * - Parsed markers found at the requested keys+ */+ async inspectMarkerKeys(markerKeys: string[]) {+ const markers: AgentSignalProcedureMarker[] = [];++ for (const markerKey of markerKeys) {+ const state = await this.store.readPolicyState(PROCEDURE_MARKER_POLICY_ID, markerKey);+ if (state?.marker) markers.push(JSON.parse(state.marker) as AgentSignalProcedureMarker);+ }++ return markers;+ }+}diff --git a/src/server/services/agentSignal/procedure/keys.ts b/src/server/services/agentSignal/procedure/keys.tsnew file mode 100644index 00000000000..af9526f1cbd--- /dev/null+++ b/src/server/services/agentSignal/procedure/keys.ts@@ -0,0 +1,108 @@+export const PROCEDURE_MARKER_POLICY_ID = 'procedure-marker';+export const PROCEDURE_MARKER_INDEX_POLICY_ID = 'procedure-marker-index';+export const PROCEDURE_RECORDS_POLICY_ID = 'procedure-records';+export const PROCEDURE_RECEIPTS_POLICY_ID = 'procedure-receipts';+export const PROCEDURE_ACCUMULATOR_POLICY_ID = 'procedure-accumulator';++/**+ * Input for building stable procedure identity from structured ids.+ */+export interface CreateProcedureKeyInput {+ /** Message id takes priority because same-turn suppression is message-scoped. */+ messageId?: string;+ /** Operation id is used when no message id exists. */+ operationId?: string;+ /** Root source id fallback from the Agent Signal chain. */+ rootSourceId: string;+ /** Tool call id is used when message and operation ids are absent. */+ toolCallId?: string;+}++/**+ * Creates a stable procedure key from structured ids only.+ *+ * Before:+ * - `{ messageId: "m1", rootSourceId: "source_1" }`+ *+ * After:+ * - `"message:m1"`+ */+export const createProcedureKey = (input: CreateProcedureKeyInput) => {+ if (input.messageId) return `message:${input.messageId}`;+ if (input.operationId) return `operation:${input.operationId}`;+ if (input.toolCallId) return `tool-call:${input.toolCallId}`;+ return `root-source:${input.rootSourceId}`;+};++/**+ * Normalizes a domain key into the coarse accumulator bucket.+ *+ * Before:+ * - `"memory:user-preference"`+ *+ * After:+ * - `"memory"`+ */+export const getCoarseProcedureDomain = (domainKey: string) => domainKey.split(':')[0] ?? domainKey;++/**+ * Input for building a fully qualified procedure marker key.+ */+export interface ProcedureMarkerKeyInput {+ /** Fine-grained domain key guarded by the marker. */+ domainKey: string;+ /** Optional intent class guarded by the marker. */+ intentClass?: string;+ /** Structured procedure key created from ids, never text. */+ procedureKey: string;+ /** Runtime scope shared by direct outcomes and planner suppression. */+ scopeKey: string;+}++/**+ * Builds a Redis policy-state key for a procedure marker.+ *+ * Use when:+ * - Writing a handled marker after procedure record persistence succeeds+ * - Reading markers for planner suppression+ *+ * Expects:+ * - Caller already selected the correct runtime scope+ *+ * Returns:+ * - Fully qualified marker key string+ */+export const buildProcedureMarkerKey = (input: ProcedureMarkerKeyInput) => {+ return [+ 'agent-signal:policy:procedure-marker',+ input.scopeKey,+ input.domainKey,+ input.intentClass ?? 'unknown',+ input.procedureKey,+ ].join(':');+};++/**+ * Creates candidate marker keys for suppression reads.+ *+ * Use when:+ * - Planner needs to check multiple plausible intent classes+ * - Direct outcomes may have written a more specific intent class than the planner inferred+ *+ * Expects:+ * - `procedureKey`, `scopeKey`, and `domainKey` identify the same procedure family+ *+ * Returns:+ * - Deduplicated marker keys in candidate order+ */+export const createProcedureMarkerKeysForRead = (+ input: ProcedureMarkerKeyInput & { intentClassCandidates?: string[] },+) => {+ const candidates = input.intentClassCandidates?.length+ ? input.intentClassCandidates+ : [input.intentClass ?? 'unknown'];++ return [...new Set(candidates)].map((intentClass) =>+ buildProcedureMarkerKey({ ...input, intentClass }),+ );+};diff --git a/src/server/services/agentSignal/procedure/marker.ts b/src/server/services/agentSignal/procedure/marker.tsnew file mode 100644index 00000000000..9b61f332f21--- /dev/null+++ b/src/server/services/agentSignal/procedure/marker.ts@@ -0,0 +1,141 @@+import type { AgentSignalPolicyStateStore } from '../store/types';+import {+ buildProcedureMarkerKey,+ PROCEDURE_MARKER_INDEX_POLICY_ID,+ PROCEDURE_MARKER_POLICY_ID,+} from './keys';+import type { AgentSignalProcedureMarker } from './types';++/**+ * Creates a marker and derives its policy-state key.+ *+ * Use when:+ * - A procedure record has already been persisted+ * - The planner or accumulator needs a compact gate+ *+ * Expects:+ * - `procedureKey` is based on structured ids only+ *+ * Returns:+ * - Marker with fully qualified key+ */+export const createProcedureMarker = (+ input: Omit<AgentSignalProcedureMarker, 'key'> & { procedureKey: string },+): AgentSignalProcedureMarker => ({+ ...input,+ key: buildProcedureMarkerKey(input),+});++/**+ * Checks whether a marker is still active.+ *+ * Use when:+ * - Reading marker state for suppression+ * - Filtering stale policy gates+ *+ * Expects:+ * - `now` is a millisecond timestamp+ *+ * Returns:+ * - Whether the marker has not expired+ */+export const isProcedureMarkerActive = (marker: AgentSignalProcedureMarker, now: number) =>+ marker.expiresAt > now;++/**+ * Checks whether marker state should suppress planner actions.+ *+ * Use when:+ * - Planner is deciding whether same-source work was already handled+ * - Only handled markers should suppress actions+ *+ * Expects:+ * - Missing markers and non-handled markers are not suppression signals+ *+ * Returns:+ * - Whether planner actions should be suppressed+ */+export const shouldSuppressByMarker = (+ marker: AgentSignalProcedureMarker | undefined,+ now: number,+) => marker?.markerType === 'handled' && isProcedureMarkerActive(marker, now);++/**+ * Writes a procedure marker and scope index entry.+ *+ * Use when:+ * - Procedure record persistence has already succeeded+ * - Eval and inspection tools need scope-local marker discovery+ *+ * Expects:+ * - Store writes are policy-state hash merges+ *+ * Returns:+ * - Resolves after marker and index writes complete+ */+export const writeProcedureMarker = async (+ store: AgentSignalPolicyStateStore,+ marker: AgentSignalProcedureMarker,+ ttlSeconds: number,+) => {+ await store.writePolicyState(+ PROCEDURE_MARKER_POLICY_ID,+ marker.key,+ { marker: JSON.stringify(marker) },+ ttlSeconds,+ );+ await store.writePolicyState(+ PROCEDURE_MARKER_INDEX_POLICY_ID,+ marker.scopeKey,+ { [`marker:${encodeURIComponent(marker.key)}`]: JSON.stringify(marker) },+ ttlSeconds,+ );+};++/**+ * Reads one procedure marker by fully qualified marker key.+ *+ * Use when:+ * - Planner checks a specific suppression candidate+ * - Inspector needs exact marker reads+ *+ * Expects:+ * - Marker payload is JSON written by {@link writeProcedureMarker}+ *+ * Returns:+ * - Parsed marker or undefined when absent+ */+export const readProcedureMarker = async (+ store: Pick<AgentSignalPolicyStateStore, 'readPolicyState'>,+ markerKey: string,+) => {+ const state = await store.readPolicyState(PROCEDURE_MARKER_POLICY_ID, markerKey);+ if (!state?.marker) return undefined;+ return JSON.parse(state.marker) as AgentSignalProcedureMarker;+};++/**+ * Reads candidate marker keys and returns the first active handled marker.+ *+ * Use when:+ * - Planner has multiple possible intent-class marker keys+ * - Suppression should stop at the first active handled marker+ *+ * Expects:+ * - `markerKeys` are already ordered by caller preference+ *+ * Returns:+ * - Active handled marker or undefined+ */+export const readFirstActiveHandledProcedureMarker = async (+ store: Pick<AgentSignalPolicyStateStore, 'readPolicyState'>,+ markerKeys: string[],+ now: number,+) => {+ for (const markerKey of markerKeys) {+ const marker = await readProcedureMarker(store, markerKey);+ if (shouldSuppressByMarker(marker, now)) return marker;+ }++ return undefined;+};diff --git a/src/server/services/agentSignal/procedure/receipt.ts b/src/server/services/agentSignal/procedure/receipt.tsnew file mode 100644index 00000000000..42aeb28b050--- /dev/null+++ b/src/server/services/agentSignal/procedure/receipt.ts@@ -0,0 +1,152 @@+import type { AgentSignalPolicyStateStore } from '../store/types';+import { getCoarseProcedureDomain, PROCEDURE_RECEIPTS_POLICY_ID } from './keys';+import type {+ AgentSignalProcedureReceipt,+ MessageAgentSignalProcedureReceiptEnvelope,+} from './types';++/**+ * Options for appending procedure receipts.+ */+export interface AppendProcedureReceiptOptions {+ /** Maximum receipts readers should keep visible. */+ maxItems: number;+ /** Policy-state ttl in seconds. */+ ttlSeconds: number;+}++/**+ * Appends one receipt field to the scope-local receipt map.+ *+ * Use when:+ * - A procedure record should become visible to context continuity+ * - Concurrent receipt writes must avoid replacing each other+ *+ * Expects:+ * - Store writes merge hash fields+ *+ * Returns:+ * - Resolves after the receipt field is persisted+ */+export const appendProcedureReceipt = async (+ store: AgentSignalPolicyStateStore,+ receipt: AgentSignalProcedureReceipt,+ options: AppendProcedureReceiptOptions,+) => {+ // Receipt writes use one hash field per receipt to avoid overwriting concurrent receipt updates.+ // Readers sort and trim after reading the hash.+ await store.writePolicyState(+ PROCEDURE_RECEIPTS_POLICY_ID,+ receipt.scopeKey,+ { [`receipt:${receipt.id}`]: JSON.stringify(receipt) },+ options.ttlSeconds,+ );+};++/**+ * Reads recent procedure receipts for one runtime scope.+ *+ * Use when:+ * - Rendering compact context continuity+ * - Inspecting recent procedure outcomes+ *+ * Expects:+ * - Receipt fields are JSON written by {@link appendProcedureReceipt}+ *+ * Returns:+ * - Receipts sorted newest first and trimmed to `maxItems`+ */+export const readProcedureReceipts = async (+ store: Pick<AgentSignalPolicyStateStore, 'readPolicyState'>,+ scopeKey: string,+ maxItems: number,+) => {+ const state = await store.readPolicyState(PROCEDURE_RECEIPTS_POLICY_ID, scopeKey);++ return Object.entries(state ?? {})+ .filter(([key]) => key.startsWith('receipt:'))+ .map(([, value]) => JSON.parse(value) as AgentSignalProcedureReceipt)+ .sort((left, right) => right.updatedAt - left.updatedAt)+ .slice(0, maxItems);+};++/**+ * Converts a receipt into compact message metadata.+ *+ * Use when:+ * - Persisting recent procedure status into message metadata+ * - Hiding internal acknowledged state from message consumers+ *+ * Expects:+ * - Receipt summary is already compact and safe for context+ *+ * Returns:+ * - Message metadata envelope+ */+export const toMessageReceiptEnvelope = (+ receipt: AgentSignalProcedureReceipt,+): MessageAgentSignalProcedureReceiptEnvelope => ({+ domainKey: receipt.domainKey,+ id: receipt.id,+ status: receipt.status === 'acknowledged' ? 'processing' : receipt.status,+ summary: receipt.summary,+ updatedAt: receipt.updatedAt,+});++/**+ * Merges one receipt envelope into message metadata.+ *+ * Use when:+ * - Updating compact message metadata after a procedure outcome+ * - Preserving unrelated metadata keys+ *+ * Expects:+ * - Existing `agentSignalReceipts` may be absent or malformed+ *+ * Returns:+ * - Metadata with a deduplicated recent receipt list+ */+export const mergeMessageReceiptEnvelope = (+ metadata: Record<string, unknown> | undefined,+ envelope: MessageAgentSignalProcedureReceiptEnvelope,+) => {+ const existing = Array.isArray(metadata?.agentSignalReceipts)+ ? (metadata.agentSignalReceipts as MessageAgentSignalProcedureReceiptEnvelope[])+ : [];++ return {+ ...metadata,+ agentSignalReceipts: [...existing.filter((item) => item.id !== envelope.id), envelope].slice(+ -8,+ ),+ };+};++/**+ * Renders procedure receipts into a compact context summary.+ *+ * Use when:+ * - Injecting recent causal facts back into model context+ * - Hiding internal receipt ids and marker state+ *+ * Expects:+ * - Receipt summaries are user-safe compact text+ *+ * Returns:+ * - A newline-delimited context summary, or empty string when nothing is visible+ */+export const renderProcedureReceiptContext = (receipts: AgentSignalProcedureReceipt[]) => {+ const visible = receipts+ .filter((receipt) => receipt.status !== 'failed' || receipt.summary.length > 0)+ .sort((left, right) => right.updatedAt - left.updatedAt)+ .slice(0, 5);++ if (visible.length === 0) return '';++ return [+ 'Recent Agent Signal updates:',+ ...visible.map(+ (receipt) => `${'-'} ${getCoarseProcedureDomain(receipt.domainKey)}: ${receipt.summary}`,+ ),+ ].join('\n');+};diff --git a/src/server/services/agentSignal/procedure/record.ts b/src/server/services/agentSignal/procedure/record.tsnew file mode 100644index 00000000000..f5261912b62--- /dev/null+++ b/src/server/services/agentSignal/procedure/record.ts@@ -0,0 +1,57 @@+import type { AgentSignalPolicyStateStore } from '../store/types';+import { PROCEDURE_RECORDS_POLICY_ID } from './keys';+import type { AgentSignalProcedureRecord } from './types';++let recordSeed = 0;++const createRecordId = () => {+ if (globalThis.crypto?.randomUUID) return `procedure-record:${globalThis.crypto.randomUUID()}`;+ recordSeed += 1;+ return `procedure-record:${Date.now().toString(36)}:${recordSeed.toString(36)}`;+};++/**+ * Creates a compact procedure record with a generated id when needed.+ *+ * Use when:+ * - Projecting existing runtime graph nodes into policy facts+ * - Direct tool outcomes need a durable synchronous projection+ *+ * Expects:+ * - Caller supplies domain, scope, refs, and status+ *+ * Returns:+ * - Procedure record with stable id+ */+export const createProcedureRecord = (+ input: Omit<AgentSignalProcedureRecord, 'id'> & { id?: string },+): AgentSignalProcedureRecord => ({+ ...input,+ id: input.id ?? createRecordId(),+});++/**+ * Writes one procedure record into the scope-local record map.+ *+ * Use when:+ * - Policy state needs compact records for inspection and continuity+ * - Record write must happen before marker writes+ *+ * Expects:+ * - Store writes merge hash fields without replacing other records+ *+ * Returns:+ * - Resolves after the record field is persisted+ */+export const writeProcedureRecordField = async (+ store: AgentSignalPolicyStateStore,+ record: AgentSignalProcedureRecord,+ ttlSeconds: number,+) => {+ await store.writePolicyState(+ PROCEDURE_RECORDS_POLICY_ID,+ record.scopeKey,+ { [`record:${record.id}`]: JSON.stringify(record) },+ ttlSeconds,+ );+};diff --git a/src/server/services/agentSignal/procedure/toolOutcome.ts b/src/server/services/agentSignal/procedure/toolOutcome.tsnew file mode 100644index 00000000000..d5ca4f5c9f7--- /dev/null+++ b/src/server/services/agentSignal/procedure/toolOutcome.ts@@ -0,0 +1,165 @@+import type { AgentSignalSource, RuntimeProcessorResult } from '@lobechat/agent-signal';+import { createSignal } from '@lobechat/agent-signal';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';++import { AGENT_SIGNAL_POLICY_SIGNAL_TYPES } from '../policies/types';+import type { RuntimeProcessorContext } from '../runtime/context';+import { defineSourceHandler } from '../runtime/middleware';+import { createProcedureKey, getCoarseProcedureDomain } from './keys';+import { createProcedureMarker } from './marker';+import { createProcedureRecord } from './record';+import type {+ AgentSignalProcedureMarker,+ AgentSignalProcedureReceipt,+ AgentSignalProcedureRecord,+} from './types';++/**+ * Storage dependencies for the tool outcome procedure source handler.+ */+export interface ToolOutcomeProcedureDeps {+ /** Appends a record into domain accumulation state. */+ accumulator: { appendRecord: (record: AgentSignalProcedureRecord) => Promise<void> };+ /** Writes handled markers after record persistence succeeds. */+ markerStore: { write: (marker: AgentSignalProcedureMarker) => Promise<void> };+ /** Provides a consistent millisecond timestamp for procedure writes. */+ now: () => number;+ /** Appends context receipts for compact continuity. */+ receiptStore: { append: (receipt: AgentSignalProcedureReceipt) => Promise<void> };+ /** Writes the compact procedure record. */+ recordStore: { write: (record: AgentSignalProcedureRecord) => Promise<void> };+ /** TTL used for marker expiration and policy-state writes. */+ ttlSeconds: number;+}++const TOOL_OUTCOME_SOURCE_TYPES = [+ AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeCompleted,+ AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeFailed,+] as const;++interface ToolOutcomePayload {+ domainKey?: string;+ intentClass?: string;+ messageId?: string;+ operationId?: string;+ outcome?: { status?: string; summary?: string };+ relatedObjects?: AgentSignalProcedureRecord['relatedObjects'];+ toolCallId?: string;+}++const shouldWriteHandledMarker = (input: {+ domainKey: string;+ intentClass?: string;+ status: string;+}) => {+ if (input.status !== 'succeeded' && input.status !== 'skipped') return false;++ const domain = getCoarseProcedureDomain(input.domainKey);+ if (domain === 'memory') {+ return input.intentClass === 'explicit_persistence';+ }+ if (domain === 'skill') {+ return input.intentClass === 'tool_command' || input.intentClass === 'explicit_persistence';+ }++ return false;+};++/**+ * Creates the source handler that normalizes direct tool outcomes into procedure projections.+ *+ * Use when:+ * - Direct memory, skill, or document tools emit generic outcome sources+ * - Same-turn suppression needs the synchronous procedure projection to already exist+ *+ * Expects:+ * - Dependencies write records before markers+ * - Source payloads use `tool.outcome.completed` or `tool.outcome.failed`+ *+ * Returns:+ * - Source handler that dispatches a `signal.tool.outcome` signal+ */+export const createToolOutcomeSourceHandler = (deps: ToolOutcomeProcedureDeps) =>+ defineSourceHandler(+ TOOL_OUTCOME_SOURCE_TYPES,+ 'source.tool-outcome.procedure',+ async (+ source: AgentSignalSource,+ context: RuntimeProcessorContext,+ ): Promise<RuntimeProcessorResult | void> => {+ const payload = source.payload as ToolOutcomePayload;+ if (!payload.domainKey || !payload.outcome?.status) return;++ const signal = createSignal({+ payload: source.payload,+ signalId: `${source.sourceId}:signal:tool-outcome`,+ signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.toolOutcome,+ source,+ timestamp: source.timestamp,+ });+ const now = deps.now();+ const record = createProcedureRecord({+ accumulatorRole: 'context',+ cheapScoreDelta: 0,+ createdAt: now,+ domainKey: payload.domainKey,+ id: `procedure-record:${source.sourceId}`,+ intentClass: payload.intentClass,+ refs: { signalIds: [signal.signalId], sourceIds: [source.sourceId] },+ relatedObjects: payload.relatedObjects,+ scopeKey: context.scopeKey,+ status: payload.outcome.status === 'failed' ? 'failed' : 'handled',+ summary: payload.outcome.summary,+ });++ await deps.recordStore.write(record);+ await deps.accumulator.appendRecord(record);++ const procedureKey = createProcedureKey({+ messageId: payload.messageId,+ operationId: payload.operationId,+ rootSourceId: source.chain.rootSourceId,+ toolCallId: payload.toolCallId,+ });++ if (+ shouldWriteHandledMarker({+ domainKey: payload.domainKey,+ intentClass: payload.intentClass,+ status: payload.outcome.status,+ })+ ) {+ await deps.markerStore.write(+ createProcedureMarker({+ createdAt: now,+ domainKey: payload.domainKey,+ expiresAt: now + deps.ttlSeconds * 1000,+ intentClass: payload.intentClass,+ markerType: 'handled',+ procedureKey,+ recordId: record.id,+ scopeKey: context.scopeKey,+ signalId: signal.signalId,+ sourceId: source.sourceId,+ }),+ );+ }++ await deps.receiptStore.append({+ createdAt: now,+ domainKey: payload.domainKey,+ id: `procedure-receipt:${record.id}`,+ intentClass: payload.intentClass,+ messageId: payload.messageId,+ recordIds: [record.id],+ relatedObjects: payload.relatedObjects,+ scopeKey: context.scopeKey,+ sourceId: source.sourceId,+ status: payload.outcome.status === 'failed' ? 'failed' : 'handled',+ summary: payload.outcome.summary ?? `${payload.domainKey} tool outcome handled.`,+ updatedAt: now,+ });++ return { signals: [signal], status: 'dispatch' };+ },+ );diff --git a/src/server/services/agentSignal/procedure/types.ts b/src/server/services/agentSignal/procedure/types.tsnew file mode 100644index 00000000000..a70a893a112--- /dev/null+++ b/src/server/services/agentSignal/procedure/types.ts@@ -0,0 +1,201 @@+export type AgentSignalProcedureStatus = 'failed' | 'handled' | 'observed' | 'suppressed';+export type AgentSignalProcedureMarkerType = 'accumulated' | 'handled' | 'suppressed';+export type AgentSignalProcedureReceiptStatus =+ | 'acknowledged'+ | 'failed'+ | 'handled'+ | 'processing'+ | 'queued'+ | 'skipped'+ | 'updated';++/**+ * Related object attached to a compact procedure fact.+ */+export interface AgentSignalProcedureRelatedObject {+ /** Stable object id in the owning subsystem. */+ objectId: string;+ /** Object family such as memory, document, skill, message, or tool. */+ objectType: string;+ /** Relationship between the procedure and the object. */+ relation?: string;+}++/**+ * Runtime graph ids referenced by one compact procedure record.+ */+export interface AgentSignalProcedureRecordRefs {+ /** Agent Signal action node ids caused by the procedure. */+ actionIds?: string[];+ /** Agent Signal executor result node ids caused by the procedure. */+ resultIds?: string[];+ /** Agent Signal signal node ids caused by the procedure. */+ signalIds?: string[];+ /** Agent Signal source node ids caused by the procedure. */+ sourceIds?: string[];+}++/**+ * Compact policy fact projected from existing Agent Signal runtime nodes.+ *+ * This is not a source, signal, action, executor result, or trace graph. Store node ids and+ * summaries here; keep raw payloads in the existing runtime graph and observability projection.+ */+export interface AgentSignalProcedureRecord {+ /** Accumulator role used by domain bucket scoring. */+ accumulatorRole?: 'candidate' | 'context' | 'ignored';+ /** Cheap deterministic score delta for weak-signal accumulation. */+ cheapScoreDelta?: number;+ /** Millisecond timestamp when the record was created. */+ createdAt: number;+ /** Fine-grained domain key such as `memory:user-preference`. */+ domainKey: string;+ /** Stable record id for policy-state fields and receipts. */+ id: string;+ /** Optional intent class inferred by the direct tool or planner. */+ intentClass?: string;+ /** Runtime graph references related to this compact projection. */+ refs: AgentSignalProcedureRecordRefs;+ /** Related domain objects changed or observed by this procedure. */+ relatedObjects?: AgentSignalProcedureRelatedObject[];+ /** Runtime scope shared by direct outcomes and planner suppression. */+ scopeKey: string;+ /** Compact procedure status used for marker and receipt projections. */+ status: AgentSignalProcedureStatus;+ /** Human-readable compact summary for context continuity. */+ summary?: string;+}++/**+ * Planner and accumulator gate stored as policy state.+ *+ * Markers answer whether a procedure has already been handled, suppressed, or accumulated. They are+ * not user-visible receipts and not full history.+ */+export interface AgentSignalProcedureMarker {+ /** Action id associated with the marker when the planner created one. */+ actionId?: string;+ /** Millisecond timestamp when the marker was created. */+ createdAt: number;+ /** Fine-grained domain key guarded by the marker. */+ domainKey: string;+ /** Millisecond timestamp after which the marker is inactive. */+ expiresAt: number;+ /** Optional intent class guarded by the marker. */+ intentClass?: string;+ /** Fully qualified policy-state key for this marker. */+ key: string;+ /** Marker behavior category. */+ markerType: AgentSignalProcedureMarkerType;+ /** Receipt id associated with this marker. */+ receiptId?: string;+ /** Record id associated with this marker. */+ recordId?: string;+ /** Runtime scope shared by direct outcomes and planner suppression. */+ scopeKey: string;+ /** Signal id associated with this marker. */+ signalId?: string;+ /** Source id associated with this marker. */+ sourceId?: string;+}++/**+ * Status projection for context injection and compact message metadata.+ *+ * Receipts never drive planner suppression; marker state is the planner truth.+ */+export interface AgentSignalProcedureReceipt {+ /** Millisecond timestamp when the receipt was created. */+ createdAt: number;+ /** Fine-grained domain key represented by the receipt. */+ domainKey: string;+ /** Stable receipt id. */+ id: string;+ /** Optional intent class represented by the receipt. */+ intentClass?: string;+ /** Message id associated with the receipt when available. */+ messageId?: string;+ /** Procedure record ids summarized by the receipt. */+ recordIds?: string[];+ /** Related domain objects changed or observed by this procedure. */+ relatedObjects?: AgentSignalProcedureRelatedObject[];+ /** Runtime scope shared by direct outcomes and planner suppression. */+ scopeKey: string;+ /** Source id associated with the receipt. */+ sourceId?: string;+ /** User-visible status of the compact procedure projection. */+ status: AgentSignalProcedureReceiptStatus;+ /** Compact summary suitable for context injection. */+ summary: string;+ /** Millisecond timestamp when the receipt was last updated. */+ updatedAt: number;+}++/**+ * Compact message metadata envelope for recent Agent Signal procedure receipts.+ */+export interface MessageAgentSignalProcedureReceiptEnvelope {+ /** Fine-grained domain key represented by the receipt. */+ domainKey: string;+ /** Stable receipt id. */+ id: string;+ /** Message-visible status excluding acknowledged internal state. */+ status: Exclude<AgentSignalProcedureReceiptStatus, 'acknowledged'>;+ /** Compact summary suitable for context continuity. */+ summary: string;+ /** Millisecond timestamp when the receipt was last updated. */+ updatedAt: number;+}++/**+ * Domain bucket state for accumulated procedure records.+ */+export interface DomainProcedureAccumulatorState {+ /** Stable bucket key combining scope and coarse domain. */+ bucketKey: string;+ /** Deterministic cheap score used before batch scoring. */+ cheapScore: number;+ /** Coarse domain bucket such as memory, skill, or document. */+ domain: 'document' | 'memory' | 'skill' | string;+ /** Millisecond timestamp for first record observed in the bucket. */+ firstSeenAt: number;+ /** Last deterministic batch score result. */+ lastBatch?: DomainProcedureBatchScore;+ /** Millisecond timestamp for last emitted score signal. */+ lastEmittedAt?: number;+ /** Millisecond timestamp for last scoring attempt. */+ lastScoredAt?: number;+ /** Last scoring error message when batch scoring failed. */+ lastScoringError?: string;+ /** Millisecond timestamp for newest record observed in the bucket. */+ lastSeenAt: number;+ /** Number of appended records. */+ recordCount: number;+ /** Record ids contained in the bucket. */+ recordIds: string[];+ /** Runtime scope shared by direct outcomes and planner suppression. */+ scopeKey: string;+ /** Bucket schema version. */+ version: '1';+}++/**+ * Deterministic score output for one accumulated procedure bucket.+ */+export interface DomainProcedureBatchScore {+ /** Aggregate score across item scores. */+ aggregateScore: number;+ /** Confidence in the deterministic P0 score. */+ confidence: number;+ /** Per-record scoring details. */+ itemScores: Array<{+ reasons: string[];+ recordId: string;+ score: number;+ suggestedAction?: 'handle' | 'ignore' | 'maintain' | 'review' | 'summarize';+ }>;+ /** Millisecond timestamp for scoring. */+ scoredAt: number;+ /** Suggested aggregate actions for the bucket. */+ suggestedActions: string[];+}diff --git a/src/server/services/agentSignal/sources/renderers/agentUserMessage.ts b/src/server/services/agentSignal/sources/renderers/agentUserMessage.tsindex 362f0cfe3f9..aa26f50a3f5 100644--- a/src/server/services/agentSignal/sources/renderers/agentUserMessage.ts+++ b/src/server/services/agentSignal/sources/renderers/agentUserMessage.ts@@ -15,11 +15,12 @@ export const agentUserMessageRenderer = {: undefined,intents: Array.isArray(input.payload.intents)? input.payload.intents.filter(- (intent): intent is 'document' | 'memory' | 'persona' | 'prompt' =>+ (intent): intent is 'document' | 'memory' | 'persona' | 'prompt' | 'skill' =>intent === 'document' ||intent === 'memory' ||intent === 'persona' ||- intent === 'prompt',+ intent === 'prompt' ||+ intent === 'skill',): undefined,memoryPayload:diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 79036fc634d..3bb1e2b6ff8 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -1575,6 +1575,7 @@ export class AiAgentService {documentId: appContext?.documentId,groupId: appContext?.groupId,scope: appContext?.scope,+ sourceMessageId: userMessageRecord?.id ?? parentMessageId ?? undefined,taskId: operationTaskId,threadId: appContext?.threadId,topicId,diff --git a/src/server/services/toolExecution/serverRuntimes/activator.ts b/src/server/services/toolExecution/serverRuntimes/activator.tsindex 28aad684569..686d407159a 100644--- a/src/server/services/toolExecution/serverRuntimes/activator.ts+++ b/src/server/services/toolExecution/serverRuntimes/activator.ts@@ -9,6 +9,11 @@ import { SkillsExecutionRuntime } from '@lobechat/builtin-tool-skills/executionRimport { AgentSkillModel } from '@/database/models/agentSkill';import { filterBuiltinSkills } from '@/helpers/skillFilters';+import {+ emitToolOutcomeSafely,+ resolveToolOutcomeScope,+} from '@/server/services/agentSignal/procedure';+import { redisPolicyStateStore } from '@/server/services/agentSignal/store/adapters/redis/policyStateStore';import { type ServerRuntimeRegistration } from './types';@@ -19,6 +24,45 @@ import { type ServerRuntimeRegistration } from './types';export const activatorRuntime: ServerRuntimeRegistration = {factory: async (context) => {const activatedIds: string[] = [];+ const emitActivationOutcome = async (input: {+ errorReason?: string;+ identifiers: string[];+ status: 'failed' | 'succeeded';+ summary: string;+ }) => {+ if (!context.userId) return;++ const { scope, scopeKey } = resolveToolOutcomeScope({+ agentId: context.agentId,+ taskId: context.taskId,+ topicId: context.topicId,+ userId: context.userId,+ });++ await emitToolOutcomeSafely({+ apiName: 'activateSkill',+ context: { agentId: context.agentId, userId: context.userId },+ domainKey: 'skill:builtin-skill',+ errorReason: input.errorReason,+ identifier: LobeActivatorIdentifier,+ intentClass: 'tool_command',+ messageId: context.messageId,+ operationId: context.operationId,+ policyStateStore: redisPolicyStateStore,+ relatedObjects: input.identifiers.map((id) => ({+ objectId: id,+ objectType: 'skill',+ relation: 'selected',+ })),+ scope,+ scopeKey,+ status: input.status,+ summary: input.summary,+ ttlSeconds: 7 * 24 * 60 * 60,+ toolAction: 'activate',+ toolCallId: context.toolCallId,+ });+ };// Create SkillsExecutionRuntime for activateSkill delegationlet skillsRuntime: SkillsExecutionRuntime | undefined;@@ -38,7 +82,27 @@ export const activatorRuntime: ServerRuntimeRegistration = {}const service: ActivatorRuntimeService = {- activateSkill: skillsRuntime ? (args) => skillsRuntime!.activateSkill(args) : undefined,+ activateSkill: skillsRuntime+ ? async (args) => {+ try {+ const result = await skillsRuntime!.activateSkill(args);+ await emitActivationOutcome({+ identifiers: [args.name],+ status: 'succeeded',+ summary: 'Activator selected a skill.',+ });+ return result;+ } catch (error) {+ await emitActivationOutcome({+ errorReason: (error as Error).message,+ identifiers: [args.name],+ status: 'failed',+ summary: 'Activator failed to select a skill.',+ });+ throw error;+ }+ }+ : undefined,getActivatedToolIds: () => [...activatedIds],getToolManifests: async (identifiers: string[]): Promise<ToolManifestInfo[]> => {// Note: context.toolManifestMap should only contain discoverable tools.@@ -68,6 +132,13 @@ export const activatorRuntime: ServerRuntimeRegistration = {activatedIds.push(id);}}+ void emitActivationOutcome({+ identifiers,+ status: 'succeeded',+ summary: 'Activator marked skills as active.',+ }).catch((error) => {+ console.error('[AgentSignal] Failed to emit activator outcome:', error);+ });},};diff --git a/src/server/services/toolExecution/serverRuntimes/agentDocuments.ts b/src/server/services/toolExecution/serverRuntimes/agentDocuments.tsindex 2f77256746d..0d87977cee8 100644--- a/src/server/services/toolExecution/serverRuntimes/agentDocuments.ts+++ b/src/server/services/toolExecution/serverRuntimes/agentDocuments.ts@@ -4,6 +4,11 @@ import { AgentDocumentsExecutionRuntime } from '@lobechat/builtin-tool-agent-docimport { TaskModel } from '@/database/models/task';import { AgentDocumentsService } from '@/server/services/agentDocuments';+import {+ emitToolOutcomeSafely,+ resolveToolOutcomeScope,+} from '@/server/services/agentSignal/procedure';+import { redisPolicyStateStore } from '@/server/services/agentSignal/store/adapters/redis/policyStateStore';import { type ServerRuntimeRegistration } from './types';@@ -14,8 +19,85 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {}const service = new AgentDocumentsService(context.serverDB, context.userId);+ const userId = context.userId;const taskModel = new TaskModel(context.serverDB, context.userId);const { taskId } = context;+ const emitDocumentOutcome = async (input: {+ agentId?: string;+ apiName: string;+ documentId?: string;+ errorReason?: string;+ relation?: string;+ status: 'failed' | 'succeeded';+ summary: string;+ toolAction: string;+ }) => {+ const { scope, scopeKey } = resolveToolOutcomeScope({+ agentId: input.agentId ?? context.agentId,+ taskId: context.taskId,+ topicId: context.topicId,+ userId,+ });++ await emitToolOutcomeSafely({+ apiName: input.apiName,+ context: { agentId: input.agentId ?? context.agentId, userId },+ domainKey: 'document:agent-document',+ errorReason: input.errorReason,+ identifier: AgentDocumentsIdentifier,+ intentClass: 'explicit_persistence',+ messageId: context.messageId,+ operationId: context.operationId,+ policyStateStore: redisPolicyStateStore,+ relatedObjects: input.documentId+ ? [{ objectId: input.documentId, objectType: 'document', relation: input.relation }]+ : undefined,+ scope,+ scopeKey,+ status: input.status,+ summary: input.summary,+ ttlSeconds: 7 * 24 * 60 * 60,+ toolAction: input.toolAction,+ toolCallId: context.toolCallId,+ });+ };++ const withDocumentOutcome = async <T>(+ input: {+ agentId?: string;+ getDocumentId?: (result: T) => string | undefined;+ apiName: string;+ relation: string;+ summary: string;+ toolAction: string;+ },+ operation: () => Promise<T>,+ ) => {+ try {+ const result = await operation();+ await emitDocumentOutcome({+ agentId: input.agentId,+ apiName: input.apiName,+ documentId: input.getDocumentId?.(result),+ relation: input.relation,+ status: 'succeeded',+ summary: input.summary,+ toolAction: input.toolAction,+ });+ return result;+ } catch (error) {+ await emitDocumentOutcome({+ agentId: input.agentId,+ apiName: input.apiName,+ errorReason: (error as Error).message,+ relation: input.relation,+ status: 'failed',+ summary: `${input.summary} failed.`,+ toolAction: input.toolAction,+ });+ throw error;+ }+ };const pinToTask = async <T extends { documentId?: string } | undefined>(doc: T): Promise<T> => {if (taskId && doc?.documentId) {@@ -26,11 +108,47 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {return new AgentDocumentsExecutionRuntime({copyDocument: async ({ agentId, id, newTitle }) =>- pinToTask(await service.copyDocumentById(id, newTitle, agentId)),+ pinToTask(+ await withDocumentOutcome(+ {+ agentId,+ apiName: 'copyDocument',+ getDocumentId: (result) => result?.documentId,+ relation: 'created',+ summary: 'Agent documents copied a document.',+ toolAction: 'copy',+ },+ () => service.copyDocumentById(id, newTitle, agentId),+ ),+ ),createDocument: async ({ agentId, content, title }) =>- pinToTask(await service.createDocument(agentId, title, content)),+ pinToTask(+ await withDocumentOutcome(+ {+ agentId,+ apiName: 'createDocument',+ getDocumentId: (result) => result?.documentId,+ relation: 'created',+ summary: 'Agent documents created a document.',+ toolAction: 'create',+ },+ () => service.createDocument(agentId, title, content),+ ),+ ),createTopicDocument: async ({ agentId, content, title, topicId }) =>- pinToTask(await service.createForTopic(agentId, title, content, topicId)),+ pinToTask(+ await withDocumentOutcome(+ {+ agentId,+ apiName: 'createTopicDocument',+ getDocumentId: (result) => result?.documentId,+ relation: 'created',+ summary: 'Agent documents created a topic document.',+ toolAction: 'create',+ },+ () => service.createForTopic(agentId, title, content, topicId),+ ),+ ),listDocuments: async ({ agentId }) => {const docs = await service.listDocuments(agentId);return docs.map((d) => ({@@ -50,18 +168,70 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {}));},modifyNodes: ({ agentId, id, operations }) =>- service.modifyDocumentNodesById(id, operations, agentId),+ withDocumentOutcome(+ {+ agentId,+ apiName: 'modifyNodes',+ getDocumentId: () => id,+ relation: 'updated',+ summary: 'Agent documents modified document nodes.',+ toolAction: 'edit',+ },+ () => service.modifyDocumentNodesById(id, operations, agentId),+ ),readDocument: ({ agentId, id }) => service.getDocumentSnapshotById(id, agentId),- removeDocument: ({ agentId, id }) => service.removeDocumentById(id, agentId),+ removeDocument: ({ agentId, id }) =>+ withDocumentOutcome(+ {+ agentId,+ apiName: 'removeDocument',+ getDocumentId: () => id,+ relation: 'removed',+ summary: 'Agent documents removed a document.',+ toolAction: 'remove',+ },+ () => service.removeDocumentById(id, agentId),+ ),renameDocument: ({ agentId, id, newTitle }) =>- service.renameDocumentById(id, newTitle, agentId),+ withDocumentOutcome(+ {+ agentId,+ apiName: 'renameDocument',+ getDocumentId: () => id,+ relation: 'updated',+ summary: 'Agent documents renamed a document.',+ toolAction: 'rename',+ },+ () => service.renameDocumentById(id, newTitle, agentId),+ ),replaceDocumentContent: ({ agentId, content, id }) =>- service.replaceDocumentContentById(id, content, agentId),+ withDocumentOutcome(+ {+ agentId,+ apiName: 'replaceDocumentContent',+ getDocumentId: () => id,+ relation: 'updated',+ summary: 'Agent documents replaced document content.',+ toolAction: 'replace',+ },+ () => service.replaceDocumentContentById(id, content, agentId),+ ),updateLoadRule: ({ agentId, id, rule }) =>- service.updateLoadRuleById(- id,- { ...rule, rule: rule.rule as DocumentLoadRule | undefined },- agentId,+ withDocumentOutcome(+ {+ agentId,+ apiName: 'updateLoadRule',+ getDocumentId: () => id,+ relation: 'updated',+ summary: 'Agent documents updated a load rule.',+ toolAction: 'update',+ },+ () =>+ service.updateLoadRuleById(+ id,+ { ...rule, rule: rule.rule as DocumentLoadRule | undefined },+ agentId,+ ),),});},diff --git a/src/server/services/toolExecution/serverRuntimes/memory.ts b/src/server/services/toolExecution/serverRuntimes/memory.tsindex 958cc6cf615..3e4c6dd5618 100644--- a/src/server/services/toolExecution/serverRuntimes/memory.ts+++ b/src/server/services/toolExecution/serverRuntimes/memory.ts@@ -44,6 +44,11 @@ import {import { userSettings } from '@/database/schemas';import { getServerDefaultFilesConfig } from '@/server/globalConfig';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import {+ emitToolOutcomeSafely,+ resolveToolOutcomeScope,+} from '@/server/services/agentSignal/procedure';+import { redisPolicyStateStore } from '@/server/services/agentSignal/store/adapters/redis/policyStateStore';import { normalizeSearchMemoryParams } from '@/server/services/memory/userMemory/searchParams';import type { ServerRuntimeRegistration } from './types';@@ -108,23 +113,83 @@ const createEmbedder = (agentRuntime: any, embeddingModel: string, userId: strin};class MemoryServerRuntimeService implements MemoryRuntimeService {+ private agentId?: string;+ private emitOutcome?: typeof emitToolOutcomeSafely;+ private messageId?: string;private memoryModel: UserMemoryModel;+ private operationId?: string;private serverDB: LobeChatDatabase;- private userId: string;+ private taskId?: string;+ private toolCallId?: string;+ private topicId?: string;private memoryEffort: MemoryEffort;+ private userId: string;constructor(options: {+ agentId?: string;+ emitOutcome?: typeof emitToolOutcomeSafely;+ messageId?: string;memoryEffort: MemoryEffort;memoryModel: UserMemoryModel;+ operationId?: string;serverDB: LobeChatDatabase;+ taskId?: string;+ toolCallId?: string;+ topicId?: string;userId: string;}) {+ this.agentId = options.agentId;+ this.emitOutcome = options.emitOutcome;+ this.messageId = options.messageId;this.memoryModel = options.memoryModel;+ this.operationId = options.operationId;this.serverDB = options.serverDB;- this.userId = options.userId;+ this.taskId = options.taskId;+ this.toolCallId = options.toolCallId;+ this.topicId = options.topicId;this.memoryEffort = options.memoryEffort;+ this.userId = options.userId;}+ private emitUserMemoryOutcome = async (input: {+ apiName: string;+ errorReason?: string;+ objectId?: string;+ relation?: string;+ status: 'failed' | 'succeeded';+ summary: string;+ toolAction: string;+ }) => {+ const { scope, scopeKey } = resolveToolOutcomeScope({+ agentId: this.agentId,+ taskId: this.taskId,+ topicId: this.topicId,+ userId: this.userId,+ });++ await this.emitOutcome?.({+ apiName: input.apiName,+ context: { agentId: this.agentId, userId: this.userId },+ domainKey: 'memory:user-preference',+ errorReason: input.errorReason,+ identifier: MemoryIdentifier,+ intentClass: 'explicit_persistence',+ messageId: this.messageId,+ operationId: this.operationId,+ policyStateStore: redisPolicyStateStore,+ relatedObjects: input.objectId+ ? [{ objectId: input.objectId, objectType: 'memory', relation: input.relation }]+ : undefined,+ scope,+ scopeKey,+ status: input.status,+ summary: input.summary,+ ttlSeconds: 7 * 24 * 60 * 60,+ toolAction: input.toolAction,+ toolCallId: this.toolCallId,+ });+ };+searchMemory = async (params: SearchMemoryParams): Promise<SearchMemoryResult> => {const normalizedParams = normalizeSearchMemoryParams(params);const { provider, model: embeddingModel } =@@ -213,6 +278,15 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {title: input.title,});+ await this.emitUserMemoryOutcome({+ apiName: 'addContextMemory',+ objectId: memory.id,+ relation: 'created',+ status: 'succeeded',+ summary: 'Memory tool saved contextual memory.',+ toolAction: 'create',+ });+return {contextId: context.id,memoryId: memory.id,@@ -220,6 +294,14 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {success: true,};} catch (error) {+ await this.emitUserMemoryOutcome({+ apiName: 'addContextMemory',+ errorReason: (error as Error).message,+ status: 'failed',+ summary: 'Memory tool failed to save contextual memory.',+ toolAction: 'create',+ });+return {message: `Failed to save memory: ${(error as Error).message}`,success: false,@@ -274,6 +356,15 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {title: input.title,});+ await this.emitUserMemoryOutcome({+ apiName: 'addActivityMemory',+ objectId: memory.id,+ relation: 'created',+ status: 'succeeded',+ summary: 'Memory tool saved activity memory.',+ toolAction: 'create',+ });+return {activityId: activity.id,memoryId: memory.id,@@ -281,6 +372,14 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {success: true,};} catch (error) {+ await this.emitUserMemoryOutcome({+ apiName: 'addActivityMemory',+ errorReason: (error as Error).message,+ status: 'failed',+ summary: 'Memory tool failed to save activity memory.',+ toolAction: 'create',+ });+return {message: `Failed to save memory: ${(error as Error).message}`,success: false,@@ -329,6 +428,15 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {title: input.title,});+ await this.emitUserMemoryOutcome({+ apiName: 'addExperienceMemory',+ objectId: memory.id,+ relation: 'created',+ status: 'succeeded',+ summary: 'Memory tool saved experience memory.',+ toolAction: 'create',+ });+return {experienceId: experience.id,memoryId: memory.id,@@ -336,6 +444,14 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {success: true,};} catch (error) {+ await this.emitUserMemoryOutcome({+ apiName: 'addExperienceMemory',+ errorReason: (error as Error).message,+ status: 'failed',+ summary: 'Memory tool failed to save experience memory.',+ toolAction: 'create',+ });+return {message: `Failed to save memory: ${(error as Error).message}`,success: false,@@ -396,6 +512,15 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {},});+ await this.emitUserMemoryOutcome({+ apiName: 'addIdentityMemory',+ objectId: userMemoryId,+ relation: 'created',+ status: 'succeeded',+ summary: 'Memory tool saved identity memory.',+ toolAction: 'create',+ });+return {identityId,memoryId: userMemoryId,@@ -403,6 +528,14 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {success: true,};} catch (error) {+ await this.emitUserMemoryOutcome({+ apiName: 'addIdentityMemory',+ errorReason: (error as Error).message,+ status: 'failed',+ summary: 'Memory tool failed to save identity memory.',+ toolAction: 'create',+ });+return {message: `Failed to save identity memory: ${(error as Error).message}`,success: false,@@ -455,6 +588,15 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {title: input.title,});+ await this.emitUserMemoryOutcome({+ apiName: 'addPreferenceMemory',+ objectId: memory.id,+ relation: 'created',+ status: 'succeeded',+ summary: 'Memory tool saved a user preference.',+ toolAction: 'create',+ });+return {memoryId: memory.id,message: 'Memory saved successfully',@@ -462,6 +604,14 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {success: true,};} catch (error) {+ await this.emitUserMemoryOutcome({+ apiName: 'addPreferenceMemory',+ errorReason: (error as Error).message,+ status: 'failed',+ summary: 'Memory tool failed to save a user preference.',+ toolAction: 'create',+ });+return {message: `Failed to save memory: ${(error as Error).message}`,success: false,@@ -562,18 +712,46 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {});if (!updated) {+ await this.emitUserMemoryOutcome({+ apiName: 'updateIdentityMemory',+ objectId: input.id,+ relation: 'missing',+ status: 'failed',+ summary: 'Memory tool could not find identity memory to update.',+ toolAction: 'update',+ });+return {message: 'Identity memory not found',success: false,};}+ await this.emitUserMemoryOutcome({+ apiName: 'updateIdentityMemory',+ objectId: input.id,+ relation: 'updated',+ status: 'succeeded',+ summary: 'Memory tool updated identity memory.',+ toolAction: 'update',+ });+return {identityId: input.id,message: 'Identity memory updated successfully',success: true,};} catch (error) {+ await this.emitUserMemoryOutcome({+ apiName: 'updateIdentityMemory',+ errorReason: (error as Error).message,+ objectId: input.id,+ relation: 'updated',+ status: 'failed',+ summary: 'Memory tool failed to update identity memory.',+ toolAction: 'update',+ });+return {message: `Failed to update identity memory: ${(error as Error).message}`,success: false,@@ -588,12 +766,30 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {const removed = await this.memoryModel.removeIdentityEntry(input.id);if (!removed) {+ await this.emitUserMemoryOutcome({+ apiName: 'removeIdentityMemory',+ objectId: input.id,+ relation: 'missing',+ status: 'failed',+ summary: 'Memory tool could not find identity memory to remove.',+ toolAction: 'remove',+ });+return {message: 'Identity memory not found',success: false,};}+ await this.emitUserMemoryOutcome({+ apiName: 'removeIdentityMemory',+ objectId: input.id,+ relation: 'removed',+ status: 'succeeded',+ summary: 'Memory tool removed identity memory.',+ toolAction: 'remove',+ });+return {identityId: input.id,message: 'Identity memory removed successfully',@@ -601,6 +797,16 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {success: true,};} catch (error) {+ await this.emitUserMemoryOutcome({+ apiName: 'removeIdentityMemory',+ errorReason: (error as Error).message,+ objectId: input.id,+ relation: 'removed',+ status: 'failed',+ summary: 'Memory tool failed to remove identity memory.',+ toolAction: 'remove',+ });+return {message: `Failed to remove identity memory: ${(error as Error).message}`,success: false,@@ -637,9 +843,16 @@ export const memoryRuntime: ServerRuntimeRegistration = {const memoryModel = new UserMemoryModel(context.serverDB, context.userId);const service = new MemoryServerRuntimeService({+ agentId: context.agentId,+ emitOutcome: emitToolOutcomeSafely,+ messageId: context.messageId,memoryEffort,memoryModel,+ operationId: context.operationId,serverDB: context.serverDB,+ taskId: context.taskId,+ toolCallId: context.toolCallId,+ topicId: context.topicId,userId: context.userId,});diff --git a/src/server/services/toolExecution/serverRuntimes/skillStore.ts b/src/server/services/toolExecution/serverRuntimes/skillStore.tsindex 51609f724d1..0d2b4f6b349 100644--- a/src/server/services/toolExecution/serverRuntimes/skillStore.ts+++ b/src/server/services/toolExecution/serverRuntimes/skillStore.ts@@ -11,6 +11,11 @@ import {import debug from 'debug';import { UserModel } from '@/database/models/user';+import {+ emitToolOutcomeSafely,+ resolveToolOutcomeScope,+} from '@/server/services/agentSignal/procedure';+import { redisPolicyStateStore } from '@/server/services/agentSignal/store/adapters/redis/policyStateStore';import { MarketService } from '@/server/services/market';import { SkillImporter } from '@/server/services/skill/importer';@@ -19,27 +24,157 @@ import { type ServerRuntimeRegistration } from './types';const log = debug('lobe-server:skill-store-runtime');class SkillStoreServerRuntimeService implements SkillStoreRuntimeService {+ private agentId?: string;+ private emitOutcome?: typeof emitToolOutcomeSafely;+ private messageId?: string;private importer: SkillImporter;private marketService: MarketService;+ private operationId?: string;+ private taskId?: string;+ private toolCallId?: string;+ private topicId?: string;+ private userId: string;- constructor(options: { importer: SkillImporter; marketService: MarketService }) {+ constructor(options: {+ agentId?: string;+ emitOutcome?: typeof emitToolOutcomeSafely;+ importer: SkillImporter;+ marketService: MarketService;+ messageId?: string;+ operationId?: string;+ taskId?: string;+ toolCallId?: string;+ topicId?: string;+ userId: string;+ }) {+ this.agentId = options.agentId;+ this.emitOutcome = options.emitOutcome;+ this.messageId = options.messageId;this.importer = options.importer;this.marketService = options.marketService;+ this.operationId = options.operationId;+ this.taskId = options.taskId;+ this.toolCallId = options.toolCallId;+ this.topicId = options.topicId;+ this.userId = options.userId;}+ private emitSkillOutcome = async (input: {+ apiName: string;+ errorReason?: string;+ intentClass?: string;+ objectId?: string;+ relation?: string;+ status: 'failed' | 'succeeded';+ summary: string;+ toolAction: string;+ }) => {+ const { scope, scopeKey } = resolveToolOutcomeScope({+ agentId: this.agentId,+ taskId: this.taskId,+ topicId: this.topicId,+ userId: this.userId,+ });++ await this.emitOutcome?.({+ apiName: input.apiName,+ context: { agentId: this.agentId, userId: this.userId },+ domainKey: 'skill:market-skill',+ errorReason: input.errorReason,+ identifier: SkillStoreIdentifier,+ intentClass: input.intentClass,+ messageId: this.messageId,+ operationId: this.operationId,+ policyStateStore: redisPolicyStateStore,+ relatedObjects: input.objectId+ ? [{ objectId: input.objectId, objectType: 'skill', relation: input.relation }]+ : undefined,+ scope,+ scopeKey,+ status: input.status,+ summary: input.summary,+ ttlSeconds: 7 * 24 * 60 * 60,+ toolAction: input.toolAction,+ toolCallId: this.toolCallId,+ });+ };+importFromGitHub = async (gitUrl: string): Promise<SkillImportServiceResult> => {- const result = await this.importer.importFromGitHub({ gitUrl });- return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };+ try {+ const result = await this.importer.importFromGitHub({ gitUrl });+ await this.emitSkillOutcome({+ apiName: 'importFromGitHub',+ intentClass: 'tool_command',+ objectId: result.skill.id,+ relation: 'created',+ status: 'succeeded',+ summary: 'Skill store imported a GitHub skill.',+ toolAction: 'import',+ });+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };+ } catch (error) {+ await this.emitSkillOutcome({+ apiName: 'importFromGitHub',+ errorReason: (error as Error).message,+ intentClass: 'tool_command',+ status: 'failed',+ summary: 'Skill store failed to import a GitHub skill.',+ toolAction: 'import',+ });+ throw error;+ }};importFromUrl = async (url: string): Promise<SkillImportServiceResult> => {- const result = await this.importer.importFromUrl({ url });- return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };+ try {+ const result = await this.importer.importFromUrl({ url });+ await this.emitSkillOutcome({+ apiName: 'importFromUrl',+ intentClass: 'tool_command',+ objectId: result.skill.id,+ relation: 'created',+ status: 'succeeded',+ summary: 'Skill store imported a skill from URL.',+ toolAction: 'import',+ });+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };+ } catch (error) {+ await this.emitSkillOutcome({+ apiName: 'importFromUrl',+ errorReason: (error as Error).message,+ intentClass: 'tool_command',+ status: 'failed',+ summary: 'Skill store failed to import a skill from URL.',+ toolAction: 'import',+ });+ throw error;+ }};importFromZipUrl = async (url: string): Promise<SkillImportServiceResult> => {- const result = await this.importer.importFromUrl({ url });- return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };+ try {+ const result = await this.importer.importFromUrl({ url });+ await this.emitSkillOutcome({+ apiName: 'importFromZipUrl',+ intentClass: 'tool_command',+ objectId: result.skill.id,+ relation: 'created',+ status: 'succeeded',+ summary: 'Skill store imported a zipped skill.',+ toolAction: 'import',+ });+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };+ } catch (error) {+ await this.emitSkillOutcome({+ apiName: 'importFromZipUrl',+ errorReason: (error as Error).message,+ intentClass: 'tool_command',+ status: 'failed',+ summary: 'Skill store failed to import a zipped skill.',+ toolAction: 'import',+ });+ throw error;+ }};searchSkill = async (@@ -50,6 +185,12 @@ class SkillStoreServerRuntimeService implements SkillStoreRuntimeService {try {const result = await this.marketService.searchSkill(params);log('Search skills result: %O', result);+ await this.emitSkillOutcome({+ apiName: 'searchSkill',+ status: 'succeeded',+ summary: 'Skill store searched marketplace skills.',+ toolAction: 'search',+ });// Transform SDK response to match expected interfacereturn {items: result.items,@@ -59,6 +200,13 @@ class SkillStoreServerRuntimeService implements SkillStoreRuntimeService {};} catch (error) {log('Error searching skills: %O', error);+ await this.emitSkillOutcome({+ apiName: 'searchSkill',+ errorReason: (error as Error).message,+ status: 'failed',+ summary: 'Skill store failed to search marketplace skills.',+ toolAction: 'search',+ });throw error;}};@@ -115,8 +263,16 @@ export const skillStoreRuntime: ServerRuntimeRegistration = {});const service = new SkillStoreServerRuntimeService({+ agentId: context.agentId,+ emitOutcome: emitToolOutcomeSafely,importer,marketService,+ messageId: context.messageId,+ operationId: context.operationId,+ taskId: context.taskId,+ toolCallId: context.toolCallId,+ topicId: context.topicId,+ userId: context.userId,});return new SkillStoreExecutionRuntime({ service });diff --git a/src/server/services/toolExecution/types.ts b/src/server/services/toolExecution/types.tsindex f71b7b7e55c..2481c793121 100644--- a/src/server/services/toolExecution/types.ts+++ b/src/server/services/toolExecution/types.ts@@ -11,12 +11,18 @@ export interface ToolExecutionContext {documentId?: string | null;/** Memory tool permission from agent chat config */memoryToolPermission?: 'read-only' | 'read-write';+ /** Source user message ID used by Agent Signal procedure suppression. */+ messageId?: string;+ /** Agent runtime operation ID for structured tool outcome identity. */+ operationId?: string;/** Conversation scope captured when the operation was created */scope?: string | null;/** Server database for LobeHub Skills execution */serverDB?: LobeChatDatabase;/** Task ID when executing within the Task system */taskId?: string;+ /** Stable LLM tool call ID for structured tool outcome identity. */+ toolCallId?: string;toolManifestMap: Record<string, LobeToolManifest>;/*** Maximum length for tool execution result content (in characters)diff --git a/src/server/workflows/agentSignal/__tests__/run.test.ts b/src/server/workflows/agentSignal/__tests__/run.test.tsindex f078735340e..2ffad7827e1 100644--- a/src/server/workflows/agentSignal/__tests__/run.test.ts+++ b/src/server/workflows/agentSignal/__tests__/run.test.ts@@ -32,7 +32,9 @@ describe('runAgentSignalWorkflow', () => {const topicId = `topic_${uuid()}`;const parentMessageId = `msg_${uuid()}`;const baseTimestamp = new Date('2026-01-01T00:00:00.000Z').getTime();- let capturedSourceEvent: AgentSignalSourceEvent | undefined;+ let capturedSourceEvent:+ | AgentSignalSourceEvent<typeof AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage>+ | undefined;await db.insert(users).values({ id: userId });@@ -177,7 +179,9 @@ describe('runAgentSignalWorkflow', () => {const now = Date.now();const executeSourceEvent: NonNullable<RunAgentSignalWorkflowDeps['executeSourceEvent']> = vi.fn(async (sourceEvent) => {- capturedSourceEvent = sourceEvent as AgentSignalSourceEvent;+ capturedSourceEvent = sourceEvent as AgentSignalSourceEvent<+ typeof AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage+ >;return undefined;},);