π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(agent-signal): S6 β migrate skillManagement to execAgent builtin agent (#15443)
Arvin Xue8b914feefd7
diff --git a/packages/builtin-agents/src/agents/skill-management/index.ts b/packages/builtin-agents/src/agents/skill-management/index.tsnew file mode 100644index 00000000000..c461a8cf0d8--- /dev/null+++ b/packages/builtin-agents/src/agents/skill-management/index.ts@@ -0,0 +1,30 @@+import { DEFAULT_MINI_PROVIDER } from '@lobechat/business-const';+import { DEFAULT_MINI_MODEL } from '@lobechat/const';++import type { BuiltinAgentDefinition } from '../../types';+import { BUILTIN_AGENT_SLUGS } from '../../types';++/**+ * Skill-Management Agent β runs after a turn when user feedback is routed to the+ * skill domain (a reusable procedure / workflow the agent should perform+ * consistently). It inspects existing managed skills and applies one safe skill+ * create/refine, or does nothing.+ *+ * Tool surface (`agent-signal-skill-management`) is the skill-only resource+ * subset (skill reads + createSkillIfAbsent / replaceSkillContentCAS), wired+ * server-side via its serverRuntime.+ */+export const SKILL_MANAGEMENT: BuiltinAgentDefinition = {+ // Background self-iteration runs on the cheap mini system model, not the+ // user's default chat model.+ persist: {+ model: DEFAULT_MINI_MODEL,+ provider: DEFAULT_MINI_PROVIDER,+ },+ runtime: {+ plugins: ['agent-signal-skill-management'],+ systemRole:+ 'You are the same-turn skill-management agent. Inspect existing managed skills and turn reusable-procedure feedback into exactly one durable skill create/refine, or do nothing. Be concise and evidence-driven.',+ },+ slug: BUILTIN_AGENT_SLUGS.skillManagement,+};diff --git a/packages/builtin-agents/src/index.ts b/packages/builtin-agents/src/index.tsindex 211b30de4f7..709791bc1a8 100644--- a/packages/builtin-agents/src/index.ts+++ b/packages/builtin-agents/src/index.ts@@ -6,6 +6,7 @@ import { NIGHTLY_REVIEW } from './agents/nightly-review';import { PAGE_AGENT } from './agents/page-agent';import { SELF_FEEDBACK_INTENT } from './agents/self-feedback-intent';import { SELF_REFLECTION } from './agents/self-reflection';+import { SKILL_MANAGEMENT } from './agents/skill-management';import { TASK_AGENT } from './agents/task-agent';import { WEB_ONBOARDING } from './agents/web-onboarding';import type { BuiltinAgentDefinition, BuiltinAgentSlug, RuntimeContext } from './types';@@ -22,6 +23,7 @@ export { NIGHTLY_REVIEW } from './agents/nightly-review';export { PAGE_AGENT } from './agents/page-agent';export { SELF_FEEDBACK_INTENT } from './agents/self-feedback-intent';export { SELF_REFLECTION } from './agents/self-reflection';+export { SKILL_MANAGEMENT } from './agents/skill-management';export { TASK_AGENT } from './agents/task-agent';export { WEB_ONBOARDING } from './agents/web-onboarding';@@ -37,6 +39,7 @@ export const BUILTIN_AGENTS: Record<BuiltinAgentSlug, BuiltinAgentDefinition> =[BUILTIN_AGENT_SLUGS.pageAgent]: PAGE_AGENT,[BUILTIN_AGENT_SLUGS.selfFeedbackIntent]: SELF_FEEDBACK_INTENT,[BUILTIN_AGENT_SLUGS.selfReflection]: SELF_REFLECTION,+ [BUILTIN_AGENT_SLUGS.skillManagement]: SKILL_MANAGEMENT,[BUILTIN_AGENT_SLUGS.taskAgent]: TASK_AGENT,[BUILTIN_AGENT_SLUGS.webOnboarding]: WEB_ONBOARDING,};@@ -52,6 +55,7 @@ export const SELF_ITERATION_AGENT_SLUGS = new Set<BuiltinAgentSlug>([BUILTIN_AGENT_SLUGS.nightlyReview,BUILTIN_AGENT_SLUGS.selfFeedbackIntent,BUILTIN_AGENT_SLUGS.selfReflection,+ BUILTIN_AGENT_SLUGS.skillManagement,]);/**diff --git a/packages/builtin-agents/src/types.ts b/packages/builtin-agents/src/types.tsindex 39f250223e3..9515cc4c238 100644--- a/packages/builtin-agents/src/types.ts+++ b/packages/builtin-agents/src/types.ts@@ -14,6 +14,7 @@ export const BUILTIN_AGENT_SLUGS = {pageAgent: 'page-agent',selfFeedbackIntent: 'self-feedback-intent',selfReflection: 'self-reflection',+ skillManagement: 'skill-management',taskAgent: 'task-agent',webOnboarding: 'web-onboarding',} as const;diff --git a/packages/builtin-tool-agent-signal/src/index.ts b/packages/builtin-tool-agent-signal/src/index.tsindex 4a1a6e050f4..2d5bfb973d9 100644--- a/packages/builtin-tool-agent-signal/src/index.ts+++ b/packages/builtin-tool-agent-signal/src/index.ts@@ -10,6 +10,7 @@ export {AGENT_SIGNAL_RESOURCE_API_NAMES,AGENT_SIGNAL_REVIEW_API_NAMES,AGENT_SIGNAL_REVIEW_TOOL_API_NAMES,+ AGENT_SIGNAL_SKILL_MANAGEMENT_TOOL_API_NAMES,AGENT_SIGNAL_TOOL_RESULT_KIND,type AgentSignalToolApiName,} from './shared/apiNames';@@ -25,9 +26,17 @@ export {AGENT_SIGNAL_FEEDBACK_INTENT_IDENTIFIER,AGENT_SIGNAL_REFLECTION_IDENTIFIER,AGENT_SIGNAL_REVIEW_IDENTIFIER,+ AGENT_SIGNAL_SKILL_MANAGEMENT_IDENTIFIER,} from './shared/identifiers';export {createAgentSignalManifest,type CreateAgentSignalManifestOptions,} from './shared/manifest';-export { REFLECTION_TOOL_APIS, RESOURCE_TOOL_APIS, REVIEW_TOOL_APIS } from './shared/schemas';+export {+ REFLECTION_TOOL_APIS,+ RESOURCE_TOOL_APIS,+ REVIEW_TOOL_APIS,+ SKILL_TOOL_APIS,+} from './shared/schemas';+export { agentSignalSkillManagementManifest } from './skill-management/manifest';+export { systemPrompt as agentSignalSkillManagementSystemPrompt } from './skill-management/systemRole';diff --git a/packages/builtin-tool-agent-signal/src/shared/apiNames.ts b/packages/builtin-tool-agent-signal/src/shared/apiNames.tsindex b28b0a1d1bd..1566a4aa313 100644--- a/packages/builtin-tool-agent-signal/src/shared/apiNames.ts+++ b/packages/builtin-tool-agent-signal/src/shared/apiNames.ts@@ -34,6 +34,18 @@ export const AGENT_SIGNAL_REFLECTION_API_NAMES = ['recordSelfFeedbackIntent',] as const;+/**+ * Skill-management tools: skill-only resource reads + writes (no memory, no+ * proposal/idea recorders). Used by the same-turn skill-management background+ * agent, which routes preference/style feedback to skills exclusively.+ */+export const AGENT_SIGNAL_SKILL_MANAGEMENT_TOOL_API_NAMES = [+ 'listManagedSkills',+ 'getManagedSkill',+ 'createSkillIfAbsent',+ 'replaceSkillContentCAS',+] as const;+export const AGENT_SIGNAL_REVIEW_TOOL_API_NAMES = [...AGENT_SIGNAL_RESOURCE_API_NAMES,...AGENT_SIGNAL_REVIEW_API_NAMES,diff --git a/packages/builtin-tool-agent-signal/src/shared/identifiers.ts b/packages/builtin-tool-agent-signal/src/shared/identifiers.tsindex e54ec8aecbb..8f8d7f21aa1 100644--- a/packages/builtin-tool-agent-signal/src/shared/identifiers.ts+++ b/packages/builtin-tool-agent-signal/src/shared/identifiers.ts@@ -1,12 +1,14 @@/**- * Builtin tool identifiers for the three self-iteration background agents.+ * Builtin tool identifiers for the self-iteration background agents.** These match the `plugins: [...]` declared by the matching builtin agents* (`@lobechat/builtin-agents`): nightly-review β review, self-reflection β- * reflection, self-feedback-intent β feedback-intent.+ * reflection, self-feedback-intent β feedback-intent, skill-management β+ * skill-management.** Identifiers are stored in message history β treat them as permanent.*/export const AGENT_SIGNAL_REVIEW_IDENTIFIER = 'agent-signal-review';export const AGENT_SIGNAL_REFLECTION_IDENTIFIER = 'agent-signal-reflection';export const AGENT_SIGNAL_FEEDBACK_INTENT_IDENTIFIER = 'agent-signal-feedback-intent';+export const AGENT_SIGNAL_SKILL_MANAGEMENT_IDENTIFIER = 'agent-signal-skill-management';diff --git a/packages/builtin-tool-agent-signal/src/shared/schemas.ts b/packages/builtin-tool-agent-signal/src/shared/schemas.tsindex 95301e2ed3e..dbf0ebb4a01 100644--- a/packages/builtin-tool-agent-signal/src/shared/schemas.ts+++ b/packages/builtin-tool-agent-signal/src/shared/schemas.ts@@ -136,6 +136,15 @@ export const RESOURCE_TOOL_APIS: ToolApiSpec[] = [},];+/**+ * Skill-only resource tools (skill reads + writes, no `writeMemory`). Derived+ * from {@link RESOURCE_TOOL_APIS} so the skill-management mode exposes exactly+ * the skill surface without duplicating schemas.+ */+export const SKILL_TOOL_APIS: ToolApiSpec[] = RESOURCE_TOOL_APIS.filter(+ (api) => api.name !== 'writeMemory',+);+export const REVIEW_TOOL_APIS: ToolApiSpec[] = [{description: 'List active and historical self-review proposals in the reviewed agent scope.',diff --git a/packages/builtin-tool-agent-signal/src/skill-management/manifest.ts b/packages/builtin-tool-agent-signal/src/skill-management/manifest.tsnew file mode 100644index 00000000000..6013f4f78e7--- /dev/null+++ b/packages/builtin-tool-agent-signal/src/skill-management/manifest.ts@@ -0,0 +1,16 @@+import { AGENT_SIGNAL_SKILL_MANAGEMENT_IDENTIFIER } from '../shared/identifiers';+import { createAgentSignalManifest } from '../shared/manifest';+import { SKILL_TOOL_APIS } from '../shared/schemas';+import { systemPrompt } from './systemRole';++/**+ * Same-turn skill-management tool surface: skill-only resource reads + writes+ * (no memory, no proposal/idea recorders). Hidden, server-executed builtin tool.+ */+export const agentSignalSkillManagementManifest = createAgentSignalManifest({+ apis: [...SKILL_TOOL_APIS],+ description: 'Read managed skills and apply one safe skill create/refine from skill feedback.',+ identifier: AGENT_SIGNAL_SKILL_MANAGEMENT_IDENTIFIER,+ systemRole: systemPrompt,+ title: 'Agent Signal Skill Management',+});diff --git a/packages/builtin-tool-agent-signal/src/skill-management/systemRole.ts b/packages/builtin-tool-agent-signal/src/skill-management/systemRole.tsnew file mode 100644index 00000000000..f3f9def15c6--- /dev/null+++ b/packages/builtin-tool-agent-signal/src/skill-management/systemRole.ts@@ -0,0 +1,11 @@+export const systemPrompt = `You are the same-turn skill-management agent for one user agent. The user just gave feedback that has already been routed to the skill domain β it describes a reusable procedure / workflow / repeatable task the agent should perform consistently from now on.++Your job: turn that feedback into exactly one durable managed-skill write, or do nothing.++Read first (listManagedSkills, getManagedSkill) to see whether an existing skill already covers this procedure. Then:+- createSkillIfAbsent: when no existing skill covers it β author a concise, reusable skill (clear name, description, and step-by-step bodyMarkdown).+- replaceSkillContentCAS: when an existing skill should be refined/extended to incorporate the feedback. Provide baseSnapshot when available; the server completes it from skillDocumentId when omitted.++The skill \`name\` MUST be a slug: lowercase ASCII letters, digits, and hyphens only (e.g. \`weekly-report-flow\`) β never spaces, uppercase, or non-ASCII characters. Put any human-readable / non-English label in \`title\` and \`description\`, not in \`name\`.++Apply at most one skill mutation. If the feedback is vague, non-procedural, or already fully covered by an existing skill, make no write. Always pass a stable idempotencyKey on writes. Be concise and evidence-driven.`;diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.tsindex e592c3935f0..f4e3b63cd62 100644--- a/packages/builtin-tools/src/identifiers.ts+++ b/packages/builtin-tools/src/identifiers.ts@@ -6,6 +6,7 @@ import {agentSignalFeedbackIntentManifest,agentSignalReflectionManifest,agentSignalReviewManifest,+ agentSignalSkillManagementManifest,} from '@lobechat/builtin-tool-agent-signal';import { CalculatorManifest } from '@lobechat/builtin-tool-calculator';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';@@ -44,6 +45,7 @@ export const builtinToolIdentifiers: string[] = [agentSignalReviewManifest.identifier,agentSignalReflectionManifest.identifier,agentSignalFeedbackIntentManifest.identifier,+ agentSignalSkillManagementManifest.identifier,SkillsManifest.identifier,SkillStoreManifest.identifier,TopicReferenceManifest.identifier,diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex a6a29101d4e..ad7dbf196da 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -6,6 +6,7 @@ import {agentSignalFeedbackIntentManifest,agentSignalReflectionManifest,agentSignalReviewManifest,+ agentSignalSkillManagementManifest,} from '@lobechat/builtin-tool-agent-signal';import { BriefManifest } from '@lobechat/builtin-tool-brief';import { CalculatorManifest } from '@lobechat/builtin-tool-calculator';@@ -169,6 +170,13 @@ export const builtinTools: LobeBuiltinTool[] = [manifest: agentSignalFeedbackIntentManifest,type: 'builtin',},+ {+ discoverable: false,+ hidden: true,+ identifier: agentSignalSkillManagementManifest.identifier,+ manifest: agentSignalSkillManagementManifest,+ type: 'builtin',+ },{discoverable: isDesktop,hidden: true,diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex f4d388968e4..079cbc9552c 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -5,7 +5,8 @@ export type AgentSignalOperationKind =| 'memory'| 'nightly-review'| 'self-feedback-intent'- | 'self-reflection';+ | 'self-reflection'+ | 'skill';/*** Run-scoped Agent Signal marker stamped onto a background agent operation atdiff --git a/src/server/services/agentSignal/operationMarker.ts b/src/server/services/agentSignal/operationMarker.tsindex 5c2270eb542..20a02f97ac3 100644--- a/src/server/services/agentSignal/operationMarker.ts+++ b/src/server/services/agentSignal/operationMarker.ts@@ -21,6 +21,7 @@ const VALID_KINDS = new Set<AgentSignalOperationKind>(['nightly-review','self-feedback-intent','self-reflection',+ 'skill',]);const isRecord = (value: unknown): value is Record<string, unknown> =>diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.integration.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.integration.test.tsdeleted file mode 100644index bb0e3603c35..00000000000--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.integration.test.ts+++ /dev/null@@ -1,166 +0,0 @@-// @vitest-environment node-import type { LobeChatDatabase } from '@lobechat/database';-import { getTestDB } from '@lobechat/database/test-utils';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { AgentDocumentVfsService } from '@/server/services/agentDocumentVfs';-import { SkillManagementDocumentService } from '@/server/services/skillManagement';--import {- cleanupTestUser,- createTestAgent,- createTestUser,-} from '../../../../../../routers/lambda/__tests__/integration/setup';-import { runSkillManagementAction } from '../skillManagement';--vi.mock('@/server/services/skill/resource', () => ({- SkillResourceService: vi.fn().mockImplementation(() => ({- listResources: vi.fn().mockResolvedValue([]),- readResource: vi.fn().mockRejectedValue(new Error('Resource not found')),- storeResources: vi.fn().mockResolvedValue({}),- })),-}));--describe('runSkillManagementAction integration', () => {- let serverDB: LobeChatDatabase;- let userId: string;- let agentId: string;-- beforeEach(async () => {- serverDB = await getTestDB();- userId = await createTestUser(serverDB);- agentId = await createTestAgent(serverDB, userId);- });-- afterEach(async () => {- await cleanupTestUser(serverDB, userId);- });-- const createManagedSkill = async (skillName: string, bodyMarkdown: string) => {- return new SkillManagementDocumentService(serverDB, userId).createSkill({- agentId,- bodyMarkdown,- description: `${skillName} description`,- name: skillName,- title: skillName,- });- };-- const readSkillIndex = async (skillName: string) => {- return (- await new AgentDocumentVfsService(serverDB, userId).read(- `./lobe/skills/agent/skills/${skillName}/SKILL.md`,- { agentId },- )- ).content;- };-- /**- * @example- * Refine reads and writes the selected managed skill through the document-backed service.- */- it('refines a real managed skill through document-backed replacement', async () => {- const skill = await createManagedSkill('review-skill', '# Review Skill');-- const result = await runSkillManagementAction(- {- agentId,- message: 'Refine the review skill.',- },- {- db: serverDB,- selfIterationEnabled: true,- skillMaintainerRunner: async ({ targetSkills }) => {- expect(targetSkills).toEqual([- expect.objectContaining({- content:- '---\ndescription: review-skill description\nname: review-skill\n---\n# Review Skill',- id: skill.bundle.agentDocumentId,- name: 'review-skill',- }),- ]);-- return {- bodyMarkdown: '# Review Skill\n\n## Procedure\n- Check failed assertions first.',- reason: 'refined review skill',- };- },- userId,- },- {- action: 'refine',- reason: 'update existing review skill',- targetSkillRefs: [skill.bundle.agentDocumentId],- },- );-- expect(result).toMatchObject({- detail: 'refined review skill',- status: 'applied',- });- expect(await readSkillIndex('review-skill')).toBe(- '---\ndescription: review-skill description\nname: review-skill\n---\n# Review Skill\n\n## Procedure\n- Check failed assertions first.',- );- });-- /**- * @example- * Consolidate updates an allowed target skill and leaves other skills untouched.- */- it('consolidates real managed skills without deleting source skills automatically', async () => {- const reviewSkill = await createManagedSkill('review-skill', '# Review Skill');- const checklistSkill = await createManagedSkill('review-checklist', '# Review Checklist');-- const result = await runSkillManagementAction(- {- agentId,- message: 'Consolidate overlapping review skills.',- },- {- db: serverDB,- selfIterationEnabled: true,- skillMaintainerRunner: async ({ targetSkills }) => {- expect(targetSkills).toEqual([- expect.objectContaining({- content:- '---\ndescription: review-skill description\nname: review-skill\n---\n# Review Skill',- id: reviewSkill.bundle.agentDocumentId,- name: 'review-skill',- }),- expect.objectContaining({- content:- '---\ndescription: review-checklist description\nname: review-checklist\n---\n# Review Checklist',- id: checklistSkill.bundle.agentDocumentId,- name: 'review-checklist',- }),- ]);-- return {- bodyMarkdown: '# Review Skill\n\n## Procedure\n- Use one consolidated checklist.',- reason: 'consolidated review skills',- };- },- userId,- },- {- action: 'consolidate',- reason: 'overlapping review skills',- targetSkillRefs: [- reviewSkill.bundle.agentDocumentId,- checklistSkill.bundle.agentDocumentId,- ],- },- );-- expect(result).toMatchObject({- detail: 'consolidated review skills',- status: 'applied',- });- expect(await readSkillIndex('review-skill')).toBe(- '---\ndescription: review-skill description\nname: review-skill\n---\n# Review Skill\n\n## Procedure\n- Use one consolidated checklist.',- );- expect(await readSkillIndex('review-checklist')).toBe(- '---\ndescription: review-checklist description\nname: review-checklist\n---\n# Review Checklist',- );- });-});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 724d91f020c..26d571bec7a 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts@@ -1,1397 +1,135 @@// @vitest-environment node-import { RequestTrigger } from '@lobechat/types';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { z } from 'zod';--import type { SkillManagementDocumentService } from '@/server/services/skillManagement';import type { RuntimeProcessorContext } from '../../../../runtime/context';-import {- collectAgentSkillDecisionCandidates,- defineSkillManagementActionHandler,- executeSkillManagementDecision,- isAgentDocumentRelatedObject,- readAgentSignalHintIsSkill,- runSkillDecisionAgentRuntime,-} from '../skillManagement';--const skillDecisionRunner = vi.fn();-const skillCreateRunner = vi.fn();-const skillMaintainerRunner = vi.fn();-const skillMaintainerService = {- createSkill: vi.fn(),- getSkill: vi.fn(),- listSkills: vi.fn(),- renameSkill: vi.fn(),- replaceSkillIndex: vi.fn(),-};-const createSkill = vi.fn();--vi.mock('@/server/services/agentDocuments/headlessEditor', () => ({- createMarkdownEditorSnapshot: vi.fn(async (content: string) => ({- content,- editorData: { markdown: content },- })),-}));--vi.mock('@/server/services/skillManagement', async (importOriginal) => {- const actual = await importOriginal<SkillManagementDocumentService>();-- return {- ...actual,- SkillManagementDocumentService: vi.fn(() => ({- createSkill,- getSkill: skillMaintainerService.getSkill,- listSkills: skillMaintainerService.listSkills,- renameSkill: skillMaintainerService.renameSkill,- replaceSkillIndex: skillMaintainerService.replaceSkillIndex,- })),- };-});--const context = {- now: () => 1,- runtimeState: {- getGuardState: vi.fn().mockResolvedValue({}),- touchGuardState: vi.fn().mockResolvedValue({}),+import { defineSkillManagementActionHandler } from '../skillManagement';++const dispatch = vi.fn();++const createContext = (applied = false) =>+ ({+ now: () => 1,+ runtimeState: {+ getGuardState: vi.fn().mockResolvedValue(applied ? { lastEventAt: 1 } : {}),+ touchGuardState: vi.fn().mockResolvedValue({}),+ },+ scopeKey: 'topic:topic_1',+ }) as unknown as RuntimeProcessorContext;++const skillAction = {+ actionId: 'act_skill',+ actionType: 'action.skill-management.handle' as const,+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },+ payload: {+ agentId: 'agent_1',+ evidence: [{ cue: 'reusable procedure', excerpt: 'Always run the weekly report this way.' }],+ feedbackHint: 'not_satisfied' as const,+ idempotencyKey: 'source_1:skill:msg_1',+ message: 'From now on, run the weekly report with these fixed steps...',+ messageId: 'msg_1',+ reason: 'reusable procedure feedback',+ serializedContext: '{"surface":"chat"}',+ topicId: 'topic_1',},- scopeKey: 'topic:topic-1',-} as const satisfies RuntimeProcessorContext;+ signal: { signalId: 'sig_1', signalType: 'signal.feedback.domain.skill' as const },+ source: { sourceId: 'source_1', sourceType: 'agent.user.message' as const },+ timestamp: 1,+};describe('defineSkillManagementActionHandler', () => {beforeEach(() => {vi.clearAllMocks();- skillCreateRunner.mockReset();- skillDecisionRunner.mockReset();- skillMaintainerRunner.mockReset();- skillMaintainerService.createSkill.mockReset();- skillMaintainerService.getSkill.mockReset();- skillMaintainerService.listSkills.mockReset();- skillMaintainerService.renameSkill.mockReset();- skillMaintainerService.replaceSkillIndex.mockReset();- createSkill.mockReset();- skillCreateRunner.mockResolvedValue({- bodyMarkdown: '# PR Review Checklist',- confidence: 0.9,- description: 'Use when creating reusable PR review checklists.',- name: 'pr-review-checklist',- reason: 'authored reusable workflow',- title: 'PR Review Checklist',- });- createSkill.mockResolvedValue({- bundle: {- agentDocumentId: 'pr-review-checklist-bundle-id',- documentId: 'pr-review-checklist-bundle-doc',- filename: 'pr-review-checklist',- title: 'PR Review Checklist',- },- content: '# PR Review Checklist',- description: 'Use when creating reusable PR review checklists.',- frontmatter: {- description: 'Use when creating reusable PR review checklists.',- name: 'pr-review-checklist',- },- index: {- agentDocumentId: 'pr-review-checklist-index-id',- documentId: 'pr-review-checklist-index-doc',- filename: 'SKILL.md',- title: 'SKILL.md',- },- name: 'pr-review-checklist',- title: 'PR Review Checklist',- });- skillMaintainerService.getSkill.mockImplementation(async ({ agentDocumentId }) => ({- bundle: {- agentDocumentId,- documentId: `${agentDocumentId}-doc`,- filename: agentDocumentId,- title: agentDocumentId,- },- content: `# ${agentDocumentId}`,- description: `${agentDocumentId} description`,- frontmatter: { description: `${agentDocumentId} description`, name: agentDocumentId },- index: {- agentDocumentId: `${agentDocumentId}-index`,- documentId: `${agentDocumentId}-index-doc`,- filename: 'SKILL.md',- title: 'SKILL.md',- },- name: agentDocumentId,- title: agentDocumentId,- }));- skillMaintainerService.replaceSkillIndex.mockResolvedValue(undefined);- skillMaintainerService.renameSkill.mockResolvedValue(undefined);- });-- it('does not run when self iteration is disabled', async () => {- const result = await executeSkillManagementDecision({- decide: vi.fn(),- payload: { agentId: 'agent-1', feedbackMessage: 'Make this a reusable checklist.' },- selfIterationEnabled: false,- });-- expect(result.status).toBe('skipped');- });-- it('runs the decision step when self iteration is enabled', async () => {- const decide = vi.fn().mockResolvedValue({ action: 'create', confidence: 0.9 });- const result = await executeSkillManagementDecision({- decide,- payload: { agentId: 'agent-1', feedbackMessage: 'Make this a reusable checklist.' },- selfIterationEnabled: true,- });-- expect(decide).toHaveBeenCalled();- expect(result.status).toBe('decided');});- /**- * @example- * Skill decisions preserve the four v1.2 action values.- */- it('returns structured results for each v1.2 decision action', async () => {- for (const action of ['create', 'refine', 'consolidate', 'noop', 'reject'] as const) {- const result = await executeSkillManagementDecision({- decide: vi.fn().mockResolvedValue({ action, confidence: 0.9 }),- payload: { agentId: 'agent-1', feedbackMessage: 'Make this reusable.' },- selfIterationEnabled: true,- });-- expect(result).toMatchObject({ decision: { action }, status: 'decided' });- }- });-- /**- * @example- * The decision agent can inspect same-turn document outcomes before returning reject.- */- it('runs read-only decision tools through AgentRuntime before submitting a decision', async () => {- const response = () =>- new Response(- new ReadableStream({- start(controller) {- controller.close();- },- }),- );- const chat = vi- .fn()- .mockImplementationOnce(async (_payload, options) => {- await options.callback.onToolsCalling({- toolsCalling: [- {- function: {- arguments: '{"messageId":"msg_1","scopeKey":"topic:topic_1"}',- name: 'agent-signal-skill-decision____listSameTurnDocumentOutcomes',- },- id: 'call_list_outcomes',- type: 'function',- },- ],- });- return response();- })- .mockImplementationOnce(async (_payload, options) => {- await options.callback.onToolsCalling({- toolsCalling: [- {- function: {- arguments: '{"agentDocumentId":"agent_doc_1"}',- name: 'agent-signal-skill-decision____readDocument',- },- id: 'call_read_document',- type: 'function',- },- ],- });- return response();- })- .mockImplementationOnce(async (_payload, options) => {- await options.callback.onToolsCalling({- toolsCalling: [- {- function: {- arguments:- '{"action":"reject","confidence":0.9,"documentRefs":["doc_1"],"reason":"The same turn created a document and forbids skill conversion.","requiredReads":[],"targetSkillRefs":[]}',- name: 'agent-signal-skill-decision____submitDecision',- },- id: 'call_submit_decision',- type: 'function',- },- ],- });- return response();- });- const tools = {- listCandidateDocuments: vi.fn(),- listSameTurnDocumentOutcomes: vi.fn().mockResolvedValue([- {- agentDocumentId: 'agent_doc_1',- hintIsSkill: true,- relation: 'created',- summary: 'Agent documents created a document.',- },- ]),- readDocument: vi.fn().mockResolvedValue({- agentDocumentId: 'agent_doc_1',- content: '# Draft',- documentId: 'documents_row_1',- title: 'Draft',- }),- };-- const result = await runSkillDecisionAgentRuntime({- model: 'test-model',- modelRuntime: { chat },- payload: {- agentId: 'agent_1',- feedbackMessage: 'Create a document for this, do not make it a skill.',- messageId: 'msg_1',- topicId: 'topic_1',- },- tools,- });-- expect(chat).toHaveBeenCalledTimes(3);- expect(chat).toHaveBeenNthCalledWith(- 1,- expect.any(Object),- expect.objectContaining({ metadata: { trigger: RequestTrigger.AgentSignal } }),- );- expect(tools.listSameTurnDocumentOutcomes).toHaveBeenCalledWith({- agentId: 'agent_1',- messageId: 'msg_1',- scopeKey: 'topic:topic_1',- topicId: 'topic_1',- });- expect(tools.readDocument).toHaveBeenCalledWith({ agentDocumentId: 'agent_doc_1' });- expect(chat.mock.calls[1]?.[0].messages).toContainEqual(- expect.objectContaining({- content: expect.stringContaining('"hintIsSkill":true'),- role: 'tool',- }),- );- expect(result).toMatchObject({- action: 'reject',- documentRefs: ['doc_1'],- reason: 'The same turn created a document and forbids skill conversion.',- });- });-- /**- * @example- * Only explicit boolean metadata becomes same-turn hint evidence.- */- it('parses hintIsSkill only from explicit boolean agent-signal metadata', () => {- expect(readAgentSignalHintIsSkill({ agentSignal: { hintIsSkill: true } })).toBe(true);- expect(readAgentSignalHintIsSkill({ agentSignal: { hintIsSkill: false } })).toBe(false);- expect(readAgentSignalHintIsSkill({ agentSignal: { hintIsSkill: 'true' } })).toBeUndefined();- expect(readAgentSignalHintIsSkill({ agentSignal: null })).toBeUndefined();- expect(readAgentSignalHintIsSkill(undefined)).toBeUndefined();- });-- /**- * @example- * Negative or missing same-turn hints remain evidence only; they do not force mutation actions.- */- it('does not force refine or consolidate from hintIsSkill false or missing document snapshots', async () => {- const response = () =>- new Response(- new ReadableStream({- start(controller) {- controller.close();- },- }),- );- const chat = vi- .fn()- .mockImplementationOnce(async (_payload, options) => {- await options.callback.onToolsCalling({- toolsCalling: [- {- function: {- arguments: '{"messageId":"msg_1","scopeKey":"topic:topic_1"}',- name: 'agent-signal-skill-decision____listSameTurnDocumentOutcomes',- },- id: 'call_list_outcomes',- type: 'function',- },- ],- });- return response();- })- .mockImplementationOnce(async (_payload, options) => {- await options.callback.onToolsCalling({- toolsCalling: [- {- function: {- arguments:- '{"action":"noop","confidence":0.7,"documentRefs":[],"reason":"Negative or missing hints are not enough to mutate a skill.","requiredReads":[],"targetSkillRefs":[]}',- name: 'agent-signal-skill-decision____submitDecision',- },- id: 'call_submit_decision',- type: 'function',- },- ],- });- return response();- });- const tools = {- listCandidateDocuments: vi.fn(),- listSameTurnDocumentOutcomes: vi.fn().mockResolvedValue([- {- agentDocumentId: 'agent_doc_false',- hintIsSkill: false,- relation: 'created',- summary: 'Document outcome explicitly says this is not a skill.',- },- {- agentDocumentId: 'agent_doc_missing_snapshot',- relation: 'created',- summary: 'Document snapshot is missing metadata.',- },- ]),- readDocument: vi.fn(),- };-- const result = await runSkillDecisionAgentRuntime({- model: 'test-model',- modelRuntime: { chat },- payload: {- agentId: 'agent_1',- feedbackMessage: 'Keep the result around if useful.',- messageId: 'msg_1',- topicId: 'topic_1',- },- tools,- });-- expect(chat.mock.calls[1]?.[0].messages).toContainEqual(- expect.objectContaining({- content: expect.stringContaining('"hintIsSkill":false'),- role: 'tool',- }),- );- expect(tools.readDocument).not.toHaveBeenCalled();- expect(result).toMatchObject({- action: 'noop',- reason: 'Negative or missing hints are not enough to mutate a skill.',- });- expect(result.action).not.toBe('refine');- expect(result.action).not.toBe('consolidate');- });-- /**- * @example- * Same-turn document receipts emitted by lobe-agent-documents use the agent document binding id.- */- it('accepts agent-document related objects for same-turn document evidence', () => {- expect(isAgentDocumentRelatedObject({ objectType: 'agent-document' })).toBe(true);- expect(isAgentDocumentRelatedObject({ objectType: 'document' })).toBe(false);- expect(isAgentDocumentRelatedObject({ objectType: 'file' })).toBe(false);- });-- /**- * @example- * 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 executeSkillManagementDecision({- decide: vi.fn().mockResolvedValue({- action: 'consolidate',- archiveSkill: { skillRef: 'skill-1' },- deleteSkill: { skillRef: 'skill-1' },- proposedLifecycleActions: [- { action: 'archive', reason: 'superseded', skillRef: 'skill-1' },- ],- }),- payload: { agentId: 'agent-1', feedbackMessage: 'These two skills overlap.' },- selfIterationEnabled: true,- });-- expect(JSON.stringify(result)).not.toContain('deleteSkill');- expect(JSON.stringify(result)).not.toContain('archiveSkill');- });-- /**- * @example- * Candidate ids are managed bundle agent document ids, while names remain display labels.- */- it('collects managed skill bundles as agent-document decision candidates', () => {- expect(- collectAgentSkillDecisionCandidates([- {- documentId: 'bundle-doc',- fileType: 'skills/bundle',- filename: 'review-skill',- id: 'bundle-binding',- parentId: null,- templateId: 'agent-skill',- title: 'Review Skill',- },- {- documentId: 'file-doc',- fileType: 'skills/index',- filename: 'SKILL.md',- id: 'file-binding',- parentId: 'bundle-doc',- templateId: 'agent-skill',- title: 'SKILL.md',- },- ] as never),- ).toEqual([{ id: 'bundle-binding', name: 'Review Skill', scope: 'agent' }]);- });-- /**- * @example- * Skill-domain feedback records a structured create decision and creates a document-backed agent skill.- */- it('runs the skill action after the injected decision step', async () => {- skillDecisionRunner.mockResolvedValue({- action: 'create',- confidence: 0.9,- reason: 'reusable workflow feedback',- });+ it('enqueues an async skill run under the skill-management slug', async () => {+ dispatch.mockResolvedValue({ operationId: 'op_1', topicId: 'topic_1' });+ const context = createContext();const handler = defineSkillManagementActionHandler({db: {} as never,- responseLanguage: 'zh-CN',+ dispatch,selfIterationEnabled: true,- skillCreateRunner,- skillDecisionRunner,userId: 'user_1',});- const result = await handler.handle(- {- actionId: 'act_skill_agent',- actionType: 'action.skill-management.handle',- chain: { chainId: 'chain_1', rootSourceId: 'source_1' },- payload: {- agentId: 'agent_1',- evidence: [{ cue: 'reusable', excerpt: 'Make this a reusable checklist.' }],- feedbackHint: 'not_satisfied',- idempotencyKey: 'source_1:skill:msg_1',- message: 'Make this a reusable checklist for PR reviews.',- reason: 'reusable workflow feedback',- 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,- );+ const result = await handler.handle(skillAction, context);- expect(skillDecisionRunner).toHaveBeenCalledWith(- expect.objectContaining({- agentId: 'agent_1',- evidence: [{ cue: 'reusable', excerpt: 'Make this a reusable checklist.' }],- feedbackMessage: 'Make this a reusable checklist for PR reviews.',- topicId: 'topic_1',- turnContext: '{"surface":"chat"}',- }),- );- expect(skillCreateRunner).toHaveBeenCalledWith(- expect.objectContaining({- languageInstruction: expect.stringContaining('Skill artifact language rules:'),- }),- );- expect(skillCreateRunner).toHaveBeenCalledWith(- expect.objectContaining({- languageInstruction: expect.stringContaining(- 'Default to zh-CN when the source evidence does not imply a better artifact language.',- ),- }),- );- expect(result).toMatchObject({- output: {- decision: { action: 'create', confidence: 0.9, reason: 'reusable workflow feedback' },- target: {- id: 'pr-review-checklist-bundle-doc',- summary: 'Use when creating reusable PR review checklists.',- title: 'PR Review Checklist',- type: 'skill',- },- },- status: 'applied',- });- expect(context.runtimeState.touchGuardState).toHaveBeenCalledTimes(1);- });-- /**- * @example- * 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({- action: 'refine',- confidence: 0.8,- reason: 'update existing skill',- targetSkillRefs: ['review-skill-bundle-id'],- });- skillMaintainerRunner.mockResolvedValue({- bodyMarkdown: '# Review Skill',- reason: 'no file changes',- });-- const handler = defineSkillManagementActionHandler({- db: {} as never,- responseLanguage: 'zh-CN',- selfIterationEnabled: true,- skillCandidateSkillsFactory: async () => [- { id: 'review-skill-bundle-id', name: 'Review Skill', scope: 'agent' },- ],- skillDecisionRunner,- skillMaintainerRunner,- skillManagementServiceFactory: () => skillMaintainerService,- userId: 'user_1',- });-- await handler.handle(- {- actionId: 'act_skill_candidate',- actionType: 'action.skill-management.handle',- chain: { chainId: 'chain_1', rootSourceId: 'source_1' },- payload: {- agentId: 'agent_1',- idempotencyKey: 'source_1:skill:candidate',- message: 'Refine the review skill.',- },- signal: {- signalId: 'sig_1',- signalType: 'signal.feedback.domain.skill',- },- source: { sourceId: 'source_1', sourceType: 'agent.user.message' },- timestamp: 1,- },- context,- );-- expect(skillDecisionRunner).toHaveBeenCalledWith(- expect.objectContaining({- candidateSkills: [{ id: 'review-skill-bundle-id', name: 'Review Skill', scope: 'agent' }],- }),- );- });-- /**- * @example- * Completion-stage skill decisions receive user-stage recorded skill-intent evidence.- */- it('passes recorded skill intent evidence to the decision runtime on completion-triggered feedback', async () => {- skillDecisionRunner.mockResolvedValue({- action: 'create',- confidence: 0.88,- documentRefs: [],- reason: 'Completion confirmed hinted workflow document.',- requiredReads: [],- targetSkillRefs: [],- });- skillCreateRunner.mockResolvedValue({- bodyMarkdown: '# YouTube Comment Fetch Workflow',- name: 'youtube-comment-fetch-workflow',- reason: 'created reusable workflow',- title: 'YouTube Comment Fetch Workflow',- });- const readCandidate = vi.fn(async (input: { scopeKey: string; sourceId: string }) => {- if (input.sourceId !== 'msg_1') return undefined;-- return {- actionIntent: 'create' as const,- confidence: 0.86,- createdAt: 1000,- explicitness: 'implicit_strong_learning' as const,- feedbackMessageId: 'msg_1',- reason: 'User asked to preserve this workflow.',- route: 'direct_decision' as const,- scopeKey: 'topic:topic-1',- sourceId: 'msg_1',- };- });- const handler = defineSkillManagementActionHandler({- db: {} as never,- procedureState: {- skillIntentRecords: { read: readCandidate, write: vi.fn() },- },- selfIterationEnabled: true,- skillCreateRunner,- skillDecisionRunner,- userId: 'user_1',- });-- await handler.handle(- {- actionId: 'act_skill_candidate',- actionType: 'action.skill-management.handle',- chain: { chainId: 'chain_1', rootSourceId: 'source_1' },- payload: {- agentId: 'agent_1',- evidence: [{ cue: 'completion', excerpt: 'assistant completed' }],- feedbackHint: 'satisfied',- idempotencyKey: 'source_1:skill:msg_1',- message: 'Nice work. Can we keep this workflow?',- messageId: 'msg_1',- reason: 'completion-triggered skill feedback',- serializedContext: '{"surface":"chat"}',- topicId: 'topic_1',- },- signal: {- signalId: 'sig_1',- signalType: 'signal.feedback.domain.skill',- },- source: {- payload: {- message: 'Nice work. Can we keep this workflow?',- messageId: 'msg_1',- trigger: 'client.runtime.complete',- },- sourceId: 'assistant_1:completion:msg_1',- sourceType: 'agent.user.message',- } as never,- timestamp: 1,- },- context,- );-- expect(readCandidate).toHaveBeenCalledWith({- scopeKey: 'topic:topic-1',- sourceId: 'msg_1',- });- expect(skillDecisionRunner).toHaveBeenCalledWith(- expect.objectContaining({- evidence: expect.arrayContaining([- expect.objectContaining({- cue: 'completion',- }),- expect.objectContaining({- cue: 'recorded_skill_intent',- excerpt: expect.stringContaining('User asked to preserve this workflow.'),- }),- ]),- }),- );- });-- /**- * @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({+ expect(dispatch).toHaveBeenCalledTimes(1);+ const dispatched = dispatch.mock.calls[0][0];+ expect(dispatched.slug).toBe('skill-management');+ expect(dispatched.agentId).toBe('agent_1');+ expect(dispatched.topicId).toBe('topic_1');+ expect(dispatched.marker).toMatchObject({agentId: 'agent_1',- messageId: 'msg_1',- scopeKey: 'topic:topic-1',+ kind: 'skill',+ sourceId: 'source_1:skill:msg_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.- */- it('skips repeated actions after the same idempotency key was already applied', async () => {- const getGuardState = vi.fn().mockResolvedValue({ lastEventAt: 1 });- const touchGuardState = vi.fn().mockResolvedValue({});- const idempotentContext = {- ...context,- runtimeState: {- getGuardState,- touchGuardState,- },- } as const satisfies RuntimeProcessorContext;-- const handler = defineSkillManagementActionHandler({- db: {} as never,- selfIterationEnabled: true,- skillDecisionRunner,- userId: 'user_1',- });-- const result = await handler.handle(- {- actionId: 'act_skill_duplicate',- actionType: 'action.skill-management.handle',- chain: { chainId: 'chain_1', rootSourceId: 'source_1' },- payload: {- agentId: 'agent_1',- idempotencyKey: 'source_1:skill:msg_1',- message: 'Make this a reusable checklist.',- },- signal: {- signalId: 'sig_1',- signalType: 'signal.feedback.domain.skill',- },- source: { sourceId: 'source_1', sourceType: 'agent.user.message' },- timestamp: 1,- },- idempotentContext,- );-- expect(skillDecisionRunner).not.toHaveBeenCalled();- expect(touchGuardState).not.toHaveBeenCalled();- expect(result).toMatchObject({- detail: 'Skill-management action already applied.',- output: { decision: { action: 'noop' } },- status: 'skipped',- });- });-- /**- * @example- * Generic praise is normalized to noop and does not create a skill document.- */- it('skips generic praise through a noop decision', async () => {- skillDecisionRunner.mockResolvedValue({ action: 'noop', reason: 'generic praise' });-- const handler = defineSkillManagementActionHandler({- db: {} as never,- selfIterationEnabled: true,- skillDecisionRunner,- userId: 'user_1',- });-- const result = await handler.handle(- {- actionId: 'act_skill_noop',- actionType: 'action.skill-management.handle',- chain: { chainId: 'chain_1', rootSourceId: 'source_1' },- payload: {- agentId: 'agent_1',- idempotencyKey: 'source_1:skill:msg_noop',- message: 'Looks good, thanks.',- },- signal: {- signalId: 'sig_1',- signalType: 'signal.feedback.domain.skill',- },- source: { sourceId: 'source_1', sourceType: 'agent.user.message' },- timestamp: 1,- },- context,- );-- expect(result).toMatchObject({- output: { decision: { action: 'noop' } },- status: 'skipped',- });- expect(context.runtimeState.touchGuardState).not.toHaveBeenCalled();- });-- /**- * @example- * Malformed structured decision output is skipped instead of failing the whole action.- */- it('skips skill-management when the decision runner returns undefined output', async () => {- // ROOT CAUSE:- //- // If modelRuntime.generateObject cannot parse provider text as JSON, it returns undefined.- // The skill-management handler parsed that undefined value as the final decision object,- // which turned a recoverable decision-output problem into signal.action.failed.- //- // We fixed this by treating non-object decision output as a noop decision.- skillDecisionRunner.mockResolvedValue(undefined);-- const handler = defineSkillManagementActionHandler({- db: {} as never,- selfIterationEnabled: true,- skillDecisionRunner,- userId: 'user_1',- });-- const result = await handler.handle(- {- actionId: 'act_skill_undefined_decision',- actionType: 'action.skill-management.handle',- chain: { chainId: 'chain_1', rootSourceId: 'source_1' },- payload: {- agentId: 'agent_1',- idempotencyKey: 'source_1:skill:undefined_decision',- message: 'Create a reusable checklist for review failures.',- },- signal: {- signalId: 'sig_1',- signalType: 'signal.feedback.domain.skill',- },- source: { sourceId: 'source_1', sourceType: 'agent.user.message' },- timestamp: 1,- },- context,- );-- expect(createSkill).not.toHaveBeenCalled();- expect(context.runtimeState.touchGuardState).not.toHaveBeenCalled();- expect(result).toMatchObject({- detail: 'decision output was not an object',- output: { decision: { action: 'noop', reason: 'decision output was not an object' } },- status: 'skipped',- });- });-- /**- * @example- * Provider parse failures surface as skipped decisions instead of failed signal actions.- */- it('skips skill-management when the decision runner rejects malformed structured output', async () => {- // ROOT CAUSE:- //- // The default skill decision runner parses generateObject output before returning it to the- // action handler. When generateObject returned undefined after a provider JSON parse failure,- // that internal parse threw a ZodError and the outer handler emitted signal.action.failed.- //- // We fixed this by downgrading malformed decision-output ZodError values to a noop decision.- const malformedStructuredOutputError = (() => {- try {- z.object({}).parse(undefined);- } catch (error) {- return error;- }- })();- skillDecisionRunner.mockRejectedValue(malformedStructuredOutputError);-- const handler = defineSkillManagementActionHandler({- db: {} as never,- selfIterationEnabled: true,- skillDecisionRunner,- userId: 'user_1',- });-- const result = await handler.handle(- {- actionId: 'act_skill_malformed_decision',- actionType: 'action.skill-management.handle',- chain: { chainId: 'chain_1', rootSourceId: 'source_1' },- payload: {- agentId: 'agent_1',- idempotencyKey: 'source_1:skill:malformed_decision',- message: 'Create a reusable checklist for review failures.',- },- signal: {- signalId: 'sig_1',- signalType: 'signal.feedback.domain.skill',- },- source: { sourceId: 'source_1', sourceType: 'agent.user.message' },- timestamp: 1,- },- context,- );-- expect(createSkill).not.toHaveBeenCalled();- expect(context.runtimeState.touchGuardState).not.toHaveBeenCalled();- expect(result).toMatchObject({- detail: 'decision structured output was malformed',- output: {- decision: { action: 'noop', reason: 'decision structured output was malformed' },- },- status: 'skipped',- });+ expect(typeof dispatched.prompt).toBe('string');+ expect(dispatched.prompt).toContain(skillAction.payload.message);+ expect(result?.status).toBe('applied');+ expect(context.runtimeState.touchGuardState).toHaveBeenCalledTimes(1);});- /**- * @example- * Disabled self-iteration stops before the decision agent and document writer.- */- it('skips skill-management before decision when self-iteration is disabled', async () => {+ it('skips when self-iteration is disabled (no dispatch)', async () => {const handler = defineSkillManagementActionHandler({db: {} as never,+ dispatch,selfIterationEnabled: false,- skillDecisionRunner,- userId: 'user_1',- });-- const result = await handler.handle(- {- actionId: 'act_skill_gate_disabled',- actionType: 'action.skill-management.handle',- chain: { chainId: 'chain_1', rootSourceId: 'source_1' },- payload: {- agentId: 'agent_1',- idempotencyKey: 'source_1:skill:gate_disabled',- message: 'Create a reusable checklist for review failures.',- },- signal: {- signalId: 'sig_1',- signalType: 'signal.feedback.domain.skill',- },- source: { sourceId: 'source_1', sourceType: 'agent.user.message' },- timestamp: 1,- },- context,- );-- expect(skillDecisionRunner).not.toHaveBeenCalled();- expect(createSkill).not.toHaveBeenCalled();- expect(result).toMatchObject({- detail: 'self iteration is disabled',- output: { decision: { action: 'noop' } },- status: 'skipped',- });- });-- /**- * @example- * Missing action context is reported as skipped with a noop decision.- */- it('skips missing agentId or message before document creation', async () => {- skillDecisionRunner.mockResolvedValue({ action: 'create', reason: 'create missing context' });-- const handler = defineSkillManagementActionHandler({- db: {} as never,- selfIterationEnabled: true,- skillDecisionRunner,- userId: 'user_1',- });-- const missingAgent = await handler.handle(- {- actionId: 'act_skill_missing_agent',- actionType: 'action.skill-management.handle',- chain: { chainId: 'chain_1', rootSourceId: 'source_1' },- payload: {- idempotencyKey: 'source_1:skill:missing_agent',- message: 'Create a reusable checklist.',- },- signal: {- signalId: 'sig_1',- signalType: 'signal.feedback.domain.skill',- },- source: { sourceId: 'source_1', sourceType: 'agent.user.message' },- timestamp: 1,- },- context,- );-- expect(missingAgent).toMatchObject({- detail: 'Missing agentId for skill-management action.',- output: { decision: { action: 'noop' } },- status: 'skipped',- });- expect(skillDecisionRunner).not.toHaveBeenCalled();- expect(createSkill).not.toHaveBeenCalled();- expect(skillMaintainerRunner).not.toHaveBeenCalled();-- vi.clearAllMocks();- skillDecisionRunner.mockResolvedValue({ action: 'create', reason: 'create missing context' });-- const missingMessage = await handler.handle(- {- actionId: 'act_skill_missing_message',- actionType: 'action.skill-management.handle',- chain: { chainId: 'chain_1', rootSourceId: 'source_1' },- payload: {- agentId: 'agent_1',- idempotencyKey: 'source_1:skill:missing_message',- message: '',- },- signal: {- signalId: 'sig_1',- signalType: 'signal.feedback.domain.skill',- },- source: { sourceId: 'source_1', sourceType: 'agent.user.message' },- timestamp: 1,- },- context,- );-- expect(missingMessage).toMatchObject({- detail: 'Missing skill-management action message.',- output: { decision: { action: 'noop' } },- status: 'skipped',- });- });-- /**- * @example- * A refine decision invokes the maintainer agent and applies returned body content.- */- it('runs the maintainer workflow for refine decisions', async () => {- skillDecisionRunner.mockResolvedValue({- action: 'refine',- reason: 'update existing review skill',- targetSkillRefs: ['review-skill-bundle-id'],- });- skillMaintainerRunner.mockResolvedValue({- bodyMarkdown: '# Review Skill\n\n## Procedure\n- Check failed assertions first.',- reason: 'refined review skill',- });-- const handler = defineSkillManagementActionHandler({- db: {} as never,- selfIterationEnabled: true,- skillDecisionRunner,- skillMaintainerRunner,- skillManagementServiceFactory: () => skillMaintainerService,- userId: 'user_1',- });-- const result = await handler.handle(- {- actionId: 'act_skill_refine',- actionType: 'action.skill-management.handle',- chain: { chainId: 'chain_1', rootSourceId: 'source_1' },- payload: {- agentId: 'agent_1',- idempotencyKey: 'source_1:skill:refine',- message: 'Refine the review skill with the failed assertion workflow.',- },- signal: {- signalId: 'sig_1',- signalType: 'signal.feedback.domain.skill',- },- source: { sourceId: 'source_1', sourceType: 'agent.user.message' },- timestamp: 1,- },- context,- );-- expect(skillMaintainerRunner).toHaveBeenCalledWith(- expect.objectContaining({- languageInstruction: expect.stringContaining('Skill artifact language rules:'),- targetSkills: [- expect.objectContaining({- content: '# review-skill-bundle-id',- id: 'review-skill-bundle-id',- name: 'review-skill-bundle-id',- }),- ],- type: 'refine',- }),- );- expect(skillMaintainerService.replaceSkillIndex).toHaveBeenCalledWith({- agentDocumentId: 'review-skill-bundle-id',- agentId: 'agent_1',- bodyMarkdown: '# Review Skill\n\n## Procedure\n- Check failed assertions first.',- description: undefined,- updateReason: 'refined review skill',- });- expect(result).toMatchObject({- detail: 'refined review skill',- output: { decision: { action: 'refine' } },- status: 'applied',- });- });-- /**- * @example- * A refine decision is skipped when the target skill cannot be resolved.- */- it('skips maintainer workflow when target refs cannot be resolved', async () => {- skillDecisionRunner.mockResolvedValue({- action: 'refine',- reason: 'update existing review skill',- targetSkillRefs: ['missing-bundle-id'],- });- skillMaintainerService.getSkill.mockResolvedValueOnce(undefined);-- const handler = defineSkillManagementActionHandler({- db: {} as never,- selfIterationEnabled: true,- skillDecisionRunner,- skillMaintainerRunner,- skillManagementServiceFactory: () => skillMaintainerService,userId: 'user_1',});- const result = await handler.handle(- {- actionId: 'act_skill_refine_invalid_target',- actionType: 'action.skill-management.handle',- chain: { chainId: 'chain_1', rootSourceId: 'source_1' },- payload: {- agentId: 'agent_1',- idempotencyKey: 'source_1:skill:refine-invalid-target',- message: 'Refine the review skill.',- },- signal: {- signalId: 'sig_1',- signalType: 'signal.feedback.domain.skill',- },- source: { sourceId: 'source_1', sourceType: 'agent.user.message' },- timestamp: 1,- },- context,- );+ const result = await handler.handle(skillAction, createContext());- expect(skillMaintainerRunner).not.toHaveBeenCalled();- expect(skillMaintainerService.replaceSkillIndex).not.toHaveBeenCalled();- expect(result).toMatchObject({- detail: expect.stringContaining('could not resolve targetSkillRefs'),- output: { decision: { action: 'refine' } },- status: 'skipped',- });+ expect(result?.status).toBe('skipped');+ expect(dispatch).not.toHaveBeenCalled();});- /**- * @example- * A consolidate decision invokes the maintainer agent with multiple target skills.- */- it('runs the maintainer workflow for consolidate decisions', async () => {- skillDecisionRunner.mockResolvedValue({- action: 'consolidate',- reason: 'overlapping review skills',- targetSkillRefs: ['review-skill-bundle-id', 'review-checklist-bundle-id'],- });- skillMaintainerRunner.mockResolvedValue({- bodyMarkdown: '# Review Skill\n\n## Procedure\n- Use one consolidated checklist.',- reason: 'consolidated review skills',- });-+ it('skips when the feedback message is missing', async () => {const handler = defineSkillManagementActionHandler({db: {} as never,+ dispatch,selfIterationEnabled: true,- skillDecisionRunner,- skillMaintainerRunner,- skillManagementServiceFactory: () => skillMaintainerService,userId: 'user_1',});const result = await handler.handle(- {- actionId: 'act_skill_consolidate',- actionType: 'action.skill-management.handle',- chain: { chainId: 'chain_1', rootSourceId: 'source_1' },- payload: {- agentId: 'agent_1',- idempotencyKey: 'source_1:skill:consolidate',- message: 'Consolidate the overlapping review skills.',- },- signal: {- signalId: 'sig_1',- signalType: 'signal.feedback.domain.skill',- },- source: { sourceId: 'source_1', sourceType: 'agent.user.message' },- timestamp: 1,- },- context,+ { ...skillAction, payload: { ...skillAction.payload, message: ' ' } },+ createContext(),);- expect(skillMaintainerRunner).toHaveBeenCalledWith(- expect.objectContaining({- targetSkills: [- expect.objectContaining({ id: 'review-skill-bundle-id' }),- expect.objectContaining({ id: 'review-checklist-bundle-id' }),- ],- type: 'consolidate',- }),- );- expect(skillMaintainerService.replaceSkillIndex).toHaveBeenCalledWith({- agentDocumentId: 'review-skill-bundle-id',- agentId: 'agent_1',- bodyMarkdown: '# Review Skill\n\n## Procedure\n- Use one consolidated checklist.',- description: undefined,- updateReason: 'consolidated review skills',- });- expect(result).toMatchObject({- detail: 'consolidated review skills',- output: { decision: { action: 'consolidate' } },- status: 'applied',- });+ expect(result?.status).toBe('skipped');+ expect(dispatch).not.toHaveBeenCalled();});- /**- * @example- * A create decision ignores message ids accidentally returned in documentRefs.- */- it('ignores non-agent-document ids in create decision documentRefs', async () => {- // ROOT CAUSE:- //- // The skill decision model may confuse the eval/client messageId with source document ids- // because both are present in the decision prompt. Querying agent_documents.id with that- // messageId fails at Postgres UUID coercion before skill creation can run.- //- // We fixed this by only reading create source documents when documentRefs contains a real- // agent_documents.id UUID. Create can still proceed from the feedback and turn context.- skillDecisionRunner.mockResolvedValue({- action: 'create',- documentRefs: ['eval-agent-signal-message-feedback-should-create-skill-1'],- reason: 'reusable workflow',- });-+ it('skips repeated actions after the same idempotency key was already applied', async () => {const handler = defineSkillManagementActionHandler({db: {} as never,+ dispatch,selfIterationEnabled: true,- skillCreateRunner,- skillDecisionRunner,userId: 'user_1',});- const result = await handler.handle(- {- actionId: 'act_skill_create_with_message_ref',- actionType: 'action.skill-management.handle',- chain: { chainId: 'chain_1', rootSourceId: 'source_1' },- payload: {- agentId: 'agent_1',- idempotencyKey: 'source_1:skill:create_with_message_ref',- message: 'Create a reusable PR review checklist.',- },- signal: {- signalId: 'sig_1',- signalType: 'signal.feedback.domain.skill',- },- source: { sourceId: 'source_1', sourceType: 'agent.user.message' },- timestamp: 1,- },- context,- );+ const result = await handler.handle(skillAction, createContext(true));- expect(skillCreateRunner).toHaveBeenCalledWith(- expect.not.objectContaining({- sourceAgentDocumentId: 'eval-agent-signal-message-feedback-should-create-skill-1',- }),- );- expect(createSkill).toHaveBeenCalledWith(- expect.objectContaining({- agentId: 'agent_1',- sourceAgentDocumentId: undefined,- }),- );- expect(result).toMatchObject({- output: { decision: { action: 'create' } },- status: 'applied',- });+ expect(result?.status).toBe('skipped');+ expect(dispatch).not.toHaveBeenCalled();});- /**- * @example- * Duplicate skill creation is reported as skipped while preserving the create decision.- */- it('skips duplicate skill creation with a structured create decision', async () => {- createSkill.mockRejectedValueOnce(new Error('Skill already exists'));- skillDecisionRunner.mockResolvedValue({ action: 'create', reason: 'reusable workflow' });+ it('surfaces dispatch failures without marking idempotency', async () => {+ dispatch.mockRejectedValue(new Error('enqueue failed'));+ const context = createContext();const handler = defineSkillManagementActionHandler({db: {} as never,+ dispatch,selfIterationEnabled: true,- skillCreateRunner,- skillDecisionRunner,userId: 'user_1',});- const result = await handler.handle(- {- actionId: 'act_skill_duplicate_create',- actionType: 'action.skill-management.handle',- chain: { chainId: 'chain_1', rootSourceId: 'source_1' },- payload: {- agentId: 'agent_1',- idempotencyKey: 'source_1:skill:duplicate_create',- message: 'Create a reusable checklist.',- },- signal: {- signalId: 'sig_1',- signalType: 'signal.feedback.domain.skill',- },- source: { sourceId: 'source_1', sourceType: 'agent.user.message' },- timestamp: 1,- },- context,- );+ const result = await handler.handle(skillAction, context);- expect(result).toMatchObject({- detail: 'Skill already exists',- output: { decision: { action: 'create' } },- status: 'skipped',- });+ expect(result?.status).toBe('failed');+ expect(context.runtimeState.touchGuardState).not.toHaveBeenCalled();});});diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.tsindex 27d76da50b6..862d8c57463 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts@@ -1,1330 +1,37 @@-import {- AgentRuntime,- type AgentRuntimeContext,- type AgentState,- GeneralChatAgent,-} from '@lobechat/agent-runtime';import type {AgenticAttempt,BaseAction,ExecutorResult,SignalAttempt,} from '@lobechat/agent-signal';-import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';-import {- generateToolsFromManifest,- type LobeToolManifest,- ToolNameResolver,-} from '@lobechat/context-engine';-import type {- ChatStreamPayload,- GenerateObjectSchema,- ModelRuntime,-} from '@lobechat/model-runtime';-import { consumeStreamUntilDone } from '@lobechat/model-runtime';-import {- AGENT_SKILL_CONSOLIDATE_SYSTEM_ROLE,- AGENT_SKILL_CREATE_SYSTEM_ROLE,- AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE,- AGENT_SKILL_REFINE_SYSTEM_ROLE,- createAgentSignalSkillLanguageInstruction,- createAgentSkillConsolidatePrompt,- createAgentSkillCreatePrompt,- createAgentSkillManagerDecisionPrompt,- createAgentSkillRefinePrompt,-} from '@lobechat/prompts';-import type { ChatToolPayload, MessageToolCall, ModelUsage } from '@lobechat/types';-import { RequestTrigger } from '@lobechat/types';-import { z } from 'zod';+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';-import type { AgentDocument } from '@/database/models/agentDocuments';-import { AgentDocumentModel } from '@/database/models/agentDocuments';import type { LobeChatDatabase } from '@/database/type';-import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';-import { AgentDocumentsService } from '@/server/services/agentDocuments';-import { getSkillBundle } from '@/server/services/agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils';-import { AgentSignalProcedureInspector } from '@/server/services/agentSignal/procedure';-import { redisPolicyStateStore } from '@/server/services/agentSignal/store/adapters/redis/policyStateStore';-import { SkillManagementDocumentService } from '@/server/services/skillManagement';-import type {- CreateSkillInput,- RenameSkillInput,- ReplaceSkillIndexInput,- SkillDetail,- SkillSummary,-} from '@/server/services/skillManagement/types';+import type { AgentSignalOperationMarker } from '@/server/services/agentSignal/operationMarker';import type { RuntimeProcessorContext } from '../../../runtime/context';import { defineActionHandler } from '../../../runtime/middleware';-import { createSkillManagementService } from '../../../services/selfIteration/tools/shared';+import { enqueueSelfIterationRun } from '../../../services/selfIteration/dispatch/enqueueSelfIterationRun';import type { ProcedureStateService } from '../../../services/types';import { hasAppliedActionIdempotency, markAppliedActionIdempotency } from '../../actionIdempotency';-import type { ActionSkillManagementHandle, AgentSignalFeedbackEvidence } from '../../types';+import type { ActionSkillManagementHandle } from '../../types';import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../../types';-import { createFeedbackActionPlannerSignalHandler } from '../feedbackAction';-import type { RecordedSkillIntent } from '../skillIntentRecord';--export interface SkillManagementCandidateSkill {- id: string;- name: string;- scope: 'agent' | 'builtin' | 'installed';-}--/**- * Payload passed from skill-domain feedback routing into skill management.- */-export interface SkillManagementSignalPayload {- /** Agent that received the feedback. */- agentId: string;- /** Optional candidate skills already identified by routing. */- candidateSkillRefs?: string[];- /** Existing skills the decision agent may target by agent document id. */- candidateSkills?: SkillManagementCandidateSkill[];- /** Evidence extracted from the feedback message. */- evidence?: Array<{ cue: string; excerpt: string }>;- /** Original feedback message that motivated the signal. */- feedbackMessage: string;- /** Message that originated this same-turn feedback action. */- messageId?: string;- /** Runtime scope used to inspect same-turn procedure state. */- scopeKey?: string;- /** Optional topic where the feedback happened. */- topicId?: string;- /** Optional relevant turn summary. */- turnContext?: string;-}--export type SkillManagementDecisionAction = 'consolidate' | 'create' | 'noop' | 'refine' | 'reject';--/**- * Normalized result returned by the skill-management decision step.- */-export interface SkillManagementDecision {- /** The v1.2 skill-management action selected for this feedback. */- action: SkillManagementDecisionAction;- /** Optional confidence score from the decision model. */- confidence?: number;- /** Optional document ids inspected while deciding. */- documentRefs?: string[];- /** Optional short explanation for observability. */- reason?: string;- /** Optional read hints that should be inspected before refinement or consolidation. */- requiredReads?: string[];- /** Optional target managed skill bundle agent document ids selected by the decision model. */- targetSkillRefs?: string[];-}--export interface SkillManagementActionResult {- decision: SkillManagementDecision;- detail?: string;- status: 'applied' | 'failed' | 'skipped';- target?: SkillManagementActionTarget;-}--export interface SkillManagementActionTarget {- agentDocumentId?: string;- documentId?: string;- id: string;- summary?: string;- title: string;- type: 'skill';-}--export interface SkillManagementActionInput {- agentId?: string;- candidateSkills?: SkillManagementCandidateSkill[];- evidence?: AgentSignalFeedbackEvidence[];- feedbackHint?: 'not_satisfied' | 'satisfied';- message: string;- messageId?: string;- reason?: string;- serializedContext?: string;- topicId?: string;-}export interface SkillManagementActionHandlerOptions {db: LobeChatDatabase;- /** Optional procedure state used to read user-stage skill intent records. */+ /**+ * Test seam: dispatch the async skill-management run. Defaults to the shared+ * `enqueueSelfIterationRun` (execAgent queue under the skill-management slug).+ */+ dispatch?: typeof enqueueSelfIterationRun;+ /** Optional procedure state (unused by the async path; kept for wiring parity). */procedureState?: Pick<ProcedureStateService, 'skillIntentRecords'>;- /** User-visible response language used as the default for newly-authored skill artifacts. */+ /** User-visible response language; reserved for prompt localisation. */responseLanguage?: string;selfIterationEnabled: boolean;- skillCandidateSkillsFactory?: (input: {- agentId: string;- }) => Promise<SkillManagementCandidateSkill[]>;- 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;}-export interface SkillDecisionDocumentOutcome {- agentDocumentId: string;- hintIsSkill?: boolean;- relation?: string;- summary?: string;-}--export interface SkillDecisionCandidateDocument {- agentDocumentId: string;- documentId: string;- filename?: string;- title?: string;-}--export interface SkillDecisionDocumentSnapshot {- agentDocumentId: string;- content?: string;- description?: string | null;- documentId?: string;- filename?: string;- metadata?: Record<string, unknown>;- title?: string;-}--export interface SkillDecisionToolset {- listCandidateDocuments: (input: {- agentId: string;- topicId?: string;- }) => Promise<SkillDecisionCandidateDocument[]>;- listSameTurnDocumentOutcomes: (input: {- agentId: string;- messageId?: string;- scopeKey?: string;- topicId?: string;- }) => Promise<SkillDecisionDocumentOutcome[]>;- readDocument: (input: { agentDocumentId: string }) => Promise<SkillDecisionDocumentSnapshot>;-}--/**- * Checks whether a procedure related object references an agent document binding.- *- * Use when:- * - Agent Signal consumes same-turn document tool receipts.- * - Producers emit `agent-document` receipts whose ids are stable agent document bindings.- *- * Expects:- * - `agent-document` object ids are `agent_documents.id`.- *- * Returns:- * - Whether the object can be read through the Agent Documents service by id.- */-export const isAgentDocumentRelatedObject = (object: { objectType: string }) =>- object.objectType === 'agent-document';--/**- * Reads the agent-signal skill hint from an agent-document snapshot.- *- * Use when:- * - Same-turn document evidence may include document creation intent.- * - Decision agents need a high-context hint without treating malformed metadata as evidence.- *- * Expects:- * - Metadata may be absent, malformed, or intentionally set to false.- *- * Returns:- * - `true` or `false` only when the metadata explicitly stores a boolean hint.- * - `undefined` when the hint is absent or malformed.- */-export const readAgentSignalHintIsSkill = (metadata: unknown): boolean | undefined => {- if (!metadata || typeof metadata !== 'object') return undefined;-- const agentSignal = (metadata as Record<string, unknown>).agentSignal;- if (!agentSignal || typeof agentSignal !== 'object') return undefined;-- const hintIsSkill = (agentSignal as Record<string, unknown>).hintIsSkill;- return typeof hintIsSkill === 'boolean' ? hintIsSkill : undefined;-};--const createRecordedSkillIntentEvidence = (- record: RecordedSkillIntent | undefined,-): AgentSignalFeedbackEvidence[] => {- if (!record) return [];-- return [- {- cue: 'recorded_skill_intent',- excerpt: `${record.explicitness}/${record.route}/${record.actionIntent ?? 'none'}: ${- record.reason ?? 'recorded skill intent'- }`,- },- ];-};--const readRecordedSkillIntentForExecution = async (- options: SkillManagementActionHandlerOptions,- action: ActionSkillManagementHandle,- context: RuntimeProcessorContext,-) => {- const reader = options.procedureState?.skillIntentRecords?.read;- if (!reader) return undefined;-- const messageId = action.payload.messageId;- if (messageId) {- const record = await reader({- scopeKey: context.scopeKey,- sourceId: messageId,- });- if (record) return record;- }-- const sourceId = action.source?.sourceId;- if (!sourceId || sourceId === messageId) return undefined;-- return reader({- scopeKey: context.scopeKey,- sourceId,- });-};--export interface SkillManagementAgentModelConfig {- model: string;- provider: string;-}--export interface SkillMaintainerWorkflowInput {- decision: SkillManagementDecision;- /** Language instruction block for persisted skill artifact text. */- languageInstruction?: string;- signal: SkillManagementActionInput;- targetSkills: Array<{- content: string;- id: string;- metadata: Record<string, unknown>;- name: string;- }>;- type: 'consolidate' | 'refine';-}--export interface SkillMaintainerWorkflowResult {- bodyMarkdown: string;- confidence?: number;- description?: string;- reason?: string;- rename?: {- newName?: string;- newTitle?: string;- };-}--export interface SkillCreateAuthoringInput {- candidateSkills?: SkillManagementCandidateSkill[];- decision: SkillManagementDecision;- /** Language instruction block for persisted skill artifact text. */- languageInstruction?: string;- signal: SkillManagementActionInput;- sourceAgentDocumentId?: string;- sourceDocumentContent?: string;-}--export interface SkillCreateAuthoringResult {- bodyMarkdown: string;- confidence?: number;- description: string;- name: string;- reason?: string;- title?: string;-}--export interface SkillManagementOperationService {- createSkill: (input: CreateSkillInput) => Promise<SkillDetail>;- getSkill: (input: {- agentDocumentId?: string;- agentId: string;- includeContent?: boolean;- name?: string;- }) => Promise<SkillDetail | undefined>;- listSkills: (input: { agentId: string }) => Promise<SkillSummary[]>;- renameSkill: (input: RenameSkillInput) => Promise<SkillDetail | undefined>;- replaceSkillIndex: (input: ReplaceSkillIndexInput) => Promise<SkillDetail | undefined>;-}--const SkillManagementDecisionSchema = z.object({- action: z.enum(['create', 'refine', 'consolidate', 'noop', 'reject']),- confidence: z.number().min(0).max(1).nullable(),- documentRefs: z.array(z.string()).default([]),- reason: z.string().nullable(),- requiredReads: z.array(z.string()),- targetSkillRefs: z.array(z.string()),-});--const SkillMaintainerWorkflowResultSchema = z.object({- bodyMarkdown: z.string(),- confidence: z.number().min(0).max(1).nullable().default(null),- description: z.string().nullable().default(null),- reason: z.string().nullable().default(null),- rename: z- .object({- newName: z.string().nullable().default(null),- newTitle: z.string().nullable().default(null),- })- .nullable()- .default(null),-});--const SkillCreateAuthoringResultSchema = z.object({- bodyMarkdown: z.string(),- confidence: z.number().min(0).max(1).nullable().default(null),- description: z.string(),- name: z.string(),- reason: z.string().nullable().default(null),- title: z.string().nullable().default(null),-});--const SkillManagementDecisionGenerateObjectSchema = {- name: 'agent_signal_skill_management_decision',- schema: {- additionalProperties: false,- properties: {- action: { enum: ['create', 'refine', 'consolidate', 'noop', 'reject'], type: 'string' },- confidence: {- anyOf: [{ maximum: 1, minimum: 0, type: 'number' }, { type: 'null' }],- },- documentRefs: { items: { type: 'string' }, type: 'array' },- reason: { type: ['string', 'null'] },- requiredReads: { items: { type: 'string' }, type: 'array' },- targetSkillRefs: { items: { type: 'string' }, type: 'array' },- },- required: [- 'action',- 'confidence',- 'documentRefs',- 'reason',- 'requiredReads',- 'targetSkillRefs',- ],- type: 'object',- },- strict: true,-} satisfies GenerateObjectSchema;--const SkillMaintainerWorkflowResultBaseGenerateObjectSchema = {- schema: {- additionalProperties: false,- properties: {- bodyMarkdown: { type: 'string' },- confidence: {- anyOf: [{ maximum: 1, minimum: 0, type: 'number' }, { type: 'null' }],- },- description: { type: ['string', 'null'] },- reason: { type: ['string', 'null'] },- rename: {- anyOf: [- {- additionalProperties: false,- properties: {- newName: { type: ['string', 'null'] },- newTitle: { type: ['string', 'null'] },- },- required: ['newName', 'newTitle'],- type: 'object',- },- { type: 'null' },- ],- },- },- required: ['bodyMarkdown', 'confidence', 'description', 'reason', 'rename'],- type: 'object',- },- strict: true,-} satisfies Omit<GenerateObjectSchema, 'name'>;--const SkillCreateAuthoringResultGenerateObjectSchema = {- name: 'agent_signal_skill_create',- schema: {- additionalProperties: false,- properties: {- bodyMarkdown: { type: 'string' },- confidence: {- anyOf: [{ maximum: 1, minimum: 0, type: 'number' }, { type: 'null' }],- },- description: { type: 'string' },- name: { type: 'string' },- reason: { type: ['string', 'null'] },- title: { type: ['string', 'null'] },- },- required: ['name', 'title', 'description', 'bodyMarkdown', 'reason', 'confidence'],- type: 'object',- },- strict: true,-} satisfies GenerateObjectSchema;--const isSkillManagementDecisionAction = (value: unknown): value is SkillManagementDecisionAction =>- value === 'create' ||- value === 'refine' ||- value === 'consolidate' ||- value === 'noop' ||- value === 'reject';--const getStringArray = (value: unknown) => {- if (!Array.isArray(value)) return undefined;-- const strings = value.filter((item): item is string => typeof item === 'string');-- return strings.length > 0 ? strings : undefined;-};--const normalizeSkillManagementDecision = (decision: unknown): SkillManagementDecision => {- if (!decision || typeof decision !== 'object') {- return { action: 'noop', reason: 'decision output was not an object' };- }-- const record = decision as Record<string, unknown>;- const action = isSkillManagementDecisionAction(record.action) ? record.action : 'noop';- const confidence = typeof record.confidence === 'number' ? record.confidence : undefined;- const documentRefs = getStringArray(record.documentRefs);- const reason = typeof record.reason === 'string' ? record.reason : undefined;- const requiredReads = getStringArray(record.requiredReads);- const targetSkillRefs = getStringArray(record.targetSkillRefs);-- return {- action,- ...(confidence === undefined ? {} : { confidence }),- ...(documentRefs === undefined ? {} : { documentRefs }),- ...(reason === undefined ? {} : { reason }),- ...(requiredReads === undefined ? {} : { requiredReads }),- ...(targetSkillRefs === undefined ? {} : { targetSkillRefs }),- };-};--const malformedDecisionOutputReason = 'decision structured output was malformed';--const skillDecisionToolIdentifier = 'agent-signal-skill-decision';--const skillDecisionManifest = {- api: [- {- description: 'List document tool outcomes from the same Agent Signal turn.',- name: 'listSameTurnDocumentOutcomes',- parameters: {- additionalProperties: false,- properties: {- messageId: { type: ['string', 'null'] },- scopeKey: { type: ['string', 'null'] },- },- required: ['messageId', 'scopeKey'],- type: 'object',- },- },- {- description: 'List candidate agent documents when same-turn outcomes are insufficient.',- name: 'listCandidateDocuments',- parameters: {- additionalProperties: false,- properties: {- agentId: { type: 'string' },- topicId: { type: ['string', 'null'] },- },- required: ['agentId', 'topicId'],- type: 'object',- },- },- {- description: 'Read one agent document by agent document id for attribution before deciding.',- name: 'readDocument',- parameters: {- additionalProperties: false,- properties: {- agentDocumentId: { type: 'string' },- documentId: { type: 'string' },- },- required: ['agentDocumentId'],- type: 'object',- },- },- {- description:- 'Submit the final skill-management decision after optional read-only inspection.',- name: 'submitDecision',- parameters: SkillManagementDecisionGenerateObjectSchema.schema,- },- ],- identifier: skillDecisionToolIdentifier,- meta: {- description: 'Read same-turn evidence and submit one skill-management decision.',- title: 'Agent Signal Skill Decision',- },- systemRole: 'Use read-only evidence tools before submitting a skill-management decision.',- type: 'builtin',-} satisfies LobeToolManifest;--interface SkillDecisionAgentRuntimeInput {- model: string;- modelRuntime: Pick<ModelRuntime, 'chat'>;- payload: SkillManagementSignalPayload;- tools: SkillDecisionToolset;-}--const toNullableString = (value: unknown) => (typeof value === 'string' ? value : undefined);--const parseToolArguments = (value: string | undefined): Record<string, unknown> => {- if (!value) return {};-- try {- const parsed = JSON.parse(value) as unknown;- return parsed && typeof parsed === 'object' && !Array.isArray(parsed)- ? (parsed as Record<string, unknown>)- : {};- } catch {- return {};- }-};--const executeSkillDecisionRuntimeTool = async (- toolCall: ChatToolPayload,- input: Pick<SkillDecisionAgentRuntimeInput, 'payload' | 'tools'>,-) => {- const args = parseToolArguments(toolCall.arguments);-- if (toolCall.apiName === 'listSameTurnDocumentOutcomes') {- return input.tools.listSameTurnDocumentOutcomes({- agentId: input.payload.agentId,- messageId: toNullableString(args.messageId) ?? input.payload.messageId,- scopeKey: toNullableString(args.scopeKey) ?? input.payload.scopeKey,- topicId: input.payload.topicId,- });- }-- if (toolCall.apiName === 'listCandidateDocuments') {- return input.tools.listCandidateDocuments({- agentId: input.payload.agentId,- topicId: toNullableString(args.topicId) ?? input.payload.topicId,- });- }-- if (toolCall.apiName === 'readDocument') {- const agentDocumentId = toNullableString(args.agentDocumentId);- if (!agentDocumentId) return { error: 'agentDocumentId is required' };-- return input.tools.readDocument({ agentDocumentId });- }-- return { error: `Unsupported skill decision tool: ${toolCall.apiName}` };-};--/**- * Runs the skill-management decision agent with the standard Agent Runtime state machine.- *- * Use when:- * - The decision step must inspect same-turn document outcomes before deciding- * - Tool use should follow the same LLM -> tool -> LLM control flow as normal agents- *- * Expects:- * - Tool implementations are read-only and scoped by agent/message/scope- * - `submitDecision` is the only terminal tool- *- * Returns:- * - Final normalized skill-management decision- *- * Call stack:- *- * createSkillDecisionRunner- * -> SkillManagementDecisionAgentService.decide- * -> {@link runSkillDecisionAgentRuntime}- * -> AgentRuntime.step- */-export const runSkillDecisionAgentRuntime = async (input: SkillDecisionAgentRuntimeInput) => {- let submittedDecision: SkillManagementDecision | undefined;- const toolNameResolver = new ToolNameResolver();- const manifestMap = { [skillDecisionToolIdentifier]: skillDecisionManifest };- const tools = generateToolsFromManifest(skillDecisionManifest);- const messages: Array<{ content: string; role: 'system' | 'user' }> = [- { content: AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE, role: 'system' },- {- content: createAgentSkillManagerDecisionPrompt({- agentId: input.payload.agentId,- ...(input.payload.candidateSkills?.length- ? { candidateSkills: input.payload.candidateSkills }- : {}),- evidence: input.payload.evidence ?? [],- feedbackMessage: input.payload.feedbackMessage,- messageId: input.payload.messageId,- scopeKey: input.payload.scopeKey,- topicId: input.payload.topicId,- turnContext: input.payload.turnContext,- }),- role: 'user',- },- ];-- const runtime = new AgentRuntime(- new GeneralChatAgent({- compressionConfig: { enabled: false },- modelRuntimeConfig: {- model: input.model,- provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,- },- operationId: `agent-signal-skill-decision:${input.payload.messageId ?? 'message'}`,- }),- {- executors: {- call_llm: async (instruction, state) => {- const payload = (instruction as { payload: { messages: ChatStreamPayload['messages'] } })- .payload;- let content = '';- let modelUsage: ModelUsage | undefined;- let rawToolCalls: MessageToolCall[] = [];-- const response = await input.modelRuntime.chat(- {- messages: payload.messages,- model: input.model,- stream: true,- tools,- },- {- callback: {- onCompletion: (data) => {- modelUsage = data.usage;- },- onText: (text) => {- content += text;- },- onToolsCalling: ({ toolsCalling }) => {- rawToolCalls = toolsCalling;- },- },- metadata: { trigger: RequestTrigger.AgentSignal },- },- );- await consumeStreamUntilDone(response);-- const assistantMessageId = `skill-decision-assistant-${state.stepCount}`;- const resolvedToolCalls = toolNameResolver.resolve(rawToolCalls, manifestMap);- const newState = structuredClone(state);-- newState.messages.push({- content,- id: assistantMessageId,- role: 'assistant',- ...(rawToolCalls.length > 0 ? { tool_calls: rawToolCalls } : {}),- });-- return {- events: [- {- result: { content, tool_calls: rawToolCalls, usage: modelUsage },- type: 'llm_result',- },- ],- newState,- nextContext: {- payload: {- hasToolsCalling: resolvedToolCalls.length > 0,- parentMessageId: assistantMessageId,- result: { content, tool_calls: rawToolCalls },- toolsCalling: resolvedToolCalls,- },- phase: 'llm_result',- session: {- messageCount: newState.messages.length,- sessionId: newState.operationId,- status: newState.status,- stepCount: newState.stepCount,- },- stepUsage: modelUsage,- } satisfies AgentRuntimeContext,- };- },- call_tool: async (instruction, state) => {- const payload = (- instruction as {- payload: {- parentMessageId: string;- toolCalling: ChatToolPayload;- };- }- ).payload;- const startedAt = Date.now();- const args = parseToolArguments(payload.toolCalling.arguments);- const data =- payload.toolCalling.apiName === 'submitDecision'- ? normalizeSkillManagementDecision(args)- : await executeSkillDecisionRuntimeTool(payload.toolCalling, input);-- if (payload.toolCalling.apiName === 'submitDecision') {- submittedDecision = data as SkillManagementDecision;- }-- const content = JSON.stringify(data);- const newState = structuredClone(state);- newState.messages.push({- content,- role: 'tool',- tool_call_id: payload.toolCalling.id,- });-- return {- events: [- {- id: payload.toolCalling.id,- result: { content, success: true },- type: 'tool_result',- },- ],- newState,- nextContext: {- payload: {- data,- executionTime: Date.now() - startedAt,- isSuccess: true,- parentMessageId: payload.parentMessageId,- toolCall: payload.toolCalling,- toolCallId: payload.toolCalling.id,- },- phase: 'tool_result',- session: {- messageCount: newState.messages.length,- sessionId: newState.operationId,- status: newState.status,- stepCount: newState.stepCount,- },- } satisfies AgentRuntimeContext,- };- },- },- },- );-- const createdAt = new Date().toISOString();- let state: AgentState = {- cost: {- calculatedAt: createdAt,- currency: 'USD',- llm: { byModel: [], currency: 'USD', total: 0 },- tools: { byTool: [], currency: 'USD', total: 0 },- total: 0,- },- createdAt,- lastModified: createdAt,- messages,- metadata: {- agentId: input.payload.agentId,- sourceMessageId: input.payload.messageId,- topicId: input.payload.topicId,- trigger: RequestTrigger.AgentSignal,- },- modelRuntimeConfig: {- model: input.model,- provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,- },- operationId: `agent-signal-skill-decision:${input.payload.messageId ?? 'message'}`,- operationToolSet: {- enabledToolIds: [skillDecisionToolIdentifier],- manifestMap,- sourceMap: { [skillDecisionToolIdentifier]: 'builtin' },- tools,- },- status: 'idle',- stepCount: 0,- toolManifestMap: manifestMap,- toolSourceMap: { [skillDecisionToolIdentifier]: 'builtin' },- tools,- usage: {- humanInteraction: {- approvalRequests: 0,- promptRequests: 0,- selectRequests: 0,- totalWaitingTimeMs: 0,- },- llm: {- apiCalls: 0,- processingTimeMs: 0,- tokens: { input: 0, output: 0, total: 0 },- },- tools: {- byTool: [],- totalCalls: 0,- totalTimeMs: 0,- },- },- userInterventionConfig: { approvalMode: 'headless' },- };- let context: AgentRuntimeContext = {- payload: {- model: input.model,- provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,- tools,- },- phase: 'user_input',- session: {- messageCount: messages.length,- sessionId: state.operationId,- status: state.status,- stepCount: state.stepCount,- },- };-- for (let step = 0; step < 14; step += 1) {- if (submittedDecision) break;- if (state.status === 'done' || state.status === 'error' || state.status === 'interrupted') {- break;- }-- const result = await runtime.step(state, context);- state = result.newState;-- if (!result.nextContext) break;- context = result.nextContext;- }-- return submittedDecision ?? createNoopDecision('decision agent did not submit a decision');-};--/**- * Executes the skill-management decision step for one skill-domain action payload.- *- * Use when:- * - Feedback has already been routed into the skill domain- * - Self-iteration policy decides whether the decision agent may run- *- * Expects:- * - `decide` performs the actual skill-management decision step- *- * Returns:- * - A skipped status when disabled, otherwise the decision result- */-export const executeSkillManagementDecision = async (input: {- decide: (payload: SkillManagementSignalPayload) => Promise<unknown>;- payload: SkillManagementSignalPayload;- selfIterationEnabled: boolean;-}) => {- if (!input.selfIterationEnabled) {- return { reason: 'self iteration is disabled', status: 'skipped' as const };- }-- let decisionOutput: unknown;-- try {- decisionOutput = await input.decide(input.payload);- } catch (error) {- if (error instanceof z.ZodError) {- return { reason: malformedDecisionOutputReason, status: 'skipped' as const };- }-- throw error;- }-- const decision = normalizeSkillManagementDecision(decisionOutput);-- return { decision, status: 'decided' as const };-};--const toSkillManagementDecision = (- value: z.infer<typeof SkillManagementDecisionSchema>,-): SkillManagementDecision => ({- action: value.action,- ...(value.confidence === null ? {} : { confidence: value.confidence }),- ...(value.documentRefs.length === 0 ? {} : { documentRefs: value.documentRefs }),- ...(value.reason === null ? {} : { reason: value.reason }),- ...(value.requiredReads.length === 0 ? {} : { requiredReads: value.requiredReads }),- ...(value.targetSkillRefs.length === 0 ? {} : { targetSkillRefs: value.targetSkillRefs }),-});--/**- * Lists managed agent skills that the decision agent may target.- *- * Use when:- * - Skill-domain feedback may refine or consolidate existing agent document skills- * - The decision prompt needs stable target ids instead of natural-language guesses- *- * Expects:- * - `documents` come from one agent's document bindings- * - Managed skill folders use their directory filename as the package id- *- * Returns:- * - Agent-scoped candidate ids that are managed skill bundle agent document ids- */-export const collectAgentSkillDecisionCandidates = (- documents: AgentDocument[],-): SkillManagementCandidateSkill[] => {- const candidates: SkillManagementCandidateSkill[] = [];-- for (const document of documents) {- const folder = getSkillBundle(documents, 'agent', document.filename);-- if (!folder || folder.id !== document.id) {- continue;- }-- candidates.push({- id: document.id,- name: document.title ?? document.filename,- scope: 'agent',- });- }-- return candidates.sort((left, right) => left.id.localeCompare(right.id));-};--const createDefaultSkillDecisionToolset = (- db: LobeChatDatabase,- userId: string,-): SkillDecisionToolset => {- const agentDocumentModel = new AgentDocumentModel(db, userId);- const agentDocumentsService = new AgentDocumentsService(db, userId);- const inspector = new AgentSignalProcedureInspector(redisPolicyStateStore);-- return {- listCandidateDocuments: async ({ agentId, topicId }) => {- const documents = topicId- ? await agentDocumentsService.listDocumentsForTopic(agentId, topicId)- : await agentDocumentModel.findByAgent(agentId);-- return documents.map((document) => ({- agentDocumentId: document.id,- documentId: document.documentId,- filename: document.filename,- title: document.title,- }));- },- listSameTurnDocumentOutcomes: async ({ messageId, scopeKey }) => {- if (!scopeKey) return [];-- const snapshot = await inspector.inspectScope(scopeKey);- const outcomes = snapshot.receipts- .filter((receipt) => receipt.domainKey.startsWith('document:'))- .filter((receipt) => !messageId || receipt.messageId === messageId)- .flatMap((receipt) =>- (receipt.relatedObjects ?? []).filter(isAgentDocumentRelatedObject).map((object) => ({- agentDocumentId: object.objectId,- relation: object.relation,- summary: receipt.summary,- })),- );-- return Promise.all(- outcomes.map(async (outcome) => {- const document = await agentDocumentsService.getDocumentSnapshotById(- outcome.agentDocumentId,- );- const hintIsSkill = readAgentSignalHintIsSkill(document?.metadata);-- return {- ...outcome,- ...(hintIsSkill === undefined ? {} : { hintIsSkill }),- };- }),- );- },- 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 };-- return {- agentDocumentId,- content: snapshot.content,- documentId: snapshot.documentId,- filename: snapshot.filename,- metadata: snapshot.metadata ?? undefined,- title: snapshot.title,- };- },- };-};--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 => ({- bodyMarkdown: value.bodyMarkdown,- ...(value.confidence === null ? {} : { confidence: value.confidence }),- ...(value.description === null ? {} : { description: value.description }),- ...(value.reason === null ? {} : { reason: value.reason }),- ...(value.rename === null- ? {}- : {- rename: {- ...(value.rename.newName === null ? {} : { newName: value.rename.newName }),- ...(value.rename.newTitle === null ? {} : { newTitle: value.rename.newTitle }),- },- }),-});--const toSkillCreateAuthoringResult = (- value: z.infer<typeof SkillCreateAuthoringResultSchema>,-): SkillCreateAuthoringResult => ({- bodyMarkdown: value.bodyMarkdown,- description: value.description,- name: value.name,- ...(value.confidence === null ? {} : { confidence: value.confidence }),- ...(value.reason === null ? {} : { reason: value.reason }),- ...(value.title === null ? {} : { title: value.title }),-});--class SkillManagementDecisionAgentService {- private readonly modelConfig: SkillManagementAgentModelConfig;-- constructor(- private db: LobeChatDatabase,- private userId: string,- modelConfig: Partial<SkillManagementAgentModelConfig> = {},- private toolsetFactory?: SkillManagementActionHandlerOptions['skillDecisionToolsetFactory'],- ) {- this.modelConfig = {- model: modelConfig.model ?? DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,- provider: modelConfig.provider ?? DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,- };- }-- async decide(input: SkillManagementSignalPayload): Promise<SkillManagementDecision> {- const modelRuntime = await initModelRuntimeFromDB(- this.db,- this.userId,- this.modelConfig.provider,- );- const candidateSkills =- input.candidateSkills ??- collectAgentSkillDecisionCandidates(- await new AgentDocumentModel(this.db, this.userId).findByAgent(input.agentId),- );-- const result = await runSkillDecisionAgentRuntime({- model: this.modelConfig.model,- modelRuntime,- payload: {- ...input,- ...(candidateSkills.length > 0 ? { candidateSkills } : {}),- },- tools:- this.toolsetFactory?.({ agentId: input.agentId }) ??- createDefaultSkillDecisionToolset(this.db, this.userId),- });-- return toSkillManagementDecision(- SkillManagementDecisionSchema.parse({- confidence: result.confidence ?? null,- documentRefs: result.documentRefs ?? [],- reason: result.reason ?? null,- requiredReads: result.requiredReads ?? [],- targetSkillRefs: result.targetSkillRefs ?? [],- action: result.action,- }),- );- }-}--class SkillMaintainerWorkflowAgentService {- private readonly modelConfig: SkillManagementAgentModelConfig;-- constructor(- private db: LobeChatDatabase,- private userId: string,- modelConfig: Partial<SkillManagementAgentModelConfig> = {},- ) {- this.modelConfig = {- model: modelConfig.model ?? DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,- provider: modelConfig.provider ?? DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,- };- }-- async run(input: SkillMaintainerWorkflowInput): Promise<SkillMaintainerWorkflowResult> {- const modelRuntime = await initModelRuntimeFromDB(- this.db,- this.userId,- this.modelConfig.provider,- );- const isRefine = input.type === 'refine';- const content = isRefine- ? createAgentSkillRefinePrompt({- languageInstruction: input.languageInstruction,- reason: input.decision.reason ?? input.signal.reason ?? 'Refine selected skill.',- signalContext: {- evidence: input.signal.evidence,- feedbackHint: input.signal.feedbackHint,- message: input.signal.message,- topicId: input.signal.topicId,- },- skillContent: input.targetSkills[0]?.content ?? '',- skillMetadata: input.targetSkills[0]?.metadata ?? {},- })- : createAgentSkillConsolidatePrompt({- languageInstruction: input.languageInstruction,- reason: input.decision.reason ?? input.signal.reason ?? 'Consolidate selected skills.',- sourceSkills: input.targetSkills,- });-- const result = await modelRuntime.generateObject(- {- messages: [- {- content: isRefine- ? AGENT_SKILL_REFINE_SYSTEM_ROLE- : AGENT_SKILL_CONSOLIDATE_SYSTEM_ROLE,- role: 'system',- },- { content, role: 'user' },- ] as never[],- model: this.modelConfig.model,- schema: {- ...SkillMaintainerWorkflowResultBaseGenerateObjectSchema,- name: `agent_signal_skill_${input.type}`,- },- },- { metadata: { trigger: RequestTrigger.AgentSignal } },- );-- return toSkillMaintainerWorkflowResult(SkillMaintainerWorkflowResultSchema.parse(result));- }-}--class SkillCreateAuthoringAgentService {- private readonly modelConfig: SkillManagementAgentModelConfig;-- constructor(- private db: LobeChatDatabase,- private userId: string,- modelConfig: Partial<SkillManagementAgentModelConfig> = {},- ) {- this.modelConfig = {- model: modelConfig.model ?? DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,- provider: modelConfig.provider ?? DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,- };- }-- async run(input: SkillCreateAuthoringInput): Promise<SkillCreateAuthoringResult> {- const modelRuntime = await initModelRuntimeFromDB(- this.db,- this.userId,- this.modelConfig.provider,- );-- const result = await modelRuntime.generateObject(- {- messages: [- {- content: AGENT_SKILL_CREATE_SYSTEM_ROLE,- role: 'system',- },- {- content: createAgentSkillCreatePrompt({- agentId: input.signal.agentId ?? '',- ...(input.candidateSkills?.length ? { candidateSkills: input.candidateSkills } : {}),- evidence: input.signal.evidence ?? [],- feedbackMessage: input.signal.message,- languageInstruction: input.languageInstruction,- sourceAgentDocumentId: input.sourceAgentDocumentId,- sourceDocumentContent: input.sourceDocumentContent,- turnContext: input.signal.serializedContext,- }),- role: 'user',- },- ] as never[],- model: this.modelConfig.model,- schema: SkillCreateAuthoringResultGenerateObjectSchema,- },- { metadata: { trigger: RequestTrigger.AgentSignal } },- );-- return toSkillCreateAuthoringResult(SkillCreateAuthoringResultSchema.parse(result));- }-}-const finalizeAttempt = (startedAt: number,status: SignalAttempt['status'],@@ -1335,484 +42,63 @@ const finalizeAttempt = (status,});-const toExecutorError = (actionId: string, error: unknown, startedAt: number): ExecutorResult => {- return {- actionId,- attempt: finalizeAttempt(startedAt, 'failed'),- error: {- cause: error,- code: 'SKILL_MANAGEMENT_EXECUTION_FAILED',- message: error instanceof Error ? error.message : String(error),- },- status: 'failed',- };-};--const createNoopDecision = (reason: string): SkillManagementDecision => ({- action: 'noop',- reason,+const toExecutorError = (actionId: string, error: unknown, startedAt: number): ExecutorResult => ({+ actionId,+ attempt: finalizeAttempt(startedAt, 'failed'),+ error: {+ cause: error,+ code: 'SKILL_MANAGEMENT_EXECUTION_FAILED',+ message: error instanceof Error ? error.message : String(error),+ },+ status: 'failed',});-const toSkippedExecutorResult = ({- actionId,- decision,- detail,- startedAt,-}: {- actionId: string;- decision: SkillManagementDecision;- detail?: string;- startedAt: number;-}): ExecutorResult => ({+const toSkippedResult = (actionId: string, detail: string, startedAt: number): ExecutorResult => ({actionId,attempt: finalizeAttempt(startedAt, 'skipped'),detail,- output: { decision },status: 'skipped',});-const isSkillManagementAction = (action: BaseAction): action is ActionSkillManagementHandle => {- return action.actionType === AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle;-};--export const createSkillDecisionRunner = (options: SkillManagementActionHandlerOptions) => {- const agent = new SkillManagementDecisionAgentService(- options.db,- options.userId,- options.skillDecisionModel,- options.skillDecisionToolsetFactory,- );-- return (input: SkillManagementSignalPayload) => agent.decide(input);-};--const resolveSkillDecisionCandidates = async (- options: SkillManagementActionHandlerOptions,- agentId: string,-) => {- if (options.skillCandidateSkillsFactory) {- return options.skillCandidateSkillsFactory({ agentId });- }-- if (options.skillDecisionRunner) {- return [];- }-- return collectAgentSkillDecisionCandidates(- await new AgentDocumentModel(options.db, options.userId).findByAgent(agentId),- );-};--const createDefaultSkillManagementService = (- options: SkillManagementActionHandlerOptions,-): SkillManagementOperationService =>- new SkillManagementDocumentService(options.db, options.userId);--const getSkillTargets = (decision: SkillManagementDecision) => decision.targetSkillRefs ?? [];--const isMaintainerDecision = (- decision: SkillManagementDecision,-): decision is SkillManagementDecision & { action: 'consolidate' | 'refine' } =>- decision.action === 'refine' || decision.action === 'consolidate';+const isSkillManagementAction = (action: BaseAction): action is ActionSkillManagementHandle =>+ action.actionType === AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle;/**- * Checks whether a model-selected source document ref can be queried as agent_documents.id.+ * Renders the same-turn skill feedback into the agent prompt. The builtin+ * skill-management agent's systemRole carries the behavioural instructions; this+ * only embeds the evidence (feedback message + routing reason + turn context).*/-const isAgentDocumentDatabaseId = (value: string) => z.string().uuid().safeParse(value).success;--const toSkillActionTarget = (- skill: Pick<SkillSummary, 'bundle' | 'description' | 'index' | 'title'>,-): SkillManagementActionTarget => ({- agentDocumentId: skill.index.agentDocumentId,- documentId: skill.index.documentId,- id: skill.bundle.documentId,- summary: skill.description,- title: skill.title,- type: 'skill',-});--const readTargetSkills = async (- service: SkillManagementOperationService,- agentId: string,- skillRefs: string[],-) => {- const results = await Promise.all(- skillRefs.map((agentDocumentId) =>- service.getSkill({ agentDocumentId, agentId, includeContent: true }),- ),- );-- return results.filter((skill): skill is SkillDetail => Boolean(skill));-};--const readSkillPrimaryLanguage = (skill?: SkillDetail) => {- const frontmatter = skill?.frontmatter;- if (!frontmatter || typeof frontmatter !== 'object') return undefined;-- const language = (frontmatter as unknown as Record<string, unknown>).language;-- return typeof language === 'string' && language.trim().length > 0 ? language.trim() : undefined;-};--const createSkillArtifactLanguageInstruction = (input: {- existingSkillLanguage?: string;- mode: 'consolidate' | 'create' | 'refine';- responseLanguage?: string;-}) =>- createAgentSignalSkillLanguageInstruction({- existingSkillLanguage: input.existingSkillLanguage,- mode: input.mode,- responseLanguage: input.responseLanguage ?? 'en-US',- });--const runMaintainerWorkflow = async (- input: SkillManagementActionInput,- options: SkillManagementActionHandlerOptions,- decision: SkillManagementDecision & { action: 'consolidate' | 'refine' },-): Promise<SkillManagementActionResult> => {- if (!input.agentId) {- return {- decision,- detail: 'Missing agentId for skill-maintainer workflow.',- status: 'skipped',- };- }-- const agentId = input.agentId;- const targetSkillRefs = getSkillTargets(decision);- const minimumTargets = decision.action === 'consolidate' ? 2 : 1;-- if (targetSkillRefs.length < minimumTargets) {- return {- decision,- detail: `Skill-management ${decision.action} requires targetSkillRefs from the decision agent.`,- status: 'skipped',- };- }-- const service =- options.skillManagementServiceFactory?.({ agentId }) ??- createDefaultSkillManagementService(options);- const workflowRunner =- options.skillMaintainerRunner ??- ((workflowInput: SkillMaintainerWorkflowInput) =>- new SkillMaintainerWorkflowAgentService(- options.db,- options.userId,- options.skillDecisionModel,- ).run(workflowInput));- const targetSkills = await readTargetSkills(service, agentId, targetSkillRefs);-- if (targetSkills.length < minimumTargets) {- return {- decision,- detail: `Skill-management ${decision.action} could not resolve targetSkillRefs.`,- status: 'skipped',- };- }-- const workflowResult = toSkillMaintainerWorkflowResult(- SkillMaintainerWorkflowResultSchema.parse(- await workflowRunner({- decision,- languageInstruction: createSkillArtifactLanguageInstruction({- existingSkillLanguage: readSkillPrimaryLanguage(targetSkills[0]),- mode: decision.action,- responseLanguage: options.responseLanguage,- }),- signal: input,- targetSkills: targetSkills.map((skill) => ({- content: skill.content ?? '',- id: skill.bundle.agentDocumentId,- metadata: { frontmatter: skill.frontmatter },- name: skill.name,- })),- type: decision.action,- }),- ),- );- const canonical = targetSkills[0];-- if (!canonical) {- return {- decision,- detail: `Skill-management ${decision.action} could not resolve targetSkillRefs.`,- status: 'skipped',- };- }-- let updatedSkill: SkillDetail | SkillSummary = canonical;-- try {- const selfIterationSkillService = createSkillManagementService({- consolidateSkill: async () => {- if (workflowResult.rename?.newName || workflowResult.rename?.newTitle) {- updatedSkill =- (await service.renameSkill({- agentDocumentId: canonical.bundle.agentDocumentId,- agentId,- newName: workflowResult.rename.newName,- newTitle: workflowResult.rename.newTitle,- updateReason: workflowResult.reason,- })) ?? updatedSkill;- }-- updatedSkill =- (await service.replaceSkillIndex({- agentDocumentId: canonical.bundle.agentDocumentId,- agentId,- bodyMarkdown: workflowResult.bodyMarkdown,- description: workflowResult.description,- updateReason: workflowResult.reason,- })) ?? updatedSkill;-- return {- skillDocumentId: canonical.bundle.agentDocumentId,- summary: workflowResult.reason,- };- },- refineSkill: async () => {- if (workflowResult.rename?.newName || workflowResult.rename?.newTitle) {- updatedSkill =- (await service.renameSkill({- agentDocumentId: canonical.bundle.agentDocumentId,- agentId,- newName: workflowResult.rename.newName,- newTitle: workflowResult.rename.newTitle,- updateReason: workflowResult.reason,- })) ?? updatedSkill;- }-- updatedSkill =- (await service.replaceSkillIndex({- agentDocumentId: canonical.bundle.agentDocumentId,- agentId,- bodyMarkdown: workflowResult.bodyMarkdown,- description: workflowResult.description,- updateReason: workflowResult.reason,- })) ?? updatedSkill;-- return {- skillDocumentId: canonical.bundle.agentDocumentId,- summary: workflowResult.reason,- };- },- });-- if (decision.action === 'consolidate') {- await selfIterationSkillService.consolidateSkill({- evidenceRefs: [],- idempotencyKey: `same-turn-skill:${canonical.bundle.agentDocumentId}`,- input: {- approval: { source: 'same_turn_feedback' },- canonicalSkillDocumentId: canonical.bundle.agentDocumentId,- sourceSkillIds: targetSkillRefs,- userId: options.userId,- },- });- } else {- await selfIterationSkillService.refineSkill({- evidenceRefs: [],- idempotencyKey: `same-turn-skill:${canonical.bundle.agentDocumentId}`,- input: {- bodyMarkdown: workflowResult.bodyMarkdown,- skillDocumentId: canonical.bundle.agentDocumentId,- userId: options.userId,- },- });- }- } catch (error) {- return {- decision,- detail: error instanceof Error ? error.message : String(error),- status: 'skipped',- };- }-- return {- decision,- detail: workflowResult.reason ?? `Applied ${decision.action} maintainer workflow.`,- status: 'applied',- target: toSkillActionTarget(updatedSkill),- };-};--const readCreateSourceDocument = async (- input: SkillManagementActionInput,- options: SkillManagementActionHandlerOptions,- decision: SkillManagementDecision,-) => {- const sourceAgentDocumentId = decision.documentRefs?.[0];-- if (!input.agentId || !sourceAgentDocumentId) {- return {};- }-- if (!isAgentDocumentDatabaseId(sourceAgentDocumentId)) {- return {};- }-- const snapshot = await new AgentDocumentsService(- options.db,- options.userId,- ).getDocumentSnapshotById(sourceAgentDocumentId);-- return {- sourceAgentDocumentId,- sourceDocumentContent: snapshot?.content,- };-};--const runCreateWorkflow = async (- input: SkillManagementActionInput,- options: SkillManagementActionHandlerOptions,- decision: SkillManagementDecision,-): Promise<SkillManagementActionResult> => {- if (!input.agentId) {- return {- decision,- detail: 'Missing agentId for skill-management create workflow.',- status: 'skipped',- };- }-- const agentId = input.agentId;- const source = await readCreateSourceDocument(input, options, decision);- const createRunner =- options.skillCreateRunner ??- ((authoringInput: SkillCreateAuthoringInput) =>- new SkillCreateAuthoringAgentService(- options.db,- options.userId,- options.skillDecisionModel,- ).run(authoringInput));- const authored = toSkillCreateAuthoringResult(- SkillCreateAuthoringResultSchema.parse(- await createRunner({- candidateSkills: input.candidateSkills,- decision,- languageInstruction: createSkillArtifactLanguageInstruction({- mode: 'create',- responseLanguage: options.responseLanguage,- }),- signal: input,- sourceAgentDocumentId: source?.sourceAgentDocumentId,- sourceDocumentContent: source?.sourceDocumentContent,- }),- ),- );- const service =- options.skillManagementServiceFactory?.({ agentId }) ??- createDefaultSkillManagementService(options);-- try {- let createdSkill: SkillDetail | undefined;- const selfIterationSkillService = createSkillManagementService({- createSkill: async () => {- const skill = await service.createSkill({- agentId,- bodyMarkdown: authored.bodyMarkdown,- description: authored.description,- name: authored.name,- sourceAgentDocumentId: source.sourceAgentDocumentId,- title: authored.title ?? authored.name,- });- createdSkill = skill;-- return {- skillDocumentId: skill.bundle.agentDocumentId,- summary: authored.reason,- };- },- });- await selfIterationSkillService.createSkill({- evidenceRefs: [],- idempotencyKey: `same-turn-skill:create:${authored.name}`,- input: {- bodyMarkdown: authored.bodyMarkdown,- description: authored.description,- name: authored.name,- title: authored.title ?? authored.name,- userId: options.userId,- },- });-- return {- decision,- detail: authored.reason ?? `Created skill ${authored.name}.`,- status: 'applied',- target: createdSkill ? toSkillActionTarget(createdSkill) : undefined,- };- } catch (error) {- if (error instanceof Error && error.message.includes('already exists')) {- return { decision, detail: error.message, status: 'skipped' };- }-- throw error;- }-};--export const runSkillManagementAction = async (- input: SkillManagementActionInput,- options: SkillManagementActionHandlerOptions,- decision: SkillManagementDecision,-): Promise<SkillManagementActionResult> => {- if (decision.action === 'reject') {- return {- decision,- detail: decision.reason ?? 'Skill-management decision was rejected.',- status: 'skipped',- };- }-- if (decision.action === 'noop') {- return {- decision,- detail: decision.reason ?? 'Skill-management decision was noop.',- status: 'skipped',- };- }-- if (!input.agentId) {- return {- decision,- detail: 'Missing agentId for skill-management action.',- status: 'skipped',- };- }-- if (input.message.trim().length === 0) {- return {- decision,- detail: 'Missing skill-management action message.',- status: 'skipped',- };- }-- if (isMaintainerDecision(decision)) {- return runMaintainerWorkflow(input, options, decision);- }-- return runCreateWorkflow(input, options, decision);-};+const buildSkillFeedbackPrompt = (input: {+ agentId: string;+ evidence?: ActionSkillManagementHandle['payload']['evidence'];+ message: string;+ reason?: string;+ serializedContext?: string;+ sourceId: string;+ userId: string;+}): string =>+ [+ `Agent id: ${input.agentId}`,+ `User id: ${input.userId}`,+ `Source id: ${input.sourceId}`,+ 'User feedback (already routed to the skill domain β a reusable procedure to capture as a managed skill):',+ input.message,+ input.reason ? `Routing reason: ${input.reason}` : undefined,+ input.serializedContext ? `Turn context: ${input.serializedContext}` : undefined,+ input.evidence?.length ? `Evidence: ${JSON.stringify(input.evidence)}` : undefined,+ ]+ .filter(Boolean)+ .join('\n');/**- * 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}+ * Executes one skill-management action by enqueueing an async `execAgent` run+ * under the builtin `skill-management` slug. The run inspects existing managed+ * skills and applies one safe skill create/refine; its durable skill receipt is+ * projected on the `agent.execution.completed` completion path from finalState.+ *+ * Returns immediately with an `applied` (enqueued) status β no synchronous+ * decision/apply, no blocking executeSync, no Vercel timeout risk. Mirrors the+ * memory-writer async path (`handleUserMemoryAction`).*/export const executeSkillManagementAction = async (action: BaseAction,@@ -1827,125 +113,87 @@ export const executeSkillManagementAction = async (try {if (await hasAppliedActionIdempotency(context, idempotencyKey)) {- // The planner emits a stable idempotency key per source message and target domain. If the- // same feedback source is reprocessed in the same runtime scope, we skip before decision- // generation to avoid creating or mutating the same skill twice.- return toSkippedExecutorResult({- actionId: action.actionId,- decision: createNoopDecision('skill-management action already applied'),- detail: 'Skill-management action already applied.',+ return toSkippedResult(+ action.actionId,+ 'Skill-management action already applied.',startedAt,- });+ );}if (!isSkillManagementAction(action)) {- return toSkippedExecutorResult({- actionId: action.actionId,- decision: createNoopDecision('unsupported skill-management action type'),- detail: 'Unsupported skill-management action type.',+ return toSkippedResult(+ action.actionId,+ 'Unsupported skill-management action type.',startedAt,- });+ );}- const message = action.payload.message?.trim();+ if (!options.selfIterationEnabled) {+ return toSkippedResult(action.actionId, 'Self iteration is disabled.', startedAt);+ }+ const message = action.payload.message?.trim();if (!message) {- return toSkippedExecutorResult({- actionId: action.actionId,- decision: createNoopDecision('missing skill-management action message'),- detail: 'Missing skill-management action message.',+ return toSkippedResult(+ action.actionId,+ 'Missing skill-management action message.',startedAt,- });+ );}- if (!action.payload.agentId) {- return toSkippedExecutorResult({- actionId: action.actionId,- decision: createNoopDecision('missing skill-management action agentId'),- detail: 'Missing agentId for skill-management action.',+ const agentId = action.payload.agentId;+ if (!agentId) {+ return toSkippedResult(+ action.actionId,+ 'Missing agentId for skill-management action.',startedAt,- });+ );}- const candidateSkills = await resolveSkillDecisionCandidates(options, action.payload.agentId);- 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 ?? []),- ...sameTurnDocumentEvidence,- ...createRecordedSkillIntentEvidence(recordedIntent),- ];- const runnerInput = {- agentId: action.payload.agentId,- ...(candidateSkills.length > 0 ? { candidateSkills } : {}),- ...(evidence.length > 0 ? { evidence } : {}),- feedbackHint: action.payload.feedbackHint,+ const sourceId = idempotencyKey ?? action.actionId;+ const { messageId, topicId } = action.payload;++ const prompt = buildSkillFeedbackPrompt({+ agentId,+ evidence: action.payload.evidence,message,- messageId: action.payload.messageId,reason: action.payload.reason,serializedContext: action.payload.serializedContext,- topicId: action.payload.topicId,- };- const decisionResult = await executeSkillManagementDecision({- decide: options.skillDecisionRunner ?? createSkillDecisionRunner(options),- payload: {- agentId: action.payload.agentId,- ...(candidateSkills.length > 0 ? { candidateSkills } : {}),- ...(evidence.length > 0 ? { evidence } : {}),- feedbackMessage: message,- messageId: action.payload.messageId,- scopeKey: context.scopeKey,- topicId: action.payload.topicId,- turnContext: action.payload.serializedContext,- },- selfIterationEnabled: options.selfIterationEnabled,+ sourceId,+ userId: options.userId,});- if (decisionResult.status === 'skipped') {- return toSkippedExecutorResult({- actionId: action.actionId,- decision: createNoopDecision(decisionResult.reason),- detail: decisionResult.reason,- startedAt,- });- }-- const result = await runSkillManagementAction(runnerInput, options, decisionResult.decision);+ // The run executes under the builtin skill-management slug, so attribute the+ // receipt to the reviewed user agent via `marker.agentId` (the operation's+ // own agentId is the builtin agent).+ const marker: AgentSignalOperationMarker = {+ agentId,+ kind: 'skill',+ sourceId,+ ...(messageId ? { anchorMessageId: messageId, triggerMessageId: messageId } : {}),+ ...(topicId ? { topicId } : {}),+ };++ const dispatch = options.dispatch ?? enqueueSelfIterationRun;+ await dispatch({+ agentId,+ db: options.db,+ marker,+ prompt,+ slug: BUILTIN_AGENT_SLUGS.skillManagement,+ ...(messageId ? { sourceMessageId: messageId } : {}),+ threadTitle: 'Agent Signal Skill',+ ...(topicId ? { topicId } : {}),+ userId: options.userId,+ });- if (result.status === 'applied') {- await markAppliedActionIdempotency(context, idempotencyKey);-- return {- actionId: action.actionId,- attempt: finalizeAttempt(startedAt, 'succeeded'),- detail: result.detail,- output: { decision: result.decision, ...(result.target ? { target: result.target } : {}) },- status: 'applied',- };- }-- if (result.status === 'failed') {- return toExecutorError(- action.actionId,- new Error(result.detail ?? 'Skill-management action failed.'),- startedAt,- );- }+ await markAppliedActionIdempotency(context, idempotencyKey);return {actionId: action.actionId,- attempt: finalizeAttempt(startedAt, 'skipped'),- detail: result.detail,- output: { decision: result.decision },- status: 'skipped',+ attempt: finalizeAttempt(startedAt, 'succeeded'),+ detail: 'Skill write enqueued.',+ status: 'applied',};} catch (error) {return toExecutorError(action.actionId, error, startedAt);@@ -1953,20 +201,15 @@ export const executeSkillManagementAction = async (};/**- * Creates the action handler that writes document-backed skills for skill-domain feedback.+ * Creates the action handler that enqueues async skill writes for skill-domain+ * feedback.** Triggering workflow:** {@link createFeedbackActionPlannerSignalHandler}* -> `action.skill-management.handle`* -> {@link defineSkillManagementActionHandler}- *- * Upstream:- * - {@link createFeedbackActionPlannerSignalHandler}- *- * Downstream:- * - {@link executeSkillManagementAction}- * - {@link SkillManagementDocumentService}+ * -> {@link executeSkillManagementAction}*/export const defineSkillManagementActionHandler = (options: SkillManagementActionHandlerOptions,diff --git a/src/server/services/agentSignal/services/__tests__/receiptService.test.ts b/src/server/services/agentSignal/services/__tests__/receiptService.test.tsindex c200542f9ac..6453ed6fa8c 100644--- a/src/server/services/agentSignal/services/__tests__/receiptService.test.ts+++ b/src/server/services/agentSignal/services/__tests__/receiptService.test.ts@@ -52,102 +52,10 @@ const result = (input: {});describe('projectAgentSignalReceipts', () => {- // Anchoring / trigger projection is kind-agnostic; it is exercised here via a- // skill action because memory receipts are no longer projected synchronously- // (they come from the async memory run's completion path).- it('prefers anchorMessageId over assistantMessageId for receipt anchoring', () => {- const anchoredSource = createSource({- payload: {- agentId: 'agent-1',- anchorMessageId: 'assistant-anchor-1',- assistantMessageId: 'assistant-legacy-1',- topicId: 'topic-1',- },- scope: { topicId: 'topic-1', userId: 'user-1' },- scopeKey: 'topic:topic-1',- sourceId: 'source-anchor-1',- sourceType: 'client.runtime.complete',- timestamp: 1_700_000,- });-- expect(- projectAgentSignalReceipts({- actions: [- action({- actionId: 'action-skill-1',- actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle,- payload: {},- }),- ],- results: [result({ actionId: 'action-skill-1', status: 'applied' })],- source: anchoredSource,- userId: 'user-1',- }),- ).toMatchObject([{ anchorMessageId: 'assistant-anchor-1' }]);- });-- it('falls back to assistantMessageId for legacy receipt anchoring payloads', () => {- expect(- projectAgentSignalReceipts({- actions: [- action({- actionId: 'action-skill-1',- actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle,- payload: {},- }),- ],- results: [result({ actionId: 'action-skill-1', status: 'applied' })],- source,- userId: 'user-1',- }),- ).toMatchObject([{ anchorMessageId: 'assistant-1' }]);- });-- it('projects triggerMessageId and falls back to messageId for legacy trigger payloads', () => {- const triggerSource = createSource({- payload: {- agentId: 'agent-1',- messageId: 'message-legacy-1',- topicId: 'topic-1',- triggerMessageId: 'message-trigger-1',- },- scope: { topicId: 'topic-1', userId: 'user-1' },- scopeKey: 'topic:topic-1',- sourceId: 'source-trigger-1',- sourceType: 'agent.user.message',- timestamp: 1_700_000,- });- const legacyTriggerSource = createSource({- payload: {- agentId: 'agent-1',- messageId: 'message-legacy-1',- topicId: 'topic-1',- },- scope: { topicId: 'topic-1', userId: 'user-1' },- scopeKey: 'topic:topic-1',- sourceId: 'source-trigger-2',- sourceType: 'agent.user.message',- timestamp: 1_700_000,- });-- const project = (projectSource: typeof triggerSource) =>- projectAgentSignalReceipts({- actions: [- action({- actionId: 'action-skill-1',- actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle,- payload: {},- }),- ],- results: [result({ actionId: 'action-skill-1', status: 'applied' })],- source: projectSource,- userId: 'user-1',- });-- expect(project(triggerSource)).toMatchObject([{ triggerMessageId: 'message-trigger-1' }]);- expect(project(legacyTriggerSource)).toMatchObject([{ triggerMessageId: 'message-legacy-1' }]);- });-+ // Same-turn feedback actions (memory + skill) no longer project receipts+ // synchronously here β both run as async execAgent runs and project on their+ // completion path (see buildSelfIterationReceipts). The kind-agnostic+ // anchoring/trigger projection is therefore covered there, not via this path.it('does not project a memory action synchronously (the completion path owns it)', () => {expect(projectAgentSignalReceipts({@@ -165,7 +73,10 @@ describe('projectAgentSignalReceipts', () => {).toEqual([]);});- it('projects applied skill-management results as updated skill receipts', () => {+ it('does not project a skill action synchronously (the completion path owns it)', () => {+ // skillManagement now runs as an async execAgent run, so its skill receipt is+ // projected on the run's completion path (see buildSelfIterationReceipts),+ // not synchronously here β mirroring the memory writer.expect(projectAgentSignalReceipts({actions: [@@ -179,51 +90,7 @@ describe('projectAgentSignalReceipts', () => {source,userId: 'user-1',}),- ).toMatchObject([{ kind: 'skill', status: 'updated', title: 'Skill updated' }]);- });-- it('projects skill target snapshots from action results', () => {- expect(- projectAgentSignalReceipts({- actions: [- action({- actionId: 'action-skill-1',- actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle,- payload: {},- }),- ],- results: [- result({- actionId: 'action-skill-1',- output: {- target: {- agentDocumentId: 'index-agent-document-1',- documentId: 'index-document-1',- id: 'document-1',- summary: 'Review metadata before diff and produce a merge decision.',- title: 'GitHub PR review workflow',- type: 'skill',- },- },- status: 'applied',- }),- ],- source,- userId: 'user-1',- }),- ).toMatchObject([- {- kind: 'skill',- target: {- agentDocumentId: 'index-agent-document-1',- documentId: 'index-document-1',- id: 'document-1',- summary: 'Review metadata before diff and produce a merge decision.',- title: 'GitHub PR review workflow',- type: 'skill',- },- },- ]);+ ).toEqual([]);});it('does not project skipped, failed, procedure, or missing-topic results', () => {diff --git a/src/server/services/agentSignal/services/receiptService.ts b/src/server/services/agentSignal/services/receiptService.tsindex 13a8fa1154f..1f936b84e9e 100644--- a/src/server/services/agentSignal/services/receiptService.ts+++ b/src/server/services/agentSignal/services/receiptService.ts@@ -2,7 +2,6 @@ import type { AgentSignalSource, BaseAction, ExecutorResult } from '@lobechat/agimport { LayersEnum } from '@lobechat/types';import { AGENT_SIGNAL_DEFAULTS } from '../constants';-import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../policies/types';import { redisReceiptStore } from '../store/adapters/redis/receiptStore';import type {ActionPlan,@@ -292,22 +291,14 @@ const getReceiptTarget = (};const toReceiptKind = (- action: BaseAction,+ _action: BaseAction,): Pick<AgentSignalReceipt, 'detail' | 'kind' | 'status' | 'title'> | undefined => {- // Memory receipts are no longer projected synchronously here: the memory- // writer runs as an async execAgent run, so its receipt is projected on the- // completion path from the run's finalState (see selfIteration/completion).- // Projecting one here too would duplicate it β and with a premature, empty- // target, since at this point the write has only been enqueued.- if (action.actionType === AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle) {- return {- detail: 'Improved how this assistant handles similar requests',- kind: 'skill',- status: 'updated',- title: 'Skill updated',- };- }-+ // Memory and skill receipts are no longer projected synchronously here: both+ // the memory writer and the skill-management action now run as async execAgent+ // runs, so their receipts are projected on the completion path from the run's+ // finalState (see selfIteration/completion). Projecting one here too would+ // duplicate it β and with a premature, empty target, since at this point the+ // write has only been enqueued.return;};diff --git a/src/server/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts b/src/server/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.tsindex 6b8444b4973..f351b937289 100644--- a/src/server/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts+++ b/src/server/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts@@ -75,6 +75,7 @@ const SUMMARY_TITLE_BY_KIND: Record<AgentSignalOperationMarker['kind'], string>'nightly-review': 'Nightly self-review completed','self-feedback-intent': 'Self-feedback intent completed','self-reflection': 'Self-reflection completed',+ 'skill': 'Skill write completed',};/**@@ -121,10 +122,10 @@ export const buildSelfIterationReceipts = (userId,} satisfies Partial<AgentSignalReceipt>;- // A single memory write surfaces as just its action receipt β no aggregate- // "review summary" (that is for nightly-review / reflection runs that capture- // ideas across multiple actions).- const includeSummary = marker.kind !== 'memory';+ // A single same-turn memory / skill write surfaces as just its action receipt+ // β no aggregate "review summary" (that is for nightly-review / reflection runs+ // that capture ideas across multiple actions).+ const includeSummary = marker.kind !== 'memory' && marker.kind !== 'skill';const summary: AgentSignalReceipt = {...base,diff --git a/src/server/services/agentSignal/services/selfIteration/dispatch/enqueueSelfIterationRun.ts b/src/server/services/agentSignal/services/selfIteration/dispatch/enqueueSelfIterationRun.tsindex 9e491092d31..5544d0f17d5 100644--- a/src/server/services/agentSignal/services/selfIteration/dispatch/enqueueSelfIterationRun.ts+++ b/src/server/services/agentSignal/services/selfIteration/dispatch/enqueueSelfIterationRun.ts@@ -4,11 +4,12 @@ import { type AgentSignalOperationMarker, RequestTrigger, ThreadType } from '@loimport { ThreadModel } from '@/database/models/thread';import type { LobeChatDatabase } from '@/database/type';-/** The three builtin self-iteration agent slugs an execAgent run can dispatch to. */+/** The builtin self-iteration agent slugs an execAgent run can dispatch to. */export type SelfIterationSlug =| typeof BUILTIN_AGENT_SLUGS.nightlyReview| typeof BUILTIN_AGENT_SLUGS.selfFeedbackIntent- | typeof BUILTIN_AGENT_SLUGS.selfReflection;+ | typeof BUILTIN_AGENT_SLUGS.selfReflection+ | typeof BUILTIN_AGENT_SLUGS.skillManagement;export interface EnqueueSelfIterationRunInput {/** The user agent being reviewed β owns the run, marker, and isolated thread. */diff --git a/src/server/services/toolExecution/serverRuntimes/agentSignalSkillManagement.ts b/src/server/services/toolExecution/serverRuntimes/agentSignalSkillManagement.tsnew file mode 100644index 00000000000..390f3dc64ab--- /dev/null+++ b/src/server/services/toolExecution/serverRuntimes/agentSignalSkillManagement.ts@@ -0,0 +1,41 @@+import {+ AGENT_SIGNAL_SKILL_MANAGEMENT_IDENTIFIER,+ AGENT_SIGNAL_SKILL_MANAGEMENT_TOOL_API_NAMES,+ AgentSignalToolExecutionRuntime,+} from '@lobechat/builtin-tool-agent-signal';++import { createResourceRuntimePrimitives } from '@/server/services/agentSignal/services/selfIteration/tools/runtimePrimitives';+import { SkillManagementDocumentService } from '@/server/services/skillManagement';++import type { ServerRuntimeRegistration } from './types';++/**+ * Registers the same-turn skill-management builtin server runtime, so an+ * `execAgent` run with `plugins: ['agent-signal-skill-management']` can execute+ * its tools. The surface is skill-only (safe managed-skill reads + creates /+ * CAS replaces) β no memory, no proposal/idea recorders. Evidence is embedded in+ * the agent's prompt, so there is no collector.+ */+export const agentSignalSkillManagementRuntime: ServerRuntimeRegistration = {+ factory: (context) => {+ const { agentId, serverDB, userId } = context;+ if (!agentId || !userId || !serverDB) {+ throw new Error('agent-signal-skill-management requires agentId, userId and serverDB');+ }++ const service = createResourceRuntimePrimitives({+ agentId,+ db: serverDB,+ memoryReason: (count) =>+ `Agent Signal skill-management memory candidate from ${count} evidence refs.`,+ skillDocumentService: new SkillManagementDocumentService(serverDB, userId),+ userId,+ });++ return new AgentSignalToolExecutionRuntime({+ apiNames: AGENT_SIGNAL_SKILL_MANAGEMENT_TOOL_API_NAMES,+ service,+ });+ },+ identifier: AGENT_SIGNAL_SKILL_MANAGEMENT_IDENTIFIER,+};diff --git a/src/server/services/toolExecution/serverRuntimes/index.ts b/src/server/services/toolExecution/serverRuntimes/index.tsindex bdf9a29287a..d21375d9262 100644--- a/src/server/services/toolExecution/serverRuntimes/index.ts+++ b/src/server/services/toolExecution/serverRuntimes/index.ts@@ -14,6 +14,7 @@ import { agentManagementRuntime } from './agentManagement';import { agentSignalFeedbackIntentRuntime } from './agentSignalFeedbackIntent';import { agentSignalReflectionRuntime } from './agentSignalReflection';import { agentSignalReviewRuntime } from './agentSignalReview';+import { agentSignalSkillManagementRuntime } from './agentSignalSkillManagement';import { briefRuntime } from './brief';import { calculatorRuntime } from './calculator';import { cloudSandboxRuntime } from './cloudSandbox';@@ -76,6 +77,7 @@ registerRuntimes([webOnboardingRuntime,lobeAgentRuntime,selfFeedbackIntentRuntime,+ agentSignalSkillManagementRuntime,agentSignalReviewRuntime,agentSignalReflectionRuntime,agentSignalFeedbackIntentRuntime,