🤯 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
🐛 fix(agent-signal,server): missing document tool outcome rendering into decision agent (#14534)
Neko85b412270b10
diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.tsindex 4b29185bf99..63f7776c7dd 100644--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts@@ -47,4 +47,75 @@ describe('AgentDocumentsExecutionRuntime', () => {documentId: 'backing-doc-1',});});++ it('forwards tool trigger metadata when creating documents with same-turn tool context', async () => {+ const createDocument = vi.fn().mockResolvedValue({+ documentId: 'backing-doc-1',+ id: 'agent-doc-1',+ title: 'Research Notes',+ });+ const runtime = createRuntime({ createDocument });++ await runtime.createDocument(+ {+ content: 'notes',+ title: 'Research Notes',+ },+ {+ agentId: 'agent-1',+ messageId: 'user-msg-1',+ operationId: 'op-client-1',+ toolCallId: 'call-create-doc-1',+ topicId: 'topic-1',+ },+ );++ expect(createDocument).toHaveBeenCalledWith({+ agentId: 'agent-1',+ content: 'notes',+ title: 'Research Notes',+ toolContext: {+ messageId: 'user-msg-1',+ operationId: 'op-client-1',+ toolCallId: 'call-create-doc-1',+ topicId: 'topic-1',+ },+ trigger: 'tool',+ });+ });++ it('does not forward tool trigger metadata without required attribution ids', async () => {+ const createDocument = vi.fn().mockResolvedValue({+ id: 'agent-doc-1',+ title: 'Draft',+ });+ const runtime = createRuntime({ createDocument });++ await runtime.createDocument(+ {+ content: 'draft',+ title: 'Draft',+ },+ { agentId: 'agent-1', messageId: 'user-msg-1' },+ );++ await runtime.createDocument(+ {+ content: 'draft',+ title: 'Draft',+ },+ { agentId: 'agent-1', toolCallId: 'call-create-doc-1' },+ );++ expect(createDocument).toHaveBeenNthCalledWith(1, {+ agentId: 'agent-1',+ content: 'draft',+ title: 'Draft',+ });+ expect(createDocument).toHaveBeenNthCalledWith(2, {+ agentId: 'agent-1',+ content: 'draft',+ title: 'Draft',+ });+ });});diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.tsindex 710714e76a1..b975be59b90 100644--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts@@ -34,10 +34,39 @@ interface AgentDocumentRecord {interface AgentDocumentOperationContext {agentId?: string | null;currentDocumentId?: string | null;+ messageId?: string | null;+ operationId?: string | null;scope?: string | null;+ taskId?: string | null;+ toolCallId?: string | null;topicId?: string | null;}+/**+ * Attribution data captured from a builtin tool call that creates an agent document.+ */+interface AgentDocumentToolContext {+ messageId: string;+ operationId?: string;+ taskId?: string | null;+ toolCallId: string;+ topicId?: string;+}++/**+ * Tool-call attribution input for document create operations.+ */+interface AgentDocumentToolTriggerInput {+ /**+ * Same-turn tool-call context used by create-class services to attribute generated documents.+ */+ toolContext?: AgentDocumentToolContext;+ /**+ * Set to `'tool'` only when the same-turn user message id and tool call id are both available.+ */+ trigger?: 'tool';+}+const CURRENT_PAGE_DOCUMENT_WRITE_ERROR_CODE = 'CURRENT_PAGE_DOCUMENT_WRITE_FORBIDDEN';const CURRENT_PAGE_DOCUMENT_WRITE_ERROR_TYPE = 'CurrentPageDocumentWriteForbidden';@@ -50,13 +79,13 @@ export interface AgentDocumentsRuntimeService {createDocument: (params: CreateDocumentArgs & {agentId: string;- },+ } & AgentDocumentToolTriggerInput,) => Promise<AgentDocumentRecord | undefined>;createTopicDocument: (params: CreateDocumentArgs & {agentId: string;topicId: string;- },+ } & AgentDocumentToolTriggerInput,) => Promise<AgentDocumentRecord | undefined>;listDocuments: (params: ListDocumentsArgs & {@@ -119,6 +148,26 @@ export class AgentDocumentsExecutionRuntime {return context.topicId;}+ private buildToolTriggerInput(+ context?: AgentDocumentOperationContext,+ ): AgentDocumentToolTriggerInput {+ if (!context?.messageId || !context.toolCallId) return {};++ const toolContext: AgentDocumentToolContext = {+ messageId: context.messageId,+ toolCallId: context.toolCallId,+ };++ if (context.operationId) toolContext.operationId = context.operationId;+ if (context.taskId) toolContext.taskId = context.taskId;+ if (context.topicId) toolContext.topicId = context.topicId;++ return {+ toolContext,+ trigger: 'tool',+ };+ }+private buildCurrentPageDocumentWriteBlockedResult(apiName: string): BuiltinServerRuntimeOutput {const message =`Cannot use lobe-agent-documents.${apiName} on the current page document ` +@@ -220,10 +269,16 @@ export class AgentDocumentsExecutionRuntime {};}+ const toolTriggerInput = this.buildToolTriggerInput(context);const created =target === 'currentTopic'- ? await this.service.createTopicDocument({ ...args, agentId, topicId: topicId! })- : await this.service.createDocument({ ...args, agentId });+ ? await this.service.createTopicDocument({+ ...args,+ ...toolTriggerInput,+ agentId,+ topicId: topicId!,+ })+ : await this.service.createDocument({ ...args, ...toolTriggerInput, agentId });if (!created) return { content: 'Failed to create agent document.', success: false };return {diff --git a/packages/builtin-tool-agent-documents/src/executor/index.ts b/packages/builtin-tool-agent-documents/src/executor/index.tsindex 147f6689f35..cec0a050fe6 100644--- a/packages/builtin-tool-agent-documents/src/executor/index.ts+++ b/packages/builtin-tool-agent-documents/src/executor/index.ts@@ -45,7 +45,11 @@ export class AgentDocumentsExecutor extends BaseExecutor<typeof AgentDocumentsApreturn this.runtime.createDocument(params, {agentId: ctx.agentId,currentDocumentId: ctx.documentId,+ messageId: ctx.sourceMessageId,+ operationId: ctx.operationId,scope: ctx.scope,+ taskId: ctx.taskId,+ toolCallId: ctx.toolCallId,topicId: ctx.topicId,});};diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.tsindex 9f2fb022bf6..9e2fa5ebb8d 100644--- a/packages/types/src/tool/builtin.ts+++ b/packages/types/src/tool/builtin.ts@@ -479,6 +479,11 @@ export interface BuiltinToolContext {*/taskId?: string | null;+ /**+ * The tool call ID from the assistant message.+ */+ toolCallId?: string;+/*** The current topic ID (only available when operating within a topic)* Used by tools that need to create messages or operations within a topicdiff --git a/src/server/routers/lambda/__tests__/agentDocument.toolOutcome.test.ts b/src/server/routers/lambda/__tests__/agentDocument.toolOutcome.test.tsnew file mode 100644index 00000000000..b739edc80f7--- /dev/null+++ b/src/server/routers/lambda/__tests__/agentDocument.toolOutcome.test.ts@@ -0,0 +1,180 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type * as AgentDocumentModels from '@/database/models/agentDocuments';+import { createCallerFactory } from '@/libs/trpc/lambda';+import { createContextInner } from '@/libs/trpc/lambda/context';+import { AgentDocumentsService } from '@/server/services/agentDocuments';+import { emitAgentDocumentToolOutcomeSafely } from '@/server/services/agentDocuments/toolOutcome';++import { agentDocumentRouter } from '../agentDocument';++const agentDocumentMocks = vi.hoisted(() => ({+ emitAgentDocumentToolOutcomeSafely: vi.fn(),+ findTopicById: vi.fn(),+ getServerDB: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: agentDocumentMocks.getServerDB,+}));++vi.mock('@/database/models/agentDocuments', async (importOriginal) => {+ const actual = await importOriginal<typeof AgentDocumentModels>();++ return {+ ...actual,+ AgentDocumentModel: vi.fn(),+ };+});++vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(() => ({+ findById: agentDocumentMocks.findTopicById,+ })),+}));++vi.mock('@/database/models/topicDocument', () => ({+ TopicDocumentModel: vi.fn(),+}));++vi.mock('@/server/services/agentDocuments', () => ({+ AgentDocumentsService: vi.fn(),+}));++vi.mock('@/server/services/agentDocumentVfs', () => ({+ AgentDocumentVfsService: vi.fn(),+}));++vi.mock('@/server/services/agentDocuments/toolOutcome', () => ({+ emitAgentDocumentToolOutcomeSafely: agentDocumentMocks.emitAgentDocumentToolOutcomeSafely,+}));++const createCaller = createCallerFactory(agentDocumentRouter);++interface MockAgentDocumentsService {+ createDocument: ReturnType<typeof vi.fn>;+ createForTopic: ReturnType<typeof vi.fn>;+}++describe('agentDocumentRouter tool outcomes', () => {+ const createdDocument = {+ documentId: 'document-1',+ filename: 'daily-brief',+ id: 'agent-document-1',+ title: 'Daily Brief',+ };++ let serviceImpl: MockAgentDocumentsService;++ beforeEach(() => {+ vi.clearAllMocks();+ agentDocumentMocks.getServerDB.mockResolvedValue({ kind: 'server-db' });+ agentDocumentMocks.findTopicById.mockResolvedValue({ title: 'Topic fallback' });++ serviceImpl = {+ createDocument: vi.fn().mockResolvedValue(createdDocument),+ createForTopic: vi.fn().mockResolvedValue(createdDocument),+ };+ vi.mocked(AgentDocumentsService).mockImplementation(+ () => serviceImpl as unknown as AgentDocumentsService,+ );+ });++ it('emits success outcome for attributed createDocument', async () => {+ const caller = createCaller(await createContextInner({ userId: 'user-1' }));++ await caller.createDocument({+ agentId: 'agent-1',+ content: 'body',+ hintIsSkill: true,+ title: 'Daily Brief',+ toolContext: {+ messageId: 'message-1',+ operationId: 'operation-1',+ taskId: 'task-1',+ toolCallId: 'tool-call-1',+ topicId: 'topic-1',+ },+ trigger: 'tool',+ });++ expect(emitAgentDocumentToolOutcomeSafely).toHaveBeenCalledWith(+ expect.objectContaining({+ agentDocumentId: 'agent-document-1',+ agentId: 'agent-1',+ apiName: 'createDocument',+ hintIsSkill: true,+ messageId: 'message-1',+ operationId: 'operation-1',+ relation: 'created',+ status: 'succeeded',+ taskId: 'task-1',+ toolAction: 'create',+ toolCallId: 'tool-call-1',+ topicId: 'topic-1',+ userId: 'user-1',+ }),+ );+ });++ it('does not emit outcome for normal createDocument', async () => {+ const caller = createCaller(await createContextInner({ userId: 'user-1' }));++ await caller.createDocument({+ agentId: 'agent-1',+ content: 'body',+ title: 'Daily Brief',+ });++ expect(emitAgentDocumentToolOutcomeSafely).not.toHaveBeenCalled();+ });++ it('rejects tool trigger without toolContext', async () => {+ const caller = createCaller(await createContextInner({ userId: 'user-1' }));++ await expect(+ caller.createDocument({+ agentId: 'agent-1',+ content: 'body',+ title: 'Daily Brief',+ trigger: 'tool',+ }),+ ).rejects.toThrow('toolContext is required when trigger is tool');+ });++ it('emits success outcome for attributed createForTopic', async () => {+ const caller = createCaller(await createContextInner({ userId: 'user-1' }));++ await caller.createForTopic({+ agentId: 'agent-1',+ content: 'body',+ title: 'Topic Brief',+ topicId: 'topic-1',+ toolContext: {+ messageId: 'message-1',+ operationId: 'operation-1',+ taskId: null,+ toolCallId: 'tool-call-1',+ },+ trigger: 'tool',+ });++ expect(emitAgentDocumentToolOutcomeSafely).toHaveBeenCalledWith(+ expect.objectContaining({+ agentDocumentId: 'agent-document-1',+ agentId: 'agent-1',+ apiName: 'createForTopic',+ messageId: 'message-1',+ operationId: 'operation-1',+ relation: 'created',+ status: 'succeeded',+ taskId: null,+ toolAction: 'create',+ toolCallId: 'tool-call-1',+ topicId: 'topic-1',+ userId: 'user-1',+ }),+ );+ });+});diff --git a/src/server/routers/lambda/agentDocument.ts b/src/server/routers/lambda/agentDocument.tsindex 377e788dcea..27b254b4725 100644--- a/src/server/routers/lambda/agentDocument.ts+++ b/src/server/routers/lambda/agentDocument.ts@@ -12,6 +12,7 @@ import { TopicDocumentModel } from '@/database/models/topicDocument';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { AgentDocumentsService } from '@/server/services/agentDocuments';+import { emitAgentDocumentToolOutcomeSafely } from '@/server/services/agentDocuments/toolOutcome';import { AgentDocumentVfsService } from '@/server/services/agentDocumentVfs';import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';import { getUnifiedSkillNamespaceRootPath } from '@/server/services/agentDocumentVfs/mounts/skills/path';@@ -78,6 +79,29 @@ const readFormatSchema = z.enum(['xml', 'markdown', 'both']).optional();const writeCreateModeSchema = z.enum(['always-new', 'if-missing', 'must-exist']).optional();const recursiveSchema = z.boolean().optional();const mountedSkillNamespaceSchema = z.literal('agent');+const agentDocumentToolContextSchema = z.object({+ messageId: z.string(),+ operationId: z.string().optional(),+ taskId: z.string().nullable().optional(),+ toolCallId: z.string(),+ topicId: z.string().optional(),+});+const agentDocumentToolTriggerSchema = z+ .object({+ // REVIEW: @nekomeowww is not fully certain this attribution boundary is clear enough.+ // TODO: Remove this explicit parameter threading if gateway-mode migration makes tool execution fully server-attributed.+ toolContext: agentDocumentToolContextSchema.optional(),+ trigger: z.literal('tool').optional(),+ })+ .superRefine((value, ctx) => {+ if (value.trigger === 'tool' && !value.toolContext) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'toolContext is required when trigger is tool',+ path: ['toolContext'],+ });+ }+ });const createMountedSkillSchema = z.object({agentId: z.string(),@@ -132,6 +156,43 @@ const agentDocumentProcedure = authedProcedure.use(serverDatabase).use(async (op});});+const emitCreateDocumentToolOutcome = async (input: {+ agentDocumentId?: string;+ agentId: string;+ apiName: string;+ errorReason?: string;+ hintIsSkill?: boolean;+ status: 'failed' | 'succeeded';+ toolContext?: z.infer<typeof agentDocumentToolContextSchema>;+ topicId?: string;+ userId: string;+}) => {+ const { toolContext } = input;++ if (!toolContext) return;++ await emitAgentDocumentToolOutcomeSafely({+ agentDocumentId: input.agentDocumentId,+ agentId: input.agentId,+ apiName: input.apiName,+ errorReason: input.errorReason,+ hintIsSkill: input.hintIsSkill,+ messageId: toolContext.messageId,+ operationId: toolContext.operationId,+ relation: 'created',+ status: input.status,+ summary:+ input.status === 'succeeded'+ ? 'Agent documents created a document.'+ : 'Agent documents failed to create a document.',+ taskId: toolContext.taskId,+ toolAction: 'create',+ toolCallId: toolContext.toolCallId,+ topicId: input.topicId ?? toolContext.topicId,+ userId: input.userId,+ });+};+export const agentDocumentRouter = router({/*** Get all available template sets@@ -655,17 +716,54 @@ export const agentDocumentRouter = router({*/createDocument: agentDocumentProcedure.input(- z.object({- agentId: z.string(),- content: z.string(),- hintIsSkill: z.boolean().optional(),- title: z.string(),- }),+ z+ .object({+ agentId: z.string(),+ content: z.string(),+ hintIsSkill: z.boolean().optional(),+ title: z.string(),+ })+ .and(agentDocumentToolTriggerSchema),).mutation(async ({ ctx, input }) => {- return ctx.agentDocumentService.createDocument(input.agentId, input.title, input.content, {- hintIsSkill: input.hintIsSkill,- });+ try {+ const doc = await ctx.agentDocumentService.createDocument(+ input.agentId,+ input.title,+ input.content,+ {+ hintIsSkill: input.hintIsSkill,+ },+ );++ if (input.trigger === 'tool') {+ await emitCreateDocumentToolOutcome({+ agentDocumentId: doc?.id,+ agentId: input.agentId,+ apiName: 'createDocument',+ hintIsSkill: input.hintIsSkill,+ status: 'succeeded',+ toolContext: input.toolContext,+ userId: ctx.userId,+ });+ }++ return doc;+ } catch (error) {+ if (input.trigger === 'tool') {+ await emitCreateDocumentToolOutcome({+ agentId: input.agentId,+ apiName: 'createDocument',+ errorReason: error instanceof Error ? error.message : String(error),+ hintIsSkill: input.hintIsSkill,+ status: 'failed',+ toolContext: input.toolContext,+ userId: ctx.userId,+ });+ }++ throw error;+ }}),/**@@ -674,26 +772,58 @@ export const agentDocumentRouter = router({*/createForTopic: agentDocumentProcedure.input(- z.object({- agentId: z.string(),- content: z.string(),- hintIsSkill: z.boolean().optional(),- title: z.string(),- topicId: z.string(),- }),+ z+ .object({+ agentId: z.string(),+ content: z.string(),+ hintIsSkill: z.boolean().optional(),+ title: z.string(),+ topicId: z.string(),+ })+ .and(agentDocumentToolTriggerSchema),).mutation(async ({ ctx, input }) => {- const topic = input.title.trim() ? undefined : await ctx.topicModel.findById(input.topicId);- const title = input.title.trim() || topic?.title || '';- const doc = await ctx.agentDocumentService.createForTopic(- input.agentId,- title,- input.content,- input.topicId,- { hintIsSkill: input.hintIsSkill },- );+ try {+ const topic = input.title.trim() ? undefined : await ctx.topicModel.findById(input.topicId);+ const title = input.title.trim() || topic?.title || '';+ const doc = await ctx.agentDocumentService.createForTopic(+ input.agentId,+ title,+ input.content,+ input.topicId,+ { hintIsSkill: input.hintIsSkill },+ );++ if (input.trigger === 'tool') {+ await emitCreateDocumentToolOutcome({+ agentDocumentId: doc?.id,+ agentId: input.agentId,+ apiName: 'createForTopic',+ hintIsSkill: input.hintIsSkill,+ status: 'succeeded',+ toolContext: input.toolContext,+ topicId: input.topicId,+ userId: ctx.userId,+ });+ }- return doc;+ return doc;+ } catch (error) {+ if (input.trigger === 'tool') {+ await emitCreateDocumentToolOutcome({+ agentId: input.agentId,+ apiName: 'createForTopic',+ errorReason: error instanceof Error ? error.message : String(error),+ hintIsSkill: input.hintIsSkill,+ status: 'failed',+ toolContext: input.toolContext,+ topicId: input.topicId,+ userId: ctx.userId,+ });+ }++ throw error;+ }}),/**diff --git a/src/server/services/agentDocuments/toolOutcome.test.ts b/src/server/services/agentDocuments/toolOutcome.test.tsnew file mode 100644index 00000000000..35034e02411--- /dev/null+++ b/src/server/services/agentDocuments/toolOutcome.test.ts@@ -0,0 +1,130 @@+import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++import type { emitAgentDocumentToolOutcomeSafely as EmitAgentDocumentToolOutcomeSafely } from './toolOutcome';++const procedureMocks = vi.hoisted(() => ({+ emitToolOutcomeSafely: vi.fn(),+ resolveToolOutcomeScope: vi.fn(() => ({+ scope: { agentId: 'agent-1', userId: 'user-1' },+ scopeKey: 'agent:agent-1:user:user-1',+ })),+}));++const policyStateStoreMocks = vi.hoisted(() => ({+ redisPolicyStateStore: { sentinel: 'redis-policy-store' },+}));++vi.mock('@/server/services/agentSignal/procedure', () => procedureMocks);+vi.mock(+ '@/server/services/agentSignal/store/adapters/redis/policyStateStore',+ () => policyStateStoreMocks,+);++let emitAgentDocumentToolOutcomeSafely: typeof EmitAgentDocumentToolOutcomeSafely;++beforeAll(async () => {+ ({ emitAgentDocumentToolOutcomeSafely } = await import('./toolOutcome'));+});++describe('emitAgentDocumentToolOutcomeSafely', () => {+ beforeEach(() => {+ procedureMocks.emitToolOutcomeSafely.mockClear();+ procedureMocks.resolveToolOutcomeScope.mockClear();+ });++ it('maps hinted document creation to a skill document outcome', async () => {+ await emitAgentDocumentToolOutcomeSafely({+ agentDocumentId: 'agent-doc-1',+ agentId: 'agent-1',+ apiName: 'createDocument',+ hintIsSkill: true,+ messageId: 'message-1',+ operationId: 'operation-1',+ relation: 'created',+ status: 'succeeded',+ summary: 'Agent documents created a document.',+ taskId: 'task-1',+ toolAction: 'create',+ toolCallId: 'tool-call-1',+ topicId: 'topic-1',+ userId: 'user-1',+ });++ expect(procedureMocks.resolveToolOutcomeScope).toHaveBeenCalledWith({+ agentId: 'agent-1',+ taskId: 'task-1',+ topicId: 'topic-1',+ userId: 'user-1',+ });+ expect(procedureMocks.emitToolOutcomeSafely).toHaveBeenCalledWith({+ apiName: 'createDocument',+ context: { agentId: 'agent-1', userId: 'user-1' },+ domainKey: 'document:agent-document',+ errorReason: undefined,+ identifier: AgentDocumentsIdentifier,+ intentClass: 'hinted_skill_document',+ messageId: 'message-1',+ operationId: 'operation-1',+ policyStateStore: policyStateStoreMocks.redisPolicyStateStore,+ relatedObjects: [+ {+ objectId: 'agent-doc-1',+ objectType: 'agent-document',+ relation: 'created',+ },+ ],+ scope: { agentId: 'agent-1', userId: 'user-1' },+ scopeKey: 'agent:agent-1:user:user-1',+ status: 'succeeded',+ summary: 'Agent documents created a document.',+ ttlSeconds: 7 * 24 * 60 * 60,+ toolAction: 'create',+ toolCallId: 'tool-call-1',+ });+ });++ it('maps non-hinted documents to explicit persistence outcomes', async () => {+ await emitAgentDocumentToolOutcomeSafely({+ agentId: 'agent-1',+ apiName: 'createDocument',+ status: 'succeeded',+ summary: 'Agent documents created a document.',+ taskId: null,+ toolAction: 'create',+ userId: 'user-1',+ });++ expect(procedureMocks.resolveToolOutcomeScope).toHaveBeenCalledWith({+ agentId: 'agent-1',+ taskId: undefined,+ topicId: undefined,+ userId: 'user-1',+ });+ expect(procedureMocks.emitToolOutcomeSafely).toHaveBeenCalledWith(+ expect.objectContaining({+ intentClass: 'explicit_persistence',+ relatedObjects: undefined,+ }),+ );+ });++ it('passes failed outcome status and error reason', async () => {+ await emitAgentDocumentToolOutcomeSafely({+ agentId: 'agent-1',+ apiName: 'replaceDocumentContent',+ errorReason: 'write failed',+ status: 'failed',+ summary: 'Agent documents replaced document content failed.',+ toolAction: 'replace',+ userId: 'user-1',+ });++ expect(procedureMocks.emitToolOutcomeSafely).toHaveBeenCalledWith(+ expect.objectContaining({+ errorReason: 'write failed',+ status: 'failed',+ }),+ );+ });+});diff --git a/src/server/services/agentDocuments/toolOutcome.ts b/src/server/services/agentDocuments/toolOutcome.tsnew file mode 100644index 00000000000..99a516f1bae--- /dev/null+++ b/src/server/services/agentDocuments/toolOutcome.ts@@ -0,0 +1,100 @@+import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';++import {+ emitToolOutcomeSafely,+ resolveToolOutcomeScope,+} from '@/server/services/agentSignal/procedure';+import { redisPolicyStateStore } from '@/server/services/agentSignal/store/adapters/redis/policyStateStore';++/** Tool outcome retention window for agent document procedure state. */+const AGENT_DOCUMENT_TOOL_OUTCOME_TTL_SECONDS = 7 * 24 * 60 * 60;++/**+ * Input for emitting an agent document tool outcome.+ */+export interface EmitAgentDocumentToolOutcomeInput {+ /** Agent document binding id related to the tool outcome. */+ agentDocumentId?: string;+ /** Agent id used to scope the outcome when available. */+ agentId?: string;+ /** Tool API method name that produced the outcome. */+ apiName: string;+ /** Compact failure reason for failed outcomes. */+ errorReason?: string;+ /** Whether the document was hinted as reusable skill material. */+ hintIsSkill?: boolean;+ /** Message id associated with the tool call when known. */+ messageId?: string;+ /** Operation id associated with the tool call when known. */+ operationId?: string;+ /** Relationship between the tool outcome and the agent document. */+ relation?: string;+ /** Outcome status produced by the tool execution. */+ status: 'failed' | 'succeeded';+ /** Compact human-readable outcome summary. */+ summary: string;+ /** Task id used to scope the outcome, or null when explicitly absent. */+ taskId?: string | null;+ /** Tool action such as create, update, copy, or replace. */+ toolAction: string;+ /** Tool call id associated with the outcome when known. */+ toolCallId?: string;+ /** Topic id used to scope the outcome when available. */+ topicId?: string;+ /** User id that owns the tool outcome. */+ userId: string;+}++/**+ * Emits an agent document tool outcome through Agent Signal.+ *+ * Use when:+ * - Agent document server tools need to record a direct persistence outcome+ * - Planner suppression needs same-turn procedure state for document changes+ *+ * Expects:+ * - `userId` is present and matches the executing user+ * - `agentDocumentId`, when provided, is the agent document binding id+ *+ * Returns:+ * - A promise that settles after safe outcome emission completes+ */+export const emitAgentDocumentToolOutcomeSafely = async (+ input: EmitAgentDocumentToolOutcomeInput,+) => {+ const { agentId, topicId, userId } = input;+ const { scope, scopeKey } = resolveToolOutcomeScope({+ agentId,+ taskId: input.taskId ?? undefined,+ topicId,+ userId,+ });++ await emitToolOutcomeSafely({+ apiName: input.apiName,+ context: { agentId, userId },+ domainKey: 'document:agent-document',+ errorReason: input.errorReason,+ identifier: AgentDocumentsIdentifier,+ intentClass: input.hintIsSkill ? 'hinted_skill_document' : 'explicit_persistence',+ messageId: input.messageId,+ operationId: input.operationId,+ policyStateStore: redisPolicyStateStore,+ relatedObjects: input.agentDocumentId+ ? [+ {+ objectId: input.agentDocumentId,+ objectType: 'agent-document',+ relation: input.relation,+ },+ ]+ : undefined,+ scope,+ scopeKey,+ status: input.status,+ summary: input.summary,+ ttlSeconds: AGENT_DOCUMENT_TOOL_OUTCOME_TTL_SECONDS,+ toolAction: input.toolAction,+ toolCallId: input.toolCallId,+ });+};diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.tsindex 235890e16df..f5eff3f04e1 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts@@ -361,7 +361,7 @@ describe('feedbackActionPlanner', () => {/*** @example- * User-stage direct skill intent is saved as a deferred candidate until completion evidence arrives.+ * User-stage direct skill intent is recorded until completion evidence arrives.*/it('defers direct skill decisions from normal user-message sources', async () => {const store = createStore();@@ -370,7 +370,7 @@ describe('feedbackActionPlanner', () => {policyStateStore: store,ttlSeconds: 3600,});- const writeCandidate = vi.spyOn(procedure.procedureState.skillCandidates!, 'write');+ const writeIntentRecord = vi.spyOn(procedure.procedureState.skillIntentRecords!, 'write');const skillActions = { prepare: vi.fn() };const handler = createFeedbackActionPlannerSignalHandler({actionServices: {@@ -400,11 +400,11 @@ describe('feedbackActionPlanner', () => {const result = await handler.handle(signal, context);expect(result).toEqual({- concluded: { reason: 'skill mutation deferred until client.runtime.complete' },+ concluded: { reason: 'skill intent recorded until client.runtime.complete' },status: 'conclude',});expect(skillActions.prepare).not.toHaveBeenCalled();- expect(writeCandidate).toHaveBeenCalledWith(+ expect(writeIntentRecord).toHaveBeenCalledWith(expect.objectContaining({actionIntent: 'create',confidence: 0.88,@@ -418,7 +418,7 @@ describe('feedbackActionPlanner', () => {}),);await expect(- procedure.procedureState.skillCandidates!.read({+ procedure.procedureState.skillIntentRecords!.read({scopeKey: 'topic:thread_1',sourceId: 'source_skill_defer',}),@@ -472,7 +472,89 @@ describe('feedbackActionPlanner', () => {/*** @example- * Server-side user-message sources have no client completion event to resume deferred mutations.+ * Completion-stage hinted document tool outcomes directly trigger skill decisions.+ */+ it('dispatches skill decisions from completion hinted document receipts even when domain classification is none', async () => {+ const store = createStore();+ const procedure = createProcedurePolicyOptions({+ now: () => 123,+ policyStateStore: store,+ ttlSeconds: 3600,+ });+ await procedure.procedureState.receipts.append({+ createdAt: 123,+ domainKey: 'document:agent-document',+ id: 'receipt_hinted_document',+ intentClass: 'hinted_skill_document',+ messageId: 'msg_skill_complete',+ relatedObjects: [+ {+ objectId: 'agent-doc-1',+ objectType: 'agent-document',+ relation: 'created',+ },+ ],+ scopeKey: 'topic:thread_1',+ sourceId: 'tool-outcome:lobe-agent-documents:createDocument:succeeded:call_1',+ status: 'handled',+ summary: 'Agent documents created a hinted skill document.',+ updatedAt: 123,+ });+ const action = {+ actionId: 'action_hinted_document',+ actionType: 'action.skill-management.handle' as const,+ payload: {},+ };+ const skillActions = {+ prepare: vi.fn(() => ({ action, reason: 'hinted document receipt', risk: 'low' as const })),+ };+ const handler = createFeedbackActionPlannerSignalHandler({+ actionServices: {+ memoryActions: { prepare: vi.fn() },+ skillActions: skillActions as never,+ },+ markerReader: { shouldSuppress: vi.fn().mockResolvedValue(false) },+ procedure: {+ now: () => 123,+ procedureState: procedure.procedureState,+ },+ });+ const signal = createDomainSignal({+ message: 'Can we keep this workflow?',+ messageId: 'msg_skill_complete',+ satisfactionResult: 'neutral',+ signalId: 'sig_none_complete',+ sourceId: 'source_complete',+ target: 'none',+ trigger: 'client.runtime.complete',+ });++ const result = await handler.handle(signal, context);++ expect(result).toEqual({ actions: [action], status: 'dispatch' });+ expect(skillActions.prepare).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ evidence: expect.arrayContaining([+ expect.objectContaining({+ cue: 'same_turn_hinted_document_receipt',+ excerpt: expect.stringContaining('agent-doc-1'),+ }),+ ]),+ message: 'Can we keep this workflow?',+ skillActionIntent: 'create',+ skillIntentExplicitness: 'implicit_strong_learning',+ skillRoute: 'direct_decision',+ target: 'skill',+ }),+ signalType: 'signal.feedback.domain.skill',+ }),+ );+ });++ /**+ * @example+ * Server-side user-message sources have no client completion event to resume recorded intents.*/it('dispatches direct skill decisions from server-side user feedback', async () => {const action = {@@ -696,8 +778,8 @@ describe('feedbackActionPlanner', () => {bucketKey: 'topic:thread_1:skill',domain: 'skill',recordIds: [- 'procedure-record:sig_skill_positive_1:skill-candidate',- 'procedure-record:sig_skill_positive_2:skill-candidate',+ 'procedure-record:sig_skill_positive_1:skill-observation-record',+ 'procedure-record:sig_skill_positive_2:skill-observation-record',],suggestedActions: ['maintain'],}),@@ -712,12 +794,12 @@ describe('feedbackActionPlanner', () => {expect.objectContaining({accumulatorRole: 'candidate',domainKey: 'skill',- id: 'procedure-record:sig_skill_positive_1:skill-candidate',+ id: 'procedure-record:sig_skill_positive_1:skill-observation-record',}),expect.objectContaining({accumulatorRole: 'candidate',domainKey: 'skill',- id: 'procedure-record:sig_skill_positive_2:skill-candidate',+ id: 'procedure-record:sig_skill_positive_2:skill-observation-record',}),]),);@@ -789,8 +871,8 @@ describe('feedbackActionPlanner', () => {bucketKey: 'topic:thread_1:skill',domain: 'skill',recordIds: [- 'procedure-record:sig_skill_state_positive_1:skill-candidate',- 'procedure-record:sig_skill_state_positive_2:skill-candidate',+ 'procedure-record:sig_skill_state_positive_1:skill-observation-record',+ 'procedure-record:sig_skill_state_positive_2:skill-observation-record',],suggestedActions: ['maintain'],}),@@ -815,7 +897,7 @@ describe('feedbackActionPlanner', () => {* @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 () => {+ it('does not accumulate context plus one satisfied skill intent record', async () => {let now = 100;const store = createStore();const procedure = createProcedurePolicyOptions({@@ -867,7 +949,7 @@ describe('feedbackActionPlanner', () => {expect.objectContaining({accumulatorRole: 'candidate',domainKey: 'skill',- id: 'procedure-record:sig_skill_positive_single:skill-candidate',+ id: 'procedure-record:sig_skill_positive_single:skill-observation-record',}),]),);diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/skillCandidate.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/skillIntentRecord.test.tssimilarity index 71%rename from src/server/services/agentSignal/policies/analyzeIntent/__tests__/skillCandidate.test.tsrename to src/server/services/agentSignal/policies/analyzeIntent/__tests__/skillIntentRecord.test.tsindex ace6d2863e9..a4b7bc7a706 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/skillCandidate.test.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/skillIntentRecord.test.ts@@ -4,7 +4,7 @@ import { describe, expect, it, vi } from 'vitest';import { createProcedureStateService } from '@/server/services/agentSignal/services/procedureStateService';import type { AgentSignalPolicyStateStore } from '@/server/services/agentSignal/store/types';-import { readDeferredSkillCandidate, writeDeferredSkillCandidate } from '../skillCandidate';+import { readRecordedSkillIntent, recordSkillIntent } from '../skillIntentRecord';const createStore = (): AgentSignalPolicyStateStore => {const state = new Map<string, Record<string, string>>();@@ -18,16 +18,16 @@ const createStore = (): AgentSignalPolicyStateStore => {};};-describe('deferred skill candidates', () => {+describe('recorded skill intents', () => {/*** @example- * User-stage direct skill intent persists as candidate state for completion-stage decisions.+ * User-stage direct skill intent persists as a recorded intent for completion-stage decisions.*/- it('writes and reads one deferred skill candidate by source id', async () => {+ it('writes and reads one recorded skill intent by source id', async () => {const store = createStore();- await writeDeferredSkillCandidate(store, {- candidate: {+ await recordSkillIntent(store, {+ record: {actionIntent: 'create',confidence: 0.86,createdAt: 1000,@@ -43,7 +43,7 @@ describe('deferred skill candidates', () => {});await expect(- readDeferredSkillCandidate(store, {+ readRecordedSkillIntent(store, {scopeKey: 'topic:topic_1',sourceId: 'source_1',}),@@ -62,18 +62,18 @@ describe('deferred skill candidates', () => {/*** @example- * Corrupt candidate JSON is ignored instead of crashing policy execution.+ * Corrupt recorded intent JSON is ignored instead of crashing policy execution.*/- it('returns undefined for malformed candidate JSON', async () => {+ it('returns undefined for malformed recorded intent JSON', async () => {const store = {readPolicyState: vi.fn().mockResolvedValue({- 'skill-candidate:source_1': '{bad-json',+ 'skill-intent-record:source_1': '{bad-json',}),writePolicyState: vi.fn(),} satisfies AgentSignalPolicyStateStore;await expect(- readDeferredSkillCandidate(store, {+ readRecordedSkillIntent(store, {scopeKey: 'topic:topic_1',sourceId: 'source_1',}),@@ -82,18 +82,18 @@ describe('deferred skill candidates', () => {/*** @example- * Candidate JSON with missing required fields is ignored instead of becoming policy input.+ * Recorded intent JSON with missing required fields is ignored instead of becoming policy input.*/- it('returns undefined for malformed candidate objects', async () => {+ it('returns undefined for malformed recorded intent objects', async () => {const store = {readPolicyState: vi.fn().mockResolvedValue({- 'skill-candidate:source_1': JSON.stringify({ sourceId: 'source_1' }),+ 'skill-intent-record:source_1': JSON.stringify({ sourceId: 'source_1' }),}),writePolicyState: vi.fn(),} satisfies AgentSignalPolicyStateStore;await expect(- readDeferredSkillCandidate(store, {+ readRecordedSkillIntent(store, {scopeKey: 'topic:topic_1',sourceId: 'source_1',}),@@ -102,12 +102,12 @@ describe('deferred skill candidates', () => {/*** @example- * Candidate payloads must match the requested source id and scope key after parsing.+ * Recorded intent payloads must match the requested source id and scope key after parsing.*/- it('returns undefined when parsed candidate identity does not match the read input', async () => {+ it('returns undefined when parsed record identity does not match the read input', async () => {const store = {readPolicyState: vi.fn().mockResolvedValue({- 'skill-candidate:source_1': JSON.stringify({+ 'skill-intent-record:source_1': JSON.stringify({createdAt: 1000,explicitness: 'explicit_action',feedbackMessageId: 'msg_1',@@ -120,7 +120,7 @@ describe('deferred skill candidates', () => {} satisfies AgentSignalPolicyStateStore;await expect(- readDeferredSkillCandidate(store, {+ readRecordedSkillIntent(store, {scopeKey: 'topic:topic_1',sourceId: 'source_1',}),@@ -129,13 +129,13 @@ describe('deferred skill candidates', () => {/*** @example- * Same source ids in different runtime scopes do not read each other's candidates.+ * Same source ids in different runtime scopes do not read each other's records.*/- it('keeps candidates separated by scope key', async () => {+ it('keeps records separated by scope key', async () => {const store = createStore();- await writeDeferredSkillCandidate(store, {- candidate: {+ await recordSkillIntent(store, {+ record: {confidence: 0.72,createdAt: 1000,explicitness: 'explicit_action',@@ -150,7 +150,7 @@ describe('deferred skill candidates', () => {});await expect(- readDeferredSkillCandidate(store, {+ readRecordedSkillIntent(store, {scopeKey: 'topic:topic_2',sourceId: 'source_1',}),@@ -159,13 +159,13 @@ describe('deferred skill candidates', () => {/*** @example- * ProcedureStateService.skillCandidates.write(candidate) applies facade-owned TTL and scope.+ * ProcedureStateService.skillIntentRecords.write(record) applies facade-owned TTL and scope.*/- it('wires skill candidate helpers through ProcedureStateService', async () => {+ it('wires skill intent record helpers through ProcedureStateService', async () => {const writePolicyState = vi.fn(async () => {});const store = {readPolicyState: vi.fn().mockResolvedValue({- 'skill-candidate:source_1': JSON.stringify({+ 'skill-intent-record:source_1': JSON.stringify({confidence: 0.7,createdAt: 1000,explicitness: 'explicit_action',@@ -183,7 +183,7 @@ describe('deferred skill candidates', () => {ttlSeconds: 90,});- await service.skillCandidates.write({+ await service.skillIntentRecords.write({confidence: 0.7,createdAt: 1000,explicitness: 'explicit_action',@@ -195,15 +195,15 @@ describe('deferred skill candidates', () => {});expect(writePolicyState).toHaveBeenCalledWith(- 'analyze-intent:skill-candidates',+ 'analyze-intent:skill-intent-records','topic:topic_1',expect.objectContaining({- 'skill-candidate:source_1': expect.any(String),+ 'skill-intent-record:source_1': expect.any(String),}),90,);await expect(- service.skillCandidates.read({+ service.skillIntentRecords.read({scopeKey: 'topic:topic_1',sourceId: 'source_1',}),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 1e810d53f67..a5d17176a65 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@@ -9,7 +9,7 @@ import type { RuntimeProcessorContext } from '../../../../runtime/context';import {collectAgentSkillDecisionCandidates,defineSkillManagementActionHandler,- handleSkillManagementSignal,+ executeSkillManagementDecision,isAgentDocumentRelatedObject,readAgentSignalHintIsSkill,runSkillDecisionAgentRuntime,@@ -124,7 +124,7 @@ describe('defineSkillManagementActionHandler', () => {});it('does not run when self iteration is disabled', async () => {- const result = await handleSkillManagementSignal({+ const result = await executeSkillManagementDecision({decide: vi.fn(),payload: { agentId: 'agent-1', feedbackMessage: 'Make this a reusable checklist.' },selfIterationEnabled: false,@@ -135,7 +135,7 @@ describe('defineSkillManagementActionHandler', () => {it('runs the decision step when self iteration is enabled', async () => {const decide = vi.fn().mockResolvedValue({ action: 'create', confidence: 0.9 });- const result = await handleSkillManagementSignal({+ const result = await executeSkillManagementDecision({decide,payload: { agentId: 'agent-1', feedbackMessage: 'Make this a reusable checklist.' },selfIterationEnabled: true,@@ -151,7 +151,7 @@ describe('defineSkillManagementActionHandler', () => {*/it('returns structured results for each v1.2 decision action', async () => {for (const action of ['create', 'refine', 'consolidate', 'noop', 'reject'] as const) {- const result = await handleSkillManagementSignal({+ const result = await executeSkillManagementDecision({decide: vi.fn().mockResolvedValue({ action, confidence: 0.9 }),payload: { agentId: 'agent-1', feedbackMessage: 'Make this reusable.' },selfIterationEnabled: true,@@ -396,7 +396,7 @@ describe('defineSkillManagementActionHandler', () => {* Removed lifecycle tools must not leak into the action result.*/it('does not return automatic lifecycle tool actions from decision output', async () => {- const result = await handleSkillManagementSignal({+ const result = await executeSkillManagementDecision({decide: vi.fn().mockResolvedValue({action: 'consolidate',archiveSkill: { skillRef: 'skill-1' },@@ -512,7 +512,7 @@ describe('defineSkillManagementActionHandler', () => {/*** @example- * Decision agents receive managed skill candidates so targetSkillRefs can be stable ids.+ * Decision agents receive managed skill intent records so targetSkillRefs can be stable ids.*/it('passes discovered candidate skills into the decision step', async () => {skillDecisionRunner.mockResolvedValue({@@ -567,9 +567,9 @@ describe('defineSkillManagementActionHandler', () => {/*** @example- * Completion-stage skill decisions receive user-stage deferred skill-candidate evidence.+ * Completion-stage skill decisions receive user-stage recorded skill-intent evidence.*/- it('passes deferred skill candidate evidence to the decision runtime on completion-triggered feedback', async () => {+ it('passes recorded skill intent evidence to the decision runtime on completion-triggered feedback', async () => {skillDecisionRunner.mockResolvedValue({action: 'create',confidence: 0.88,@@ -602,7 +602,7 @@ describe('defineSkillManagementActionHandler', () => {const handler = defineSkillManagementActionHandler({db: {} as never,procedureState: {- skillCandidates: { read: readCandidate, write: vi.fn() },+ skillIntentRecords: { read: readCandidate, write: vi.fn() },},selfIterationEnabled: true,skillCreateRunner,@@ -655,7 +655,7 @@ describe('defineSkillManagementActionHandler', () => {cue: 'completion',}),expect.objectContaining({- cue: 'deferred_skill_candidate',+ cue: 'recorded_skill_intent',excerpt: expect.stringContaining('User asked to preserve this workflow.'),}),]),@@ -663,6 +663,115 @@ describe('defineSkillManagementActionHandler', () => {);});+ /**+ * @example+ * Same-turn hinted document outcomes are resolved before the decision runner is called.+ */+ it('eagerly injects hinted same-turn document evidence into the decision step', async () => {+ skillDecisionRunner.mockResolvedValue({+ action: 'create',+ confidence: 0.88,+ reason: 'Hinted workflow document should be analyzed as skill evidence.',+ });+ const listSameTurnDocumentOutcomes = vi.fn(async () => [+ {+ agentDocumentId: 'agent-doc-1',+ hintIsSkill: true,+ relation: 'created',+ summary: 'Agent documents created a document.',+ },+ {+ agentDocumentId: 'agent-doc-2',+ hintIsSkill: true,+ relation: 'created',+ summary: 'Agent documents created a documented workflow.',+ },+ ]);+ const readDocument = vi.fn(async ({ agentDocumentId }: { agentDocumentId: string }) =>+ agentDocumentId === 'agent-doc-2'+ ? {+ agentDocumentId: 'agent-doc-2',+ content: `# Should Not Be Injected\n\n${'This full content must not appear. '.repeat(20)}`,+ description: 'Reusable workflow description from the document metadata.',+ documentId: 'doc-2',+ title: 'Documented Workflow',+ }+ : {+ agentDocumentId: 'agent-doc-1',+ content: `# YouTube Workflow\n\nFetch comments, summarize them, and keep the process reusable. ${'Detailed implementation step. '.repeat(+ 12,+ )}TAIL_SHOULD_BE_TRUNCATED`,+ documentId: 'doc-1',+ title: 'YouTube Workflow',+ },+ );+ const handler = defineSkillManagementActionHandler({+ db: {} as never,+ selfIterationEnabled: true,+ skillCreateRunner,+ skillDecisionRunner,+ skillDecisionToolsetFactory: () => ({+ listCandidateDocuments: vi.fn(),+ listSameTurnDocumentOutcomes,+ readDocument,+ }),+ userId: 'user_1',+ });++ await handler.handle(+ {+ actionId: 'act_skill_hinted_document',+ actionType: 'action.skill-management.handle',+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },+ payload: {+ agentId: 'agent_1',+ idempotencyKey: 'source_1:skill:msg_1',+ message: 'Nice work. Can we keep this workflow?',+ messageId: 'msg_1',+ serializedContext: '{"surface":"chat"}',+ topicId: 'topic_1',+ },+ signal: {+ signalId: 'sig_1',+ signalType: 'signal.feedback.domain.skill',+ },+ source: { sourceId: 'source_1', sourceType: 'agent.user.message' },+ timestamp: 1,+ },+ context,+ );++ expect(listSameTurnDocumentOutcomes).toHaveBeenCalledWith({+ agentId: 'agent_1',+ messageId: 'msg_1',+ scopeKey: 'topic:topic-1',+ topicId: 'topic_1',+ });+ expect(readDocument).toHaveBeenCalledWith({ agentDocumentId: 'agent-doc-1' });+ expect(readDocument).toHaveBeenCalledWith({ agentDocumentId: 'agent-doc-2' });+ expect(skillDecisionRunner).toHaveBeenCalledWith(+ expect.objectContaining({+ evidence: expect.arrayContaining([+ expect.objectContaining({+ cue: 'same_turn_hinted_document',+ excerpt: expect.stringContaining('hintIsSkill=true'),+ }),+ expect.objectContaining({+ cue: 'same_turn_hinted_document_content',+ excerpt: expect.stringContaining('Fetch comments'),+ }),+ expect.objectContaining({+ cue: 'same_turn_hinted_document_description',+ excerpt: expect.stringContaining('Reusable workflow description'),+ }),+ ]),+ }),+ );+ const decisionInput = skillDecisionRunner.mock.calls[0]?.[0];+ expect(JSON.stringify(decisionInput?.evidence)).not.toContain('TAIL_SHOULD_BE_TRUNCATED');+ expect(JSON.stringify(decisionInput?.evidence)).not.toContain('Should Not Be Injected');+ });+/*** @example* Replayed action keys are skipped without running the document writer.diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.tsindex 79f67d6d3aa..6dd880e56c3 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts@@ -61,7 +61,7 @@ import { hasAppliedActionIdempotency, markAppliedActionIdempotency } from '../..import type { ActionSkillManagementHandle, AgentSignalFeedbackEvidence } from '../../types';import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../../types';import { createFeedbackActionPlannerSignalHandler } from '../feedbackAction';-import type { DeferredSkillCandidate } from '../skillCandidate';+import type { RecordedSkillIntent } from '../skillIntentRecord';export interface SkillManagementCandidateSkill {id: string;@@ -143,8 +143,8 @@ export interface SkillManagementActionInput {export interface SkillManagementActionHandlerOptions {db: LobeChatDatabase;- /** Optional procedure state used to read user-stage skill candidates. */- procedureState?: Pick<ProcedureStateService, 'skillCandidates'>;+ /** Optional procedure state used to read user-stage skill intent records. */+ procedureState?: Pick<ProcedureStateService, 'skillIntentRecords'>;selfIterationEnabled: boolean;skillCandidateSkillsFactory?: (input: {agentId: string;@@ -152,6 +152,8 @@ export interface SkillManagementActionHandlerOptions {skillCreateRunner?: (input: SkillCreateAuthoringInput) => Promise<unknown>;skillDecisionModel?: SkillManagementAgentModelConfig;skillDecisionRunner?: (input: SkillManagementSignalPayload) => Promise<unknown>;+ /** Optional factory used to inspect same-turn document outcomes before decision. */+ skillDecisionToolsetFactory?: (input: { agentId: string }) => SkillDecisionToolset;skillMaintainerRunner?: (input: SkillMaintainerWorkflowInput) => Promise<unknown>;skillManagementServiceFactory?: (input: { agentId: string }) => SkillManagementOperationService;userId: string;@@ -174,6 +176,7 @@ export interface SkillDecisionCandidateDocument {export interface SkillDecisionDocumentSnapshot {agentDocumentId: string;content?: string;+ description?: string | null;documentId?: string;filename?: string;metadata?: Record<string, unknown>;@@ -234,36 +237,36 @@ export const readAgentSignalHintIsSkill = (metadata: unknown): boolean | undefinreturn typeof hintIsSkill === 'boolean' ? hintIsSkill : undefined;};-const createDeferredSkillCandidateEvidence = (- candidate: DeferredSkillCandidate | undefined,+const createRecordedSkillIntentEvidence = (+ record: RecordedSkillIntent | undefined,): AgentSignalFeedbackEvidence[] => {- if (!candidate) return [];+ if (!record) return [];return [{- cue: 'deferred_skill_candidate',- excerpt: `${candidate.explicitness}/${candidate.route}/${candidate.actionIntent ?? 'none'}: ${- candidate.reason ?? 'deferred skill intent'+ cue: 'recorded_skill_intent',+ excerpt: `${record.explicitness}/${record.route}/${record.actionIntent ?? 'none'}: ${+ record.reason ?? 'recorded skill intent'}`,},];};-const readDeferredSkillCandidateForAction = async (+const readRecordedSkillIntentForExecution = async (options: SkillManagementActionHandlerOptions,action: ActionSkillManagementHandle,context: RuntimeProcessorContext,) => {- const reader = options.procedureState?.skillCandidates?.read;+ const reader = options.procedureState?.skillIntentRecords?.read;if (!reader) return undefined;const messageId = action.payload.messageId;if (messageId) {- const candidate = await reader({+ const record = await reader({scopeKey: context.scopeKey,sourceId: messageId,});- if (candidate) return candidate;+ if (record) return record;}const sourceId = action.source?.sourceId;@@ -866,7 +869,7 @@ export const runSkillDecisionAgentRuntime = async (input: SkillDecisionAgentRunt};/**- * Handles one skill-domain Agent Signal payload.+ * Executes the skill-management decision step for one skill-domain action payload.** Use when:* - Feedback has already been routed into the skill domain@@ -878,7 +881,7 @@ export const runSkillDecisionAgentRuntime = async (input: SkillDecisionAgentRunt* Returns:* - A skipped status when disabled, otherwise the decision result*/-export const handleSkillManagementSignal = async (input: {+export const executeSkillManagementDecision = async (input: {decide: (payload: SkillManagementSignalPayload) => Promise<unknown>;payload: SkillManagementSignalPayload;selfIterationEnabled: boolean;@@ -1002,6 +1005,13 @@ const createDefaultSkillDecisionToolset = ();},readDocument: async ({ agentDocumentId }) => {+ // NOTICE:+ // This is the Agent Signal decision-only inspection tool, not the chat-visible+ // lobe-agent-documents.readDocument tool and not a skill runtime document tool.+ // The decision agent needs a read-only snapshot to evaluate hinted same-turn documents+ // without invoking user-facing tool permissions or mutating agent document state.+ // Keep this boundary until Agent Signal decision tools are unified with a scoped+ // read-only tool registry.const snapshot = await agentDocumentsService.getDocumentSnapshotById(agentDocumentId);if (!snapshot) return { agentDocumentId };@@ -1017,6 +1027,101 @@ const createDefaultSkillDecisionToolset = (};};+const hintedDocumentEvidenceContentLength = 200;++/**+ * Normalizes document evidence for compact decision prompts.+ *+ * Before:+ * - "# Title\n\nLong body..."+ *+ * After:+ * - "# Title Long body..."+ */+const toCompactDocumentEvidenceExcerpt = (content: string) => {+ const normalized = content.replaceAll(/\s+/g, ' ').trim();++ if (normalized.length <= hintedDocumentEvidenceContentLength) return normalized;++ return `${normalized.slice(0, hintedDocumentEvidenceContentLength)}...`;+};++const getDocumentDescription = (document: SkillDecisionDocumentSnapshot) => {+ const description = document.description?.trim();++ if (description) return description;++ const metadataDescription = document.metadata?.description;+ return typeof metadataDescription === 'string' && metadataDescription.trim()+ ? metadataDescription.trim()+ : undefined;+};++const getSkillDecisionToolset = (options: SkillManagementActionHandlerOptions, agentId: string) =>+ options.skillDecisionToolsetFactory?.({ agentId }) ??+ createDefaultSkillDecisionToolset(options.db, options.userId);++const collectHintedSameTurnDocumentEvidence = async (+ input: {+ agentId: string;+ messageId?: string;+ scopeKey: string;+ topicId?: string;+ },+ options: SkillManagementActionHandlerOptions,+): Promise<AgentSignalFeedbackEvidence[]> => {+ if (!input.messageId) return [];++ const tools = getSkillDecisionToolset(options, input.agentId);+ const outcomes = await tools.listSameTurnDocumentOutcomes({+ agentId: input.agentId,+ messageId: input.messageId,+ scopeKey: input.scopeKey,+ topicId: input.topicId,+ });+ const hintedOutcomes = outcomes.filter((outcome) => outcome.hintIsSkill === true);++ if (hintedOutcomes.length === 0) return [];++ const evidence: AgentSignalFeedbackEvidence[] = [];++ for (const outcome of hintedOutcomes) {+ evidence.push({+ cue: 'same_turn_hinted_document',+ excerpt: [+ `agentDocumentId=${outcome.agentDocumentId}`,+ `hintIsSkill=true`,+ outcome.relation ? `relation=${outcome.relation}` : undefined,+ outcome.summary ? `summary=${outcome.summary}` : undefined,+ ]+ .filter(Boolean)+ .join('; '),+ });++ const document = await tools.readDocument({ agentDocumentId: outcome.agentDocumentId });+ const description = getDocumentDescription(document);++ evidence.push({+ cue: description+ ? 'same_turn_hinted_document_description'+ : 'same_turn_hinted_document_content',+ excerpt: [+ `agentDocumentId=${outcome.agentDocumentId}`,+ document.title ? `title=${document.title}` : undefined,+ description+ ? `description=${description}`+ : document.content+ ? `content=${toCompactDocumentEvidenceExcerpt(document.content)}`+ : undefined,+ ]+ .filter(Boolean)+ .join('; '),+ });+ }++ return evidence;+};+const toSkillMaintainerWorkflowResult = (value: z.infer<typeof SkillMaintainerWorkflowResultSchema>,): SkillMaintainerWorkflowResult => ({@@ -1052,6 +1157,7 @@ class SkillManagementDecisionAgentService {private db: LobeChatDatabase,private userId: string,modelConfig: Partial<SkillManagementAgentModelConfig> = {},+ private toolsetFactory?: SkillManagementActionHandlerOptions['skillDecisionToolsetFactory'],) {this.modelConfig = {model: modelConfig.model ?? DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,@@ -1078,7 +1184,9 @@ class SkillManagementDecisionAgentService {...input,...(candidateSkills.length > 0 ? { candidateSkills } : {}),},- tools: createDefaultSkillDecisionToolset(this.db, this.userId),+ tools:+ this.toolsetFactory?.({ agentId: input.agentId }) ??+ createDefaultSkillDecisionToolset(this.db, this.userId),});return toSkillManagementDecision(@@ -1262,6 +1370,7 @@ export const createSkillDecisionRunner = (options: SkillManagementActionHandlerOoptions.db,options.userId,options.skillDecisionModel,+ options.skillDecisionToolsetFactory,);return (input: SkillManagementSignalPayload) => agent.decide(input);@@ -1638,7 +1747,25 @@ export const runSkillManagementAction = async (return runCreateWorkflow(input, options, decision);};-export const handleSkillManagementAction = async (+/**+ * Executes one skill-management action by collecting evidence, deciding, and applying mutations.+ *+ * Triggering workflow:+ *+ * {@link defineSkillManagementActionHandler}+ * -> `action.skill-management.handle`+ * -> {@link executeSkillManagementAction}+ * -> {@link executeSkillManagementDecision}+ *+ * Upstream:+ * - {@link defineSkillManagementActionHandler}+ *+ * Downstream:+ * - {@link executeSkillManagementDecision}+ * - {@link runMaintainerWorkflow}+ * - {@link runCreateWorkflow}+ */+export const executeSkillManagementAction = async (action: BaseAction,options: SkillManagementActionHandlerOptions,context: RuntimeProcessorContext,@@ -1692,10 +1819,20 @@ export const handleSkillManagementAction = async (}const candidateSkills = await resolveSkillDecisionCandidates(options, action.payload.agentId);- const deferredCandidate = await readDeferredSkillCandidateForAction(options, action, context);+ const recordedIntent = await readRecordedSkillIntentForExecution(options, action, context);+ const sameTurnDocumentEvidence = await collectHintedSameTurnDocumentEvidence(+ {+ agentId: action.payload.agentId,+ messageId: action.payload.messageId,+ scopeKey: context.scopeKey,+ topicId: action.payload.topicId,+ },+ options,+ );const evidence = [...(action.payload.evidence ?? []),- ...createDeferredSkillCandidateEvidence(deferredCandidate),+ ...sameTurnDocumentEvidence,+ ...createRecordedSkillIntentEvidence(recordedIntent),];const runnerInput = {agentId: action.payload.agentId,@@ -1708,7 +1845,7 @@ export const handleSkillManagementAction = async (serializedContext: action.payload.serializedContext,topicId: action.payload.topicId,};- const decisionResult = await handleSkillManagementSignal({+ const decisionResult = await executeSkillManagementDecision({decide: options.skillDecisionRunner ?? createSkillDecisionRunner(options),payload: {agentId: action.payload.agentId,@@ -1779,7 +1916,7 @@ export const handleSkillManagementAction = async (* - {@link createFeedbackActionPlannerSignalHandler}** Downstream:- * - {@link runSkillManagementAction}+ * - {@link executeSkillManagementAction}* - {@link SkillManagementDocumentService}*/export const defineSkillManagementActionHandler = (@@ -1789,7 +1926,7 @@ export const defineSkillManagementActionHandler = (AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle,'handler.skill-management.handle',async (action, context: RuntimeProcessorContext) => {- return handleSkillManagementAction(action, options, context);+ return executeSkillManagementAction(action, options, context);},);};diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.tsindex 9727a09ddb4..cf7d1e451a7 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts@@ -32,12 +32,13 @@ import { createDefaultActionServices } from '../../services/actionServices';import type { ProcedureMarkerSuppressInput, ProcedureStateService } from '../../services/types';import type { SignalFeedbackDomainMemory } from '../types';import { AGENT_SIGNAL_POLICY_SIGNAL_TYPES } from '../types';-import type { DeferredSkillCandidate } from './skillCandidate';+import type { RecordedSkillIntent } from './skillIntentRecord';/*** Weak positive skill feedback needs repeated observations before the accumulator emits.*/const SATISFIED_SKILL_CHEAP_SCORE_DELTA = 0.6;+const hintedSkillDocumentIntentClass = 'hinted_skill_document';/*** Marker reader dependency used by both legacy and procedure-state planner options.@@ -110,14 +111,77 @@ const isAccumulatingSkillSignal = ();};-const shouldDeferSkillMutationUntilClientCompletion = (signal: FeedbackDomainSignal) => {+const detectClientStartNeedsSkillIntentRecord = (signal: FeedbackDomainSignal) => {return signal.payload.trigger === AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart;};-const createDeferredSkillCandidate = (+const detectClientComplete = (signal: FeedbackDomainSignal) => {+ return signal.payload.trigger === AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete;+};++const findCompletionHintedDocumentReceipts = async (+ signal: FeedbackDomainSignal,+ context: RuntimeProcessorContext,+ procedureState?: ProcedureStateService,+) => {+ if (!detectClientComplete(signal)) return [];+ if (!procedureState) return [];++ const snapshot = await procedureState.inspect.scope(context.scopeKey);++ return snapshot.receipts.filter((receipt) => {+ if (receipt.domainKey !== 'document:agent-document') return false;+ if (receipt.intentClass !== hintedSkillDocumentIntentClass) return false;+ if (receipt.messageId !== signal.payload.messageId) return false;+ if (receipt.status !== 'handled') return false;++ return (receipt.relatedObjects ?? []).some(+ (object) => object.objectType === 'agent-document' && object.relation === 'created',+ );+ });+};++const createHintedDocumentEvidence = (+ receipts: Awaited<ReturnType<typeof findCompletionHintedDocumentReceipts>>,+) =>+ receipts.map((receipt) => ({+ cue: 'same_turn_hinted_document_receipt',+ excerpt: [+ receipt.summary,+ ...(receipt.relatedObjects ?? [])+ .filter((object) => object.objectType === 'agent-document')+ .map((object) => `agentDocumentId=${object.objectId}`),+ ]+ .filter(Boolean)+ .join('; '),+ }));++const createHintedDocumentSkillSignal = (+ signal: FeedbackDomainSignal,+ receipts: Awaited<ReturnType<typeof findCompletionHintedDocumentReceipts>>,+): NonSatisfiedSkillActionServiceSignal => ({+ ...signal,+ payload: {+ ...signal.payload,+ conflictPolicy: { forbiddenWith: ['none'], mode: 'fanout', priority: 80 },+ evidence: [...(signal.payload.evidence ?? []), ...createHintedDocumentEvidence(receipts)],+ reason: 'completion included a createDocument tool outcome with hintIsSkill=true',+ satisfactionResult: 'not_satisfied',+ skillActionIntent: 'create',+ skillIntentConfidence: 0.9,+ skillIntentExplicitness: 'implicit_strong_learning',+ skillIntentReason: 'A same-turn agent document was created with hintIsSkill=true.',+ skillRoute: 'direct_decision',+ target: 'skill',+ },+ signalId: `${signal.signalId}:hinted-skill-document`,+ signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainSkill,+});++const createRecordedSkillIntent = (signal: NonSatisfiedSkillActionServiceSignal,context: RuntimeProcessorContext,-): DeferredSkillCandidate => ({+): RecordedSkillIntent => ({...(signal.payload.skillActionIntent ? { actionIntent: signal.payload.skillActionIntent } : {}),...(typeof signal.payload.skillIntentConfidence === 'number'? { confidence: signal.payload.skillIntentConfidence }@@ -333,11 +397,27 @@ export const createFeedbackActionPlannerSignalHandler = ({ procedureState },{ onSuppress: () => transitionSuppressedProcedure(signal, procedureContext) },);-if (suppression.type === 'transition' || suppression.type === 'stop') {return suppression.result;}+ const hintedDocumentReceipts = await findCompletionHintedDocumentReceipts(+ signal,+ procedureContext,+ options.procedure?.procedureState,+ );++ if (hintedDocumentReceipts.length > 0) {+ const plan = actionServices.skillActions.prepare(+ createHintedDocumentSkillSignal(signal, hintedDocumentReceipts),+ );++ return {+ actions: [plan.action],+ status: 'dispatch',+ };+ }+if (isMemorySignal(signal)) {const plan = actionServices.memoryActions.prepare(signal);@@ -348,13 +428,13 @@ export const createFeedbackActionPlannerSignalHandler = (}if (isDirectSkillDecisionSignal(signal)) {- if (shouldDeferSkillMutationUntilClientCompletion(signal)) {- await options.procedure?.procedureState?.skillCandidates?.write(- createDeferredSkillCandidate(signal, procedureContext),+ if (detectClientStartNeedsSkillIntentRecord(signal)) {+ await options.procedure?.procedureState?.skillIntentRecords?.write(+ createRecordedSkillIntent(signal, procedureContext),);return {- concluded: { reason: 'skill mutation deferred until client.runtime.complete' },+ concluded: { reason: 'skill intent recorded until client.runtime.complete' },status: 'conclude',};}diff --git a/src/server/services/agentSignal/policies/analyzeIntent/skillCandidate.ts b/src/server/services/agentSignal/policies/analyzeIntent/skillIntentRecord.tssimilarity index 63%rename from src/server/services/agentSignal/policies/analyzeIntent/skillCandidate.tsrename to src/server/services/agentSignal/policies/analyzeIntent/skillIntentRecord.tsindex df5019b221f..1d73aed88d0 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/skillCandidate.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/skillIntentRecord.ts@@ -7,9 +7,9 @@ import type {AgentSignalSkillIntentRoute,} from '../types';-const POLICY_ID = 'analyze-intent:skill-candidates';+const POLICY_ID = 'analyze-intent:skill-intent-records';-const DeferredSkillCandidateSchema = z.object({+const RecordedSkillIntentSchema = z.object({actionIntent: z.enum(['create', 'refine', 'consolidate', 'maintain', 'noop']).optional(),confidence: z.number().min(0).max(1).optional(),createdAt: z.number(),@@ -27,33 +27,33 @@ const DeferredSkillCandidateSchema = z.object({});/**- * Deferred skill candidate stored between user-message and completion analysis stages.+ * Recorded skill intent stored between user-message and completion analysis stages.*/-export interface DeferredSkillCandidate {+export interface RecordedSkillIntent {/** Optional skill-management action hint selected before final-turn evidence is hydrated. */actionIntent?: AgentSignalSkillActionIntent;/** Optional confidence of the user-stage skill-intent classifier, from 0 to 1. */confidence?: number;- /** Time the candidate was written, in epoch milliseconds. */+ /** Time the record was written, in epoch milliseconds. */createdAt: number;/** Whether the user-stage feedback looked explicit, strong implicit, weak, or non-skill. */explicitness: AgentSignalSkillIntentExplicitness;- /** User feedback message id that produced this candidate. */+ /** User feedback message id that produced this record. */feedbackMessageId: string;/** Optional private-safe reason suitable for traces and eval assertions. */reason?: string;/** Runtime route selected before completion-stage evidence is available. */route: AgentSignalSkillIntentRoute;- /** Runtime scope key where the candidate is visible. */+ /** Runtime scope key where the record is visible. */scopeKey: string;- /** Source id that produced this candidate. */+ /** Source id that produced this record. */sourceId: string;}-const candidateField = (sourceId: string) => `skill-candidate:${sourceId}`;+const recordField = (sourceId: string) => `skill-intent-record:${sourceId}`;/**- * Writes one deferred skill candidate to policy state.+ * Writes one recorded skill intent to policy state.** Use when:* - User-message analysis finds skill intent before assistant completion@@ -63,12 +63,12 @@ const candidateField = (sourceId: string) => `skill-candidate:${sourceId}`;* - `scopeKey` matches the later completion source scope** Returns:- * - Resolves after the candidate field is stored+ * - Resolves after the record field is stored*/-export const writeDeferredSkillCandidate = async (+export const recordSkillIntent = async (store: AgentSignalPolicyStateStore,input: {- candidate: DeferredSkillCandidate;+ record: RecordedSkillIntent;scopeKey: string;ttlSeconds: number;},@@ -77,42 +77,42 @@ export const writeDeferredSkillCandidate = async (POLICY_ID,input.scopeKey,{- [candidateField(input.candidate.sourceId)]: JSON.stringify(input.candidate),+ [recordField(input.record.sourceId)]: JSON.stringify(input.record),},input.ttlSeconds,);};/**- * Reads one deferred skill candidate from policy state.+ * Reads one recorded skill intent from policy state.** Use when:* - Completion-stage skill management needs earlier user-stage intent** Expects:- * - Candidate JSON may be absent, malformed, or structurally invalid+ * - Record JSON may be absent, malformed, or structurally invalid** Returns:- * - Parsed candidate, or `undefined` when unavailable+ * - Parsed record, or `undefined` when unavailable*/-export const readDeferredSkillCandidate = async (+export const readRecordedSkillIntent = async (store: AgentSignalPolicyStateStore,input: {scopeKey: string;sourceId: string;},-): Promise<DeferredSkillCandidate | undefined> => {+): Promise<RecordedSkillIntent | undefined> => {const state = await store.readPolicyState(POLICY_ID, input.scopeKey);- const raw = state?.[candidateField(input.sourceId)];+ const raw = state?.[recordField(input.sourceId)];if (!raw) return undefined;try {- const candidate = DeferredSkillCandidateSchema.parse(JSON.parse(raw));- if (candidate.scopeKey !== input.scopeKey || candidate.sourceId !== input.sourceId) {+ const record = RecordedSkillIntentSchema.parse(JSON.parse(raw));+ if (record.scopeKey !== input.scopeKey || record.sourceId !== input.sourceId) {return undefined;}- return candidate;+ return record;} catch {return undefined;}diff --git a/src/server/services/agentSignal/procedure/batchScorer.ts b/src/server/services/agentSignal/procedure/batchScorer.tsindex ebd6e93f48a..7d7957d860b 100644--- a/src/server/services/agentSignal/procedure/batchScorer.ts+++ b/src/server/services/agentSignal/procedure/batchScorer.ts@@ -35,7 +35,7 @@ export const scoreDomainProcedureBatch = (): 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;+ // - observed 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,@@ -44,7 +44,7 @@ export const scoreDomainProcedureBatch = (const score = record.accumulatorRole === 'candidate' ? (record.cheapScoreDelta ?? 0) : 0;return {- reasons: score > 0 ? ['candidate-record'] : ['context-record'],+ reasons: score > 0 ? ['observed-record'] : ['context-record'],recordId: record.id,score,suggestedAction: score > 0 ? ('maintain' as const) : undefined,diff --git a/src/server/services/agentSignal/processors/__tests__/procedure.test.ts b/src/server/services/agentSignal/processors/__tests__/procedure.test.tsindex 07bcb537d9c..c8f07b73ba8 100644--- a/src/server/services/agentSignal/processors/__tests__/procedure.test.ts+++ b/src/server/services/agentSignal/processors/__tests__/procedure.test.ts@@ -312,7 +312,7 @@ describe('procedure processors', () => {cheapScoreDelta: 0.6,createdAt: 1000,domainKey: 'skill',- id: 'procedure-record:sig_skill:skill-candidate',+ id: 'procedure-record:sig_skill:skill-observation-record',intentClass: 'implicit_positive',refs: {signalIds: ['sig_skill'],@@ -326,7 +326,7 @@ describe('procedure processors', () => {expect(write).toHaveBeenCalledWith(expectedRecord);expect(appendAndScore).toHaveBeenCalledWith(expectedRecord);expect(result).toEqual({- reason: 'accumulated skill candidate',+ reason: 'recorded skill observation',type: 'continue',value: { record: expectedRecord, scored: undefined },});diff --git a/src/server/services/agentSignal/processors/procedure.ts b/src/server/services/agentSignal/processors/procedure.tsindex 3a3bee56abc..77de5ef399d 100644--- a/src/server/services/agentSignal/processors/procedure.ts+++ b/src/server/services/agentSignal/processors/procedure.ts@@ -186,7 +186,7 @@ export const suppressHandled = async (};/**- * Writes and scores one satisfied skill procedure candidate.+ * Records and scores one satisfied skill procedure observation.** Use when:* - Weak positive skill feedback should accumulate before action planning@@ -230,7 +230,7 @@ export const accumulateSignal = async (cheapScoreDelta: options.scoreDelta,createdAt: context.now(),domainKey: 'skill',- id: `procedure-record:${signal.signalId}:skill-candidate`,+ id: `procedure-record:${signal.signalId}:skill-observation-record`,intentClass: toPlannerIntentClass(payload.satisfactionResult),refs: {signalIds: [signal.signalId],@@ -244,7 +244,7 @@ export const accumulateSignal = async (await services.procedureState.records.write(record);const scored = await services.procedureState.accumulators.appendAndScore(record);- return continueWith('accumulated skill candidate', { record, scored });+ return continueWith('recorded skill observation', { record, scored });};/**diff --git a/src/server/services/agentSignal/services/procedureStateService.ts b/src/server/services/agentSignal/services/procedureStateService.tsindex 1cb62fc9beb..82f23622695 100644--- a/src/server/services/agentSignal/services/procedureStateService.ts+++ b/src/server/services/agentSignal/services/procedureStateService.ts@@ -1,7 +1,7 @@import {- readDeferredSkillCandidate,- writeDeferredSkillCandidate,-} from '../policies/analyzeIntent/skillCandidate';+ readRecordedSkillIntent,+ recordSkillIntent,+} from '../policies/analyzeIntent/skillIntentRecord';import {appendAndScoreProcedureAccumulatorRecord,appendProcedureAccumulatorRecord,@@ -18,8 +18,8 @@ import { writeProcedureRecordField } from '../procedure/record';import type { AgentSignalPolicyStateStore } from '../store/types';import type { ProcedureStateService } from './types';-type ProcedureStateServiceWithSkillCandidates = ProcedureStateService & {- skillCandidates: NonNullable<ProcedureStateService['skillCandidates']>;+type ProcedureStateServiceWithSkillIntentRecords = ProcedureStateService & {+ skillIntentRecords: NonNullable<ProcedureStateService['skillIntentRecords']>;};/**@@ -49,7 +49,7 @@ export interface CreateProcedureStateServiceInput {*/export const createProcedureStateService = (input: CreateProcedureStateServiceInput,-): ProcedureStateServiceWithSkillCandidates => {+): ProcedureStateServiceWithSkillIntentRecords => {const now = input.now ?? (() => Date.now());const inspector = new AgentSignalProcedureInspector(input.policyStateStore);@@ -65,12 +65,12 @@ export const createProcedureStateService = (inspect: {scope: (scopeKey) => inspector.inspectScope(scopeKey),},- skillCandidates: {- read: (candidateInput) => readDeferredSkillCandidate(input.policyStateStore, candidateInput),- write: (candidate) =>- writeDeferredSkillCandidate(input.policyStateStore, {- candidate,- scopeKey: candidate.scopeKey,+ skillIntentRecords: {+ read: (recordInput) => readRecordedSkillIntent(input.policyStateStore, recordInput),+ write: (record) =>+ recordSkillIntent(input.policyStateStore, {+ record,+ scopeKey: record.scopeKey,ttlSeconds: input.ttlSeconds,}),},diff --git a/src/server/services/agentSignal/services/types.ts b/src/server/services/agentSignal/services/types.tsindex 8d18ae130be..b5d6390ae01 100644--- a/src/server/services/agentSignal/services/types.ts+++ b/src/server/services/agentSignal/services/types.ts@@ -1,4 +1,4 @@-import type { DeferredSkillCandidate } from '../policies/analyzeIntent/skillCandidate';+import type { RecordedSkillIntent } from '../policies/analyzeIntent/skillIntentRecord';import type { ProcedureAccumulatorScoreResult } from '../procedure/accumulators/procedure';import type { AgentSignalProcedureInspectionSnapshot } from '../procedure/inspector';import type { ProcedureMarkerKeyInput } from '../procedure/keys';@@ -76,14 +76,14 @@ export interface ProcedureStateService {/** Writes one compact procedure record field. */write: (record: AgentSignalProcedureRecord) => Promise<void>;};- /** Deferred skill-candidate operations between user and completion analysis stages. */- skillCandidates?: {- /** Reads one deferred skill candidate by source id. */+ /** Recorded skill-intent operations between user and completion analysis stages. */+ skillIntentRecords?: {+ /** Reads one recorded skill intent by source id. */read: (input: {scopeKey: string;sourceId: string;- }) => Promise<DeferredSkillCandidate | undefined>;- /** Writes one deferred skill candidate with facade-owned expiry semantics. */- write: (candidate: DeferredSkillCandidate) => Promise<void>;+ }) => Promise<RecordedSkillIntent | undefined>;+ /** Writes one recorded skill intent with facade-owned expiry semantics. */+ write: (record: RecordedSkillIntent) => Promise<void>;};}diff --git a/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.ts b/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.tsindex 286ffade16a..b6ac4b713d8 100644--- a/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.ts+++ b/src/server/services/agentSignal/sources/hydration/__tests__/clientRuntimeComplete.test.ts@@ -340,6 +340,72 @@ describe('resolveClientRuntimeCompleteFeedbackSource', () => {});});+ /**+ * @example+ * client.runtime.complete({ assistantMessageId: "final-assistant" }) walks assistant -> tool -> assistant -> user.+ */+ it('hydrates a multi-step assistant completion through tool parents to the original user message', async () => {+ const db = await getTestDB();+ const userId = `user_${uuid()}`;+ const topicId = `topic_${uuid()}`;+ const parentMessageId = `msg_${uuid()}`;+ const firstAssistantMessageId = `msg_${uuid()}`;+ const toolMessageId = `msg_${uuid()}`;+ const finalAssistantMessageId = `msg_${uuid()}`;++ await db.insert(users).values({ id: userId });+ await db.insert(topics).values({ id: topicId, title: 'Workflow Topic', userId });+ await db.insert(messages).values([+ {+ content: 'Create a reusable skill from this workflow.',+ id: parentMessageId,+ role: 'user',+ topicId,+ userId,+ },+ {+ content: 'I will create the skill document.',+ id: firstAssistantMessageId,+ parentId: parentMessageId,+ role: 'assistant',+ topicId,+ userId,+ },+ {+ content: 'Created skill document.',+ id: toolMessageId,+ parentId: firstAssistantMessageId,+ role: 'tool',+ topicId,+ userId,+ },+ {+ content: 'Done, the workflow is now reusable.',+ id: finalAssistantMessageId,+ parentId: toolMessageId,+ role: 'assistant',+ topicId,+ userId,+ },+ ]);++ const result = await resolveClientRuntimeCompleteFeedbackSource(+ createCompleteSource({ assistantMessageId: finalAssistantMessageId }),+ { db, userId },+ );++ expect(result.diagnostic).toEqual({+ kind: AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,+ status: 'resolved',+ });+ expect(result.contextBoundaryMessageId).toBe(finalAssistantMessageId);+ expect(result.source?.payload.message).toBe('Create a reusable skill from this workflow.');+ expect(result.source?.payload.messageId).toBe(parentMessageId);+ expect(result.source?.sourceId).toBe(+ `${finalAssistantMessageId}:completion:${parentMessageId}`,+ );+ });+/*** @example* client.runtime.complete with an empty persisted user message cannot produce feedback text.diff --git a/src/server/services/agentSignal/sources/hydration/clientRuntimeComplete.ts b/src/server/services/agentSignal/sources/hydration/clientRuntimeComplete.tsindex 9b03dfbba38..3f5d007c150 100644--- a/src/server/services/agentSignal/sources/hydration/clientRuntimeComplete.ts+++ b/src/server/services/agentSignal/sources/hydration/clientRuntimeComplete.ts@@ -101,18 +101,32 @@ export const resolveClientRuntimeCompleteFeedbackSource = async (return skipped('non-assistant-message');}- if (typeof assistantMessage.parentId !== 'string') {+ let currentParentId = assistantMessage.parentId;++ if (typeof currentParentId !== 'string') {return skipped('missing-parent-message-id');}- const parentMessage = await messageModel.findById(assistantMessage.parentId);+ let parentMessage = await messageModel.findById(currentParentId);if (!parentMessage) {return skipped('parent-message-not-found');}- if (parentMessage.role !== 'user') {- return skipped('non-user-parent');+ const visited = new Set<string>([assistantMessage.id]);++ while (parentMessage.role !== 'user') {+ if (visited.has(parentMessage.id) || typeof parentMessage.parentId !== 'string') {+ return skipped('non-user-parent');+ }++ visited.add(parentMessage.id);+ currentParentId = parentMessage.parentId;+ parentMessage = await messageModel.findById(currentParentId);++ if (!parentMessage) {+ return skipped('parent-message-not-found');+ }}if (!parentMessage.content) {diff --git a/src/server/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts b/src/server/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.tsindex 9106f5d62e9..0262c7a8fb6 100644--- a/src/server/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts+++ b/src/server/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts@@ -6,17 +6,13 @@ import { AgentDocumentsService } from '@/server/services/agentDocuments';import { agentDocumentsRuntime } from '../agentDocuments';-const agentSignalProcedureMocks = vi.hoisted(() => ({- emitToolOutcomeSafely: vi.fn(),- resolveToolOutcomeScope: vi.fn(() => ({- scope: { agentId: 'agent-1', userId: 'user-1' },- scopeKey: 'agent:agent-1:user:user-1',- })),+const agentDocumentToolOutcomeMocks = vi.hoisted(() => ({+ emitAgentDocumentToolOutcomeSafely: vi.fn(),}));vi.mock('@/server/services/agentDocuments');vi.mock('@/database/models/task');-vi.mock('@/server/services/agentSignal/procedure', () => agentSignalProcedureMocks);+vi.mock('@/server/services/agentDocuments/toolOutcome', () => agentDocumentToolOutcomeMocks);describe('agentDocumentsRuntime', () => {it('should have correct identifier', () => {@@ -54,8 +50,7 @@ describe('agentDocumentsRuntime auto-pin to task', () => {let pinDocument: ReturnType<typeof vi.fn>;beforeEach(() => {- agentSignalProcedureMocks.emitToolOutcomeSafely.mockClear();- agentSignalProcedureMocks.resolveToolOutcomeScope.mockClear();+ agentDocumentToolOutcomeMocks.emitAgentDocumentToolOutcomeSafely.mockClear();serviceImpl = {copyDocumentById: vi.fn().mockResolvedValue(newDoc),createDocument: vi.fn().mockResolvedValue(newDoc),@@ -89,16 +84,27 @@ describe('agentDocumentsRuntime auto-pin to task', () => {await runtime.createDocument({ content: 'body', title: 'Daily Brief' }, { agentId: 'agent-1' });- expect(agentSignalProcedureMocks.emitToolOutcomeSafely).toHaveBeenCalledWith(+ expect(agentDocumentToolOutcomeMocks.emitAgentDocumentToolOutcomeSafely).toHaveBeenCalledWith(expect.objectContaining({+ agentDocumentId: 'agent-doc-assoc-id',apiName: 'createDocument',- relatedObjects: [- {- objectId: 'agent-doc-assoc-id',- objectType: 'agent-document',- relation: 'created',- },- ],+ relation: 'created',+ }),+ );+ });++ it('marks hinted create outcomes as skill document intents', async () => {+ const runtime = agentDocumentsRuntime.factory(buildContext('task-1'));++ await runtime.createDocument(+ { content: 'body', hintIsSkill: true, title: 'Reusable Workflow' },+ { agentId: 'agent-1' },+ );++ expect(agentDocumentToolOutcomeMocks.emitAgentDocumentToolOutcomeSafely).toHaveBeenCalledWith(+ expect.objectContaining({+ apiName: 'createDocument',+ hintIsSkill: true,}),);});@@ -108,16 +114,11 @@ describe('agentDocumentsRuntime auto-pin to task', () => {await runtime.copyDocument({ id: 'source-agent-doc-id' }, { agentId: 'agent-1' });- expect(agentSignalProcedureMocks.emitToolOutcomeSafely).toHaveBeenCalledWith(+ expect(agentDocumentToolOutcomeMocks.emitAgentDocumentToolOutcomeSafely).toHaveBeenCalledWith(expect.objectContaining({+ agentDocumentId: 'agent-doc-assoc-id',apiName: 'copyDocument',- relatedObjects: [- {- objectId: 'agent-doc-assoc-id',- objectType: 'agent-document',- relation: 'created',- },- ],+ relation: 'created',}),);});@@ -131,16 +132,11 @@ describe('agentDocumentsRuntime auto-pin to task', () => {{ agentId: 'agent-1' },);- expect(agentSignalProcedureMocks.emitToolOutcomeSafely).toHaveBeenCalledWith(+ expect(agentDocumentToolOutcomeMocks.emitAgentDocumentToolOutcomeSafely).toHaveBeenCalledWith(expect.objectContaining({+ agentDocumentId: 'agent-doc-assoc-id',apiName: 'renameDocument',- relatedObjects: [- {- objectId: 'agent-doc-assoc-id',- objectType: 'agent-document',- relation: 'updated',- },- ],+ relation: 'updated',}),);});diff --git a/src/server/services/toolExecution/serverRuntimes/agentDocuments.ts b/src/server/services/toolExecution/serverRuntimes/agentDocuments.tsindex d261afa1a3f..5a7422f625c 100644--- a/src/server/services/toolExecution/serverRuntimes/agentDocuments.ts+++ b/src/server/services/toolExecution/serverRuntimes/agentDocuments.ts@@ -4,11 +4,7 @@ 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 { emitAgentDocumentToolOutcomeSafely } from '@/server/services/agentDocuments/toolOutcome';import { type ServerRuntimeRegistration } from './types';@@ -27,44 +23,28 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {agentDocumentId?: string;apiName: string;errorReason?: string;+ hintIsSkill?: boolean;relation?: string;status: 'failed' | 'succeeded';summary: string;toolAction: string;}) => {- const { scope, scopeKey } = resolveToolOutcomeScope({+ await emitAgentDocumentToolOutcomeSafely({+ agentDocumentId: input.agentDocumentId,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',+ hintIsSkill: input.hintIsSkill,messageId: context.messageId,operationId: context.operationId,- policyStateStore: redisPolicyStateStore,- relatedObjects: input.agentDocumentId- ? [- {- objectId: input.agentDocumentId,- objectType: 'agent-document',- relation: input.relation,- },- ]- : undefined,- scope,- scopeKey,+ relation: input.relation,status: input.status,summary: input.summary,- ttlSeconds: 7 * 24 * 60 * 60,+ taskId: context.taskId,toolAction: input.toolAction,toolCallId: context.toolCallId,+ topicId: context.topicId,+ userId,});};@@ -73,6 +53,7 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {agentId?: string;getAgentDocumentId?: (result: T) => string | undefined;apiName: string;+ hintIsSkill?: boolean;relation: string;summary: string;toolAction: string;@@ -85,6 +66,7 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {agentId: input.agentId,agentDocumentId: input.getAgentDocumentId?.(result),apiName: input.apiName,+ hintIsSkill: input.hintIsSkill,relation: input.relation,status: 'succeeded',summary: input.summary,@@ -96,6 +78,7 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {agentId: input.agentId,apiName: input.apiName,errorReason: (error as Error).message,+ hintIsSkill: input.hintIsSkill,relation: input.relation,status: 'failed',summary: `${input.summary} failed.`,@@ -134,6 +117,7 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {agentId,apiName: 'createDocument',getAgentDocumentId: (result) => result?.id,+ hintIsSkill,relation: 'created',summary: 'Agent documents created a document.',toolAction: 'create',@@ -148,6 +132,7 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {agentId,apiName: 'createTopicDocument',getAgentDocumentId: (result) => result?.id,+ hintIsSkill,relation: 'created',summary: 'Agent documents created a topic document.',toolAction: 'create',diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.tsindex a360255f5e7..242f5dde851 100644--- a/src/services/agentDocument.ts+++ b/src/services/agentDocument.ts@@ -39,6 +39,19 @@ const getAgentDocumentId = (value: unknown) => getStringField(value, 'id');const getDocumentId = (value: unknown) => getStringField(value, 'documentId');+interface AgentDocumentToolContext {+ messageId: string;+ operationId?: string;+ taskId?: string | null;+ toolCallId: string;+ topicId?: string;+}++interface AgentDocumentToolTriggerInput {+ toolContext?: AgentDocumentToolContext;+ trigger?: 'tool';+}+class AgentDocumentService {getTemplates = async () => {return lambdaClient.agentDocument.getTemplates.query();@@ -75,12 +88,14 @@ class AgentDocumentService {return result;};- createDocument = async (params: {- agentId: string;- content: string;- hintIsSkill?: boolean;- title: string;- }) => {+ createDocument = async (+ params: {+ agentId: string;+ content: string;+ hintIsSkill?: boolean;+ title: string;+ } & AgentDocumentToolTriggerInput,+ ) => {const result = await lambdaClient.agentDocument.createDocument.mutate(params);await invalidateDocumentMutation({agentDocumentId: getAgentDocumentId(result),@@ -92,13 +107,15 @@ class AgentDocumentService {return result;};- createForTopic = async (params: {- agentId: string;- content: string;- hintIsSkill?: boolean;- title: string;- topicId: string;- }) => {+ createForTopic = async (+ params: {+ agentId: string;+ content: string;+ hintIsSkill?: boolean;+ title: string;+ topicId: string;+ } & AgentDocumentToolTriggerInput,+ ) => {const result = await lambdaClient.agentDocument.createForTopic.mutate(params);await invalidateDocumentMutation({agentDocumentId: getAgentDocumentId(result),diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.tsindex 12b4f0fa879..46d8eee6146 100644--- a/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.ts+++ b/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.ts@@ -13,6 +13,20 @@ import {simulateOperationCancellation,} from './helpers';+vi.mock('@/utils/localStorage', () => {+ class AsyncLocalStorage<State> {+ async getFromLocalStorage(): Promise<State> {+ return {} as State;+ }++ async saveToLocalStorage(): Promise<void> {+ return undefined;+ }+ }++ return { AsyncLocalStorage };+});+describe('call_tool executor', () => {describe('Basic Behavior', () => {it('should create tool message and execute tool successfully', async () => {@@ -460,10 +474,11 @@ describe('call_tool executor', () => {// Thenexpect(mockStore.startOperation).toHaveBeenNthCalledWith(1, {type: 'toolCalling',- context: {+ context: expect.objectContaining({agentId: 'sess_op',+ sourceMessageId: 'msg_parent',topicId: 'topic_op',- },+ }),parentOperationId: context.operationId,metadata: expect.objectContaining({identifier: 'lobe-web-browsing',diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.tsindex ac46bb29223..71f16704d15 100644--- a/src/store/chat/agents/createAgentExecutors.ts+++ b/src/store/chat/agents/createAgentExecutors.ts@@ -678,6 +678,27 @@ export const createAgentExecutors = (context: {// Get context from operationconst opContext = getOperationContext();+ // Get assistant message to derive the same-turn source user message when the root+ // runtime operation is anchored to the assistant message.+ const latestMessages = context.get().dbMessagesMap[context.messageKey] || [];+ const existingToolMessage = payload.skipCreateToolMessage+ ? latestMessages.find((m) => m.id === payload.parentMessageId)+ : undefined;+ const assistantMessage =+ latestMessages.find((m) => m.id === payload.parentMessageId && m.role === 'assistant') ??+ (existingToolMessage?.parentId+ ? latestMessages.find(+ (m) => m.id === existingToolMessage.parentId && m.role === 'assistant',+ )+ : undefined) ??+ (opContext.messageId+ ? latestMessages.find((m) => m.id === opContext.messageId && m.role === 'assistant')+ : undefined) ??+ latestMessages.findLast((m) => m.role === 'assistant');+ const sourceMessageId =+ opContext.sourceMessageId ??+ assistantMessage?.parentId ??+ (opContext.messageId !== assistantMessage?.id ? opContext.messageId : undefined);// ============ Create toolCalling operation (top-level) ============const { operationId: toolOperationId } = context.get().startOperation({@@ -686,6 +707,7 @@ export const createAgentExecutors = (context: {agentId: opContext.agentId!,groupId: opContext.groupId,scope: opContext.scope,+ sourceMessageId,topicId: opContext.topicId,threadId: opContext.threadId,viewedTask: opContext.viewedTask,@@ -700,24 +722,17 @@ export const createAgentExecutors = (context: {});try {- // Get assistant message to extract groupId- const latestMessages = context.get().dbMessagesMap[context.messageKey] || [];- // Find the last assistant message (should be created by call_llm)- const assistantMessage = latestMessages.findLast((m) => m.role === 'assistant');-let toolMessageId: string;if (payload.skipCreateToolMessage) {// Reuse existing tool message (resumption mode)toolMessageId = payload.parentMessageId;- // Check if tool message already exists (e.g., from human approval flow)- const existingToolMessage = latestMessages.find((m) => m.id === toolMessageId)!;log('[%s][call_tool] Resuming with existing tool message: %s (status: %s)',sessionLogId,toolMessageId,- existingToolMessage.pluginIntervention?.status,+ existingToolMessage?.pluginIntervention?.status,);} else {// Create new tool message (normal mode)diff --git a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.tsindex ef602bc9d1d..7bd2606c4f9 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts@@ -28,32 +28,18 @@ const agentSignalBridgeMock = vi.hoisted(() => ({emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),}));-vi.hoisted(() => {- // NOTICE:- // Ensure store modules see a full Storage-compatible localStorage during import.- // Vitest can provide a partial localStorage object when invoked with an empty- // `--localstorage-file`, which breaks packages/utils/src/localStorage.ts at collection time.- // Source/context: matches the focused store test setup pattern in src/services/chat/chat.test.ts.- // Removal condition: safe to delete when Vitest setup guarantees getItem/setItem before imports.- const storage = new Map<string, string>();-- Object.defineProperty(globalThis, 'localStorage', {- configurable: true,- value: {- clear: () => storage.clear(),- getItem: (key: string) => storage.get(key) ?? null,- key: (index: number) => Array.from(storage.keys())[index] ?? null,- get length() {- return storage.size;- },- removeItem: (key: string) => {- storage.delete(key);- },- setItem: (key: string, value: string) => {- storage.set(key, value);- },- },- });+vi.mock('@/utils/localStorage', () => {+ class AsyncLocalStorage<State> {+ async getFromLocalStorage(): Promise<State> {+ return {} as State;+ }++ async saveToLocalStorage(): Promise<void> {+ return undefined;+ }+ }++ return { AsyncLocalStorage };});interface AgentRuntimeStepContext {@@ -1743,6 +1729,93 @@ describe('StreamingExecutor actions', () => {);});+ it('emits client.runtime.complete with the parent assistant message id for pre-created assistant turns', async () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ useChatStore.setState({+ executeClientAgent: realExecAgentRuntime,+ });+ });++ let operationId!: string;++ act(() => {+ const res = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ });+ operationId = res.operationId;+ });++ act(() => {+ useChatStore.setState((state) => ({+ messagesMap: {+ ...state.messagesMap,+ [messageMapKey({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID })]: [+ createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ parentId: TEST_IDS.USER_MESSAGE_ID,+ role: 'assistant',+ }),+ ],+ },+ }));+ });++ mockInternalCreateAgentState({+ state: createMockRuntimeState(operationId!, 'done'),+ context: {+ phase: 'init',+ payload: { model: 'gpt-4o-mini', provider: 'openai' },+ session: {+ sessionId: TEST_IDS.SESSION_ID,+ messageCount: 0,+ status: 'done',+ stepCount: 1,+ },+ },+ agentConfig: createMockResolvedAgentConfig(),+ });++ await act(async () => {+ await result.current.executeClientAgent({+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ messages: [],+ parentMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ parentMessageType: 'assistant',+ operationId: operationId!,+ skipCreateFirstMessage: true,+ });+ });++ // ROOT CAUSE:+ //+ // Normal client chat pre-creates an assistant message and starts runtime+ // with parentMessageId equal to that assistant id.+ //+ // Before the fix, completion only searched descendant assistant messages:+ // parent assistant -> undefined assistantMessageId.+ //+ // We fixed this by accepting the parent assistant itself when no later+ // descendant assistant exists.+ expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ operationId,+ status: 'completed',+ }),+ sourceId: `${operationId}:client:complete`,+ sourceType: 'client.runtime.complete',+ }),+ );+ });+it('does not attach an unrelated assistant message id to client.runtime.complete', async () => {const { result } = renderHook(() => useChatStore());@@ -1819,6 +1892,92 @@ describe('StreamingExecutor actions', () => {);});+ it('emits client.runtime.complete with the final assistant message id after tool turns', async () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ useChatStore.setState({+ executeClientAgent: realExecAgentRuntime,+ });+ });++ let operationId!: string;++ act(() => {+ const res = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ });+ operationId = res.operationId;+ });++ act(() => {+ useChatStore.setState((state) => ({+ messagesMap: {+ ...state.messagesMap,+ [messageMapKey({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID })]: [+ createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ }),+ createMockMessage({+ id: 'assistant-step-1',+ parentId: TEST_IDS.USER_MESSAGE_ID,+ role: 'assistant',+ }),+ createMockMessage({+ id: 'tool-step-1',+ parentId: 'assistant-step-1',+ role: 'tool',+ }),+ createMockMessage({+ id: 'assistant-final',+ parentId: 'tool-step-1',+ role: 'assistant',+ }),+ ],+ },+ }));+ });++ mockInternalCreateAgentState({+ state: createMockRuntimeState(operationId!, 'done'),+ context: {+ phase: 'init',+ payload: { model: 'gpt-4o-mini', provider: 'openai' },+ session: {+ sessionId: TEST_IDS.SESSION_ID,+ messageCount: 0,+ status: 'done',+ stepCount: 1,+ },+ },+ agentConfig: createMockResolvedAgentConfig(),+ });++ await act(async () => {+ await result.current.executeClientAgent({+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ messages: [],+ parentMessageId: TEST_IDS.USER_MESSAGE_ID,+ parentMessageType: 'user',+ operationId: operationId!,+ });+ });++ expect(agentSignalBridgeMock.emitClientAgentSignalSourceEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ assistantMessageId: 'assistant-final',+ operationId,+ status: 'completed',+ }),+ sourceId: `${operationId}:client:complete`,+ sourceType: 'client.runtime.complete',+ }),+ );+ });+it('emits client.runtime.complete before returning for queued follow-up messages', async () => {vi.useFakeTimers();diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.tsindex cf66640edd5..889cb6297fa 100644--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts@@ -110,10 +110,33 @@ const normalizeClientRuntimeCompleteStatus = (return undefined;};-const findCompletionAssistantMessageId = (messages: UIChatMessage[], parentMessageId: string) => {- return messages.findLast(- (message) => message.role === 'assistant' && message.parentId === parentMessageId,- )?.id;+const findCompletionAssistantMessageId = (+ messages: UIChatMessage[],+ parentMessageId: string,+ parentMessageType: 'user' | 'assistant' | 'tool',+) => {+ const messagesById = new Map(messages.map((message) => [message.id, message]));+ const parentMessage = messagesById.get(parentMessageId);+ const isDescendantOfParent = (message: UIChatMessage) => {+ let currentParentId = message.parentId;+ const visited = new Set<string>();++ while (currentParentId && !visited.has(currentParentId)) {+ if (currentParentId === parentMessageId) return true;+ visited.add(currentParentId);+ currentParentId = messagesById.get(currentParentId)?.parentId;+ }++ return false;+ };++ return (+ messages.findLast((message) => message.role === 'assistant' && isDescendantOfParent(message))+ ?.id ??+ (parentMessageType === 'assistant' && parentMessage?.role === 'assistant'+ ? parentMessage.id+ : undefined)+ );};/**@@ -614,7 +637,13 @@ export class StreamingExecutorActionImpl {const emitRuntimeCompleteSource = () => {const finalMessages = this.#get().messagesMap[messageKey] || [];- const assistantMessageId = findCompletionAssistantMessageId(finalMessages, parentMessageId);+ const assistantMessageId =+ findCompletionAssistantMessageId(finalMessages, parentMessageId, parentMessageType) ??+ findCompletionAssistantMessageId(+ this.#get().dbMessagesMap[messageKey] || [],+ parentMessageId,+ parentMessageType,+ );const operationStatus = this.#get().operations[operationId]?.status;void emitClientAgentSignalSourceEvent({diff --git a/src/store/chat/slices/plugin/action.test.ts b/src/store/chat/slices/plugin/action.test.tsindex cc296654797..2fb5e555472 100644--- a/src/store/chat/slices/plugin/action.test.ts+++ b/src/store/chat/slices/plugin/action.test.ts@@ -1,6 +1,11 @@import { PLUGIN_SCHEMA_API_MD5_PREFIX, PLUGIN_SCHEMA_SEPARATOR } from '@lobechat/const';import { ToolNameResolver } from '@lobechat/context-engine';-import { type ChatToolPayload, type MessageToolCall, type UIChatMessage } from '@lobechat/types';+import type {+ BuiltinToolContext,+ ChatToolPayload,+ MessageToolCall,+ UIChatMessage,+} from '@lobechat/types';import { act, renderHook } from '@testing-library/react';import { type Mock } from 'vitest';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -10,6 +15,20 @@ import { useChatStore } from '@/store/chat/store';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { useToolStore } from '@/store/tool';+vi.mock('@/utils/localStorage', () => {+ class AsyncLocalStorage<State> {+ async getFromLocalStorage(): Promise<State> {+ return {} as State;+ }++ async saveToLocalStorage(): Promise<void> {+ return undefined;+ }+ }++ return { AsyncLocalStorage };+});+vi.mock('zustand/traditional');// Mock messageService@@ -290,6 +309,107 @@ describe('ChatPluginAction', () => {});});+ it('should pass tool call id and explicit source user message id to Tool Store executor', async () => {+ const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(true);++ const { result } = renderHook(() => useChatStore());+ const messageId = 'tool-message-id';++ act(() => {+ const rootOperationId = result.current.startOperation({+ type: 'execAgentRuntime',+ context: {+ agentId: 'agent-1',+ messageId: 'assistant-msg-1',+ sourceMessageId: 'root-user-msg-1',+ },+ }).operationId;++ const toolOperationId = result.current.startOperation({+ type: 'executeToolCall',+ context: { messageId, sourceMessageId: 'user-msg-1' },+ parentOperationId: rootOperationId,+ }).operationId;++ result.current.associateMessageWithOperation(messageId, toolOperationId);+ });++ let capturedContext: BuiltinToolContext | undefined;+ vi.spyOn(useToolStore.getState(), 'invokeBuiltinTool').mockImplementation(+ async (_id, _api, _params, ctx) => {+ capturedContext = ctx;+ return { success: true };+ },+ );++ const payload = {+ identifier: 'test-tool',+ apiName: 'mockBuiltinAction',+ arguments: JSON.stringify({ input: 'test' }),+ id: 'tool-call-1',+ type: 'builtin',+ } as ChatToolPayload;++ await act(async () => {+ await result.current.invokeBuiltinTool(messageId, payload);+ });++ expect(capturedContext?.messageId).toBe(messageId);+ expect(capturedContext?.sourceMessageId).toBe('user-msg-1');+ expect(capturedContext?.toolCallId).toBe('tool-call-1');+ });++ it('should fall back to root operation message id as source message id', async () => {+ const hasExecutorModule = await import('@/store/tool/slices/builtin/executors');+ vi.spyOn(hasExecutorModule, 'hasExecutor').mockReturnValue(true);++ const { result } = renderHook(() => useChatStore());+ const messageId = 'tool-message-id';++ act(() => {+ const rootOperationId = result.current.startOperation({+ type: 'execAgentRuntime',+ context: {+ agentId: 'agent-1',+ messageId: 'user-msg-1',+ },+ }).operationId;++ const toolOperationId = result.current.startOperation({+ type: 'executeToolCall',+ context: { messageId },+ parentOperationId: rootOperationId,+ }).operationId;++ result.current.associateMessageWithOperation(messageId, toolOperationId);+ });++ let capturedContext: BuiltinToolContext | undefined;+ vi.spyOn(useToolStore.getState(), 'invokeBuiltinTool').mockImplementation(+ async (_id, _api, _params, ctx) => {+ capturedContext = ctx;+ return { success: true };+ },+ );++ const payload = {+ identifier: 'test-tool',+ apiName: 'mockBuiltinAction',+ arguments: JSON.stringify({ input: 'test' }),+ id: 'tool-call-1',+ type: 'builtin',+ } as ChatToolPayload;++ await act(async () => {+ await result.current.invokeBuiltinTool(messageId, payload);+ });++ expect(capturedContext?.messageId).toBe(messageId);+ expect(capturedContext?.sourceMessageId).toBe('user-msg-1');+ expect(capturedContext?.toolCallId).toBe('tool-call-1');+ });+describe('registerAfterCompletion with Tool Store executor', () => {it('should create registerAfterCompletion when root execAgentRuntime operation exists', async () => {// Mock hasExecutor to return truediff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.tsindex 0e45e525090..4a1b23b14d8 100644--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts@@ -156,9 +156,13 @@ export class PluginTypesActionImpl {registerAfterCompletion,scope,signal: operation?.abortController?.signal,- sourceMessageId: rootRuntimeOperationContext?.messageId,+ sourceMessageId:+ operation?.context?.sourceMessageId ??+ rootRuntimeOperationContext?.sourceMessageId ??+ rootRuntimeOperationContext?.messageId,stepContext,taskId,+ toolCallId: payload.id,topicId,});diff --git a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts b/src/store/tool/slices/builtin/executors/lobe-agent-documents.tsindex 3ceb1fb2ec6..129816a007f 100644--- a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts+++ b/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts@@ -7,10 +7,25 @@ import { agentDocumentService } from '@/services/agentDocument';const runtime = new AgentDocumentsExecutionRuntime({copyDocument: ({ agentId, id, newTitle }) =>agentDocumentService.copyDocument({ agentId, id, newTitle }),- createDocument: ({ agentId, content, hintIsSkill, title }) =>- agentDocumentService.createDocument({ agentId, content, hintIsSkill, title }),- createTopicDocument: ({ agentId, content, hintIsSkill, title, topicId }) =>- agentDocumentService.createForTopic({ agentId, content, hintIsSkill, title, topicId }),+ createDocument: ({ agentId, content, hintIsSkill, title, toolContext, trigger }) =>+ agentDocumentService.createDocument({+ agentId,+ content,+ hintIsSkill,+ title,+ toolContext,+ trigger,+ }),+ createTopicDocument: ({ agentId, content, hintIsSkill, title, toolContext, topicId, trigger }) =>+ agentDocumentService.createForTopic({+ agentId,+ content,+ hintIsSkill,+ title,+ toolContext,+ topicId,+ trigger,+ }),listDocuments: async ({ agentId }) => {const docs = await agentDocumentService.listDocuments({ agentId });return docs.map((d) => ({