Skip to content

🤯 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.

✨ feat(app,server,agent-signal,cli): new policy for Skill management running inside of Agent Signal (#14281)

Neko9fff5fccf020
diff --git a/apps/cli/src/commands/agent.test.ts b/apps/cli/src/commands/agent.test.ts
index fbbe232067f..90875920129 100644
--- a/apps/cli/src/commands/agent.test.ts
+++ b/apps/cli/src/commands/agent.test.ts
@@ -39,7 +39,6 @@ const { mockTrpcClient } = vi.hoisted(() => ({
agentSkills: {
createSkill: { mutate: vi.fn() },
deleteSkill: { mutate: vi.fn() },
- promoteSkill: { mutate: vi.fn() },
updateSkill: { mutate: vi.fn() },
},
aiAgent: {
@@ -1036,12 +1035,12 @@ describe('agent command', () => {
.mockResolvedValueOnce([
{
mode: 8,
- name: 'agent-topic',
- path: './lobe/skills/agent-topic',
+ name: 'builtin',
+ path: './lobe/skills/builtin',
type: 'directory',
},
])
- .mockRejectedValueOnce(new Error('Topic ID is required for the agent-topic namespace'));
+ .mockRejectedValueOnce(new Error('Failed to list builtin skills'));
const program = createProgram();
await program.parseAsync([
@@ -1063,12 +1062,10 @@ describe('agent command', () => {
});
expect(mockTrpcClient.agentDocument.listDocumentsByPath.query).toHaveBeenNthCalledWith(2, {
agentId: 'a1',
- path: './lobe/skills/agent-topic',
+ path: './lobe/skills/builtin',
topicId: undefined,
});
- expect(log.warn).toHaveBeenCalledWith(
- './lobe/skills/agent-topic: Topic ID is required for the agent-topic namespace',
- );
+ expect(log.warn).toHaveBeenCalledWith('./lobe/skills/builtin: Failed to list builtin skills');
});
it('should read SKILL.md when cat targets a skill directory alias', async () => {
diff --git a/apps/cli/src/commands/agent/spaceFs.ts b/apps/cli/src/commands/agent/spaceFs.ts
index c34619a7f1f..4935c9a3347 100644
--- a/apps/cli/src/commands/agent/spaceFs.ts
+++ b/apps/cli/src/commands/agent/spaceFs.ts
@@ -14,7 +14,6 @@ const SKILL_FILE_NAME = 'SKILL.md';
const SKILL_NAMESPACE_PREFIXES = {
'agent': './lobe/skills/agent/skills',
- 'agent-topic': './lobe/skills/agent-topic/skills',
'builtin': './lobe/skills/builtin/skills',
'installed-active': './lobe/skills/installed/active/skills',
'installed-all': './lobe/skills/installed/all/skills',
@@ -26,8 +25,6 @@ const FS_PATH_ALIASES = {
'skills': 'agent',
'installed-active': 'installed-active',
'installed-all': 'installed-all',
- 'topic-skills': 'agent-topic',
- 'topic': 'agent-topic',
} as const;
type SkillFsNamespace = keyof typeof SKILL_NAMESPACE_PREFIXES;
@@ -94,7 +91,7 @@ function resolveAgentFsPath(input = 'agent:/'): AgentFsResolvedPath {
if (!target) {
exitWithError(
- `Unknown fs namespace "${aliasMatch[1]}". Use agent, skills, topic-skills, builtin, installed-all, or installed-active.`,
+ `Unknown fs namespace "${aliasMatch[1]}". Use agent, skills, builtin, installed-all, or installed-active.`,
);
}
@@ -156,12 +153,6 @@ function resolveAgentFsPath(input = 'agent:/'): AgentFsResolvedPath {
};
}
-function requireTopicId(namespace: SkillFsNamespace | undefined, topicId?: string) {
- if (namespace === 'agent-topic' && !topicId) {
- exitWithError('--topic-id is required for agent-topic fs paths.');
- }
-}
-
function requireSkillNamespace(resolved: AgentFsResolvedPath): SkillFsNamespace {
if (!resolved.namespace) {
exitWithError(`Expected a skill namespace path, but received "${resolved.path}".`);
@@ -191,8 +182,7 @@ function toDisplayPath(path: string) {
for (const [namespace, prefix] of Object.entries(SKILL_NAMESPACE_PREFIXES) as Array<
[SkillFsNamespace, string]
>) {
- const alias =
- namespace === 'agent' ? 'skills' : namespace === 'agent-topic' ? 'topic-skills' : namespace;
+ const alias = namespace === 'agent' ? 'skills' : namespace;
if (path === prefix) return `${alias}:/`;
if (path.startsWith(`${prefix}/`)) return `${alias}:/${path.slice(prefix.length + 1)}`;
}
@@ -316,7 +306,6 @@ async function getFsNode(client: AgentFsClient, context: AgentFsContext, path: s
async function readFsFile(client: AgentFsClient, context: AgentFsContext, inputPath: string) {
const resolved = resolveAgentFsPath(inputPath);
- requireTopicId(resolved.namespace, context.topicId);
const readPath =
resolved.skillName && !resolved.filePath
@@ -349,7 +338,6 @@ async function writeFsFile(
content: string,
) {
const resolved = resolveAgentFsPath(inputPath);
- requireTopicId(resolved.namespace, context.topicId);
const existing = await getFsNode(
client,
context,
@@ -376,7 +364,6 @@ async function mkdirFsPath(
options?: { recursive?: boolean },
) {
const resolved = resolveAgentFsPath(inputPath);
- requireTopicId(resolved.namespace, context.topicId);
return client.agentDocument.mkdirDocumentByPath.mutate({
agentId: context.agentId,
@@ -393,7 +380,6 @@ async function deleteFsPath(
options?: { force?: boolean; recursive?: boolean },
) {
const resolved = resolveAgentFsPath(inputPath);
- requireTopicId(resolved.namespace, context.topicId);
return client.agentDocument.deleteDocumentByPath.mutate({
agentId: context.agentId,
@@ -414,9 +400,6 @@ async function copyFsPath(
const sourceResolved = resolveAgentFsPath(source);
const destinationResolved = resolveAgentFsPath(destination);
- requireTopicId(sourceResolved.namespace, context.topicId);
- requireTopicId(destinationResolved.namespace, context.topicId);
-
return client.agentDocument.copyDocumentByPath.mutate({
agentId: context.agentId,
force,
@@ -436,9 +419,6 @@ async function renameFsPath(
const sourceResolved = resolveAgentFsPath(source);
const destinationResolved = resolveAgentFsPath(destination);
- requireTopicId(sourceResolved.namespace, context.topicId);
- requireTopicId(destinationResolved.namespace, context.topicId);
-
return client.agentDocument.renameDocumentByPath.mutate({
agentId: context.agentId,
force,
@@ -450,7 +430,6 @@ async function renameFsPath(
async function listTrashFsPath(client: AgentFsClient, context: AgentFsContext, inputPath?: string) {
const resolved = resolveAgentFsPath(inputPath || 'agent:/');
- requireTopicId(resolved.namespace, context.topicId);
return (await client.agentDocument.listTrashDocumentsByPath.query({
agentId: context.agentId,
@@ -465,7 +444,6 @@ async function restoreTrashFsPath(
inputPath: string,
) {
const resolved = resolveAgentFsPath(inputPath);
- requireTopicId(resolved.namespace, context.topicId);
return client.agentDocument.restoreDocumentFromTrashByPath.mutate({
agentId: context.agentId,
@@ -481,7 +459,6 @@ async function deleteTrashFsPath(
options?: { force?: boolean; recursive?: boolean },
) {
const resolved = resolveAgentFsPath(inputPath);
- requireTopicId(resolved.namespace, context.topicId);
return client.agentDocument.deleteDocumentPermanentlyByPath.mutate({
agentId: context.agentId,
@@ -531,7 +508,6 @@ function registerFsCommands(fsCommand: Command) {
.option('-l, --long', 'Use long listing format')
.option('-A, --agent-id <id>', 'Agent ID')
.option('-s, --slug <slug>', 'Agent slug')
- .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
.option('--cursor <cursor>', 'Directory pagination cursor')
.option('-L, --limit <n>', 'Maximum number of entries')
.option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
@@ -552,7 +528,6 @@ function registerFsCommands(fsCommand: Command) {
const client = await getTrpcClient();
const context = await resolveAgentFsContext(client, options);
const resolved = resolveAgentFsPath(inputPath || 'agent:/');
- requireTopicId(resolved.namespace, context.topicId);
const nodes = ((await client.agentDocument.listDocumentsByPath.query({
agentId: context.agentId,
@@ -590,7 +565,6 @@ function registerFsCommands(fsCommand: Command) {
.description('Print a tree view of the VFS')
.option('-A, --agent-id <id>', 'Agent ID')
.option('-s, --slug <slug>', 'Agent slug')
- .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
.action(
async (
inputPath: string | undefined,
@@ -599,7 +573,6 @@ function registerFsCommands(fsCommand: Command) {
const client = await getTrpcClient();
const context = await resolveAgentFsContext(client, options);
const resolved = resolveAgentFsPath(inputPath || 'agent:/');
- requireTopicId(resolved.namespace, context.topicId);
console.log(pc.bold(toDisplayPath(resolved.path)));
const warnings: string[] = [];
@@ -616,7 +589,6 @@ function registerFsCommands(fsCommand: Command) {
.description('Read a VFS file')
.option('-A, --agent-id <id>', 'Agent ID')
.option('-s, --slug <slug>', 'Agent slug')
- .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
.action(
async (inputPath: string, options: { agentId?: string; slug?: string; topicId?: string }) => {
const client = await getTrpcClient();
@@ -631,7 +603,6 @@ function registerFsCommands(fsCommand: Command) {
.description('Show VFS node metadata')
.option('-A, --agent-id <id>', 'Agent ID')
.option('-s, --slug <slug>', 'Agent slug')
- .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
.option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
.action(
async (
@@ -646,7 +617,6 @@ function registerFsCommands(fsCommand: Command) {
const client = await getTrpcClient();
const context = await resolveAgentFsContext(client, options);
const resolved = resolveAgentFsPath(inputPath);
- requireTopicId(resolved.namespace, context.topicId);
const node = await getFsNode(client, context, resolved.path);
@@ -669,7 +639,6 @@ function registerFsCommands(fsCommand: Command) {
.description('Create or update a VFS file')
.option('-A, --agent-id <id>', 'Agent ID')
.option('-s, --slug <slug>', 'Agent slug')
- .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
.option('-c, --content <content>', 'File content')
.option('-F, --content-file <path>', 'Read content from a local file')
.action(
@@ -696,7 +665,6 @@ function registerFsCommands(fsCommand: Command) {
.description('Write content to a VFS file')
.option('-A, --agent-id <id>', 'Agent ID')
.option('-s, --slug <slug>', 'Agent slug')
- .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
.option('-c, --content <content>', 'File content')
.option('-F, --content-file <path>', 'Read content from a local file')
.action(
@@ -723,7 +691,6 @@ function registerFsCommands(fsCommand: Command) {
.description('Create a VFS directory')
.option('-A, --agent-id <id>', 'Agent ID')
.option('-s, --slug <slug>', 'Agent slug')
- .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
.option('-p, --parents', 'Create parent directories as needed')
.action(
async (
@@ -746,7 +713,6 @@ function registerFsCommands(fsCommand: Command) {
.description('Delete a VFS node into trash')
.option('-A, --agent-id <id>', 'Agent ID')
.option('-s, --slug <slug>', 'Agent slug')
- .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
.option('-r, --recursive', 'Recursively delete a directory subtree')
.option('-f, --force', 'Forward force semantics to the VFS delete primitive')
.option('--yes', 'Skip confirmation prompt')
@@ -785,7 +751,6 @@ function registerFsCommands(fsCommand: Command) {
.description('Copy a VFS node')
.option('-A, --agent-id <id>', 'Agent ID')
.option('-s, --slug <slug>', 'Agent slug')
- .option('-t, --topic-id <id>', 'Topic ID for agent-topic source or destination paths')
.option('-f, --force', 'Overwrite the destination if it exists')
.action(
async (
@@ -807,7 +772,6 @@ function registerFsCommands(fsCommand: Command) {
.description('Move or rename a VFS node')
.option('-A, --agent-id <id>', 'Agent ID')
.option('-s, --slug <slug>', 'Agent slug')
- .option('-t, --topic-id <id>', 'Topic ID for agent-topic source or destination paths')
.option('-f, --force', 'Overwrite the destination if it exists')
.action(
async (
@@ -839,7 +803,6 @@ function registerFsCommands(fsCommand: Command) {
.description('List trashed VFS nodes')
.option('-A, --agent-id <id>', 'Agent ID')
.option('-s, --slug <slug>', 'Agent slug')
- .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
.option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
.action(
async (
@@ -875,7 +838,6 @@ function registerFsCommands(fsCommand: Command) {
.description('Restore a soft-deleted VFS node')
.option('-A, --agent-id <id>', 'Agent ID')
.option('-s, --slug <slug>', 'Agent slug')
- .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
.action(
async (inputPath: string, options: { agentId?: string; slug?: string; topicId?: string }) => {
const client = await getTrpcClient();
@@ -892,7 +854,6 @@ function registerFsCommands(fsCommand: Command) {
.description('Permanently delete a trashed VFS node')
.option('-A, --agent-id <id>', 'Agent ID')
.option('-s, --slug <slug>', 'Agent slug')
- .option('-t, --topic-id <id>', 'Topic ID for agent-topic paths')
.option('-r, --recursive', 'Recursively delete a directory subtree')
.option('-f, --force', 'Forward force semantics to the permanent delete primitive')
.option('--yes', 'Skip confirmation prompt')
diff --git a/packages/agent-signal/src/base/types.ts b/packages/agent-signal/src/base/types.ts
index 74058f79aa1..6002bbb1053 100644
--- a/packages/agent-signal/src/base/types.ts
+++ b/packages/agent-signal/src/base/types.ts
@@ -118,6 +118,7 @@ export interface ExecutorResultBase {
attempt: SignalAttempt | AgenticAttempt;
detail?: string;
emittedSignalIds?: string[];
+ output?: Record<string, unknown>;
}
/**
diff --git a/packages/builtin-tool-skill-maintainer/package.json b/packages/builtin-tool-skill-maintainer/package.json
new file mode 100644
index 00000000000..ed5d3ad1ff8
--- /dev/null
+++ b/packages/builtin-tool-skill-maintainer/package.json
@@ -0,0 +1,12 @@
+{
+ "name": "@lobechat/builtin-tool-skill-maintainer",
+ "version": "1.0.0",
+ "private": true,
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "main": "./src/index.ts",
+ "devDependencies": {
+ "@lobechat/types": "workspace:*"
+ }
+}
diff --git a/packages/builtin-tool-skill-maintainer/src/index.ts b/packages/builtin-tool-skill-maintainer/src/index.ts
new file mode 100644
index 00000000000..1cb90a1fdf1
--- /dev/null
+++ b/packages/builtin-tool-skill-maintainer/src/index.ts
@@ -0,0 +1,2 @@
+export { SkillMaintainerManifest } from './manifest';
+export { SkillMaintainerApiName, SkillMaintainerIdentifier } from './types';
diff --git a/packages/builtin-tool-skill-maintainer/src/manifest.test.ts b/packages/builtin-tool-skill-maintainer/src/manifest.test.ts
new file mode 100644
index 00000000000..7f32f4fff9b
--- /dev/null
+++ b/packages/builtin-tool-skill-maintainer/src/manifest.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+
+import { SkillMaintainerManifest } from './manifest';
+
+describe('SkillMaintainerManifest', () => {
+ /**
+ * @example
+ * The hidden skill maintainer exposes the complete v1.2 tool surface.
+ */
+ it('exposes only the v1.2 skill-management tools', () => {
+ expect(SkillMaintainerManifest.api.map((item) => item.name).sort()).toEqual([
+ 'consolidate',
+ 'readSkillFile',
+ 'refine',
+ 'removeSkillFile',
+ 'updateSkill',
+ 'writeSkillFile',
+ ]);
+ });
+
+ /**
+ * @example
+ * Lifecycle and broad exploration APIs stay out of the active manifest.
+ */
+ it('does not expose exploratory or lifecycle mutation tools', () => {
+ const names = SkillMaintainerManifest.api.map((item) => item.name);
+
+ expect(names).not.toContain('createSkill');
+ expect(names).not.toContain('deleteSkill');
+ expect(names).not.toContain('forkSkill');
+ expect(names).not.toContain('mergeSkill');
+ });
+});
diff --git a/packages/builtin-tool-skill-maintainer/src/manifest.ts b/packages/builtin-tool-skill-maintainer/src/manifest.ts
new file mode 100644
index 00000000000..631da613ffc
--- /dev/null
+++ b/packages/builtin-tool-skill-maintainer/src/manifest.ts
@@ -0,0 +1,109 @@
+import type { BuiltinToolManifest } from '@lobechat/types';
+
+import { SkillMaintainerApiName, SkillMaintainerIdentifier } from './types';
+
+const skillRefProperties = {
+ skillRef: { type: 'string' },
+} as const;
+
+const filePathProperties = {
+ path: { type: 'string' },
+ ...skillRefProperties,
+} as const;
+
+/**
+ * System-only builtin manifest for automatic skill maintenance.
+ *
+ * Use when:
+ * - Agent Signal delegates refinement or consolidation to maintainer tools
+ * - A hidden system surface needs merge orchestration APIs
+ *
+ * Expects:
+ * - Calls are made by trusted orchestration code
+ *
+ * Returns:
+ * - A hidden builtin tool manifest with maintainer APIs
+ */
+export const SkillMaintainerManifest: BuiltinToolManifest = {
+ api: [
+ {
+ description: 'Read one package-relative file from a managed skill.',
+ name: SkillMaintainerApiName.readSkillFile,
+ parameters: {
+ properties: filePathProperties,
+ required: ['skillRef', 'path'],
+ type: 'object',
+ },
+ },
+ {
+ description: 'Update one existing package-relative file in a managed skill.',
+ name: SkillMaintainerApiName.updateSkill,
+ parameters: {
+ properties: {
+ content: { type: 'string' },
+ reason: { type: 'string' },
+ ...filePathProperties,
+ },
+ required: ['skillRef', 'path', 'content', 'reason'],
+ type: 'object',
+ },
+ },
+ {
+ description: 'Write one package-relative file in a managed skill.',
+ name: SkillMaintainerApiName.writeSkillFile,
+ parameters: {
+ properties: {
+ content: { type: 'string' },
+ reason: { type: 'string' },
+ ...filePathProperties,
+ },
+ required: ['skillRef', 'path', 'content', 'reason'],
+ type: 'object',
+ },
+ },
+ {
+ description: 'Remove one package-relative file from a managed skill.',
+ name: SkillMaintainerApiName.removeSkillFile,
+ parameters: {
+ properties: {
+ reason: { type: 'string' },
+ ...filePathProperties,
+ },
+ required: ['skillRef', 'path', 'reason'],
+ type: 'object',
+ },
+ },
+ {
+ description: 'Run single-skill refinement for a target skill reference.',
+ name: SkillMaintainerApiName.refine,
+ parameters: {
+ properties: {
+ reason: { type: 'string' },
+ skillRef: { type: 'string' },
+ },
+ required: ['skillRef', 'reason'],
+ type: 'object',
+ },
+ },
+ {
+ description: 'Find and reconcile overlapping skills.',
+ name: SkillMaintainerApiName.consolidate,
+ parameters: {
+ properties: {
+ reason: { type: 'string' },
+ sourceSkillIds: { items: { type: 'string' }, type: 'array' },
+ },
+ required: ['sourceSkillIds'],
+ type: 'object',
+ },
+ },
+ ],
+ identifier: SkillMaintainerIdentifier,
+ meta: {
+ description:
+ 'Run hidden Agent Signal maintenance actions for skill refinement and consolidation.',
+ title: 'Skill Maintainer',
+ },
+ systemRole: 'Maintain skills through Agent Signal. This tool is system-only.',
+ type: 'builtin',
+};
diff --git a/packages/builtin-tool-skill-maintainer/src/types.ts b/packages/builtin-tool-skill-maintainer/src/types.ts
new file mode 100644
index 00000000000..7296a7bd5dc
--- /dev/null
+++ b/packages/builtin-tool-skill-maintainer/src/types.ts
@@ -0,0 +1,12 @@
+/** Stable identifier for the system-only skill maintainer builtin tool. */
+export const SkillMaintainerIdentifier = 'lobe-skill-maintainer';
+
+/** API names exposed by the system-only skill maintainer builtin tool. */
+export const SkillMaintainerApiName = {
+ consolidate: 'consolidate',
+ readSkillFile: 'readSkillFile',
+ refine: 'refine',
+ removeSkillFile: 'removeSkillFile',
+ updateSkill: 'updateSkill',
+ writeSkillFile: 'writeSkillFile',
+} as const;
diff --git a/packages/builtin-tool-skill-maintainer/vitest.config.mts b/packages/builtin-tool-skill-maintainer/vitest.config.mts
new file mode 100644
index 00000000000..4ac6027d578
--- /dev/null
+++ b/packages/builtin-tool-skill-maintainer/vitest.config.mts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'node',
+ },
+});
diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.json
index 2b6d62031fa..19827651454 100644
--- a/packages/builtin-tools/package.json
+++ b/packages/builtin-tools/package.json
@@ -35,6 +35,7 @@
"@lobechat/builtin-tool-notebook": "workspace:*",
"@lobechat/builtin-tool-page-agent": "workspace:*",
"@lobechat/builtin-tool-remote-device": "workspace:*",
+ "@lobechat/builtin-tool-skill-maintainer": "workspace:*",
"@lobechat/builtin-tool-skill-store": "workspace:*",
"@lobechat/builtin-tool-skills": "workspace:*",
"@lobechat/builtin-tool-task": "workspace:*",
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index 4a9b5a73255..587303a0385 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -16,6 +16,7 @@ import { MemoryManifest } from '@lobechat/builtin-tool-memory';
import { MessageManifest } from '@lobechat/builtin-tool-message';
import { PageAgentManifest } from '@lobechat/builtin-tool-page-agent';
import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
+import { SkillMaintainerManifest } from '@lobechat/builtin-tool-skill-maintainer';
import { SkillStoreManifest } from '@lobechat/builtin-tool-skill-store';
import { SkillsManifest } from '@lobechat/builtin-tool-skills';
import { TaskManifest } from '@lobechat/builtin-tool-task';
@@ -109,6 +110,13 @@ export const builtinTools: LobeBuiltinTool[] = [
manifest: SkillStoreManifest,
type: 'builtin',
},
+ {
+ discoverable: false,
+ hidden: true,
+ identifier: SkillMaintainerManifest.identifier,
+ manifest: SkillMaintainerManifest,
+ type: 'builtin',
+ },
{
discoverable: isDesktop,
hidden: true,
diff --git a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
index e35154258e0..eabdff04655 100644
--- a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
+++ b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
@@ -129,8 +129,8 @@ describe('AgentDocumentModel', () => {
expect(countAfter.length).toBe(countBefore.length);
});
- it('should reject associating a document when a live sibling already owns the same path', async () => {
- await agentDocumentModel.create(agentId, 'associated.md', 'managed');
+ it('should allow associating documents when a live sibling already owns the same filename', async () => {
+ const existing = await agentDocumentModel.create(agentId, 'associated.md', 'managed');
const [doc] = await serverDB
.insert(documents)
.values({
@@ -146,9 +146,15 @@ describe('AgentDocumentModel', () => {
})
.returning();
- await expect(
- agentDocumentModel.associate({ agentId, documentId: doc!.id }),
- ).rejects.toThrow();
+ const associated = await agentDocumentModel.associate({ agentId, documentId: doc!.id });
+ const matched = await agentDocumentModel.listByParentAndFilename(
+ agentId,
+ null,
+ 'associated.md',
+ );
+
+ expect(associated.id).toBeDefined();
+ expect(matched.map((item) => item.documentId)).toEqual([existing.documentId, doc!.id]);
});
});
@@ -195,10 +201,22 @@ describe('AgentDocumentModel', () => {
expect(result.accessPublic).toBe(0);
});
- it('should reject duplicate live siblings at the database boundary', async () => {
- await agentDocumentModel.create(agentId, 'duplicate.md', 'first');
+ it('should allow duplicate live sibling filenames at the database boundary', async () => {
+ const first = await agentDocumentModel.create(agentId, 'duplicate.md', 'first', {
+ createdAt: new Date('2024-01-01T00:00:00.000Z'),
+ });
+ const second = await agentDocumentModel.create(agentId, 'duplicate.md', 'second', {
+ createdAt: new Date('2024-01-02T00:00:00.000Z'),
+ });
+
+ const matched = await agentDocumentModel.listByParentAndFilename(
+ agentId,
+ null,
+ 'duplicate.md',
+ );
- await expect(agentDocumentModel.create(agentId, 'duplicate.md', 'second')).rejects.toThrow();
+ expect(second.documentId).not.toBe(first.documentId);
+ expect(matched.map((item) => item.documentId)).toEqual([first.documentId, second.documentId]);
});
it('should allow different agents to use the same root filename', async () => {
@@ -221,13 +239,11 @@ describe('AgentDocumentModel', () => {
expect(second.content).toBe('second');
});
- it('should allow callers to opt out of sibling uniqueness for managed mount documents', async () => {
+ it('should allow managed mount documents to reuse storage filenames', async () => {
const first = await agentDocumentModel.create(agentId, 'skills', '', {
- uniqueSibling: false,
metadata: { mount: { namespace: 'topic', role: 'root' } },
});
const second = await agentDocumentModel.create(agentId, 'skills', '', {
- uniqueSibling: false,
metadata: { mount: { namespace: 'agent', role: 'root' } },
});
@@ -396,22 +412,31 @@ describe('AgentDocumentModel', () => {
expect(doc?.source).toBe(`agent-document://${agentId}/${encodeURIComponent('new.md')}`);
});
- it('should reject moving a document over an existing live sibling path', async () => {
+ it('should allow moving a document over an existing live sibling filename', async () => {
const folder = await agentDocumentModel.create(agentId, 'move-folder', '', {
fileType: DOCUMENT_FOLDER_TYPE,
title: 'move-folder',
});
const source = await agentDocumentModel.create(agentId, 'source.md', 'source');
- await agentDocumentModel.create(agentId, 'target.md', 'target', {
+ const target = await agentDocumentModel.create(agentId, 'target.md', 'target', {
parentId: folder.documentId,
});
- await expect(
- agentDocumentModel.movePath(source.id, {
- filename: 'target.md',
- parentId: folder.documentId,
- }),
- ).rejects.toThrow();
+ const moved = await agentDocumentModel.movePath(source.id, {
+ filename: 'target.md',
+ parentId: folder.documentId,
+ });
+ const matched = await agentDocumentModel.listByParentAndFilename(
+ agentId,
+ folder.documentId,
+ 'target.md',
+ );
+
+ expect(moved?.id).toBe(source.id);
+ expect(matched.map((item) => item.documentId)).toEqual([
+ source.documentId,
+ target.documentId,
+ ]);
});
it('should copy into a new record and keep policy/template metadata', async () => {
@@ -610,13 +635,20 @@ describe('AgentDocumentModel', () => {
expect(rawDoc).toBeDefined();
});
- it('should reject restoring a deleted document over an existing live sibling path', async () => {
+ it('should restore a deleted document even when a live sibling has the same filename', async () => {
const first = await agentDocumentModel.create(agentId, 'restore-conflict.md', 'first');
await agentDocumentModel.delete(first.id, 'replace');
- await agentDocumentModel.create(agentId, 'restore-conflict.md', 'second');
+ const second = await agentDocumentModel.create(agentId, 'restore-conflict.md', 'second');
+
+ await agentDocumentModel.restore(first.id);
+ const matched = await agentDocumentModel.listByParentAndFilename(
+ agentId,
+ null,
+ 'restore-conflict.md',
+ );
- await expect(agentDocumentModel.restore(first.id)).rejects.toThrow();
+ expect(matched.map((item) => item.documentId)).toEqual([first.documentId, second.documentId]);
});
it('should return empty string from getAgentContext when no loadable docs exist', async () => {
diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.ts
index c87834649b5..a8cc9c3db14 100644
--- a/packages/database/src/models/agentDocuments/agentDocument.ts
+++ b/packages/database/src/models/agentDocuments/agentDocument.ts
@@ -1,4 +1,4 @@
-import { and, desc, eq, inArray, isNotNull, isNull, ne } from 'drizzle-orm';
+import { and, asc, desc, eq, inArray, isNotNull, isNull } from 'drizzle-orm';
import type { DocumentItem, NewAgentDocument, NewDocument } from '../../schemas';
import { agentDocuments, documents } from '../../schemas';
@@ -36,23 +36,6 @@ interface AgentDocumentQueryOptions {
limit?: number;
}
-/**
- * Options for runtime VFS sibling uniqueness checks.
- */
-interface AgentDocumentSiblingUniquenessOptions {
- /**
- * Whether to enforce one live ordinary document per `agentId + parentId + filename`.
- *
- * @default true
- *
- * NOTICE:
- * Set this to `false` only for managed mount documents that are not resolved through the
- * ordinary document VFS tree. Managed mounts can reuse backing storage names such as `skills`
- * while exposing distinct mounted namespaces.
- */
- uniqueSibling?: boolean;
-}
-
export class AgentDocumentModel {
private userId: string;
private db: LobeChatDatabase;
@@ -121,52 +104,6 @@ export class AgentDocumentModel {
return [isNull(agentDocuments.deletedAt)];
}
- /**
- * Guards the agent-visible VFS sibling invariant before writes.
- *
- * Runtime enforcement is required for now because `agentId`/`deletedAt` live on `agent_documents`
- * while `parentId`/`filename` live on `documents`.
- */
- private async assertNoLiveSiblingConflict(
- db: Pick<LobeChatDatabase, 'select'>,
- params: {
- agentId: string;
- excludeAgentDocumentId?: string;
- excludeDocumentId?: string;
- filename: string;
- parentId: string | null;
- },
- ) {
- const excludeAgentDocument = params.excludeAgentDocumentId
- ? ne(agentDocuments.id, params.excludeAgentDocumentId)
- : undefined;
- const excludeDocument = params.excludeDocumentId
- ? ne(agentDocuments.documentId, params.excludeDocumentId)
- : undefined;
-
- // TODO: Move this extra conflict query to a schema-level invariant when VFS path ownership fields live on one table.
- const [conflict] = await db
- .select({ id: agentDocuments.id })
- .from(agentDocuments)
- .innerJoin(documents, eq(agentDocuments.documentId, documents.id))
- .where(
- and(
- eq(agentDocuments.userId, this.userId),
- eq(agentDocuments.agentId, params.agentId),
- eq(documents.filename, params.filename),
- params.parentId ? eq(documents.parentId, params.parentId) : isNull(documents.parentId),
- isNull(agentDocuments.deletedAt),
- ...(excludeAgentDocument ? [excludeAgentDocument] : []),
- ...(excludeDocument ? [excludeDocument] : []),
- ),
- )
- .limit(1);
-
- if (conflict) {
- throw new Error(`Agent document sibling already exists: ${params.filename}`);
- }
- }
-
private normalizeListOffset(cursor?: string): number {
if (!cursor) return 0;
@@ -196,7 +133,7 @@ export class AgentDocumentModel {
...this.buildDeletedAtFilters(options),
),
)
- .orderBy(desc(agentDocuments.updatedAt));
+ .orderBy(asc(agentDocuments.createdAt), asc(agentDocuments.id));
return results.map(({ settings, doc }) => this.toAgentDocument(settings, doc));
}
@@ -210,22 +147,18 @@ export class AgentDocumentModel {
*
* Expects:
* - `documentId` belongs to the current user.
- * - `uniqueSibling` defaults to `true` for ordinary VFS documents.
+ * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately.
*
* Returns:
* - The inserted agent document binding id, or an empty id when the source document is missing.
*
- * NOTICE:
- * Pass `uniqueSibling: false` only for managed mount documents whose visible path is resolved by
- * the mount provider instead of the ordinary `parentId + filename` VFS tree.
*/
async associate(params: {
agentId: string;
documentId: string;
- uniqueSibling?: boolean;
policyLoad?: PolicyLoad;
}): Promise<{ id: string }> {
- const { agentId, documentId, uniqueSibling = true, policyLoad } = params;
+ const { agentId, documentId, policyLoad } = params;
return this.db.transaction(async (trx) => {
const [doc] = await trx
@@ -236,15 +169,6 @@ export class AgentDocumentModel {
if (!doc) return { id: '' };
- if (uniqueSibling) {
- await this.assertNoLiveSiblingConflict(trx, {
- agentId,
- excludeDocumentId: documentId,
- filename: doc.filename ?? '',
- parentId: doc.parentId ?? null,
- });
- }
-
const [result] = await trx
.insert(agentDocuments)
.values({
@@ -280,14 +204,11 @@ export class AgentDocumentModel {
*
* Expects:
* - `filename` is a single VFS segment supplied by the caller.
- * - `uniqueSibling` defaults to `true` for ordinary VFS documents.
+ * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately.
*
* Returns:
* - The created agent document with joined document content and metadata.
*
- * NOTICE:
- * Pass `uniqueSibling: false` only for managed mount documents whose storage filename can
- * intentionally collide with ordinary-looking names outside the ordinary VFS resolver.
*/
async create(
agentId: string,
@@ -306,12 +227,11 @@ export class AgentDocumentModel {
templateId?: string;
title?: string;
updatedAt?: Date;
- } & AgentDocumentSiblingUniquenessOptions,
+ },
): Promise<AgentDocument> {
const {
createdAt,
editorData,
- uniqueSibling = true,
fileType = 'agent/document',
loadPosition,
loadRules,
@@ -329,14 +249,6 @@ export class AgentDocumentModel {
const normalizedPolicy = normalizePolicy(loadPosition, loadRules, policy);
return this.db.transaction(async (trx) => {
- if (uniqueSibling) {
- await this.assertNoLiveSiblingConflict(trx, {
- agentId,
- filename,
- parentId: parentId ?? null,
- });
- }
-
const documentPayload: NewDocument = {
content,
createdAt,
@@ -480,20 +392,13 @@ export class AgentDocumentModel {
*
* Expects:
* - `newTitle` is a human-readable title that can be normalized into a filename.
- * - `uniqueSibling` defaults to `true` for ordinary VFS documents.
+ * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately.
*
* Returns:
* - The renamed agent document, or `undefined` when the binding is not visible.
*
- * NOTICE:
- * Pass `uniqueSibling: false` only for managed mount documents whose provider owns collision
- * handling outside the ordinary document VFS tree.
*/
- async rename(
- documentId: string,
- newTitle: string,
- options: AgentDocumentSiblingUniquenessOptions = {},
- ): Promise<AgentDocument | undefined> {
+ async rename(documentId: string, newTitle: string): Promise<AgentDocument | undefined> {
const existing = await this.findById(documentId);
if (!existing) return undefined;
@@ -502,18 +407,8 @@ export class AgentDocumentModel {
const filename = buildDocumentFilename(title);
const source = `agent-document://${existing.agentId}/${encodeURIComponent(filename)}`;
- const { uniqueSibling = true } = options;
await this.db.transaction(async (trx) => {
- if (uniqueSibling) {
- await this.assertNoLiveSiblingConflict(trx, {
- agentId: existing.agentId,
- excludeAgentDocumentId: existing.id,
- filename,
- parentId: existing.parentId,
- });
- }
-
await trx
.update(documents)
.set({
@@ -537,18 +432,15 @@ export class AgentDocumentModel {
* Expects:
* - `filename` is already validated as a single VFS path segment
* - `parentId` points to a document row owned by the same user, or `null` for root
- * - `uniqueSibling` defaults to `true` for ordinary VFS documents
+ * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately
*
* Returns:
* - The same agent document binding after the backing document row is moved
*
- * NOTICE:
- * Pass `uniqueSibling: false` only for managed mount documents whose provider owns collision
- * handling outside the ordinary document VFS tree.
*/
async movePath(
documentId: string,
- params: { filename: string; parentId: string | null } & AgentDocumentSiblingUniquenessOptions,
+ params: { filename: string; parentId: string | null },
): Promise<AgentDocument | undefined> {
const existing = await this.findById(documentId);
if (!existing) return undefined;
@@ -557,18 +449,8 @@ export class AgentDocumentModel {
if (!filename) return existing;
const source = `agent-document://${existing.agentId}/${encodeURIComponent(filename)}`;
- const { uniqueSibling = true } = params;
await this.db.transaction(async (trx) => {
- if (uniqueSibling) {
- await this.assertNoLiveSiblingConflict(trx, {
- agentId: existing.agentId,
- excludeAgentDocumentId: existing.id,
- filename,
- parentId: params.parentId,
- });
- }
-
await trx
.update(documents)
.set({
@@ -671,14 +553,11 @@ export class AgentDocumentModel {
*
* Expects:
* - `filename` addresses the current agent's ordinary filename lookup.
- * - `uniqueSibling` is forwarded only to the create path and defaults to `true` there.
+ * - Duplicate filenames are allowed; the first matching filename is the oldest live binding.
*
* Returns:
* - The updated or created agent document.
*
- * NOTICE:
- * Pass `uniqueSibling: false` only when the create path is creating managed mount documents
- * whose visible uniqueness is enforced by a provider-specific resolver.
*/
async upsert(
agentId: string,
@@ -694,12 +573,11 @@ export class AgentDocumentModel {
policyLoad?: PolicyLoad;
templateId?: string;
updatedAt?: Date;
- } & AgentDocumentSiblingUniquenessOptions,
+ },
): Promise<AgentDocument> {
const {
createdAt,
editorData,
- uniqueSibling,
loadPosition,
loadRules,
metadata,
@@ -734,7 +612,6 @@ export class AgentDocumentModel {
return this.create(agentId, filename, content, {
createdAt,
editorData,
- uniqueSibling,
loadPosition,
loadRules,
metadata,
@@ -854,7 +731,7 @@ export class AgentDocumentModel {
...this.buildDeletedAtFilters(options),
),
)
- .orderBy(desc(agentDocuments.updatedAt))
+ .orderBy(asc(agentDocuments.createdAt), asc(agentDocuments.id))
.limit(1);
if (!result) return undefined;
@@ -881,7 +758,7 @@ export class AgentDocumentModel {
...this.buildDeletedAtFilters(options),
),
)
- .orderBy(desc(agentDocuments.updatedAt))
+ .orderBy(asc(agentDocuments.createdAt), asc(agentDocuments.id))
.limit(1);
if (!result) return undefined;
@@ -893,14 +770,14 @@ export class AgentDocumentModel {
* Lists agent document bindings that share one tree segment.
*
* Use when:
- * - VFS callers need to reject ambiguous sibling paths before create, write, or restore
+ * - VFS callers need to choose the visible entry for a path segment
* - Migration checks need to detect duplicate `parentId + filename` rows
*
* Expects:
* - `parentId` is the canonical document row parent id, not the agent document id
*
* Returns:
- * - Matching bindings ordered newest first, optionally capped for conflict probes
+ * - Matching bindings ordered oldest first so duplicate filename resolution is deterministic
*/
async listByParentAndFilename(
agentId: string,
@@ -921,7 +798,7 @@ export class AgentDocumentModel {
...this.buildDeletedAtFilters(options),
),
)
- .orderBy(desc(agentDocuments.updatedAt))
+ .orderBy(asc(agentDocuments.createdAt), asc(agentDocuments.id))
.limit(options?.limit ?? 9999)
.offset(this.normalizeListOffset(options?.cursor));
@@ -970,7 +847,7 @@ export class AgentDocumentModel {
...this.buildDeletedAtFilters(options),
),
)
- .orderBy(desc(agentDocuments.updatedAt))
+ .orderBy(asc(agentDocuments.createdAt), asc(agentDocuments.id))
.limit(options?.limit ?? 9999)
.offset(this.normalizeListOffset(options?.cursor));
@@ -1080,34 +957,18 @@ export class AgentDocumentModel {
*
* Expects:
* - `documentId` may refer to a deleted binding owned by the current user.
- * - `uniqueSibling` defaults to `true` for ordinary VFS documents.
+ * - Duplicate filenames are allowed; path-style callers resolve visible duplicates separately.
*
* Returns:
* - Nothing; missing bindings are ignored.
*
- * NOTICE:
- * Pass `uniqueSibling: false` only for managed mount documents whose provider owns restore
- * collision handling outside the ordinary document VFS tree.
*/
- async restore(
- documentId: string,
- options: AgentDocumentSiblingUniquenessOptions = {},
- ): Promise<void> {
+ async restore(documentId: string): Promise<void> {
const existing = await this.findByIdWithOptions(documentId, { includeDeleted: true });
if (!existing) return;
- const { uniqueSibling = true } = options;
await this.db.transaction(async (trx) => {
- if (uniqueSibling) {
- await this.assertNoLiveSiblingConflict(trx, {
- agentId: existing.agentId,
- excludeAgentDocumentId: existing.id,
- filename: existing.filename,
- parentId: existing.parentId,
- });
- }
-
await trx
.update(agentDocuments)
.set({
diff --git a/packages/prompts/src/agents/agentSkillManager.ts b/packages/prompts/src/agents/agentSkillManager.ts
new file mode 100644
index 00000000000..c6edb60502d
--- /dev/null
+++ b/packages/prompts/src/agents/agentSkillManager.ts
@@ -0,0 +1,33 @@
+import {
+ AGENT_SKILL_CONSOLIDATE_SYSTEM_ROLE,
+ AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE,
+ AGENT_SKILL_REFINE_SYSTEM_ROLE,
+} from '../prompts/agentSkillManager';
+
+/**
+ * Agent definitions used by Agent Signal skill-management workers.
+ *
+ * Use when:
+ * - Registering small agents that decide, refine, or consolidate skills
+ * - Looking up stable identifiers for skill-management prompts
+ *
+ * Expects:
+ * - Prompt modules expose strict JSON system roles
+ *
+ * Returns:
+ * - Immutable agent identifiers and system roles
+ */
+export const agentSkillManagerAgents = {
+ decision: {
+ identifier: 'agent-skill-manager-decision',
+ systemRole: AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE,
+ },
+ consolidate: {
+ identifier: 'agent-skill-manager-consolidate',
+ systemRole: AGENT_SKILL_CONSOLIDATE_SYSTEM_ROLE,
+ },
+ refine: {
+ identifier: 'agent-skill-manager-refine',
+ systemRole: AGENT_SKILL_REFINE_SYSTEM_ROLE,
+ },
+} as const;
diff --git a/packages/prompts/src/agents/index.ts b/packages/prompts/src/agents/index.ts
index 1d16e230c8e..9a6ae87d44d 100644
--- a/packages/prompts/src/agents/index.ts
+++ b/packages/prompts/src/agents/index.ts
@@ -1,2 +1,3 @@
+export * from './agentSkillManager';
export * from './pageContentContext';
export * from './pageSelectionContext';
diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/index.ts b/packages/prompts/src/prompts/agentSignal/analyzeIntent/index.ts
index 5391949f7d2..df0c54b4422 100644
--- a/packages/prompts/src/prompts/agentSignal/analyzeIntent/index.ts
+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/index.ts
@@ -1,3 +1,4 @@
+export * from '../../agentSkillManager';
export * from './feedbackSatisfaction';
export * from './gate';
export * from './planMemory';
diff --git a/packages/prompts/src/prompts/agentSkillManager/consolidate.ts b/packages/prompts/src/prompts/agentSkillManager/consolidate.ts
new file mode 100644
index 00000000000..cd56320ffa0
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSkillManager/consolidate.ts
@@ -0,0 +1,69 @@
+/**
+ * Input used by the focused skill consolidation prompt.
+ */
+export interface AgentSkillConsolidatePromptInput {
+ /** Reason the source skills should be consolidated. */
+ reason: string;
+ /** Overlapping skills that should be reconciled. */
+ sourceSkills: Array<{
+ content: string;
+ id: string;
+ metadata: Record<string, unknown>;
+ resourceTreeSummary?: string;
+ }>;
+ /** Optional existing skill to receive the consolidated result. */
+ targetSkill?: {
+ content: string;
+ id: string;
+ metadata: Record<string, unknown>;
+ };
+}
+
+/**
+ * System role for consolidating overlapping skills.
+ *
+ * Use when:
+ * - Agent Signal found duplicate or overlapping skills
+ * - A maintainer should produce focused file operations for one consolidated skill
+ *
+ * Expects:
+ * - Multiple source skills and an optional target skill
+ *
+ * Returns:
+ * - A strict JSON-only instruction contract for the model
+ */
+export const AGENT_SKILL_CONSOLIDATE_SYSTEM_ROLE = `You are a focused skill consolidation agent.
+
+Consolidate multiple overlapping skills into one better skill package.
+Return exactly one minified JSON object and nothing else.
+
+Valid output:
+{"operations":[{"name":"updateSkill"|"writeSkillFile"|"removeSkillFile","arguments":{}}],"proposedLifecycleActions":[{"action":"archive"|"promote"|"fork"|"delete","skillRef":"skill-id","reason":"short reason"}],"reason":"short reason","confidence":0.0}
+
+Allowed operation names:
+- "updateSkill": replace or update an existing package-relative skill file.
+- "writeSkillFile": create or overwrite an additional package-relative skill file.
+- "removeSkillFile": remove an obsolete package-relative skill file.
+
+Use proposedLifecycleActions only for human review.
+Never apply delete, archive, promote, or fork automatically.
+Do not expose broad exploration tools.
+Preserve concrete procedures, triggers, pitfalls, and verification steps.
+Do not invent unsupported process steps.`;
+
+/**
+ * Builds the user prompt for a multi-skill consolidation pass.
+ *
+ * Use when:
+ * - Several skills overlap and should be reconciled
+ * - The result will be applied through skill management tools
+ *
+ * Expects:
+ * - Source skills include their current content and metadata
+ *
+ * Returns:
+ * - A compact prompt containing serialized consolidation context
+ */
+export const createAgentSkillConsolidatePrompt = (input: AgentSkillConsolidatePromptInput) => {
+ return `Consolidate these skills.\ninput=${JSON.stringify(input)}`;
+};
diff --git a/packages/prompts/src/prompts/agentSkillManager/decision.test.ts b/packages/prompts/src/prompts/agentSkillManager/decision.test.ts
new file mode 100644
index 00000000000..f55dfe1d01b
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSkillManager/decision.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from 'vitest';
+
+import { AGENT_SKILL_CONSOLIDATE_SYSTEM_ROLE } from './consolidate';
+import {
+ AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE,
+ createAgentSkillManagerDecisionPrompt,
+} from './decision';
+import { AGENT_SKILL_REFINE_SYSTEM_ROLE as REFINE_SYSTEM_ROLE } from './refine';
+
+describe('agentSkillManager decision prompt', () => {
+ it('requires strict JSON and exposes the four actions', () => {
+ expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).toContain('create');
+ expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).toContain('refine');
+ expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).toContain('consolidate');
+ expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).toContain('noop');
+ expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).toContain('Do not wrap the JSON');
+ expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).toContain('candidateSkills[].id');
+ expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).toContain('managed skill package names');
+ });
+
+ it('serializes feedback context into the user prompt', () => {
+ const prompt = createAgentSkillManagerDecisionPrompt({
+ agentId: 'agent-1',
+ candidateSkills: [{ id: 'skill-1', name: 'Review Checklist', scope: 'agent' }],
+ evidence: [{ cue: 'reusable', excerpt: 'This should become a reusable checklist.' }],
+ feedbackMessage: 'This should become a reusable checklist.',
+ topicId: 'topic-1',
+ turnContext: 'The assistant produced a five-step code review workflow.',
+ });
+
+ expect(prompt).toContain('"agentId":"agent-1"');
+ expect(prompt).toContain('"topicId":"topic-1"');
+ expect(prompt).toContain('Review Checklist');
+ });
+
+ /**
+ * @example
+ * Decision prompts may choose `create`, but must not expose lifecycle tools.
+ */
+ it('limits decisions to the v1.2 action set', () => {
+ expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).toContain('"create"');
+ expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).toContain('"refine"');
+ expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).toContain('"consolidate"');
+ expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).toContain('"noop"');
+ expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).not.toContain('deleteSkill');
+ expect(AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE).not.toContain('mergeSkill');
+ });
+
+ /**
+ * @example
+ * Refinement applies focused file operations instead of patch/rewrite modes.
+ */
+ it('limits refine output to focused v1.2 file operations', () => {
+ expect(REFINE_SYSTEM_ROLE).toContain('updateSkill');
+ expect(REFINE_SYSTEM_ROLE).toContain('writeSkillFile');
+ expect(REFINE_SYSTEM_ROLE).toContain('removeSkillFile');
+ expect(REFINE_SYSTEM_ROLE).toContain('proposedLifecycleActions');
+ expect(REFINE_SYSTEM_ROLE).not.toContain('deleteSkill');
+ expect(REFINE_SYSTEM_ROLE).not.toContain('patchSkill');
+ expect(REFINE_SYSTEM_ROLE).not.toContain('rewriteSkillFile');
+ });
+
+ /**
+ * @example
+ * Consolidation can propose lifecycle follow-up, but cannot apply it.
+ */
+ it('limits consolidate output to file operations and human lifecycle proposals', () => {
+ expect(AGENT_SKILL_CONSOLIDATE_SYSTEM_ROLE).toContain('proposedLifecycleActions');
+ expect(AGENT_SKILL_CONSOLIDATE_SYSTEM_ROLE).toContain('updateSkill');
+ expect(AGENT_SKILL_CONSOLIDATE_SYSTEM_ROLE).toContain('writeSkillFile');
+ expect(AGENT_SKILL_CONSOLIDATE_SYSTEM_ROLE).toContain('removeSkillFile');
+ expect(AGENT_SKILL_CONSOLIDATE_SYSTEM_ROLE).not.toContain('mergeSkill');
+ expect(AGENT_SKILL_CONSOLIDATE_SYSTEM_ROLE).not.toContain('deleteSkill');
+ });
+});
diff --git a/packages/prompts/src/prompts/agentSkillManager/decision.ts b/packages/prompts/src/prompts/agentSkillManager/decision.ts
new file mode 100644
index 00000000000..c584c16d9c2
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSkillManager/decision.ts
@@ -0,0 +1,79 @@
+/**
+ * Input used to decide how feedback should affect agent skills.
+ */
+export interface AgentSkillManagerDecisionPromptInput {
+ /** Agent that received the feedback. */
+ agentId: string;
+ /** Skills that may already satisfy or overlap with the feedback. */
+ candidateSkills?: Array<{
+ id: string;
+ name: string;
+ scope: 'agent' | 'builtin' | 'installed';
+ }>;
+ /** Evidence extracted from feedback and nearby turns. */
+ evidence: Array<{ cue: string; excerpt: string }>;
+ /** Original user feedback message. */
+ feedbackMessage: string;
+ /** Optional topic context when feedback happened inside a topic. */
+ topicId?: string;
+ /** Optional summary of the relevant assistant turn. */
+ turnContext?: string;
+}
+
+/**
+ * System role for the skill-management decision agent.
+ *
+ * Use when:
+ * - Agent Signal routes feedback into the skill domain
+ * - A small agent must choose create, refine, consolidate, or noop
+ *
+ * Expects:
+ * - The caller provides feedback context in the paired user prompt
+ *
+ * Returns:
+ * - A strict JSON-only instruction contract for the model
+ */
+export const AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE = `You are the Agent Signal skill-management decision agent.
+
+You are not chatting with the user.
+You decide whether feedback routed to the "skill" domain should create, refine, consolidate, or no-op.
+You must output exactly one minified JSON object and nothing else.
+Do not wrap the JSON in markdown fences.
+
+Valid actions:
+- "create": create a new agent-level skill from reusable procedural feedback.
+- "refine": improve one existing skill.
+- "consolidate": merge or reconcile multiple overlapping skills.
+- "noop": do not create or update a skill.
+
+Rules:
+- Create only when the feedback contains a reusable procedure and enough context.
+- Refine when one existing skill is clearly the target.
+- Consolidate when multiple skills overlap.
+- When candidateSkills are provided, targetSkillIds must be selected from candidateSkills[].id.
+- targetSkillIds are managed skill package names, not document ids or display names.
+- No-op for generic praise, style preferences, memory-like facts, or insufficient context.
+- Prefer patch/refine over duplicate creation.
+- Agent-level managed skills are agent documents, not agent_skills rows.
+
+Return exactly:
+{"action":"create"|"refine"|"consolidate"|"noop","confidence":0.0,"reason":"short reason","targetSkillIds":[],"requiredReads":[]}`;
+
+/**
+ * Builds the user prompt for the skill-management decision agent.
+ *
+ * Use when:
+ * - Passing normalized feedback context into the decision agent
+ * - Preserving candidate skill and evidence fields as JSON
+ *
+ * Expects:
+ * - Input is already filtered to skill-domain feedback
+ *
+ * Returns:
+ * - A compact prompt containing serialized decision context
+ */
+export const createAgentSkillManagerDecisionPrompt = (
+ input: AgentSkillManagerDecisionPromptInput,
+) => {
+ return `Decide the skill-management action for this feedback.\ninput=${JSON.stringify(input)}`;
+};
diff --git a/packages/prompts/src/prompts/agentSkillManager/index.ts b/packages/prompts/src/prompts/agentSkillManager/index.ts
new file mode 100644
index 00000000000..813cbe75e01
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSkillManager/index.ts
@@ -0,0 +1,3 @@
+export * from './consolidate';
+export * from './decision';
+export * from './refine';
diff --git a/packages/prompts/src/prompts/agentSkillManager/refine.ts b/packages/prompts/src/prompts/agentSkillManager/refine.ts
new file mode 100644
index 00000000000..5d4ed98937a
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSkillManager/refine.ts
@@ -0,0 +1,63 @@
+/**
+ * Input used by the focused skill refinement prompt.
+ */
+export interface AgentSkillRefinePromptInput {
+ /** Reason the skill should be refined. */
+ reason: string;
+ /** Optional package tree summary for adjacent resources. */
+ resourceTreeSummary?: string;
+ /** Optional Agent Signal context that motivated the refinement. */
+ signalContext?: Record<string, unknown>;
+ /** Current skill content to improve. */
+ skillContent: string;
+ /** Current skill metadata to patch when needed. */
+ skillMetadata: Record<string, unknown>;
+}
+
+/**
+ * System role for improving one existing skill.
+ *
+ * Use when:
+ * - Agent Signal selected one target skill for refinement
+ * - The maintainer should choose focused v1.2 file operations
+ *
+ * Expects:
+ * - One skill's content and metadata
+ *
+ * Returns:
+ * - A strict JSON-only instruction contract for the model
+ */
+export const AGENT_SKILL_REFINE_SYSTEM_ROLE = `You are a focused skill refinement agent.
+
+Improve one skill only.
+Return exactly one minified JSON object and nothing else.
+
+Valid output:
+{"operations":[{"name":"updateSkill"|"writeSkillFile"|"removeSkillFile","arguments":{}}],"proposedLifecycleActions":[],"reason":"short reason","confidence":0.0}
+
+Allowed operation names:
+- "updateSkill": replace or update an existing package-relative skill file.
+- "writeSkillFile": create or overwrite an additional package-relative skill file.
+- "removeSkillFile": remove an obsolete package-relative skill file.
+
+Use "updateSkill" for SKILL.md changes.
+Use "writeSkillFile" for new supporting resources.
+Use "removeSkillFile" only for package files made obsolete by the refinement.
+Do not delete, archive, promote, or fork skills.`;
+
+/**
+ * Builds the user prompt for a single-skill refinement pass.
+ *
+ * Use when:
+ * - A maintainer agent needs the current skill content and metadata
+ * - The result will be applied through skill management tools
+ *
+ * Expects:
+ * - Input describes exactly one skill
+ *
+ * Returns:
+ * - A compact prompt containing serialized refinement context
+ */
+export const createAgentSkillRefinePrompt = (input: AgentSkillRefinePromptInput) => {
+ return `Refine this skill.\ninput=${JSON.stringify(input)}`;
+};
diff --git a/packages/prompts/src/prompts/index.ts b/packages/prompts/src/prompts/index.ts
index 0b044197989..da1243c928b 100644
--- a/packages/prompts/src/prompts/index.ts
+++ b/packages/prompts/src/prompts/index.ts
@@ -1,6 +1,7 @@
export * from './agentBuilder';
export * from './agentGroup';
export * from './agentSignal';
+export * from './agentSkillManager';
export * from './botPlatformContext';
export * from './chatMessages';
export * from './compressContext';
diff --git a/src/server/routers/lambda/__tests__/integration/agentSkills.integration.test.ts b/src/server/routers/lambda/__tests__/integration/agentSkills.integration.test.ts
index f5661e67309..be272e244c1 100644
--- a/src/server/routers/lambda/__tests__/integration/agentSkills.integration.test.ts
+++ b/src/server/routers/lambda/__tests__/integration/agentSkills.integration.test.ts
@@ -8,13 +8,7 @@ import { AgentDocumentModel } from '@/database/models/agentDocuments';
import { agentDocumentRouter } from '../../agentDocument';
import { agentSkillsRouter } from '../../agentSkills';
-import {
- cleanupTestUser,
- createTestAgent,
- createTestContext,
- createTestTopic,
- createTestUser,
-} from './setup';
+import { cleanupTestUser, createTestAgent, createTestContext, createTestUser } from './setup';
// Mock getServerDB to return our test database instance
let testDB: LobeChatDatabase;
@@ -110,20 +104,17 @@ describe('Skill Router Integration Tests', () => {
agentId,
namespace,
skillName,
- topicId,
}: {
agentId: string;
- namespace: 'agent' | 'agent-topic';
+ namespace: 'agent';
skillName: string;
- topicId?: string;
}) => {
const documents = await agentDocumentModel.findByAgent(agentId);
const document = documents.find(
(item) =>
item.filename === 'SKILL.md' &&
item.metadata?.lobeSkill?.namespace === namespace &&
- item.metadata?.lobeSkill?.skillName === skillName &&
- item.metadata?.lobeSkill?.topicId === topicId,
+ item.metadata?.lobeSkill?.skillName === skillName,
);
if (!document) {
@@ -503,61 +494,6 @@ describe('Skill Router Integration Tests', () => {
expect(fileNode.content?.trimEnd()).toBe('# Research Helper\n\nUse this skill for research.');
});
- it('should create and update an agent-topic skill through the VFS API', async () => {
- const caller = agentDocumentRouter.createCaller(createTestContext(userId));
- const agentId = await createTestAgent(serverDB, userId);
- const topicId = await createTestTopic(serverDB, userId);
-
- const created = await caller.createSkillByPath({
- agentId,
- content: '# Topic Draft\n\nInitial topic skill content.',
- skillName: 'topic-draft',
- targetNamespace: 'agent-topic',
- topicId,
- });
-
- if (!created) {
- throw new Error('Expected createSkill to return a topic skill file node');
- }
-
- const updated = await caller.updateSkillByPath({
- agentId,
- content: '# Topic Draft\n\nUpdated topic skill content.',
- path: created.path,
- topicId,
- });
-
- if (!updated) {
- throw new Error('Expected updateSkill to return an updated topic skill file node');
- }
-
- expect(updated.mount?.namespace).toBe('agent-topic');
-
- const updatedFile = await caller.readDocumentByPath({
- agentId,
- path: updated.path,
- topicId,
- });
-
- if (!updatedFile) {
- throw new Error('Expected readDocumentByPath to return the updated topic skill file');
- }
-
- expect(updatedFile.content?.trimEnd()).toBe('# Topic Draft\n\nUpdated topic skill content.');
-
- const persistedFile = (await agentDocumentModel.findByAgent(agentId)).find(
- (document) =>
- document.filename === 'SKILL.md' &&
- document.metadata?.lobeSkill?.namespace === 'agent-topic' &&
- document.metadata?.lobeSkill?.skillName === 'topic-draft' &&
- document.metadata?.lobeSkill?.topicId === topicId,
- );
-
- expect(persistedFile?.content.trimEnd()).toBe(
- '# Topic Draft\n\nUpdated topic skill content.',
- );
- });
-
it('should delete an agent skill through the VFS API', async () => {
const caller = agentDocumentRouter.createCaller(createTestContext(userId));
const agentId = await createTestAgent(serverDB, userId);
@@ -586,46 +522,6 @@ describe('Skill Router Integration Tests', () => {
).rejects.toThrow();
});
- it('should promote an agent-topic skill into the agent namespace', async () => {
- const caller = agentDocumentRouter.createCaller(createTestContext(userId));
- const agentId = await createTestAgent(serverDB, userId);
- const topicId = await createTestTopic(serverDB, userId);
-
- const created = await caller.createSkillByPath({
- agentId,
- content: '# Topic Specialist\n\nPromote this skill.',
- skillName: 'topic-specialist',
- targetNamespace: 'agent-topic',
- topicId,
- });
-
- if (!created) {
- throw new Error('Expected createSkill to return a promotable topic skill file node');
- }
-
- const promoted = await caller.promoteSkillByPath({
- agentId,
- path: created.path,
- targetName: 'agent-specialist',
- topicId,
- });
-
- if (!promoted) {
- throw new Error('Expected promoteSkill to return a promoted skill file node');
- }
-
- expect(promoted.mount?.namespace).toBe('agent');
- expect(promoted.path).toBe('./lobe/skills/agent/skills/agent-specialist/SKILL.md');
-
- const promotedFile = await caller.readDocumentByPath({ agentId, path: promoted.path });
-
- if (!promotedFile) {
- throw new Error('Expected promoted agent skill file to exist');
- }
-
- expect(promotedFile.content?.trimEnd()).toBe('# Topic Specialist\n\nPromote this skill.');
- });
-
it('should surface CONFLICT when creating a duplicate VFS skill', async () => {
const caller = agentDocumentRouter.createCaller(createTestContext(userId));
const agentId = await createTestAgent(serverDB, userId);
@@ -659,30 +555,6 @@ describe('Skill Router Integration Tests', () => {
).rejects.toMatchObject({ code: 'NOT_FOUND' });
});
- it('should surface METHOD_NOT_SUPPORTED when promoting from a non-promotable namespace', async () => {
- const caller = agentDocumentRouter.createCaller(createTestContext(userId));
- const agentId = await createTestAgent(serverDB, userId);
-
- const created = await caller.createSkillByPath({
- agentId,
- content: '# Local Skill\n\nNo promote support.',
- skillName: 'local-skill',
- targetNamespace: 'agent',
- });
-
- if (!created) {
- throw new Error('Expected createSkill to return a local skill file node');
- }
-
- await expect(
- caller.promoteSkillByPath({
- agentId,
- path: created.path,
- topicId: 'topic-1',
- }),
- ).rejects.toMatchObject({ code: 'METHOD_NOT_SUPPORTED' });
- });
-
it('should surface BAD_REQUEST for invalid skill names', async () => {
const caller = agentDocumentRouter.createCaller(createTestContext(userId));
const agentId = await createTestAgent(serverDB, userId);
@@ -697,47 +569,6 @@ describe('Skill Router Integration Tests', () => {
).rejects.toMatchObject({ code: 'BAD_REQUEST' });
});
- it('should surface BAD_REQUEST when agent-topic skill creation is missing topicId', async () => {
- const caller = agentDocumentRouter.createCaller(createTestContext(userId));
- const agentId = await createTestAgent(serverDB, userId);
-
- await expect(
- caller.createSkillByPath({
- agentId,
- content: '# Topic Skill',
- skillName: 'topic-skill',
- targetNamespace: 'agent-topic',
- }),
- ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
- });
-
- it('should surface BAD_REQUEST for invalid promote target names', async () => {
- const caller = agentDocumentRouter.createCaller(createTestContext(userId));
- const agentId = await createTestAgent(serverDB, userId);
- const topicId = await createTestTopic(serverDB, userId);
-
- const created = await caller.createSkillByPath({
- agentId,
- content: '# Topic Specialist\n\nPromote this skill.',
- skillName: 'topic-specialist',
- targetNamespace: 'agent-topic',
- topicId,
- });
-
- if (!created) {
- throw new Error('Expected createSkill to return a promotable topic skill file node');
- }
-
- await expect(
- caller.promoteSkillByPath({
- agentId,
- path: created.path,
- targetName: 'bad/name',
- topicId,
- }),
- ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
- });
-
it('should surface BAD_REQUEST for unsupported VFS file paths on update', async () => {
const caller = agentDocumentRouter.createCaller(createTestContext(userId));
const agentId = await createTestAgent(serverDB, userId);
diff --git a/src/server/routers/lambda/agentDocument.ts b/src/server/routers/lambda/agentDocument.ts
index e5c0dff872c..8539e6f7370 100644
--- a/src/server/routers/lambda/agentDocument.ts
+++ b/src/server/routers/lambda/agentDocument.ts
@@ -77,34 +77,24 @@ const toolLoadRuleSchema = z.object({
const readFormatSchema = z.enum(['xml', 'markdown', 'both']).optional();
const writeCreateModeSchema = z.enum(['always-new', 'if-missing', 'must-exist']).optional();
const recursiveSchema = z.boolean().optional();
-const mountedSkillNamespaceSchema = z.enum(['agent', 'agent-topic']);
+const mountedSkillNamespaceSchema = z.literal('agent');
const createMountedSkillSchema = z.object({
agentId: z.string(),
content: z.string(),
skillName: z.string().min(1),
targetNamespace: mountedSkillNamespaceSchema,
- topicId: z.string().optional(),
});
const deleteMountedSkillSchema = z.object({
agentId: z.string(),
path: z.string(),
- topicId: z.string().optional(),
-});
-
-const promoteMountedSkillSchema = z.object({
- agentId: z.string(),
- path: z.string(),
- targetName: z.string().optional(),
- topicId: z.string(),
});
const updateMountedSkillSchema = z.object({
agentId: z.string(),
content: z.string(),
path: z.string(),
- topicId: z.string().optional(),
});
const liteXMLOperationSchema = z.union([
@@ -442,7 +432,6 @@ export const agentDocumentRouter = router({
input.content,
{
agentId: input.agentId,
- topicId: input.topicId,
},
{ createMode: 'always-new' },
);
@@ -460,7 +449,6 @@ export const agentDocumentRouter = router({
input.content,
{
agentId: input.agentId,
- topicId: input.topicId,
},
{ createMode: 'must-exist' },
);
@@ -475,30 +463,12 @@ export const agentDocumentRouter = router({
try {
await ctx.agentDocumentVfsService.delete(input.path, {
agentId: input.agentId,
- topicId: input.topicId,
});
} catch (error) {
handleAgentDocumentVfsError(error);
}
}),
- promoteSkillByPath: agentDocumentProcedure
- .input(promoteMountedSkillSchema)
- .mutation(async ({ ctx, input }) => {
- try {
- return await ctx.agentDocumentVfsService.promoteSkill(
- input.path,
- {
- agentId: input.agentId,
- topicId: input.topicId,
- },
- { targetName: input.targetName },
- );
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
/**
* Tool-oriented: create a VFS directory
*/
diff --git a/src/server/services/agentDocumentVfs/index.test.ts b/src/server/services/agentDocumentVfs/index.test.ts
index 9c6fbfb6713..ea9c1c0dedc 100644
--- a/src/server/services/agentDocumentVfs/index.test.ts
+++ b/src/server/services/agentDocumentVfs/index.test.ts
@@ -75,6 +75,16 @@ describe('AgentDocumentVfsService', () => {
id: 'agent-doc-1',
updatedAt: new Date('2024-01-02T00:00:00.000Z'),
},
+ {
+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,
+ content: 'newer duplicate',
+ createdAt: new Date('2024-01-02T00:00:00.000Z'),
+ documentId: 'documents-duplicate',
+ fileType: 'agent/document',
+ filename: 'SOUL.md',
+ id: 'agent-doc-duplicate',
+ updatedAt: new Date('2024-01-03T00:00:00.000Z'),
+ },
]);
const service = new AgentDocumentVfsService(db, userId);
@@ -82,7 +92,6 @@ describe('AgentDocumentVfsService', () => {
expect(mockAgentDocumentModel.listByParent).toHaveBeenCalledWith('agent-1', null, {
cursor: undefined,
- limit: 100,
});
expect(nodes).toEqual([
expect.objectContaining({
@@ -100,6 +109,7 @@ describe('AgentDocumentVfsService', () => {
type: 'directory',
}),
]);
+ expect(nodes).toHaveLength(2);
});
it('stats the unified VFS root as a synthetic directory', async () => {
@@ -168,7 +178,7 @@ describe('AgentDocumentVfsService', () => {
'agent-1',
null,
'SOUL.md',
- { limit: 2 },
+ {},
);
expect(node).toEqual(
expect.objectContaining({
@@ -217,11 +227,12 @@ describe('AgentDocumentVfsService', () => {
);
});
- it('rejects ordinary path resolution when duplicate siblings own the path segment', async () => {
+ it('resolves duplicate ordinary path segments to the oldest sibling', async () => {
mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([
{
accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,
content: 'first',
+ createdAt: new Date('2024-01-01T00:00:00.000Z'),
documentId: 'documents-first',
fileType: 'agent/document',
filename: 'notes.md',
@@ -230,6 +241,7 @@ describe('AgentDocumentVfsService', () => {
{
accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,
content: 'second',
+ createdAt: new Date('2024-01-02T00:00:00.000Z'),
documentId: 'documents-second',
fileType: 'agent/document',
filename: 'notes.md',
@@ -238,10 +250,11 @@ describe('AgentDocumentVfsService', () => {
]);
const service = new AgentDocumentVfsService(db, userId);
+ const stats = await service.stat('./notes.md', { agentId: 'agent-1' });
- await expect(service.stat('./notes.md', { agentId: 'agent-1' })).rejects.toMatchObject({
- code: 'CONFLICT',
- });
+ if (!stats) throw new Error('Expected ./notes.md stats to resolve');
+
+ expect(stats.documentId).toBe('documents-first');
expect(mockAgentDocumentModel.create).not.toHaveBeenCalled();
});
@@ -524,7 +537,7 @@ describe('AgentDocumentVfsService', () => {
});
});
- it('rejects restore when a live node already owns the target parent filename', async () => {
+ it('restores trash entries when a live sibling already owns the same filename', async () => {
mockAgentDocumentModel.findByIdWithOptions.mockResolvedValue({
accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,
content: 'deleted',
@@ -549,15 +562,37 @@ describe('AgentDocumentVfsService', () => {
parentId: null,
updatedAt: new Date('2024-01-04T00:00:00.000Z'),
});
+ mockAgentDocumentModel.listByParentAndFilename.mockResolvedValue([
+ {
+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,
+ content: 'deleted',
+ createdAt: new Date('2024-01-01T00:00:00.000Z'),
+ documentId: 'deleted-doc-1',
+ fileType: 'agent/document',
+ filename: 'draft.md',
+ id: 'deleted-agent-doc-1',
+ parentId: null,
+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),
+ },
+ {
+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,
+ content: 'live',
+ createdAt: new Date('2024-01-04T00:00:00.000Z'),
+ documentId: 'live-doc-1',
+ fileType: 'agent/document',
+ filename: 'draft.md',
+ id: 'live-agent-doc-1',
+ parentId: null,
+ updatedAt: new Date('2024-01-04T00:00:00.000Z'),
+ },
+ ]);
const service = new AgentDocumentVfsService(db, userId);
- await expect(
- service.restoreFromTrash('deleted-agent-doc-1', { agentId: 'agent-1' }),
- ).rejects.toMatchObject({
- code: 'CONFLICT',
- });
- expect(mockAgentDocumentModel.restore).not.toHaveBeenCalled();
+ const stats = await service.restoreFromTrash('deleted-agent-doc-1', { agentId: 'agent-1' });
+
+ expect(stats.documentId).toBe('deleted-doc-1');
+ expect(mockAgentDocumentModel.restore).toHaveBeenCalledWith('deleted-agent-doc-1');
});
it('permanently deletes ordinary directory subtrees child-first', async () => {
@@ -665,7 +700,6 @@ describe('AgentDocumentVfsService', () => {
expect(mockAgentDocumentModel.listByParent).toHaveBeenCalledTimes(1);
expect(mockAgentDocumentModel.listByParent).toHaveBeenCalledWith('agent-1', null, {
cursor: undefined,
- limit: 100,
});
expect(mockAgentDocumentModel.findByParentAndFilename).not.toHaveBeenCalled();
});
diff --git a/src/server/services/agentDocumentVfs/index.ts b/src/server/services/agentDocumentVfs/index.ts
index fab02e2f6ef..6e4f5190b1d 100644
--- a/src/server/services/agentDocumentVfs/index.ts
+++ b/src/server/services/agentDocumentVfs/index.ts
@@ -315,8 +315,6 @@ export class AgentDocumentVfsService {
);
if (existing) {
- await this.assertUniqueOrdinarySibling(ctx.agentId, parentId, segment, existing.id);
-
if (existing.fileType !== DOCUMENT_FOLDER_TYPE) {
throw new AgentDocumentVfsError(
`Path segment is not a directory: ${nextPath}`,
@@ -334,8 +332,6 @@ export class AgentDocumentVfsService {
throw new AgentDocumentVfsError(`Parent path not found: ${nextPath}`, 'BAD_REQUEST');
}
- await this.assertNoOrdinarySiblingConflict(ctx.agentId, parentId, segment);
-
const created = await this.agentDocumentModel.create(ctx.agentId, segment, '', {
fileType: DOCUMENT_FOLDER_TYPE,
parentId,
@@ -500,39 +496,6 @@ export class AgentDocumentVfsService {
}
}
- /**
- * Promotes a topic-scoped skill into an agent-scoped mounted skill.
- *
- * Use when:
- * - Router APIs need the old promote behavior through the unified VFS path surface
- *
- * Returns:
- * - The promoted mounted skill metadata
- */
- async promoteSkill(path: string, ctx: AgentDocumentVfsContext, options: { targetName?: string }) {
- const normalizedPath = normalizeAgentDocumentPath(path);
-
- if (!isSkillPath(normalizedPath)) {
- throw new AgentDocumentVfsError(`Path is not a skill mount path: ${path}`, 'BAD_REQUEST');
- }
-
- if (!ctx.topicId) {
- throw new AgentDocumentVfsError(
- 'Topic ID is required to promote a topic skill',
- 'BAD_REQUEST',
- );
- }
-
- const nextNode = await this.skillMount.promote({
- agentId: ctx.agentId,
- path: normalizedPath,
- targetName: options.targetName,
- topicId: ctx.topicId,
- });
-
- return this.toMountedStats(nextNode);
- }
-
/**
* Lists agent-scoped trash entries.
*
@@ -586,7 +549,6 @@ export class AgentDocumentVfsService {
const ancestors = await this.collectDeletedAncestors(root, ctx.agentId);
const subtree = await this.collectOrdinarySubtree(root, ctx.agentId, true);
- await this.assertNoRestoreConflicts([...ancestors, ...subtree], ctx.agentId);
for (const ancestor of ancestors.reverse()) {
if (ancestor.deletedAt) {
@@ -671,10 +633,12 @@ export class AgentDocumentVfsService {
): Promise<AgentDocumentNode[]> {
const docs = await this.agentDocumentModel.listByParent(agentId, parentId, {
cursor: options.cursor,
- limit: normalizeListLimit(options.limit),
});
+ const visibleDocs = selectOldestByFilename(docs);
return applyListLimit(
- docs.map((doc) => this.toOrdinaryNode(doc, buildOrdinaryPath(parentPath, doc.filename))),
+ visibleDocs.map((doc) =>
+ this.toOrdinaryNode(doc, buildOrdinaryPath(parentPath, doc.filename)),
+ ),
options,
);
}
@@ -704,15 +668,10 @@ export class AgentDocumentVfsService {
segment,
{
...options,
- limit: 2,
},
);
- if (candidates.length > 1) {
- throw new AgentDocumentVfsError(`Duplicate VFS path segment: ${segment}`, 'CONFLICT');
- }
-
- current = candidates[0];
+ current = selectOldestAgentDocument(candidates);
if (!current) return undefined;
parentId = current.documentId;
}
@@ -827,13 +786,6 @@ export class AgentDocumentVfsService {
throw new AgentDocumentVfsError(`Path is not a file: ${path}`, 'BAD_REQUEST');
}
- await this.assertUniqueOrdinarySibling(
- ctx.agentId,
- existing.parentId,
- existing.filename,
- existing.id,
- );
-
if (createMode === 'always-new') {
throw new AgentDocumentVfsError(`Path already exists: ${path}`, 'BAD_REQUEST');
}
@@ -879,12 +831,6 @@ export class AgentDocumentVfsService {
);
}
- await this.assertNoOrdinarySiblingConflict(
- ctx.agentId,
- parentNode?.documentId ?? null,
- filename,
- );
-
const snapshot = await createMarkdownEditorSnapshot(content);
const created = await this.agentDocumentModel.create(ctx.agentId, filename, snapshot.content, {
editorData: snapshot.editorData,
@@ -958,8 +904,6 @@ export class AgentDocumentVfsService {
}
const parentId = parentNode?.documentId ?? null;
- await this.assertNoOrdinarySiblingConflict(ctx.agentId, parentId, filename);
-
const moved = await this.agentDocumentModel.movePath(sourceNode.id, {
filename,
parentId,
@@ -1068,7 +1012,6 @@ export class AgentDocumentVfsService {
this.createSyntheticDirectoryNode('./lobe/skills/builtin', 'builtin'),
this.createSyntheticDirectoryNode('./lobe/skills/installed', 'installed'),
this.createSyntheticDirectoryNode('./lobe/skills/agent', 'agent'),
- this.createSyntheticDirectoryNode('./lobe/skills/agent-topic', 'agent-topic'),
];
}
@@ -1144,67 +1087,6 @@ export class AgentDocumentVfsService {
return ancestors;
}
- private async assertNoRestoreConflicts(nodes: AgentDocument[], agentId: string): Promise<void> {
- for (const node of nodes) {
- if (!node.deletedAt) continue;
-
- const liveNode = await this.agentDocumentModel.findByParentAndFilename(
- agentId,
- node.parentId,
- node.filename,
- );
-
- if (liveNode && liveNode.id !== node.id) {
- throw new AgentDocumentVfsError(
- `Cannot restore over live path: ${node.filename}`,
- 'CONFLICT',
- );
- }
-
- await this.assertUniqueOrdinarySibling(agentId, node.parentId, node.filename, node.id);
- }
- }
-
- private async assertNoOrdinarySiblingConflict(
- agentId: string,
- parentId: string | null,
- filename: string,
- ): Promise<void> {
- const conflicts = await this.agentDocumentModel.listByParentAndFilename(
- agentId,
- parentId,
- filename,
- {
- limit: 1,
- },
- );
-
- if (conflicts.length > 0) {
- throw new AgentDocumentVfsError(`Path already exists: ${filename}`, 'CONFLICT');
- }
- }
-
- private async assertUniqueOrdinarySibling(
- agentId: string,
- parentId: string | null,
- filename: string,
- expectedAgentDocumentId: string,
- ): Promise<void> {
- const conflicts = await this.agentDocumentModel.listByParentAndFilename(
- agentId,
- parentId,
- filename,
- {
- limit: 2,
- },
- );
- const unexpectedConflicts = conflicts.filter((node) => node.id !== expectedAgentDocumentId);
-
- if (unexpectedConflicts.length > 0) {
- throw new AgentDocumentVfsError(`Duplicate VFS path segment: ${filename}`, 'CONFLICT');
- }
- }
-
private async buildOrdinaryPathFromNode(node: AgentDocument, agentId: string): Promise<string> {
const segments = [node.filename];
let parentId = node.parentId;
@@ -1225,7 +1107,7 @@ export class AgentDocumentVfsService {
private async deleteMountedSkill(path: string, ctx: AgentDocumentVfsContext) {
const { namespace, skillName } = inferMountedSkillIdentity(resolveWritableMountedPath(path));
- if (namespace !== 'agent' && namespace !== 'agent-topic') {
+ if (namespace !== 'agent') {
throw new AgentDocumentVfsError(`Path is read-only: ${path}`, 'FORBIDDEN');
}
@@ -1273,6 +1155,29 @@ const normalizeListLimit = (limit?: number) => {
const applyListLimit = <T>(items: T[], options: AgentDocumentListOptions) =>
items.slice(0, normalizeListLimit(options.limit));
+const compareAgentDocumentAge = (left: AgentDocument, right: AgentDocument) => {
+ const leftCreatedAt = left.createdAt?.getTime?.() ?? 0;
+ const rightCreatedAt = right.createdAt?.getTime?.() ?? 0;
+
+ if (leftCreatedAt !== rightCreatedAt) return leftCreatedAt - rightCreatedAt;
+
+ return left.id.localeCompare(right.id);
+};
+
+const selectOldestAgentDocument = (documents: AgentDocument[]) =>
+ [...documents].sort(compareAgentDocumentAge)[0];
+
+const selectOldestByFilename = (documents: AgentDocument[]) => {
+ const visibleByFilename = new Map<string, AgentDocument>();
+
+ for (const document of [...documents].sort(compareAgentDocumentAge)) {
+ if (visibleByFilename.has(document.filename)) continue;
+ visibleByFilename.set(document.filename, document);
+ }
+
+ return [...visibleByFilename.values()];
+};
+
const isDescendantPath = (parentPath: string, childPath: string) =>
childPath !== parentPath && childPath.startsWith(`${parentPath}/`);
@@ -1294,7 +1199,7 @@ const assertNotSelfReferentialCopy = (
};
const inferMountedSkillIdentity = (path: string) => {
- for (const namespace of ['agent', 'agent-topic'] as const) {
+ for (const namespace of ['agent'] as const) {
const prefix = getUnifiedSkillNamespaceRootPath(namespace);
if (path === prefix || !path.startsWith(`${prefix}/`)) continue;
@@ -1348,12 +1253,6 @@ const resolveSkillMountSource = (namespace: SkillNamespace) => {
const SKILL_MOUNT_ACCESS = {
'agent': AgentAccess.READ | AgentAccess.LIST | AgentAccess.WRITE | AgentAccess.DELETE,
- 'agent-topic':
- AgentAccess.READ |
- AgentAccess.LIST |
- AgentAccess.WRITE |
- AgentAccess.DELETE |
- AgentAccess.EXECUTE,
'builtin': AgentAccess.READ | AgentAccess.LIST,
'installed-active': AgentAccess.READ | AgentAccess.LIST,
'installed-all': AgentAccess.READ | AgentAccess.LIST,
@@ -1366,13 +1265,7 @@ const skillNodeToMode = (node: SkillMountNode): AgentAccess => {
const resolveWritableMountedPath = (path: string) => {
if (!isSkillPath(path)) return path;
- for (const namespace of [
- 'agent',
- 'agent-topic',
- 'builtin',
- 'installed-active',
- 'installed-all',
- ] as const) {
+ for (const namespace of ['agent', 'builtin', 'installed-active', 'installed-all'] as const) {
const prefix = getUnifiedSkillNamespaceRootPath(namespace);
if (path === prefix) {
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/SkillMount.test.ts b/src/server/services/agentDocumentVfs/mounts/skills/SkillMount.test.ts
index 1183598a29b..811c11e7a2d 100644
--- a/src/server/services/agentDocumentVfs/mounts/skills/SkillMount.test.ts
+++ b/src/server/services/agentDocumentVfs/mounts/skills/SkillMount.test.ts
@@ -50,33 +50,32 @@ describe('SkillMount', () => {
expect(result).toEqual([{ name: 'installed-skill' }]);
});
- it('creates agent-topic skills through the writable provider', async () => {
- const agentTopicProvider = {
- create: vi.fn().mockResolvedValue({ path: './lobe/skills/agent-topic/skills/a/SKILL.md' }),
+ it('creates agent skills through the writable provider', async () => {
+ const agentProvider = {
+ create: vi.fn().mockResolvedValue({ path: './lobe/skills/agent/skills/a/SKILL.md' }),
delete: vi.fn(),
get: vi.fn(),
list: vi.fn(),
- promote: vi.fn(),
update: vi.fn(),
};
- const service = new SkillMount({ 'agent-topic': agentTopicProvider } as any);
+ const service = new SkillMount({ agent: agentProvider } as any);
const result = await service.create({
agentId: 'agent-1',
content: '# A',
skillName: 'a',
- targetNamespace: 'agent-topic',
+ targetNamespace: 'agent',
topicId: 'topic-1',
});
- expect(agentTopicProvider.create).toHaveBeenCalledWith({
+ expect(agentProvider.create).toHaveBeenCalledWith({
agentId: 'agent-1',
content: '# A',
skillName: 'a',
- targetNamespace: 'agent-topic',
+ targetNamespace: 'agent',
topicId: 'topic-1',
});
- expect(result.path).toContain('/agent-topic/skills/a/SKILL.md');
+ expect(result.path).toContain('/agent/skills/a/SKILL.md');
});
it('routes updateSkill and deleteSkill by path namespace', async () => {
@@ -115,35 +114,6 @@ describe('SkillMount', () => {
expect(updateResult.path).toBe('./lobe/skills/agent/skills/a/SKILL.md');
});
- it('routes promoteSkill through the agent-topic writable provider', async () => {
- const agentTopicProvider = {
- create: vi.fn(),
- delete: vi.fn(),
- get: vi.fn(),
- list: vi.fn(),
- promote: vi
- .fn()
- .mockResolvedValue({ path: './lobe/skills/agent/skills/promoted-a/SKILL.md' }),
- update: vi.fn(),
- };
- const service = new SkillMount({ 'agent-topic': agentTopicProvider } as any);
-
- const result = await service.promote({
- agentId: 'agent-1',
- path: './lobe/skills/agent-topic/skills/a/SKILL.md',
- targetName: 'promoted-a',
- topicId: 'topic-1',
- });
-
- expect(agentTopicProvider.promote).toHaveBeenCalledWith({
- agentId: 'agent-1',
- path: './lobe/skills/agent-topic/skills/a/SKILL.md',
- targetName: 'promoted-a',
- topicId: 'topic-1',
- });
- expect(result.path).toBe('./lobe/skills/agent/skills/promoted-a/SKILL.md');
- });
-
it('rejects write operations for non-writable namespaces', async () => {
const builtinProvider = { get: vi.fn(), list: vi.fn() };
const service = new SkillMount({ builtin: builtinProvider } as any);
@@ -156,23 +126,4 @@ describe('SkillMount', () => {
}),
).rejects.toThrow('Namespace "builtin" is not writable');
});
-
- it('rejects promoteSkill when the writable provider does not support promotion', async () => {
- const agentProvider = {
- create: vi.fn(),
- delete: vi.fn(),
- get: vi.fn(),
- list: vi.fn(),
- update: vi.fn(),
- };
- const service = new SkillMount({ agent: agentProvider } as any);
-
- await expect(
- service.promote({
- agentId: 'agent-1',
- path: './lobe/skills/agent/skills/a/SKILL.md',
- topicId: 'topic-1',
- }),
- ).rejects.toThrow('Namespace "agent" does not support promote');
- });
});
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/SkillMount.ts b/src/server/services/agentDocumentVfs/mounts/skills/SkillMount.ts
index 6e05e592eea..64b50491ec2 100644
--- a/src/server/services/agentDocumentVfs/mounts/skills/SkillMount.ts
+++ b/src/server/services/agentDocumentVfs/mounts/skills/SkillMount.ts
@@ -7,7 +7,7 @@ export interface CreateSkillInput {
agentId: string;
content: string;
skillName: string;
- targetNamespace: 'agent' | 'agent-topic';
+ targetNamespace: 'agent';
topicId?: string;
}
@@ -24,13 +24,6 @@ export interface DeleteSkillInput {
topicId?: string;
}
-export interface PromoteSkillInput {
- agentId: string;
- path: string;
- targetName?: string;
- topicId: string;
-}
-
export interface SkillMountProvider {
get: (input: SkillMountProviderRequest) => Promise<SkillMountNode>;
list: (input: SkillMountProviderRequest) => Promise<SkillMountNode[]>;
@@ -39,7 +32,6 @@ export interface SkillMountProvider {
export interface WritableSkillMountProvider extends SkillMountProvider {
create: (input: CreateSkillInput) => Promise<SkillMountNode>;
delete: (input: DeleteSkillInput) => Promise<void>;
- promote?: (input: PromoteSkillInput) => Promise<SkillMountNode>;
update: (input: UpdateSkillInput) => Promise<SkillMountNode>;
}
@@ -97,20 +89,6 @@ export class SkillMount {
return provider.delete(input);
}
- async promote(input: PromoteSkillInput) {
- const provider = this.getWritableProviderByPath(input.path);
-
- if (!provider.promote) {
- const { namespace } = SkillMountPathResolver.resolve(input.path);
- throw new AgentDocumentVfsError(
- `Namespace "${namespace}" does not support promote`,
- 'METHOD_NOT_SUPPORTED',
- );
- }
-
- return provider.promote(input);
- }
-
private getProvider(namespace: SkillMountNode['namespace']) {
const provider = this.providers[namespace];
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/createSkillMount.ts b/src/server/services/agentDocumentVfs/mounts/skills/createSkillMount.ts
index 7519dda37ec..7fb3466a17c 100644
--- a/src/server/services/agentDocumentVfs/mounts/skills/createSkillMount.ts
+++ b/src/server/services/agentDocumentVfs/mounts/skills/createSkillMount.ts
@@ -36,10 +36,6 @@ export const createSkillMount = (db: LobeChatDatabase, userId: string) => {
agentDocumentModel,
documentService,
}),
- 'agent-topic': new ProviderSkillsAgentDocument('agent-topic', {
- agentDocumentModel,
- documentService,
- }),
'builtin': new ProviderSkillsBuiltin(),
'installed-active': new ProviderSkillsInstalledActive({
agentModel,
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/path.ts b/src/server/services/agentDocumentVfs/mounts/skills/path.ts
index c66bd6f05ec..8d0fae1732d 100644
--- a/src/server/services/agentDocumentVfs/mounts/skills/path.ts
+++ b/src/server/services/agentDocumentVfs/mounts/skills/path.ts
@@ -4,7 +4,6 @@ export type SkillNamespace = SkillMountNode['namespace'];
export const SKILL_NAMESPACES = [
'agent',
- 'agent-topic',
'builtin',
'installed-active',
'installed-all',
@@ -14,7 +13,6 @@ const UNIFIED_SKILL_ROOT_PREFIX = './lobe/skills';
const SKILL_NAMESPACE_SEGMENTS = {
'agent': ['agent', 'skills'],
- 'agent-topic': ['agent-topic', 'skills'],
'builtin': ['builtin', 'skills'],
'installed-active': ['installed', 'active', 'skills'],
'installed-all': ['installed', 'all', 'skills'],
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsAgentDocument.test.ts b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsAgentDocument.test.ts
index e3655412f89..21299da739b 100644
--- a/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsAgentDocument.test.ts
+++ b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsAgentDocument.test.ts
@@ -79,19 +79,12 @@ describe('Agent skill VFS providers', () => {
parentId: 'folder-1',
}),
createAgentDocument({
- documentId: 'topic-folder',
+ documentId: 'plain-folder',
fileType: 'custom/folder',
- filename: 'topic-skill',
- id: 'agent-doc-topic-folder',
- metadata: {
- lobeSkill: {
- namespace: 'agent-topic',
- role: 'skill-folder',
- skillName: 'topic-skill',
- topicId: 'topic-1',
- },
- },
- parentId: 'root-topic',
+ filename: 'plain-folder',
+ id: 'agent-doc-plain-folder',
+ metadata: null,
+ parentId: null,
}),
]);
@@ -175,6 +168,7 @@ describe('Agent skill VFS providers', () => {
expect(documentService.createDocument).toHaveBeenNthCalledWith(3, {
content: '# Skill',
editorData: { markdown: '# Skill' },
+ fileType: 'skill/index',
metadata: { lobeSkill: { namespace: 'agent', role: 'skill-file', skillName: 'writer' } },
parentId: 'folder-1',
title: 'SKILL.md',
@@ -183,22 +177,75 @@ describe('Agent skill VFS providers', () => {
agentId: 'agent-1',
documentId: 'root-1',
policyLoad: 'disabled',
- uniqueSibling: false,
});
expect(agentDocumentModel.associate).toHaveBeenNthCalledWith(2, {
agentId: 'agent-1',
documentId: 'folder-1',
policyLoad: 'disabled',
- uniqueSibling: false,
});
expect(agentDocumentModel.associate).toHaveBeenNthCalledWith(3, {
agentId: 'agent-1',
documentId: 'file-1',
- uniqueSibling: false,
});
expect(result.path).toBe('./lobe/skills/agent/skills/writer/SKILL.md');
});
+ /**
+ * @example
+ * A partially-created skill folder reserves the package name and blocks duplicate creation.
+ */
+ it('rejects creating a skill when the managed skill folder already exists without SKILL.md', async () => {
+ const provider = new ProviderSkillsAgentDocument('agent', {
+ agentDocumentModel,
+ documentService,
+ });
+ agentDocumentModel.findByAgent.mockResolvedValue([
+ {
+ documentId: 'root-doc',
+ filename: 'skills',
+ id: 'root-binding',
+ metadata: {
+ lobeSkill: {
+ namespace: 'agent',
+ role: 'namespace-root',
+ },
+ },
+ parentId: null,
+ },
+ {
+ documentId: 'folder-doc',
+ filename: 'writer',
+ id: 'folder-binding',
+ metadata: {
+ lobeSkill: {
+ namespace: 'agent',
+ role: 'skill-folder',
+ skillName: 'writer',
+ },
+ },
+ parentId: 'root-doc',
+ },
+ ] as never);
+
+ await expect(
+ provider.create({
+ agentId: 'agent-1',
+ content: '# Writer',
+ skillName: 'writer',
+ targetNamespace: 'agent',
+ }),
+ ).rejects.toMatchObject({
+ code: 'CONFLICT',
+ message: 'Skill already exists',
+ });
+
+ expect(documentService.createDocument).not.toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: 'SKILL.md',
+ }),
+ );
+ });
+
it('updates an agent skill through the document model and saves history when content changes', async () => {
agentDocumentModel.findByAgent.mockResolvedValue([
createAgentDocument({
@@ -267,271 +314,4 @@ describe('Agent skill VFS providers', () => {
expect(documentService.deleteDocument).toHaveBeenCalledWith('folder-1');
});
});
-
- describe('ProviderSkillsAgentDocument agent-topic namespace', () => {
- it('lists only topic-matching tree-backed skills', async () => {
- agentDocumentModel.findByAgent.mockResolvedValue([
- createAgentDocument({
- documentId: 'topic-folder-1',
- fileType: 'custom/folder',
- filename: 'topic-skill-a',
- id: 'agent-doc-topic-a',
- metadata: {
- lobeSkill: {
- namespace: 'agent-topic',
- role: 'skill-folder',
- skillName: 'topic-skill-a',
- topicId: 'topic-1',
- },
- },
- parentId: 'root-topic-1',
- }),
- createAgentDocument({
- documentId: 'topic-folder-2',
- fileType: 'custom/folder',
- filename: 'topic-skill-b',
- id: 'agent-doc-topic-b',
- metadata: {
- lobeSkill: {
- namespace: 'agent-topic',
- role: 'skill-folder',
- skillName: 'topic-skill-b',
- topicId: 'topic-2',
- },
- },
- parentId: 'root-topic-2',
- }),
- ]);
-
- const provider = new ProviderSkillsAgentDocument('agent-topic', {
- agentDocumentModel,
- documentService,
- });
-
- const result = await provider.list({
- agentId: 'agent-1',
- path: './lobe/skills/agent-topic/skills',
- resolvedPath: { namespace: 'agent-topic', relativePath: '' },
- topicId: 'topic-1',
- });
-
- expect(result).toEqual([
- expect.objectContaining({
- name: 'topic-skill-a',
- namespace: 'agent-topic',
- path: './lobe/skills/agent-topic/skills/topic-skill-a',
- }),
- ]);
- });
-
- it('creates a topic skill with metadata scoped to the topic', async () => {
- agentDocumentModel.findByAgent.mockResolvedValue([]);
- documentService.createDocument
- .mockResolvedValueOnce({
- fileType: 'custom/folder',
- filename: 'skills',
- id: 'root-topic-1',
- metadata: {
- lobeSkill: { namespace: 'agent-topic', role: 'namespace-root', topicId: 'topic-1' },
- },
- parentId: null,
- title: 'skills',
- })
- .mockResolvedValueOnce({
- fileType: 'custom/folder',
- filename: 'topic-skill',
- id: 'topic-folder-1',
- metadata: {
- lobeSkill: {
- namespace: 'agent-topic',
- role: 'skill-folder',
- skillName: 'topic-skill',
- topicId: 'topic-1',
- },
- },
- parentId: 'root-topic-1',
- title: 'topic-skill',
- })
- .mockResolvedValueOnce({
- content: 'topic content',
- fileType: 'custom/document',
- filename: 'SKILL.md',
- id: 'topic-file-1',
- metadata: {
- lobeSkill: {
- namespace: 'agent-topic',
- role: 'skill-file',
- skillName: 'topic-skill',
- topicId: 'topic-1',
- },
- },
- parentId: 'topic-folder-1',
- title: 'SKILL.md',
- });
-
- const provider = new ProviderSkillsAgentDocument('agent-topic', {
- agentDocumentModel,
- documentService,
- });
-
- const result = await provider.create({
- agentId: 'agent-1',
- content: 'topic content',
- skillName: 'topic-skill',
- targetNamespace: 'agent-topic',
- topicId: 'topic-1',
- });
-
- expect(documentService.createDocument).toHaveBeenNthCalledWith(2, {
- editorData: { root: { children: [], type: 'root' } },
- fileType: 'custom/folder',
- metadata: {
- lobeSkill: {
- namespace: 'agent-topic',
- role: 'skill-folder',
- skillName: 'topic-skill',
- topicId: 'topic-1',
- },
- },
- parentId: 'root-topic-1',
- title: 'topic-skill',
- });
- expect(result.path).toBe('./lobe/skills/agent-topic/skills/topic-skill/SKILL.md');
- });
-
- it('soft-deletes the topic skill subtree without touching other topics', async () => {
- agentDocumentModel.findByAgent.mockResolvedValue([
- createAgentDocument({
- documentId: 'topic-folder-1',
- fileType: 'custom/folder',
- filename: 'topic-skill',
- id: 'agent-doc-topic-folder',
- metadata: {
- lobeSkill: {
- namespace: 'agent-topic',
- role: 'skill-folder',
- skillName: 'topic-skill',
- topicId: 'topic-1',
- },
- },
- parentId: 'root-topic-1',
- }),
- createAgentDocument({
- documentId: 'topic-file-1',
- filename: 'SKILL.md',
- id: 'agent-doc-topic-file',
- metadata: {
- lobeSkill: {
- namespace: 'agent-topic',
- role: 'skill-file',
- skillName: 'topic-skill',
- topicId: 'topic-1',
- },
- },
- parentId: 'topic-folder-1',
- }),
- ]);
-
- const provider = new ProviderSkillsAgentDocument('agent-topic', {
- agentDocumentModel,
- documentService,
- });
-
- await provider.delete({
- agentId: 'agent-1',
- path: './lobe/skills/agent-topic/skills/topic-skill/SKILL.md',
- topicId: 'topic-1',
- });
-
- expect(documentService.deleteDocument).toHaveBeenCalledWith('topic-folder-1');
- });
-
- it('promotes a topic skill by copying it into the agent namespace', async () => {
- agentDocumentModel.findByAgent.mockResolvedValue([
- createAgentDocument({
- content: 'topic content',
- documentId: 'topic-file-1',
- filename: 'SKILL.md',
- id: 'agent-doc-topic-file',
- metadata: {
- lobeSkill: {
- namespace: 'agent-topic',
- role: 'skill-file',
- skillName: 'topic-skill',
- topicId: 'topic-1',
- },
- },
- parentId: 'topic-folder-1',
- }),
- ]);
- documentService.createDocument
- .mockResolvedValueOnce({
- fileType: 'custom/folder',
- filename: 'skills',
- id: 'root-agent-1',
- metadata: { lobeSkill: { namespace: 'agent', role: 'namespace-root' } },
- parentId: null,
- title: 'skills',
- })
- .mockResolvedValueOnce({
- fileType: 'custom/folder',
- filename: 'promoted-skill',
- id: 'agent-folder-1',
- metadata: {
- lobeSkill: { namespace: 'agent', role: 'skill-folder', skillName: 'promoted-skill' },
- },
- parentId: 'root-agent-1',
- title: 'promoted-skill',
- })
- .mockResolvedValueOnce({
- content: 'topic content',
- fileType: 'custom/document',
- filename: 'SKILL.md',
- id: 'agent-file-1',
- metadata: {
- lobeSkill: { namespace: 'agent', role: 'skill-file', skillName: 'promoted-skill' },
- },
- parentId: 'agent-folder-1',
- title: 'SKILL.md',
- });
-
- const provider = new ProviderSkillsAgentDocument('agent-topic', {
- agentDocumentModel,
- documentService,
- });
-
- if (!provider.promote) {
- throw new Error('Expected agent-topic provider to support skill promotion');
- }
-
- const result = await provider.promote({
- agentId: 'agent-1',
- path: './lobe/skills/agent-topic/skills/topic-skill/SKILL.md',
- targetName: 'promoted-skill',
- topicId: 'topic-1',
- });
-
- expect(documentService.createDocument).toHaveBeenNthCalledWith(2, {
- editorData: { root: { children: [], type: 'root' } },
- fileType: 'custom/folder',
- metadata: {
- lobeSkill: {
- lineage: {
- sourceDocumentId: 'topic-file-1',
- sourceNamespace: 'agent-topic',
- sourceSkillName: 'topic-skill',
- sourceTopicId: 'topic-1',
- },
- namespace: 'agent',
- role: 'skill-folder',
- skillName: 'promoted-skill',
- },
- },
- parentId: 'root-agent-1',
- title: 'promoted-skill',
- });
- expect(result.namespace).toBe('agent');
- expect(result.path).toBe('./lobe/skills/agent/skills/promoted-skill/SKILL.md');
- });
- });
});
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsAgentDocument.ts b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsAgentDocument.ts
index 3da1e9bba22..87fd769297b 100644
--- a/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsAgentDocument.ts
+++ b/src/server/services/agentDocumentVfs/mounts/skills/providers/ProviderSkillsAgentDocument.ts
@@ -4,7 +4,6 @@ import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors
import type {
CreateSkillInput,
DeleteSkillInput,
- PromoteSkillInput,
SkillMountProviderRequest,
UpdateSkillInput,
WritableSkillMountProvider,
@@ -18,8 +17,6 @@ import {
buildSkillFileNode,
buildSkillNamespaceRootNode,
createSkillTree,
- EMPTY_EDITOR_DATA,
- getRequiredTopicId,
getResolvedSkillName,
getScopedSkillDocuments,
getSkillFile,
@@ -32,28 +29,23 @@ import {
} from './providerSkillsAgentDocumentUtils';
interface ProviderSkillsAgentDocumentConfig {
- namespace: 'agent' | 'agent-topic';
+ namespace: 'agent';
}
const DOCUMENT_SKILL_PROVIDER_CONFIGS = {
- 'agent': {
+ agent: {
namespace: 'agent',
},
- 'agent-topic': {
- namespace: 'agent-topic',
- },
-} as const satisfies Record<'agent' | 'agent-topic', ProviderSkillsAgentDocumentConfig>;
+} as const satisfies Record<'agent', ProviderSkillsAgentDocumentConfig>;
/**
* Provides writable VFS operations for document-backed skills.
*
* Use when:
* - Serving agent-level skills from agent documents.
- * - Serving topic-level draft skills from agent documents.
*
* Expects:
- * - Managed skill documents carry `metadata.lobeSkill` with namespace, role, and topic scope.
- * - Topic-backed requests pass `topicId`.
+ * - Managed skill documents carry `metadata.lobeSkill` with namespace and role.
*
* Returns:
* - Skill VFS nodes whose paths use the target unified `./lobe/skills/...` layout.
@@ -61,22 +53,14 @@ const DOCUMENT_SKILL_PROVIDER_CONFIGS = {
export class ProviderSkillsAgentDocument implements WritableSkillMountProvider {
private readonly config: ProviderSkillsAgentDocumentConfig;
- readonly promote?: (input: PromoteSkillInput) => Promise<SkillMountNode>;
-
constructor(
namespace: ProviderSkillsAgentDocumentConfig['namespace'],
private readonly deps: ProviderSkillsAgentDocumentDeps,
) {
this.config = DOCUMENT_SKILL_PROVIDER_CONFIGS[namespace];
-
- if (namespace === 'agent-topic') {
- this.promote = (input) => this.promoteTopicSkill(input);
- }
}
async get(input: SkillMountProviderRequest): Promise<SkillMountNode> {
- const topicId = this.getTopicId(input.topicId);
-
if (!input.resolvedPath.skillName) {
return buildSkillNamespaceRootNode(this.config.namespace);
}
@@ -88,13 +72,11 @@ export class ProviderSkillsAgentDocument implements WritableSkillMountProvider {
const documents = await this.deps.agentDocumentModel.findByAgent(input.agentId);
if (!input.resolvedPath.filePath) {
- assertSkillDocument(getSkillFolder(documents, this.config.namespace, skillName, topicId));
+ assertSkillDocument(getSkillFolder(documents, this.config.namespace, skillName));
return buildSkillDirectoryNode(this.config.namespace, skillName);
}
- const document = assertSkillDocument(
- getSkillFile(documents, this.config.namespace, skillName, topicId),
- );
+ const document = assertSkillDocument(getSkillFile(documents, this.config.namespace, skillName));
const content = await projectDocumentContent(document);
return buildSkillFileNode({
@@ -105,21 +87,18 @@ export class ProviderSkillsAgentDocument implements WritableSkillMountProvider {
}
async list(input: SkillMountProviderRequest): Promise<SkillMountNode[]> {
- const topicId = this.getTopicId(input.topicId);
const documents = getScopedSkillDocuments(
await this.deps.agentDocumentModel.findByAgent(input.agentId),
this.config.namespace,
- topicId,
);
if (!input.resolvedPath.skillName) {
- return sortSkillFolders(
- listScopedSkillFolders(documents, this.config.namespace, topicId),
- ).map((document) =>
- buildSkillDirectoryNode(
- this.config.namespace,
- getSkillMetadata(document)?.skillName ?? document.filename,
- ),
+ return sortSkillFolders(listScopedSkillFolders(documents, this.config.namespace)).map(
+ (document) =>
+ buildSkillDirectoryNode(
+ this.config.namespace,
+ getSkillMetadata(document)?.skillName ?? document.filename,
+ ),
);
}
@@ -127,7 +106,7 @@ export class ProviderSkillsAgentDocument implements WritableSkillMountProvider {
input.resolvedPath.skillName,
input.resolvedPath.filePath,
);
- assertSkillDocument(getSkillFolder(documents, this.config.namespace, skillName, topicId));
+ assertSkillDocument(getSkillFolder(documents, this.config.namespace, skillName));
return [
buildSkillFileNode({
@@ -138,12 +117,11 @@ export class ProviderSkillsAgentDocument implements WritableSkillMountProvider {
}
async create(input: CreateSkillInput): Promise<SkillMountNode> {
- const topicId = this.getTopicId(input.topicId);
const skillName = getValidatedSkillName(input.skillName, 'skillName');
const documents = await this.deps.agentDocumentModel.findByAgent(input.agentId);
- if (getSkillFolder(documents, this.config.namespace, skillName, topicId)) {
- throw new AgentDocumentVfsError(`Skill "${skillName}" already exists`, 'CONFLICT');
+ if (getSkillFolder(documents, this.config.namespace, skillName)) {
+ throw new AgentDocumentVfsError('Skill already exists', 'CONFLICT');
}
const snapshot = await createMarkdownEditorSnapshot(input.content);
@@ -156,7 +134,6 @@ export class ProviderSkillsAgentDocument implements WritableSkillMountProvider {
editorData: snapshot.editorData,
namespace: this.config.namespace,
skillName,
- topicId,
});
return buildSkillFileNode({
@@ -167,13 +144,10 @@ export class ProviderSkillsAgentDocument implements WritableSkillMountProvider {
}
async update(input: UpdateSkillInput): Promise<SkillMountNode> {
- const topicId = this.getTopicId(input.topicId);
const resolvedPath = SkillMountPathResolver.resolve(input.path);
const skillName = getResolvedSkillName(resolvedPath.skillName, resolvedPath.filePath);
const documents = await this.deps.agentDocumentModel.findByAgent(input.agentId);
- const document = assertSkillDocument(
- getSkillFile(documents, this.config.namespace, skillName, topicId),
- );
+ const document = assertSkillDocument(getSkillFile(documents, this.config.namespace, skillName));
const existingContent = await projectDocumentContent(document);
const snapshot = await createMarkdownEditorSnapshot(input.content);
@@ -197,63 +171,14 @@ export class ProviderSkillsAgentDocument implements WritableSkillMountProvider {
}
async delete(input: DeleteSkillInput): Promise<void> {
- const topicId = this.getTopicId(input.topicId);
const resolvedPath = SkillMountPathResolver.resolve(input.path);
const skillName = getResolvedSkillName(resolvedPath.skillName, resolvedPath.filePath);
const documents = getScopedSkillDocuments(
await this.deps.agentDocumentModel.findByAgent(input.agentId),
this.config.namespace,
- topicId,
- );
- const folder = assertSkillDocument(
- getSkillFolder(documents, this.config.namespace, skillName, topicId),
);
+ const folder = assertSkillDocument(getSkillFolder(documents, this.config.namespace, skillName));
await this.deps.documentService.deleteDocument(folder.documentId);
}
-
- private async promoteTopicSkill(input: PromoteSkillInput): Promise<SkillMountNode> {
- const topicId = getRequiredTopicId(input.topicId);
- const resolvedPath = SkillMountPathResolver.resolve(input.path);
- const skillName = getResolvedSkillName(resolvedPath.skillName, resolvedPath.filePath);
- const targetName = input.targetName
- ? getValidatedSkillName(input.targetName, 'targetName')
- : skillName;
- const documents = await this.deps.agentDocumentModel.findByAgent(input.agentId);
-
- if (getSkillFolder(documents, 'agent', targetName)) {
- throw new AgentDocumentVfsError(`Skill "${targetName}" already exists`, 'CONFLICT');
- }
-
- const sourceFile = assertSkillDocument(
- getSkillFile(documents, 'agent-topic', skillName, topicId),
- );
- const content = await projectDocumentContent(sourceFile);
-
- await createSkillTree({
- agentDocumentModel: this.deps.agentDocumentModel,
- agentId: input.agentId,
- content,
- documentService: this.deps.documentService,
- editorData: sourceFile.editorData ?? EMPTY_EDITOR_DATA,
- lineage: {
- sourceDocumentId: sourceFile.documentId,
- sourceNamespace: 'agent-topic',
- sourceSkillName: skillName,
- sourceTopicId: topicId,
- },
- namespace: 'agent',
- skillName: targetName,
- });
-
- return buildSkillFileNode({
- content,
- namespace: 'agent',
- skillName: targetName,
- });
- }
-
- private getTopicId(topicId?: string) {
- return this.config.namespace === 'agent-topic' ? getRequiredTopicId(topicId) : undefined;
- }
}
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils.ts b/src/server/services/agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils.ts
index a89fa2cca4b..9ff55909722 100644
--- a/src/server/services/agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils.ts
+++ b/src/server/services/agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils.ts
@@ -8,12 +8,7 @@ import { getUnifiedSkillNamespaceRootPath } from '../path';
import type { SkillMountNode } from '../types';
export interface AgentSkillDocumentModelLike {
- associate: (params: {
- agentId: string;
- documentId: string;
- policyLoad?: PolicyLoad;
- uniqueSibling?: boolean;
- }) => Promise<{
+ associate: (params: { agentId: string; documentId: string; policyLoad?: PolicyLoad }) => Promise<{
id: string;
}>;
delete: (documentId: string, deleteReason?: string) => Promise<void>;
@@ -74,31 +69,24 @@ export interface CreateSkillTreeInput {
content: string;
documentService: DocumentTreeServiceLike;
editorData: Record<string, any>;
- lineage?: LobeSkillMetadata['lineage'];
- namespace: 'agent' | 'agent-topic';
+ namespace: 'agent';
skillName: string;
- topicId?: string;
}
export interface LobeSkillMetadata {
- lineage?: {
- sourceDocumentId: string;
- sourceNamespace: 'agent-topic';
- sourceSkillName?: string;
- sourceTopicId?: string;
- };
- namespace: 'agent' | 'agent-topic';
+ namespace: 'agent';
role: 'namespace-root' | 'skill-file' | 'skill-folder';
skillName?: string;
- topicId?: string;
}
export const EMPTY_EDITOR_DATA = { root: { children: [], type: 'root' } };
export const SKILL_FILE_NAME = 'SKILL.md';
+export const SKILL_INDEX_FILE_TYPE = 'skill/index';
+
export const buildSkillDirectoryNode = (
- namespace: Extract<SkillMountNode['namespace'], 'agent' | 'agent-topic'>,
+ namespace: Extract<SkillMountNode['namespace'], 'agent'>,
skillName: string,
): SkillMountNode => ({
name: skillName,
@@ -109,7 +97,7 @@ export const buildSkillDirectoryNode = (
});
export const buildSkillNamespaceRootNode = (
- namespace: Extract<SkillMountNode['namespace'], 'agent' | 'agent-topic'>,
+ namespace: Extract<SkillMountNode['namespace'], 'agent'>,
): SkillMountNode => ({
name: 'skills',
namespace,
@@ -124,7 +112,7 @@ export const buildSkillFileNode = ({
skillName,
}: {
content?: string;
- namespace: Extract<SkillMountNode['namespace'], 'agent' | 'agent-topic'>;
+ namespace: Extract<SkillMountNode['namespace'], 'agent'>;
skillName: string;
}): SkillMountNode => ({
...(content !== undefined ? { content } : {}),
@@ -158,17 +146,6 @@ export const getValidatedSkillName = (
return trimmed;
};
-export const getRequiredTopicId = (topicId?: string) => {
- if (!topicId) {
- throw new AgentDocumentVfsError(
- 'Topic ID is required for the agent-topic namespace',
- 'BAD_REQUEST',
- );
- }
-
- return topicId;
-};
-
export const getResolvedSkillName = (skillName?: string, filePath?: string) => {
if (!skillName) {
throw new AgentDocumentVfsError('Skill path must include a skill name', 'BAD_REQUEST');
@@ -208,8 +185,7 @@ export const isManagedSkillDocument = (document: Pick<AgentDocument, 'metadata'>
export const isSkillDocumentInScope = (
document: Pick<AgentDocument, 'metadata'>,
- namespace: 'agent' | 'agent-topic',
- topicId?: string,
+ namespace: 'agent',
) => {
const metadata = getSkillMetadata(document);
@@ -217,37 +193,25 @@ export const isSkillDocumentInScope = (
return false;
}
- if (namespace === 'agent-topic') {
- return metadata.topicId === topicId;
- }
-
- return !metadata.topicId;
+ return true;
};
-export const getScopedSkillDocuments = (
- documents: AgentDocument[],
- namespace: 'agent' | 'agent-topic',
- topicId?: string,
-) => documents.filter((document) => isSkillDocumentInScope(document, namespace, topicId));
+export const getScopedSkillDocuments = (documents: AgentDocument[], namespace: 'agent') =>
+ documents.filter((document) => isSkillDocumentInScope(document, namespace));
-export const getNamespaceRoot = (
- documents: AgentDocument[],
- namespace: 'agent' | 'agent-topic',
- topicId?: string,
-) =>
- getScopedSkillDocuments(documents, namespace, topicId).find(
+export const getNamespaceRoot = (documents: AgentDocument[], namespace: 'agent') =>
+ getScopedSkillDocuments(documents, namespace).find(
(document) => getSkillMetadata(document)?.role === 'namespace-root',
);
export const getSkillFolder = (
documents: AgentDocument[],
- namespace: 'agent' | 'agent-topic',
+ namespace: 'agent',
skillName: string,
- topicId?: string,
) => {
- const root = getNamespaceRoot(documents, namespace, topicId);
+ const root = getNamespaceRoot(documents, namespace);
- return getScopedSkillDocuments(documents, namespace, topicId).find((document) => {
+ return getScopedSkillDocuments(documents, namespace).find((document) => {
const metadata = getSkillMetadata(document);
return (
@@ -258,15 +222,10 @@ export const getSkillFolder = (
});
};
-export const getSkillFile = (
- documents: AgentDocument[],
- namespace: 'agent' | 'agent-topic',
- skillName: string,
- topicId?: string,
-) => {
- const folder = getSkillFolder(documents, namespace, skillName, topicId);
+export const getSkillFile = (documents: AgentDocument[], namespace: 'agent', skillName: string) => {
+ const folder = getSkillFolder(documents, namespace, skillName);
- return getScopedSkillDocuments(documents, namespace, topicId).find((document) => {
+ return getScopedSkillDocuments(documents, namespace).find((document) => {
const metadata = getSkillMetadata(document);
return (
@@ -277,14 +236,10 @@ export const getSkillFile = (
});
};
-export const listScopedSkillFolders = (
- documents: AgentDocument[],
- namespace: 'agent' | 'agent-topic',
- topicId?: string,
-) => {
- const root = getNamespaceRoot(documents, namespace, topicId);
+export const listScopedSkillFolders = (documents: AgentDocument[], namespace: 'agent') => {
+ const root = getNamespaceRoot(documents, namespace);
- return getScopedSkillDocuments(documents, namespace, topicId).filter((document) => {
+ return getScopedSkillDocuments(documents, namespace).filter((document) => {
const metadata = getSkillMetadata(document);
return metadata?.role === 'skill-folder' && (!root || document.parentId === root.documentId);
@@ -299,19 +254,11 @@ export const assertSkillDocument = <T>(document: T | undefined, message = 'Skill
return document;
};
-export const createSkillMetadata = ({
- lineage,
- namespace,
- role,
- skillName,
- topicId,
-}: LobeSkillMetadata) => ({
+export const createSkillMetadata = ({ namespace, role, skillName }: LobeSkillMetadata) => ({
lobeSkill: {
- ...(lineage ? { lineage } : {}),
namespace,
role,
...(skillName ? { skillName } : {}),
- ...(topicId ? { topicId } : {}),
} satisfies LobeSkillMetadata,
});
@@ -320,16 +267,14 @@ export const ensureNamespaceRoot = async ({
agentDocumentModel,
documentService,
namespace,
- topicId,
}: {
agentDocumentModel: AgentSkillDocumentModelLike;
agentId: string;
documentService: DocumentTreeServiceLike;
- namespace: 'agent' | 'agent-topic';
- topicId?: string;
+ namespace: 'agent';
}): Promise<{ documentId: string }> => {
const documents = await agentDocumentModel.findByAgent(agentId);
- const existingRoot = getNamespaceRoot(documents, namespace, topicId);
+ const existingRoot = getNamespaceRoot(documents, namespace);
if (existingRoot) {
return { documentId: existingRoot.documentId };
@@ -338,7 +283,7 @@ export const ensureNamespaceRoot = async ({
const root = await documentService.createDocument({
editorData: EMPTY_EDITOR_DATA,
fileType: DOCUMENT_FOLDER_TYPE,
- metadata: createSkillMetadata({ namespace, role: 'namespace-root', topicId }),
+ metadata: createSkillMetadata({ namespace, role: 'namespace-root' }),
title: 'skills',
});
@@ -346,7 +291,6 @@ export const ensureNamespaceRoot = async ({
agentId,
documentId: root.id,
policyLoad: PolicyLoad.DISABLED,
- uniqueSibling: false,
});
return { documentId: root.id };
@@ -358,14 +302,17 @@ export const createSkillTree = async ({
content,
documentService,
editorData,
- lineage,
namespace,
skillName,
- topicId,
}: CreateSkillTreeInput) => {
const existingDocuments = await agentDocumentModel.findByAgent(agentId);
- const existingRoot = getNamespaceRoot(existingDocuments, namespace, topicId);
- const existingFolder = getSkillFolder(existingDocuments, namespace, skillName, topicId);
+ const existingRoot = getNamespaceRoot(existingDocuments, namespace);
+ const existingFolder = getSkillFolder(existingDocuments, namespace, skillName);
+ const existingFile = getSkillFile(existingDocuments, namespace, skillName);
+
+ if (existingFolder || existingFile) {
+ throw new AgentDocumentVfsError('Skill already exists', 'CONFLICT');
+ }
const root = existingRoot
? { documentId: existingRoot.documentId }
@@ -374,7 +321,6 @@ export const createSkillTree = async ({
agentId,
documentService,
namespace,
- topicId,
});
const createdRootId: string | undefined = existingRoot ? undefined : root.documentId;
@@ -382,48 +328,40 @@ export const createSkillTree = async ({
let createdFileId: string | undefined;
try {
- const folder = existingFolder
- ? { id: existingFolder.documentId }
- : await documentService.createDocument({
- editorData: EMPTY_EDITOR_DATA,
- fileType: DOCUMENT_FOLDER_TYPE,
- metadata: createSkillMetadata({
- lineage,
- namespace,
- role: 'skill-folder',
- skillName,
- topicId,
- }),
- parentId: root.documentId,
- title: skillName,
- });
-
- if (!existingFolder) {
- createdFolderId = folder.id;
- await agentDocumentModel.associate({
- agentId,
- documentId: folder.id,
- policyLoad: PolicyLoad.DISABLED,
- uniqueSibling: false,
- });
- }
+ const folder = await documentService.createDocument({
+ editorData: EMPTY_EDITOR_DATA,
+ fileType: DOCUMENT_FOLDER_TYPE,
+ metadata: createSkillMetadata({
+ namespace,
+ role: 'skill-folder',
+ skillName,
+ }),
+ parentId: root.documentId,
+ title: skillName,
+ });
+
+ createdFolderId = folder.id;
+ await agentDocumentModel.associate({
+ agentId,
+ documentId: folder.id,
+ policyLoad: PolicyLoad.DISABLED,
+ });
const file = await documentService.createDocument({
content,
editorData,
+ fileType: SKILL_INDEX_FILE_TYPE,
metadata: createSkillMetadata({
- lineage,
namespace,
role: 'skill-file',
skillName,
- topicId,
}),
parentId: folder.id,
title: SKILL_FILE_NAME,
});
createdFileId = file.id;
- await agentDocumentModel.associate({ agentId, documentId: file.id, uniqueSibling: false });
+ await agentDocumentModel.associate({ agentId, documentId: file.id });
return { fileDocumentId: file.id, folderDocumentId: folder.id };
} catch (error) {
diff --git a/src/server/services/agentDocumentVfs/mounts/skills/types.ts b/src/server/services/agentDocumentVfs/mounts/skills/types.ts
index c36d58c8dfe..cff92bcbb10 100644
--- a/src/server/services/agentDocumentVfs/mounts/skills/types.ts
+++ b/src/server/services/agentDocumentVfs/mounts/skills/types.ts
@@ -7,7 +7,7 @@ export interface SkillMountNode {
content?: string;
contentType?: 'text/markdown';
name: string;
- namespace: 'builtin' | 'installed-all' | 'installed-active' | 'agent' | 'agent-topic';
+ namespace: 'builtin' | 'installed-all' | 'installed-active' | 'agent';
path: string;
readOnly: boolean;
size?: number;
diff --git a/src/server/services/agentDocuments/index.ts b/src/server/services/agentDocuments/index.ts
index 88a9c7b14fa..cb835876e75 100644
--- a/src/server/services/agentDocuments/index.ts
+++ b/src/server/services/agentDocuments/index.ts
@@ -7,6 +7,7 @@ import type {
} from '@lobechat/agent-templates';
import { DocumentLoadPosition, getDocumentTemplate } from '@lobechat/agent-templates';
import type { LobeChatDatabase } from '@lobechat/database';
+import { DOCUMENT_FOLDER_TYPE } from '@lobechat/database/schemas';
import type {
AgentDocument,
@@ -73,6 +74,8 @@ export class AgentDocumentsService {
doc: T | undefined,
): Promise<T | undefined> {
if (!doc?.editorData) return doc;
+ if (doc.fileType === DOCUMENT_FOLDER_TYPE) return doc;
+ if (isManagedSkillDocument(doc)) return doc;
try {
const snapshot = await exportEditorDataSnapshot({
@@ -426,6 +429,7 @@ export class AgentDocumentsService {
const docs = await this.agentDocumentModel.findByAgent(agentId);
return docs.map((d) => ({
documentId: d.documentId,
+ fileType: d.fileType,
filename: d.filename,
id: d.id,
loadPosition: d.policy?.context?.position,
@@ -444,6 +448,7 @@ export class AgentDocumentsService {
.filter((doc): doc is AgentDocumentWithRules => Boolean(doc))
.map((doc) => ({
documentId: doc.documentId,
+ fileType: doc.fileType,
filename: doc.filename,
id: doc.id,
loadPosition: doc.policy?.context?.position,
diff --git a/src/server/services/agentSignal/__tests__/index.integration.test.ts b/src/server/services/agentSignal/__tests__/index.integration.test.ts
index 10818b1b3e1..e401a7d636b 100644
--- a/src/server/services/agentSignal/__tests__/index.integration.test.ts
+++ b/src/server/services/agentSignal/__tests__/index.integration.test.ts
@@ -36,6 +36,7 @@ const loadIndexIntegrationModule = async (options: LoadIndexIntegrationModuleOpt
vi.doUnmock('../featureGate');
vi.doUnmock('../observability/projector');
vi.doUnmock('../observability/store');
+ vi.doUnmock('../orchestrator');
vi.doUnmock('../runtime/AgentSignalRuntime');
vi.doUnmock('../sources');
vi.doUnmock('@/server/services/agentDocuments');
@@ -95,18 +96,26 @@ afterEach(() => {
});
describe('emitAgentSignalSourceEvent integration', () => {
- it('returns early when the feature gate is disabled', async () => {
- const emitSourceEvent = vi.fn();
- const { emitAgentSignalSourceEvent } = await loadIndexIntegrationModule({
- featureGateEnabled: false,
- mockEmitSourceEvent: emitSourceEvent,
- });
+ it('passes the enabled self-iteration policy into immediate source execution', async () => {
+ vi.resetModules();
- const result = await emitAgentSignalSourceEvent(
+ const executeAgentSignalSourceEvent = vi.fn().mockResolvedValue(undefined);
+ const isAgentSignalEnabledForUser = vi.fn().mockResolvedValue(true);
+
+ vi.doMock('../featureGate', () => ({
+ isAgentSignalEnabledForUser,
+ }));
+ vi.doMock('../orchestrator', () => ({
+ executeAgentSignalSourceEvent,
+ }));
+
+ const { emitAgentSignalSourceEvent } = await import('../emitter');
+
+ await emitAgentSignalSourceEvent(
{
- payload: { message: 'Remember this.', messageId: 'msg-disabled' },
+ payload: { message: 'Create a reusable skill.', messageId: 'msg-skill' },
scopeKey: 'topic:topic-1',
- sourceId: 'eval-agent-signal-disabled',
+ sourceId: 'source-skill',
sourceType: 'agent.user.message',
timestamp: 1_710_000_000_000,
},
@@ -117,8 +126,17 @@ describe('emitAgentSignalSourceEvent integration', () => {
},
);
- expect(result).toBeUndefined();
- expect(emitSourceEvent).not.toHaveBeenCalled();
+ expect(executeAgentSignalSourceEvent).toHaveBeenCalledWith(
+ expect.any(Object),
+ expect.any(Object),
+ expect.objectContaining({
+ policyOptions: {
+ skillManagement: {
+ selfIterationEnabled: true,
+ },
+ },
+ }),
+ );
});
it('orchestrates source emission through the runtime boundary', async () => {
diff --git a/src/server/services/agentSignal/emitter.ts b/src/server/services/agentSignal/emitter.ts
index 9e5ace7cb35..c8b13b0d66b 100644
--- a/src/server/services/agentSignal/emitter.ts
+++ b/src/server/services/agentSignal/emitter.ts
@@ -7,6 +7,7 @@ import { AgentSignalWorkflow } from '@/server/workflows/agentSignal';
import { isAgentSignalEnabledForUser } from './featureGate';
import type { GeneratedAgentSignalEmissionResult } from './orchestrator';
+import type { CreateDefaultAgentSignalPoliciesOptions } from './policies';
import { AgentSignalScopeKey } from './scopeKey';
import type { EmitSourceEventInput } from './sources';
import type {
@@ -48,8 +49,18 @@ export interface AgentSignalSourceEventInput<
}
/** One AgentSignal emission execution option set. */
+export interface AgentSignalPolicyOptionOverrides extends Omit<
+ Partial<CreateDefaultAgentSignalPoliciesOptions>,
+ 'skillManagement'
+> {
+ skillManagement?: Partial<
+ NonNullable<CreateDefaultAgentSignalPoliciesOptions['skillManagement']>
+ >;
+}
+
export interface AgentSignalEmitOptions {
ignoreError?: boolean;
+ policyOptions?: AgentSignalPolicyOptionOverrides;
}
/** One AgentSignal async handoff result. */
@@ -88,6 +99,20 @@ export const resolveSourceScopeKey = (payload: Record<string, unknown>) => {
});
};
+const withSelfIterationPolicy = (
+ options: AgentSignalEmitOptions,
+ selfIterationEnabled: boolean,
+): AgentSignalEmitOptions => ({
+ ...options,
+ policyOptions: {
+ ...options.policyOptions,
+ skillManagement: {
+ ...options.policyOptions?.skillManagement,
+ selfIterationEnabled,
+ },
+ },
+});
+
/**
* Emits one source event into the AgentSignal pipeline and executes matching policies.
*
@@ -106,13 +131,15 @@ export const emitAgentSignalSourceEvent = async <TSourceType extends AgentSignal
context: AgentSignalExecutionContext,
options: AgentSignalEmitOptions = {},
): Promise<DedupedSourceEventResult | GeneratedAgentSignalEmissionResult | undefined> => {
- if (!(await isAgentSignalEnabledForUser(context.db, context.userId))) {
+ const selfIterationEnabled = await isAgentSignalEnabledForUser(context.db, context.userId);
+
+ if (!selfIterationEnabled) {
return undefined;
}
const { executeAgentSignalSourceEvent } = await import('./orchestrator');
- return executeAgentSignalSourceEvent(input, context, options);
+ return executeAgentSignalSourceEvent(input, context, withSelfIterationPolicy(options, true));
};
/**
diff --git a/src/server/services/agentSignal/observability/__tests__/traceEvents.test.ts b/src/server/services/agentSignal/observability/__tests__/traceEvents.test.ts
index 57dcfc30d96..1ba9d683eaa 100644
--- a/src/server/services/agentSignal/observability/__tests__/traceEvents.test.ts
+++ b/src/server/services/agentSignal/observability/__tests__/traceEvents.test.ts
@@ -39,6 +39,7 @@ describe('toAgentSignalTraceEvents', () => {
{
actionId: 'action_1',
attempt: { completedAt: 5, current: 1, startedAt: 4, status: 'succeeded' },
+ output: { decision: { action: 'create' } },
status: 'applied',
},
],
@@ -62,6 +63,45 @@ describe('toAgentSignalTraceEvents', () => {
expect.objectContaining({
attemptCurrent: 1,
attemptStatus: 'succeeded',
+ outputDecision: { action: 'create' },
+ }),
+ );
+ });
+
+ /**
+ * @example
+ * const failed = toAgentSignalTraceEvents({ results: [{ status: 'failed', error: { message: 'boom' } }] });
+ * expect(failed.at(-1)?.data.errorMessage).toBe('boom');
+ */
+ it('keeps failed action error messages in trace events', () => {
+ const events = toAgentSignalTraceEvents({
+ actions: [],
+ results: [
+ {
+ actionId: 'action_failed',
+ attempt: { completedAt: 5, current: 1, startedAt: 4, status: 'failed' },
+ error: {
+ code: 'SKILL_MANAGEMENT_EXECUTION_FAILED',
+ message: 'model output did not match schema',
+ },
+ status: 'failed',
+ },
+ ],
+ signals: [],
+ source: {
+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },
+ payload: { message: 'remember this', messageId: 'msg_1' },
+ scopeKey: 'topic:t1',
+ sourceId: 'source_1',
+ sourceType: 'agent.user.message',
+ timestamp: 1,
+ },
+ });
+
+ expect(events.at(-1)?.data).toEqual(
+ expect.objectContaining({
+ errorCode: 'SKILL_MANAGEMENT_EXECUTION_FAILED',
+ errorMessage: 'model output did not match schema',
}),
);
});
diff --git a/src/server/services/agentSignal/observability/traceEvents.ts b/src/server/services/agentSignal/observability/traceEvents.ts
index 54f6247c144..cb7dad2e1f7 100644
--- a/src/server/services/agentSignal/observability/traceEvents.ts
+++ b/src/server/services/agentSignal/observability/traceEvents.ts
@@ -64,6 +64,15 @@ export const toAgentSignalTraceEvents = (input: {
attemptStatus: result.attempt.status,
detail: result.detail,
errorCode: result.status === 'failed' ? result.error.code : undefined,
+ errorMessage: result.status === 'failed' ? result.error.message : undefined,
+ outputDecision:
+ result.output &&
+ typeof result.output === 'object' &&
+ 'decision' in result.output &&
+ result.output.decision &&
+ typeof result.output.decision === 'object'
+ ? result.output.decision
+ : undefined,
runId: 'runId' in result.attempt ? result.attempt.runId : undefined,
status: result.status,
},
diff --git a/src/server/services/agentSignal/orchestrator.ts b/src/server/services/agentSignal/orchestrator.ts
index 234a730b207..7a58264fbdd 100644
--- a/src/server/services/agentSignal/orchestrator.ts
+++ b/src/server/services/agentSignal/orchestrator.ts
@@ -17,10 +17,7 @@ import {
} from './emitter';
import { projectAgentSignalObservability } from './observability/projector';
import { persistAgentSignalObservability } from './observability/store';
-import {
- createDefaultAgentSignalPolicies,
- type CreateDefaultAgentSignalPoliciesOptions,
-} from './policies';
+import { createDefaultAgentSignalPolicies } from './policies';
import type { RuntimeGuardBackend } from './runtime/AgentSignalRuntime';
import { createAgentSignalRuntime } from './runtime/AgentSignalRuntime';
import { emitSourceEvent } from './sources';
@@ -30,7 +27,6 @@ import type { AgentSignalSourceEventStore } from './store/types';
export { createAgentSignalRuntime } from './runtime/AgentSignalRuntime';
interface ExecuteAgentSignalSourceEventOptions extends AgentSignalEmitOptions {
- policyOptions?: Partial<CreateDefaultAgentSignalPoliciesOptions>;
runtimeGuardBackend?: RuntimeGuardBackend;
store?: AgentSignalSourceEventStore;
}
@@ -128,6 +124,13 @@ const executeAgentSignalSourceEventCore = async <TSourceType extends AgentSignal
...options.policyOptions?.userMemory,
userId: context.userId,
},
+ skillManagement: {
+ db: context.db,
+ ...options.policyOptions?.skillManagement,
+ selfIterationEnabled:
+ options.policyOptions?.skillManagement?.selfIterationEnabled ?? false,
+ userId: context.userId,
+ },
}),
});
const runtimeResult = await runtime.emitNormalized(emission.source);
diff --git a/src/server/services/agentSignal/policies/actionIdempotency.ts b/src/server/services/agentSignal/policies/actionIdempotency.ts
index e8c943b9ea9..f2691313f34 100644
--- a/src/server/services/agentSignal/policies/actionIdempotency.ts
+++ b/src/server/services/agentSignal/policies/actionIdempotency.ts
@@ -5,6 +5,11 @@ const ACTION_IDEMPOTENCY_LANE_PREFIX = 'action-idempotency';
/**
* Creates the scope-local guard lane for one planned action idempotency key.
*
+ * Agent Signal stores guard state inside `RuntimeProcessorContext.runtimeState`, so this lane is
+ * evaluated within the current runtime scope key, such as `topic:tpc_xxx`. Reusing the same
+ * source/message id in the same scope will therefore skip after the first successful application;
+ * using a new source id or a different scope gets a separate guard record.
+ *
* Before:
* - `source_1:memory:msg_1`
*
@@ -58,5 +63,7 @@ export const markAppliedActionIdempotency = async (
) => {
if (!idempotencyKey) return;
+ // The marker is written only after the durable side effect succeeds, so failed/skipped attempts
+ // remain retryable while successful memory/skill mutations are protected from duplicate replay.
await ctx.runtimeState.touchGuardState(createActionIdempotencyLane(idempotencyKey), ctx.now());
};
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts
index 8e2aae5ae10..18ca6683b85 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts
@@ -179,7 +179,7 @@ describe('feedbackActionPlanner', () => {
expect(second).toEqual(first);
});
- it('does not plan actions for unsupported future domains yet', async () => {
+ it('plans skill-management actions for skill domain signals', async () => {
const handler = createFeedbackActionPlannerSignalHandler();
const skillResult = await handler.handle(
createDomainSignal({
@@ -192,6 +192,26 @@ describe('feedbackActionPlanner', () => {
context,
);
+ expect(skillResult).toEqual(
+ expect.objectContaining({
+ actions: [
+ expect.objectContaining({
+ actionType: 'action.skill-management.handle',
+ payload: expect.objectContaining({
+ idempotencyKey: 'source_2:skill:msg_2',
+ message: 'This successful workflow should become a reusable skill.',
+ serializedContext:
+ '<feedback_analysis_context><message>context</message></feedback_analysis_context>',
+ }),
+ }),
+ ],
+ status: 'dispatch',
+ }),
+ );
+ });
+
+ it('does not plan actions for unsupported prompt domain yet', async () => {
+ const handler = createFeedbackActionPlannerSignalHandler();
const promptResult = await handler.handle(
createDomainSignal({
message: 'Stop saying "Below is a detailed analysis" before every answer.',
@@ -203,7 +223,6 @@ describe('feedbackActionPlanner', () => {
context,
);
- expect(skillResult).toBeUndefined();
expect(promptResult).toBeUndefined();
});
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.ts
new file mode 100644
index 00000000000..243c81d6472
--- /dev/null
+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.integration.test.ts
@@ -0,0 +1,190 @@
+// @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 { AgentDocumentModel } from '@/database/models/agentDocuments';
+import { createMarkdownEditorSnapshot } from '@/server/services/agentDocuments/headlessEditor';
+import { AgentDocumentVfsService } from '@/server/services/agentDocumentVfs';
+import { createSkillTree } from '@/server/services/agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils';
+import { DocumentService } from '@/server/services/document';
+
+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, content: string) => {
+ const snapshot = await createMarkdownEditorSnapshot(content);
+
+ await createSkillTree({
+ agentDocumentModel: new AgentDocumentModel(serverDB, userId),
+ agentId,
+ content: snapshot.content,
+ documentService: new DocumentService(serverDB, userId),
+ editorData: snapshot.editorData,
+ namespace: 'agent',
+ 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 real resolver and VFS adapter.
+ */
+ it('refines a real managed skill through resolver and VFS-backed maintainer operations', async () => {
+ 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([
+ {
+ content: '# Review Skill\n',
+ id: 'review-skill',
+ metadata: {},
+ },
+ ]);
+
+ return {
+ operations: [
+ {
+ arguments: {
+ content: '# Review Skill\n\n## Procedure\n- Check failed assertions first.',
+ path: 'SKILL.md',
+ skillRef: 'review-skill',
+ },
+ name: 'updateSkill',
+ },
+ ],
+ reason: 'refined review skill',
+ };
+ },
+ userId,
+ },
+ {
+ action: 'refine',
+ reason: 'update existing review skill',
+ targetSkillIds: ['review-skill'],
+ },
+ );
+
+ expect(result).toMatchObject({
+ detail: 'refined review skill',
+ status: 'applied',
+ });
+ expect(await readSkillIndex('review-skill')).toBe(
+ '# Review Skill\n\n## Procedure\n\n- Check failed assertions first.\n',
+ );
+ });
+
+ /**
+ * @example
+ * Consolidate updates an allowed target skill and does not apply lifecycle proposals.
+ */
+ it('consolidates real managed skills without applying lifecycle proposals automatically', async () => {
+ await createManagedSkill('review-skill', '# Review Skill');
+ 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([
+ {
+ content: '# Review Skill\n',
+ id: 'review-skill',
+ metadata: {},
+ },
+ {
+ content: '# Review Checklist\n',
+ id: 'review-checklist',
+ metadata: {},
+ },
+ ]);
+
+ return {
+ operations: [
+ {
+ arguments: {
+ content: '# Review Skill\n\n## Procedure\n- Use one consolidated checklist.',
+ path: 'SKILL.md',
+ skillRef: 'review-skill',
+ },
+ name: 'updateSkill',
+ },
+ ],
+ proposedLifecycleActions: [
+ {
+ action: 'archive',
+ reason: 'merged into review-skill',
+ skillRef: 'review-checklist',
+ },
+ ],
+ reason: 'consolidated review skills',
+ };
+ },
+ userId,
+ },
+ {
+ action: 'consolidate',
+ reason: 'overlapping review skills',
+ targetSkillIds: ['review-skill', 'review-checklist'],
+ },
+ );
+
+ expect(result).toMatchObject({
+ detail: 'consolidated review skills',
+ status: 'applied',
+ });
+ expect(await readSkillIndex('review-skill')).toBe(
+ '# Review Skill\n\n## Procedure\n\n- Use one consolidated checklist.\n',
+ );
+ expect(await readSkillIndex('review-checklist')).toBe('# Review Checklist\n');
+ });
+});
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.ts
new file mode 100644
index 00000000000..11bce108978
--- /dev/null
+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts
@@ -0,0 +1,736 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as ProviderSkillsAgentDocumentUtils from '@/server/services/agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils';
+import { createSkillTree } from '@/server/services/agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils';
+
+import type { RuntimeProcessorContext } from '../../../../runtime/context';
+import {
+ collectAgentSkillDecisionCandidates,
+ defineSkillManagementActionHandler,
+ handleSkillManagementSignal,
+} from '../skillManagement';
+
+const skillDecisionRunner = vi.fn();
+const skillMaintainerRunner = vi.fn();
+const skillMaintainerService = {
+ readSkillFile: vi.fn(),
+ removeSkillFile: vi.fn(),
+ updateSkill: vi.fn(),
+ writeSkillFile: vi.fn(),
+};
+
+vi.mock('@/server/services/agentDocuments/headlessEditor', () => ({
+ createMarkdownEditorSnapshot: vi.fn(async (content: string) => ({
+ content,
+ editorData: { markdown: content },
+ })),
+}));
+
+vi.mock(
+ '@/server/services/agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils',
+ async (importOriginal) => {
+ const actual = await importOriginal<typeof ProviderSkillsAgentDocumentUtils>();
+
+ return {
+ ...actual,
+ createSkillTree: vi.fn(),
+ };
+ },
+);
+
+const context = {
+ now: () => 1,
+ runtimeState: {
+ getGuardState: vi.fn().mockResolvedValue({}),
+ touchGuardState: vi.fn().mockResolvedValue({}),
+ },
+ scopeKey: 'topic:topic-1',
+} as const satisfies RuntimeProcessorContext;
+
+describe('defineSkillManagementActionHandler', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ skillDecisionRunner.mockReset();
+ skillMaintainerRunner.mockReset();
+ skillMaintainerService.readSkillFile.mockReset();
+ skillMaintainerService.removeSkillFile.mockReset();
+ skillMaintainerService.updateSkill.mockReset();
+ skillMaintainerService.writeSkillFile.mockReset();
+ });
+
+ it('does not run when self iteration is disabled', async () => {
+ const result = await handleSkillManagementSignal({
+ 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 handleSkillManagementSignal({
+ 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'] as const) {
+ const result = await handleSkillManagementSignal({
+ 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
+ * Removed lifecycle tools must not leak into the action result.
+ */
+ it('does not return automatic lifecycle tool actions from decision output', async () => {
+ const result = await handleSkillManagementSignal({
+ 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 package names, while names remain display labels.
+ */
+ it('collects managed skill folders as package-name decision candidates', () => {
+ expect(
+ collectAgentSkillDecisionCandidates([
+ {
+ documentId: 'folder-doc',
+ filename: 'Review Skill',
+ metadata: {
+ lobeSkill: {
+ namespace: 'agent',
+ role: 'skill-folder',
+ skillName: 'review-skill',
+ },
+ },
+ title: 'Review Skill',
+ },
+ {
+ documentId: 'file-doc',
+ filename: 'SKILL.md',
+ metadata: {
+ lobeSkill: {
+ namespace: 'agent',
+ role: 'skill-file',
+ skillName: 'review-skill',
+ },
+ },
+ title: 'SKILL.md',
+ },
+ ] as never),
+ ).toEqual([{ id: 'review-skill', 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',
+ });
+
+ const handler = defineSkillManagementActionHandler({
+ db: {} as never,
+ selfIterationEnabled: true,
+ 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,
+ );
+
+ expect(skillDecisionRunner).toHaveBeenCalledWith({
+ agentId: 'agent_1',
+ evidence: [{ cue: 'reusable', excerpt: 'Make this a reusable checklist.' }],
+ feedbackMessage: 'Make this a reusable checklist for PR reviews.',
+ topicId: 'topic_1',
+ turnContext: '{"surface":"chat"}',
+ });
+ expect(result).toMatchObject({
+ output: {
+ decision: { action: 'create', confidence: 0.9, reason: 'reusable workflow feedback' },
+ },
+ status: 'applied',
+ });
+ expect(context.runtimeState.touchGuardState).toHaveBeenCalledTimes(1);
+ });
+
+ /**
+ * @example
+ * Decision agents receive managed skill package candidates so targetSkillIds 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',
+ targetSkillIds: ['review-skill'],
+ });
+ skillMaintainerService.readSkillFile.mockResolvedValue('# Review Skill');
+ skillMaintainerRunner.mockResolvedValue({ operations: [], reason: 'no file changes' });
+
+ const handler = defineSkillManagementActionHandler({
+ db: {} as never,
+ selfIterationEnabled: true,
+ skillCandidateSkillsFactory: async () => [
+ { id: 'review-skill', name: 'Review Skill', scope: 'agent' },
+ ],
+ skillDecisionRunner,
+ skillMaintainerRunner,
+ skillMaintainerServiceFactory: () => 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', name: 'Review Skill', scope: 'agent' }],
+ }),
+ );
+ });
+
+ /**
+ * @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
+ * Disabled self-iteration stops before the decision agent and document writer.
+ */
+ it('skips skill-management before decision when self-iteration is disabled', async () => {
+ const handler = defineSkillManagementActionHandler({
+ db: {} as never,
+ 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(createSkillTree).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(createSkillTree).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 file operations.
+ */
+ it('runs the maintainer workflow for refine decisions', async () => {
+ skillDecisionRunner.mockResolvedValue({
+ action: 'refine',
+ reason: 'update existing review skill',
+ targetSkillIds: ['review-skill'],
+ });
+ skillMaintainerService.readSkillFile.mockResolvedValue('# Review Skill');
+ skillMaintainerRunner.mockResolvedValue({
+ operations: [
+ {
+ arguments: {
+ content: '# Review Skill\n\n## Procedure\n- Check failed assertions first.',
+ path: 'SKILL.md',
+ skillRef: 'review-skill',
+ },
+ name: 'updateSkill',
+ },
+ ],
+ reason: 'refined review skill',
+ });
+
+ const handler = defineSkillManagementActionHandler({
+ db: {} as never,
+ selfIterationEnabled: true,
+ skillDecisionRunner,
+ skillMaintainerRunner,
+ skillMaintainerServiceFactory: () => 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({
+ targetSkills: [{ content: '# Review Skill', id: 'review-skill', metadata: {} }],
+ type: 'refine',
+ }),
+ );
+ expect(skillMaintainerService.updateSkill).toHaveBeenCalledWith({
+ content: '# Review Skill\n\n## Procedure\n- Check failed assertions first.',
+ path: 'SKILL.md',
+ skillRef: 'review-skill',
+ });
+ expect(result).toMatchObject({
+ detail: 'refined review skill',
+ output: { decision: { action: 'refine' } },
+ status: 'applied',
+ });
+ });
+
+ /**
+ * @example
+ * A maintainer operation naming a non-target skill is rejected before mutation.
+ */
+ it('rejects maintainer operations that target skills outside the decision target set', async () => {
+ skillDecisionRunner.mockResolvedValue({
+ action: 'refine',
+ reason: 'update existing review skill',
+ targetSkillIds: ['review-skill'],
+ });
+ skillMaintainerService.readSkillFile.mockResolvedValue('# Review Skill');
+ skillMaintainerRunner.mockResolvedValue({
+ operations: [
+ {
+ arguments: {
+ content: '# Other Skill',
+ path: 'SKILL.md',
+ skillRef: 'other-skill',
+ },
+ name: 'updateSkill',
+ },
+ ],
+ reason: 'attempted cross-target write',
+ });
+
+ const handler = defineSkillManagementActionHandler({
+ db: {} as never,
+ selfIterationEnabled: true,
+ skillDecisionRunner,
+ skillMaintainerRunner,
+ skillMaintainerServiceFactory: () => 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,
+ );
+
+ expect(skillMaintainerService.updateSkill).not.toHaveBeenCalled();
+ expect(skillMaintainerService.writeSkillFile).not.toHaveBeenCalled();
+ expect(skillMaintainerService.removeSkillFile).not.toHaveBeenCalled();
+ expect(result).toMatchObject({
+ error: {
+ message: expect.stringContaining('other-skill'),
+ },
+ status: 'failed',
+ });
+ });
+
+ /**
+ * @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',
+ targetSkillIds: ['review-skill', 'review-checklist'],
+ });
+ skillMaintainerService.readSkillFile
+ .mockResolvedValueOnce('# Review Skill')
+ .mockResolvedValueOnce('# Review Checklist');
+ skillMaintainerRunner.mockResolvedValue({
+ operations: [
+ {
+ arguments: {
+ content: '# Review Skill\n\n## Procedure\n- Use one consolidated checklist.',
+ path: 'SKILL.md',
+ skillRef: 'review-skill',
+ },
+ name: 'updateSkill',
+ },
+ ],
+ proposedLifecycleActions: [
+ {
+ action: 'archive',
+ reason: 'merged into review-skill',
+ skillRef: 'review-checklist',
+ },
+ ],
+ reason: 'consolidated review skills',
+ });
+
+ const handler = defineSkillManagementActionHandler({
+ db: {} as never,
+ selfIterationEnabled: true,
+ skillDecisionRunner,
+ skillMaintainerRunner,
+ skillMaintainerServiceFactory: () => 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,
+ );
+
+ expect(skillMaintainerRunner).toHaveBeenCalledWith(
+ expect.objectContaining({
+ targetSkills: [
+ { content: '# Review Skill', id: 'review-skill', metadata: {} },
+ { content: '# Review Checklist', id: 'review-checklist', metadata: {} },
+ ],
+ type: 'consolidate',
+ }),
+ );
+ expect(skillMaintainerService.updateSkill).toHaveBeenCalledWith({
+ content: '# Review Skill\n\n## Procedure\n- Use one consolidated checklist.',
+ path: 'SKILL.md',
+ skillRef: 'review-skill',
+ });
+ expect(result).toMatchObject({
+ detail: 'consolidated review skills',
+ output: { decision: { action: 'consolidate' } },
+ status: 'applied',
+ });
+ });
+
+ /**
+ * @example
+ * Duplicate skill creation is reported as skipped while preserving the create decision.
+ */
+ it('skips duplicate skill creation with a structured create decision', async () => {
+ vi.mocked(createSkillTree).mockRejectedValueOnce(new Error('Skill already exists'));
+ skillDecisionRunner.mockResolvedValue({ action: 'create', reason: 'reusable workflow' });
+
+ const handler = defineSkillManagementActionHandler({
+ db: {} as never,
+ selfIterationEnabled: true,
+ 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,
+ );
+
+ expect(result).toMatchObject({
+ detail: 'Skill already exists',
+ output: { decision: { action: 'create' } },
+ status: 'skipped',
+ });
+ });
+});
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/index.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/index.ts
index ce0f004e09f..ba901944282 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/index.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/index.ts
@@ -1 +1,2 @@
+export * from './skillManagement';
export * from './userMemory';
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts
new file mode 100644
index 00000000000..3607732de17
--- /dev/null
+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts
@@ -0,0 +1,968 @@
+import type {
+ AgenticAttempt,
+ BaseAction,
+ ExecutorResult,
+ SignalAttempt,
+} from '@lobechat/agent-signal';
+import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';
+import type { GenerateObjectSchema } from '@lobechat/model-runtime';
+import {
+ AGENT_SKILL_CONSOLIDATE_SYSTEM_ROLE,
+ AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE,
+ AGENT_SKILL_REFINE_SYSTEM_ROLE,
+ createAgentSkillConsolidatePrompt,
+ createAgentSkillManagerDecisionPrompt,
+ createAgentSkillRefinePrompt,
+} from '@lobechat/prompts';
+import { RequestTrigger } from '@lobechat/types';
+import { z } from 'zod';
+
+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 { createMarkdownEditorSnapshot } from '@/server/services/agentDocuments/headlessEditor';
+import { AgentDocumentVfsService } from '@/server/services/agentDocumentVfs';
+import {
+ createSkillTree,
+ getSkillFolder,
+ getSkillMetadata,
+} from '@/server/services/agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils';
+import { DocumentService } from '@/server/services/document';
+import { SkillMaintainerService } from '@/server/services/skillMaintainer/SkillMaintainerService';
+import { SkillReferenceResolver } from '@/server/services/skillMaintainer/SkillReferenceResolver';
+import { VfsSkillPackageAdapter } from '@/server/services/skillMaintainer/VfsSkillPackageAdapter';
+
+import type { RuntimeProcessorContext } from '../../../runtime/context';
+import { defineActionHandler } from '../../../runtime/middleware';
+import { hasAppliedActionIdempotency, markAppliedActionIdempotency } from '../../actionIdempotency';
+import type { ActionSkillManagementHandle, AgentSignalFeedbackEvidence } from '../../types';
+import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../../types';
+import { createFeedbackActionPlannerSignalHandler } from '../feedbackAction';
+
+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 package id. */
+ candidateSkills?: SkillManagementCandidateSkill[];
+ /** Evidence extracted from the feedback message. */
+ evidence?: Array<{ cue: string; excerpt: string }>;
+ /** Original feedback message that motivated the signal. */
+ feedbackMessage: string;
+ /** Optional topic where the feedback happened. */
+ topicId?: string;
+ /** Optional relevant turn summary. */
+ turnContext?: string;
+}
+
+export type SkillManagementDecisionAction = 'consolidate' | 'create' | 'noop' | 'refine';
+
+/**
+ * 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 short explanation for observability. */
+ reason?: string;
+ /** Optional file paths that should be read before refinement or consolidation. */
+ requiredReads?: string[];
+ /** Optional target skill identifiers selected by the decision model. */
+ targetSkillIds?: string[];
+}
+
+export interface SkillManagementActionResult {
+ decision: SkillManagementDecision;
+ detail?: string;
+ status: 'applied' | 'failed' | 'skipped';
+}
+
+export interface SkillManagementActionInput {
+ agentId?: string;
+ candidateSkills?: SkillManagementCandidateSkill[];
+ evidence?: AgentSignalFeedbackEvidence[];
+ feedbackHint?: 'not_satisfied' | 'satisfied';
+ message: string;
+ reason?: string;
+ serializedContext?: string;
+ topicId?: string;
+}
+
+export interface SkillManagementActionHandlerOptions {
+ db: LobeChatDatabase;
+ selfIterationEnabled: boolean;
+ skillCandidateSkillsFactory?: (input: {
+ agentId: string;
+ }) => Promise<SkillManagementCandidateSkill[]>;
+ skillDecisionModel?: SkillManagementAgentModelConfig;
+ skillDecisionRunner?: (input: SkillManagementSignalPayload) => Promise<unknown>;
+ skillMaintainerRunner?: (input: SkillMaintainerWorkflowInput) => Promise<unknown>;
+ skillMaintainerServiceFactory?: (input: {
+ agentId: string;
+ }) => SkillMaintainerFileOperationService;
+ userId: string;
+}
+
+export interface SkillManagementAgentModelConfig {
+ model: string;
+ provider: string;
+}
+
+export interface SkillMaintainerOperation {
+ arguments: Record<string, unknown>;
+ name: 'removeSkillFile' | 'updateSkill' | 'writeSkillFile';
+}
+
+export interface SkillMaintainerWorkflowInput {
+ decision: SkillManagementDecision;
+ signal: SkillManagementActionInput;
+ targetSkills: Array<{
+ content: string;
+ id: string;
+ metadata: Record<string, unknown>;
+ }>;
+ type: 'consolidate' | 'refine';
+}
+
+export interface SkillMaintainerWorkflowResult {
+ confidence?: number;
+ operations: SkillMaintainerOperation[];
+ proposedLifecycleActions?: Array<Record<string, unknown>>;
+ reason?: string;
+}
+
+export interface SkillMaintainerFileOperationService {
+ readSkillFile: (input: { path: string; skillRef: string }) => Promise<string>;
+ removeSkillFile: (input: { path: string; skillRef: string }) => Promise<void>;
+ updateSkill: (input: { content: string; path: string; skillRef: string }) => Promise<void>;
+ writeSkillFile: (input: { content: string; path: string; skillRef: string }) => Promise<void>;
+}
+
+const SkillManagementDecisionSchema = z.object({
+ action: z.enum(['create', 'refine', 'consolidate', 'noop']),
+ confidence: z.number().min(0).max(1).nullable(),
+ reason: z.string().nullable(),
+ requiredReads: z.array(z.string()),
+ targetSkillIds: z.array(z.string()),
+});
+
+const SkillMaintainerOperationSchema = z.object({
+ arguments: z.record(z.string(), z.unknown()),
+ name: z.enum(['updateSkill', 'writeSkillFile', 'removeSkillFile']),
+});
+
+const SkillMaintainerWorkflowResultSchema = z.object({
+ confidence: z.number().min(0).max(1).nullable().default(null),
+ operations: z.array(SkillMaintainerOperationSchema),
+ proposedLifecycleActions: z.array(z.record(z.string(), z.unknown())).default([]),
+ reason: z.string().nullable().default(null),
+});
+
+const SkillManagementDecisionGenerateObjectSchema = {
+ name: 'agent_signal_skill_management_decision',
+ schema: {
+ additionalProperties: false,
+ properties: {
+ action: { enum: ['create', 'refine', 'consolidate', 'noop'], type: 'string' },
+ confidence: {
+ anyOf: [{ maximum: 1, minimum: 0, type: 'number' }, { type: 'null' }],
+ },
+ reason: { type: ['string', 'null'] },
+ requiredReads: { items: { type: 'string' }, type: 'array' },
+ targetSkillIds: { items: { type: 'string' }, type: 'array' },
+ },
+ required: ['action', 'confidence', 'reason', 'requiredReads', 'targetSkillIds'],
+ type: 'object',
+ },
+ strict: true,
+} satisfies GenerateObjectSchema;
+
+const SkillMaintainerWorkflowResultBaseGenerateObjectSchema = {
+ schema: {
+ additionalProperties: false,
+ properties: {
+ confidence: {
+ anyOf: [{ maximum: 1, minimum: 0, type: 'number' }, { type: 'null' }],
+ },
+ operations: {
+ items: {
+ additionalProperties: false,
+ properties: {
+ arguments: { additionalProperties: {}, type: 'object' },
+ name: {
+ enum: ['updateSkill', 'writeSkillFile', 'removeSkillFile'],
+ type: 'string',
+ },
+ },
+ required: ['arguments', 'name'],
+ type: 'object',
+ },
+ type: 'array',
+ },
+ proposedLifecycleActions: {
+ items: { additionalProperties: {}, type: 'object' },
+ type: 'array',
+ },
+ reason: { type: ['string', 'null'] },
+ },
+ required: ['confidence', 'operations', 'proposedLifecycleActions', 'reason'],
+ type: 'object',
+ },
+ strict: true,
+} satisfies Omit<GenerateObjectSchema, 'name'>;
+
+const isSkillManagementDecisionAction = (value: unknown): value is SkillManagementDecisionAction =>
+ value === 'create' || value === 'refine' || value === 'consolidate' || value === 'noop';
+
+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 reason = typeof record.reason === 'string' ? record.reason : undefined;
+ const requiredReads = getStringArray(record.requiredReads);
+ const targetSkillIds = getStringArray(record.targetSkillIds);
+
+ return {
+ action,
+ ...(confidence === undefined ? {} : { confidence }),
+ ...(reason === undefined ? {} : { reason }),
+ ...(requiredReads === undefined ? {} : { requiredReads }),
+ ...(targetSkillIds === undefined ? {} : { targetSkillIds }),
+ };
+};
+
+/**
+ * Handles one skill-domain Agent Signal 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 handleSkillManagementSignal = async (input: {
+ decide: (payload: SkillManagementSignalPayload) => Promise<unknown>;
+ payload: SkillManagementSignalPayload;
+ selfIterationEnabled: boolean;
+}) => {
+ if (!input.selfIterationEnabled) {
+ return { reason: 'self iteration is disabled', status: 'skipped' as const };
+ }
+
+ const decision = normalizeSkillManagementDecision(await input.decide(input.payload));
+
+ return { decision, status: 'decided' as const };
+};
+
+const toSkillManagementDecision = (
+ value: z.infer<typeof SkillManagementDecisionSchema>,
+): SkillManagementDecision => ({
+ action: value.action,
+ ...(value.confidence === null ? {} : { confidence: value.confidence }),
+ ...(value.reason === null ? {} : { reason: value.reason }),
+ ...(value.requiredReads.length === 0 ? {} : { requiredReads: value.requiredReads }),
+ ...(value.targetSkillIds.length === 0 ? {} : { targetSkillIds: value.targetSkillIds }),
+});
+
+/**
+ * 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 store package names in `metadata.lobeSkill.skillName`
+ *
+ * Returns:
+ * - Agent-scoped candidate ids that are package names for `targetSkillIds`
+ */
+export const collectAgentSkillDecisionCandidates = (
+ documents: AgentDocument[],
+): SkillManagementCandidateSkill[] => {
+ const candidates: SkillManagementCandidateSkill[] = [];
+
+ for (const document of documents) {
+ const metadata = getSkillMetadata(document);
+
+ if (
+ metadata?.namespace !== 'agent' ||
+ metadata.role !== 'skill-folder' ||
+ !metadata.skillName
+ ) {
+ continue;
+ }
+
+ candidates.push({
+ id: metadata.skillName,
+ name: document.title ?? document.filename ?? metadata.skillName,
+ scope: 'agent',
+ });
+ }
+
+ return candidates.sort((left, right) => left.id.localeCompare(right.id));
+};
+
+const toSkillMaintainerWorkflowResult = (
+ value: z.infer<typeof SkillMaintainerWorkflowResultSchema>,
+): SkillMaintainerWorkflowResult => ({
+ operations: value.operations,
+ ...(value.confidence === null ? {} : { confidence: value.confidence }),
+ ...(value.proposedLifecycleActions.length === 0
+ ? {}
+ : { proposedLifecycleActions: value.proposedLifecycleActions }),
+ ...(value.reason === null ? {} : { reason: value.reason }),
+});
+
+class SkillManagementDecisionAgentService {
+ 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 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 modelRuntime.generateObject(
+ {
+ messages: [
+ { content: AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE, role: 'system' },
+ {
+ content: createAgentSkillManagerDecisionPrompt({
+ agentId: input.agentId,
+ ...(candidateSkills.length > 0 ? { candidateSkills } : {}),
+ evidence: input.evidence ?? [],
+ feedbackMessage: input.feedbackMessage,
+ topicId: input.topicId,
+ turnContext: input.turnContext,
+ }),
+ role: 'user',
+ },
+ ] as never[],
+ model: this.modelConfig.model,
+ schema: SkillManagementDecisionGenerateObjectSchema,
+ },
+ { metadata: { trigger: RequestTrigger.Memory } },
+ );
+
+ return toSkillManagementDecision(SkillManagementDecisionSchema.parse(result));
+ }
+}
+
+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({
+ 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({
+ 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.Memory } },
+ );
+
+ return toSkillMaintainerWorkflowResult(SkillMaintainerWorkflowResultSchema.parse(result));
+ }
+}
+
+const finalizeAttempt = (
+ startedAt: number,
+ status: SignalAttempt['status'],
+): SignalAttempt | AgenticAttempt => ({
+ completedAt: Date.now(),
+ current: 1,
+ startedAt,
+ status,
+});
+
+const toExecutorError = (actionId: string, error: unknown, startedAt: number): ExecutorResult => {
+ return {
+ actionId,
+ attempt: finalizeAttempt(startedAt, 'failed'),
+ error: {
+ cause: error,
+ code: 'SKILL_MANAGEMENT_EXECUTION_FAILED',
+ message: error instanceof Error ? error.message : String(error),
+ },
+ status: 'failed',
+ };
+};
+
+const createNoopDecision = (reason: string): SkillManagementDecision => ({
+ action: 'noop',
+ reason,
+});
+
+const toSkippedExecutorResult = ({
+ actionId,
+ decision,
+ detail,
+ startedAt,
+}: {
+ actionId: string;
+ decision: SkillManagementDecision;
+ 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;
+};
+
+/**
+ * Normalizes feedback text into a skill package name.
+ *
+ * Before:
+ * - "This review workflow should become a reusable checklist."
+ *
+ * After:
+ * - "review-workflow-reusable-checklist"
+ */
+export const normalizeSkillPackageName = (message: string) => {
+ const words = message
+ .toLowerCase()
+ .replaceAll(/[^a-z0-9]+/g, ' ')
+ .trim()
+ .split(/\s+/)
+ .filter((word) => word.length > 2 && !['should', 'this', 'that', 'become'].includes(word))
+ .slice(0, 5);
+
+ return words.length > 0 ? words.join('-') : 'agent-signal-skill';
+};
+
+export const createSkillDecisionRunner = (options: SkillManagementActionHandlerOptions) => {
+ const agent = new SkillManagementDecisionAgentService(
+ options.db,
+ options.userId,
+ options.skillDecisionModel,
+ );
+
+ 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 toSkillTitle = (skillName: string) =>
+ skillName
+ .split('-')
+ .map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`)
+ .join(' ');
+
+const toSkillContent = (input: SkillManagementActionInput, skillName: string) => {
+ const evidence = input.evidence?.map((item) => `- ${item.cue}: ${item.excerpt}`).join('\n');
+ const context = input.serializedContext ? `\n\n## Context\n${input.serializedContext}` : '';
+ const evidenceBlock = evidence ? `\n\n## Evidence\n${evidence}` : '';
+ const reason = input.reason ? `\n\n## Reason\n${input.reason}` : '';
+
+ return `# ${toSkillTitle(skillName)}
+
+## Trigger
+Use when similar feedback or work requires this reusable procedure.
+
+## Procedure
+- Apply the workflow requested in the feedback.
+- Preserve concrete checks, ordering, and verification criteria from the source turn.
+- Re-check the result before responding.
+
+## Source Feedback
+${input.message}${reason}${evidenceBlock}${context}
+`;
+};
+
+const createDefaultSkillMaintainerService = (
+ options: SkillManagementActionHandlerOptions,
+ agentId: string,
+): SkillMaintainerFileOperationService => {
+ const vfs = new AgentDocumentVfsService(options.db, options.userId);
+ const agentDocumentModel = new AgentDocumentModel(options.db, options.userId);
+ const ctx = { agentId };
+
+ return new SkillMaintainerService({
+ adapter: new VfsSkillPackageAdapter({
+ delete: async (path) => {
+ await vfs.delete(path, ctx);
+ },
+ list: (path) => vfs.list(path, ctx),
+ read: async (path) => {
+ return (await vfs.read(path, ctx)).content;
+ },
+ write: async (path, content) => {
+ await vfs.write(path, content, ctx, { createMode: 'if-missing' });
+ },
+ }),
+ resolver: new SkillReferenceResolver({
+ findAgentSkillById: async (id) => {
+ const skillFolder = getSkillFolder(
+ await agentDocumentModel.findByAgent(agentId),
+ 'agent',
+ id,
+ );
+
+ return skillFolder ? { id } : undefined;
+ },
+ }),
+ });
+};
+
+const getSkillTargets = (decision: SkillManagementDecision) => decision.targetSkillIds ?? [];
+
+const isMaintainerDecision = (
+ decision: SkillManagementDecision,
+): decision is SkillManagementDecision & { action: 'consolidate' | 'refine' } =>
+ decision.action === 'refine' || decision.action === 'consolidate';
+
+// TODO(@nekomeowww): Split the maintainer workflow orchestration out of this action file.
+// This module currently owns decision schemas, LLM runners, VFS-backed service construction,
+// file-operation application, and create/refine/consolidate action orchestration. Keeping all
+// of that here makes the action handler harder to scan and will make future maintainer rules
+// risky to add because model contracts and file mutation behavior change in the same module.
+// Expected shape: keep this file focused on action input/output, idempotency, and top-level
+// dispatch; move refine/consolidate runner setup, target reads, policy checks, and operation
+// application into a small `skillMaintainerWorkflow` module with focused tests.
+const readTargetSkills = async (
+ service: SkillMaintainerFileOperationService,
+ skillRefs: string[],
+) => {
+ return Promise.all(
+ skillRefs.map(async (skillRef) => ({
+ content: await service.readSkillFile({ path: 'SKILL.md', skillRef }),
+ id: skillRef,
+ metadata: {},
+ })),
+ );
+};
+
+const getOperationStringArgument = (
+ operation: SkillMaintainerOperation,
+ key: 'content' | 'path' | 'skillRef',
+ fallback?: string,
+) => {
+ const value = operation.arguments[key];
+
+ return typeof value === 'string' && value.trim().length > 0 ? value : fallback;
+};
+
+const applyMaintainerOperations = async (
+ service: SkillMaintainerFileOperationService,
+ operations: SkillMaintainerOperation[],
+ targetSkillIds: string[],
+) => {
+ const allowedSkillRefs = new Set(targetSkillIds);
+ const defaultSkillRef = targetSkillIds[0];
+
+ if (!defaultSkillRef) {
+ throw new Error('Invalid maintainer workflow: missing target skill refs');
+ }
+
+ const normalizedOperations = operations.map((operation) => {
+ const skillRef = getOperationStringArgument(operation, 'skillRef', defaultSkillRef);
+ const path = getOperationStringArgument(operation, 'path');
+
+ if (!skillRef || !path) {
+ throw new Error(`Invalid ${operation.name} operation: missing skillRef or path`);
+ }
+
+ if (!allowedSkillRefs.has(skillRef)) {
+ throw new Error(
+ `Invalid ${operation.name} operation: skillRef is not a decision target: ${skillRef}`,
+ );
+ }
+
+ return { operation, path, skillRef };
+ });
+
+ for (const { operation, path, skillRef } of normalizedOperations) {
+ if (operation.name === 'removeSkillFile') {
+ await service.removeSkillFile({ path, skillRef });
+ continue;
+ }
+
+ const content = getOperationStringArgument(operation, 'content');
+
+ if (!content) {
+ throw new Error(`Invalid ${operation.name} operation: missing content`);
+ }
+
+ if (operation.name === 'updateSkill') {
+ await service.updateSkill({ content, path, skillRef });
+ continue;
+ }
+
+ await service.writeSkillFile({ content, path, skillRef });
+ }
+};
+
+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 targetSkillIds = getSkillTargets(decision);
+ const minimumTargets = decision.action === 'consolidate' ? 2 : 1;
+
+ if (targetSkillIds.length < minimumTargets) {
+ return {
+ decision,
+ detail: `Skill-management ${decision.action} requires targetSkillIds from the decision agent.`,
+ status: 'skipped',
+ };
+ }
+
+ const service =
+ options.skillMaintainerServiceFactory?.({ agentId: input.agentId }) ??
+ createDefaultSkillMaintainerService(options, input.agentId);
+ const workflowRunner =
+ options.skillMaintainerRunner ??
+ ((workflowInput: SkillMaintainerWorkflowInput) =>
+ new SkillMaintainerWorkflowAgentService(
+ options.db,
+ options.userId,
+ options.skillDecisionModel,
+ ).run(workflowInput));
+ const targetSkills = await readTargetSkills(service, targetSkillIds);
+ const workflowResult = toSkillMaintainerWorkflowResult(
+ SkillMaintainerWorkflowResultSchema.parse(
+ await workflowRunner({
+ decision,
+ signal: input,
+ targetSkills,
+ type: decision.action,
+ }),
+ ),
+ );
+
+ await applyMaintainerOperations(service, workflowResult.operations, targetSkillIds);
+
+ return {
+ decision,
+ detail: workflowResult.reason ?? `Applied ${decision.action} maintainer workflow.`,
+ status: 'applied',
+ };
+};
+
+export const runSkillManagementAction = async (
+ input: SkillManagementActionInput,
+ options: SkillManagementActionHandlerOptions,
+ decision: SkillManagementDecision,
+): Promise<SkillManagementActionResult> => {
+ 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);
+ }
+
+ const skillName = normalizeSkillPackageName(input.message);
+ const snapshot = await createMarkdownEditorSnapshot(toSkillContent(input, skillName));
+
+ try {
+ await createSkillTree({
+ agentDocumentModel: new AgentDocumentModel(options.db, options.userId),
+ agentId: input.agentId,
+ content: snapshot.content,
+ documentService: new DocumentService(options.db, options.userId),
+ editorData: snapshot.editorData,
+ namespace: 'agent',
+ skillName,
+ });
+
+ return { decision, detail: `Created skill ${skillName}.`, status: 'applied' };
+ } catch (error) {
+ if (error instanceof Error && error.message.includes('already exists')) {
+ return { decision, detail: error.message, status: 'skipped' };
+ }
+
+ throw error;
+ }
+};
+
+export const handleSkillManagementAction = async (
+ action: BaseAction,
+ options: SkillManagementActionHandlerOptions,
+ context: RuntimeProcessorContext,
+): Promise<ExecutorResult> => {
+ const startedAt = Date.now();
+ const idempotencyKey =
+ 'idempotencyKey' in action.payload && typeof action.payload.idempotencyKey === 'string'
+ ? action.payload.idempotencyKey
+ : undefined;
+
+ try {
+ if (await hasAppliedActionIdempotency(context, idempotencyKey)) {
+ // 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.',
+ startedAt,
+ });
+ }
+
+ if (!isSkillManagementAction(action)) {
+ return toSkippedExecutorResult({
+ actionId: action.actionId,
+ decision: createNoopDecision('unsupported skill-management action type'),
+ detail: 'Unsupported skill-management action type.',
+ 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.',
+ startedAt,
+ });
+ }
+
+ if (!action.payload.agentId) {
+ return toSkippedExecutorResult({
+ actionId: action.actionId,
+ decision: createNoopDecision('missing skill-management action agentId'),
+ detail: 'Missing agentId for skill-management action.',
+ startedAt,
+ });
+ }
+
+ const candidateSkills = await resolveSkillDecisionCandidates(options, action.payload.agentId);
+ const runnerInput = {
+ agentId: action.payload.agentId,
+ ...(candidateSkills.length > 0 ? { candidateSkills } : {}),
+ evidence: action.payload.evidence,
+ feedbackHint: action.payload.feedbackHint,
+ message,
+ reason: action.payload.reason,
+ serializedContext: action.payload.serializedContext,
+ topicId: action.payload.topicId,
+ };
+ const decisionResult = await handleSkillManagementSignal({
+ decide: options.skillDecisionRunner ?? createSkillDecisionRunner(options),
+ payload: {
+ agentId: action.payload.agentId,
+ ...(candidateSkills.length > 0 ? { candidateSkills } : {}),
+ evidence: action.payload.evidence,
+ feedbackMessage: message,
+ topicId: action.payload.topicId,
+ turnContext: action.payload.serializedContext,
+ },
+ selfIterationEnabled: options.selfIterationEnabled,
+ });
+
+ 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);
+
+ if (result.status === 'applied') {
+ await markAppliedActionIdempotency(context, idempotencyKey);
+
+ return {
+ actionId: action.actionId,
+ attempt: finalizeAttempt(startedAt, 'succeeded'),
+ detail: result.detail,
+ output: { decision: result.decision },
+ status: 'applied',
+ };
+ }
+
+ if (result.status === 'failed') {
+ return toExecutorError(
+ action.actionId,
+ new Error(result.detail ?? 'Skill-management action failed.'),
+ startedAt,
+ );
+ }
+
+ return {
+ actionId: action.actionId,
+ attempt: finalizeAttempt(startedAt, 'skipped'),
+ detail: result.detail,
+ output: { decision: result.decision },
+ status: 'skipped',
+ };
+ } catch (error) {
+ return toExecutorError(action.actionId, error, startedAt);
+ }
+};
+
+/**
+ * Creates the action handler that writes document-backed skills for skill-domain feedback.
+ *
+ * Triggering workflow:
+ *
+ * {@link createFeedbackActionPlannerSignalHandler}
+ * -> `action.skill-management.handle`
+ * -> {@link defineSkillManagementActionHandler}
+ *
+ * Upstream:
+ * - {@link createFeedbackActionPlannerSignalHandler}
+ *
+ * Downstream:
+ * - {@link runSkillManagementAction}
+ * - {@link createSkillTree}
+ */
+export const defineSkillManagementActionHandler = (
+ options: SkillManagementActionHandlerOptions,
+) => {
+ return defineActionHandler(
+ AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle,
+ 'handler.skill-management.handle',
+ async (action, context: RuntimeProcessorContext) => {
+ return handleSkillManagementAction(action, options, context);
+ },
+ );
+};
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts
index 250253ac4d8..248aaff2f8f 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts
@@ -8,6 +8,19 @@ import {
type AgentSignalFeedbackSourceHints,
} from '../types';
+/**
+ * Builds the durable action idempotency key for one planned feedback action.
+ *
+ * The key intentionally uses the root source id, target domain, and message id so retries of the
+ * same feedback source do not replay durable side effects, while memory and skill fan-out actions
+ * stay independent from each other.
+ *
+ * Before:
+ * - rootSourceId="msg_1", target="skill", messageId="msg_1"
+ *
+ * After:
+ * - "msg_1:skill:msg_1"
+ */
const createStableIdempotencyKey = (
signal: BaseSignal,
target: AgentSignalFeedbackDomainTarget,
@@ -80,6 +93,39 @@ const buildPlannedActions = (signal: BaseSignal): BaseAction[] => {
];
}
+ if (payload.target === 'skill') {
+ return [
+ {
+ actionId: `${signal.signalId}:action:skill-management`,
+ actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle,
+ chain: {
+ chainId: signal.chain.chainId,
+ parentNodeId: signal.signalId,
+ parentSignalId: signal.signalId,
+ rootSourceId: signal.chain.rootSourceId,
+ },
+ payload: {
+ agentId: payload.agentId,
+ conflictPolicy: payload.conflictPolicy,
+ evidence: payload.evidence,
+ feedbackHint: payload.satisfactionResult === 'satisfied' ? 'satisfied' : 'not_satisfied',
+ idempotencyKey,
+ message: payload.message,
+ reason: payload.reason,
+ serializedContext,
+ sourceHints: payload.sourceHints,
+ topicId: payload.topicId,
+ },
+ signal: {
+ signalId: signal.signalId,
+ signalType: signal.signalType,
+ },
+ source: signal.source,
+ timestamp: signal.timestamp,
+ },
+ ];
+ }
+
return [];
};
@@ -97,6 +143,7 @@ const buildPlannedActions = (signal: BaseSignal): BaseAction[] => {
*
* Downstream:
* - `action.user-memory.handle`
+ * - `action.skill-management.handle`
*/
export const createFeedbackActionPlannerSignalHandler = () => {
const listenedSignalTypes = [
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomainAgent.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomainAgent.ts
index 9a771e29744..a97f71a6c1b 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomainAgent.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomainAgent.ts
@@ -1,4 +1,5 @@
import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';
+import type { GenerateObjectSchema } from '@lobechat/model-runtime';
import { chainAgentSignalAnalyzeIntentRoute } from '@lobechat/prompts';
import { RequestTrigger } from '@lobechat/types';
import debug from 'debug';
@@ -7,7 +8,6 @@ import { z } from 'zod';
import type { LobeChatDatabase } from '@/database/type';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
-import { buildGenerateObjectSchema } from '../../../../../../packages/memory-user-memory/src/utils/zod';
import type {
AgentSignalFeedbackEvidence,
AgentSignalFeedbackPhase1DomainTarget,
@@ -36,6 +36,45 @@ const FeedbackDomainJudgeAgentResultSchema = z.object({
export type FeedbackDomainJudgeAgentResult = z.infer<typeof FeedbackDomainJudgeAgentResultSchema>;
+const FeedbackDomainGenerateObjectSchema = {
+ name: 'agent_signal_feedback_domain_route',
+ schema: {
+ additionalProperties: false,
+ properties: {
+ targets: {
+ items: {
+ additionalProperties: false,
+ properties: {
+ confidence: { maximum: 1, minimum: 0, type: 'number' },
+ evidence: {
+ items: {
+ additionalProperties: false,
+ properties: {
+ cue: { type: 'string' },
+ excerpt: { type: 'string' },
+ },
+ required: ['cue', 'excerpt'],
+ type: 'object',
+ },
+ type: 'array',
+ },
+ reason: { type: 'string' },
+ target: { enum: ['memory', 'none', 'prompt', 'skill'], type: 'string' },
+ },
+ required: ['confidence', 'evidence', 'reason', 'target'],
+ type: 'object',
+ },
+ maxItems: 4,
+ minItems: 1,
+ type: 'array',
+ },
+ },
+ required: ['targets'],
+ type: 'object',
+ },
+ strict: true,
+} satisfies GenerateObjectSchema;
+
export interface FeedbackDomainJudgeAgentModelConfig {
model: string;
provider: string;
@@ -107,9 +146,7 @@ export class FeedbackDomainJudgeAgentService {
{
messages: payload.messages as any[],
model: this.modelConfig.model,
- schema: buildGenerateObjectSchema(FeedbackDomainJudgeAgentResultSchema, {
- name: 'agent_signal_feedback_domain_route',
- }),
+ schema: FeedbackDomainGenerateObjectSchema,
},
{ metadata: { trigger: RequestTrigger.Memory } },
);
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts
index b40e9feae2d..f272a41703f 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts
@@ -1,5 +1,6 @@
import type { RuntimeProcessorResult } from '@lobechat/agent-signal';
import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';
+import type { GenerateObjectSchema } from '@lobechat/model-runtime';
import { chainAgentSignalAnalyzeIntentFeedbackSatisfaction } from '@lobechat/prompts';
import { RequestTrigger } from '@lobechat/types';
import debug from 'debug';
@@ -8,7 +9,6 @@ import { z } from 'zod';
import type { LobeChatDatabase } from '@/database/type';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
-import { buildGenerateObjectSchema } from '../../../../../../packages/memory-user-memory/src/utils/zod';
import { defineSourceHandler } from '../../runtime/middleware';
import { AGENT_SIGNAL_SOURCE_TYPES, type SourceAgentUserMessage } from '../../sourceTypes';
import {
@@ -36,6 +36,33 @@ type FeedbackSatisfactionStagePayloadResult = z.infer<
typeof FeedbackSatisfactionStagePayloadSchema
>;
+const FeedbackSatisfactionGenerateObjectSchema = {
+ name: 'agent_signal_feedback_satisfaction',
+ schema: {
+ additionalProperties: false,
+ properties: {
+ confidence: { maximum: 1, minimum: 0, type: 'number' },
+ evidence: {
+ items: {
+ additionalProperties: false,
+ properties: {
+ cue: { type: 'string' },
+ excerpt: { type: 'string' },
+ },
+ required: ['cue', 'excerpt'],
+ type: 'object',
+ },
+ type: 'array',
+ },
+ reason: { type: 'string' },
+ result: { enum: ['neutral', 'not_satisfied', 'satisfied'], type: 'string' },
+ },
+ required: ['confidence', 'evidence', 'reason', 'result'],
+ type: 'object',
+ },
+ strict: true,
+} satisfies GenerateObjectSchema;
+
/**
* One normalized satisfaction-judge input.
*/
@@ -148,9 +175,7 @@ export class FeedbackSatisfactionJudgeAgentService implements FeedbackSatisfacti
{
messages: payload.messages as any[],
model: this.modelConfig.model,
- schema: buildGenerateObjectSchema(FeedbackSatisfactionStagePayloadSchema, {
- name: 'agent_signal_feedback_satisfaction',
- }),
+ schema: FeedbackSatisfactionGenerateObjectSchema,
},
{ metadata: { trigger: RequestTrigger.Memory } },
);
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/index.ts b/src/server/services/agentSignal/policies/analyzeIntent/index.ts
index a744a8c02e1..e6c8bb76afc 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/index.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/index.ts
@@ -1,6 +1,9 @@
import { defineAgentSignalHandlers } from '../../runtime/middleware';
-import type { UserMemoryActionHandlerOptions } from './actions';
-import { defineUserMemoryActionHandler } from './actions';
+import type {
+ SkillManagementActionHandlerOptions,
+ UserMemoryActionHandlerOptions,
+} from './actions';
+import { defineSkillManagementActionHandler, defineUserMemoryActionHandler } from './actions';
import { createFeedbackActionPlannerSignalHandler } from './feedbackAction';
import type { CreateFeedbackDomainJudgePolicyOptions } from './feedbackDomain';
import {
@@ -13,6 +16,7 @@ import { createFeedbackSatisfactionJudgeProcessor } from './feedbackSatisfaction
export interface CreateAnalyzeIntentPolicyOptions {
feedbackDomainJudge?: CreateFeedbackDomainJudgePolicyOptions['feedbackDomainJudge'];
feedbackSatisfactionJudge?: CreateFeedbackSatisfactionJudgePolicyOptions;
+ skillManagement?: SkillManagementActionHandlerOptions;
userMemory?: UserMemoryActionHandlerOptions;
}
@@ -27,6 +31,9 @@ export const createAnalyzeIntentPolicy = (options: CreateAnalyzeIntentPolicyOpti
resolveDomains: feedbackDomainResolver,
}),
createFeedbackActionPlannerSignalHandler(),
+ ...(options.skillManagement
+ ? [defineSkillManagementActionHandler(options.skillManagement)]
+ : []),
...(options.userMemory ? [defineUserMemoryActionHandler(options.userMemory)] : []),
]);
};
diff --git a/src/server/services/agentSignal/policies/index.ts b/src/server/services/agentSignal/policies/index.ts
index fc6719b1d5f..32546fdf768 100644
--- a/src/server/services/agentSignal/policies/index.ts
+++ b/src/server/services/agentSignal/policies/index.ts
@@ -1,6 +1,9 @@
import type { AgentSignalMiddleware } from '../runtime/middleware';
import { createAnalyzeIntentPolicy } from './analyzeIntent';
-import type { UserMemoryActionHandlerOptions } from './analyzeIntent/actions';
+import type {
+ SkillManagementActionHandlerOptions,
+ UserMemoryActionHandlerOptions,
+} from './analyzeIntent/actions';
import type { CreateFeedbackDomainJudgePolicyOptions } from './analyzeIntent/feedbackDomain';
import type { CreateFeedbackSatisfactionJudgePolicyOptions } from './analyzeIntent/feedbackSatisfaction';
@@ -15,6 +18,7 @@ export * from './types';
export interface CreateDefaultAgentSignalPoliciesOptions extends CreateFeedbackDomainJudgePolicyOptions {
feedbackSatisfactionJudge?: CreateFeedbackSatisfactionJudgePolicyOptions;
+ skillManagement?: SkillManagementActionHandlerOptions;
userMemory?: UserMemoryActionHandlerOptions;
}
diff --git a/src/server/services/agentSignal/policies/types.ts b/src/server/services/agentSignal/policies/types.ts
index f69305d3018..670facf94aa 100644
--- a/src/server/services/agentSignal/policies/types.ts
+++ b/src/server/services/agentSignal/policies/types.ts
@@ -33,6 +33,7 @@ export const AGENT_SIGNAL_POLICY_SIGNAL_TYPES = {
export const AGENT_SIGNAL_POLICY_ACTION_TYPES = {
nudgeHandle: 'action.nudge.handle',
personaHandle: 'action.persona.handle',
+ skillManagementHandle: 'action.skill-management.handle',
userMemoryHandle: 'action.user-memory.handle',
} as const;
@@ -213,6 +214,18 @@ export interface AgentSignalPolicyActionPayloadMap {
topicId?: string;
update?: Record<string, unknown>;
};
+ [AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle]: {
+ agentId?: string;
+ conflictPolicy?: AgentSignalFeedbackDomainConflictPolicy;
+ evidence?: AgentSignalFeedbackEvidence[];
+ feedbackHint?: Exclude<AgentSignalFeedbackSatisfactionResult, 'neutral'>;
+ idempotencyKey: string;
+ message: string;
+ reason?: string;
+ serializedContext?: string;
+ sourceHints?: AgentSignalFeedbackSourceHints;
+ topicId?: string;
+ };
[AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle]: {
agentId?: string;
conflictPolicy?: AgentSignalFeedbackDomainConflictPolicy;
@@ -290,6 +303,10 @@ export type ActionUserMemoryHandle = AgentSignalPolicyActionVariant<'action.user
/** Server-owned alias for persona updates. */
export type ActionPersonaHandle = AgentSignalPolicyActionVariant<'action.persona.handle'>;
+/** Server-owned alias for skill-management actions. */
+export type ActionSkillManagementHandle =
+ AgentSignalPolicyActionVariant<'action.skill-management.handle'>;
+
/** Server-owned alias for memory-nudge actions. */
export type ActionNudgeHandle = AgentSignalPolicyActionVariant<'action.nudge.handle'>;
diff --git a/src/server/services/skillMaintainer/SkillMaintainerService.test.ts b/src/server/services/skillMaintainer/SkillMaintainerService.test.ts
new file mode 100644
index 00000000000..0b78c3766de
--- /dev/null
+++ b/src/server/services/skillMaintainer/SkillMaintainerService.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { SkillMaintainerService } from './SkillMaintainerService';
+import type { SkillReferenceResolver } from './SkillReferenceResolver';
+import type { ManagedSkillReference } from './types';
+import type { VfsSkillPackageAdapter } from './VfsSkillPackageAdapter';
+
+describe('SkillMaintainerService', () => {
+ it('reads a managed skill file through the VFS adapter', async () => {
+ const skill = { rootPath: './root', writable: true } as ManagedSkillReference;
+ const resolver = {
+ resolve: vi.fn().mockResolvedValue(skill),
+ } as unknown as SkillReferenceResolver;
+ const adapter = {
+ read: vi.fn().mockResolvedValue('# Skill'),
+ } as unknown as VfsSkillPackageAdapter;
+ const service = new SkillMaintainerService({ adapter, resolver });
+
+ const content = await service.readSkillFile({
+ path: 'SKILL.md',
+ skillRef: 'agent-skill-1',
+ });
+
+ expect(content).toBe('# Skill');
+ expect(adapter.read).toHaveBeenCalledWith(skill, 'SKILL.md');
+ });
+
+ it('updates only an existing managed skill file', async () => {
+ const skill = { rootPath: './root', writable: true } as ManagedSkillReference;
+ const resolver = {
+ resolve: vi.fn().mockResolvedValue(skill),
+ } as unknown as SkillReferenceResolver;
+ const adapter = {
+ read: vi.fn().mockResolvedValue('old'),
+ write: vi.fn(),
+ } as unknown as VfsSkillPackageAdapter;
+ const service = new SkillMaintainerService({ adapter, resolver });
+
+ await service.updateSkill({
+ content: 'new',
+ path: 'SKILL.md',
+ skillRef: 'agent-skill-1',
+ });
+
+ expect(adapter.read).toHaveBeenCalledWith(skill, 'SKILL.md');
+ expect(adapter.write).toHaveBeenCalledWith(skill, 'SKILL.md', 'new');
+ });
+
+ it('writes and removes package-relative skill files', async () => {
+ const skill = { rootPath: './root', writable: true } as ManagedSkillReference;
+ const resolver = {
+ resolve: vi.fn().mockResolvedValue(skill),
+ } as unknown as SkillReferenceResolver;
+ const adapter = {
+ delete: vi.fn(),
+ write: vi.fn(),
+ } as unknown as VfsSkillPackageAdapter;
+ const service = new SkillMaintainerService({ adapter, resolver });
+
+ await service.writeSkillFile({
+ content: 'reference',
+ path: 'references/guide.md',
+ skillRef: 'agent-skill-1',
+ });
+ await service.removeSkillFile({
+ path: 'references/guide.md',
+ skillRef: 'agent-skill-1',
+ });
+
+ expect(adapter.write).toHaveBeenCalledWith(skill, 'references/guide.md', 'reference');
+ expect(adapter.delete).toHaveBeenCalledWith(skill, 'references/guide.md');
+ });
+});
diff --git a/src/server/services/skillMaintainer/SkillMaintainerService.ts b/src/server/services/skillMaintainer/SkillMaintainerService.ts
new file mode 100644
index 00000000000..4537493568b
--- /dev/null
+++ b/src/server/services/skillMaintainer/SkillMaintainerService.ts
@@ -0,0 +1,54 @@
+import type { SkillReferenceResolver } from './SkillReferenceResolver';
+import type { VfsSkillPackageAdapter } from './VfsSkillPackageAdapter';
+
+/**
+ * Dependencies for v1.2 skill maintainer file operations.
+ */
+export interface SkillMaintainerServiceDeps {
+ /** Adapter used for package file reads and writes. */
+ adapter: VfsSkillPackageAdapter;
+ /** Resolver used to turn external references into managed skill packages. */
+ resolver: SkillReferenceResolver;
+}
+
+/**
+ * Applies v1.2 file operations to managed skill packages.
+ *
+ * Use when:
+ * - A hidden maintainer action needs to read or mutate one skill package file
+ * - Higher-level refinement or consolidation code has already chosen the target skill
+ *
+ * Expects:
+ * - Callers run their own policy checks before invoking mutating operations
+ *
+ * Returns:
+ * - Completed file operations scoped under the resolved skill root
+ */
+export class SkillMaintainerService {
+ constructor(private deps: SkillMaintainerServiceDeps) {}
+
+ async readSkillFile(input: { path: string; skillRef: string }) {
+ const skill = await this.deps.resolver.resolve(input.skillRef);
+
+ return this.deps.adapter.read(skill, input.path);
+ }
+
+ async updateSkill(input: { content: string; path: string; skillRef: string }) {
+ const skill = await this.deps.resolver.resolve(input.skillRef);
+
+ await this.deps.adapter.read(skill, input.path);
+ await this.deps.adapter.write(skill, input.path, input.content);
+ }
+
+ async writeSkillFile(input: { content: string; path: string; skillRef: string }) {
+ const skill = await this.deps.resolver.resolve(input.skillRef);
+
+ await this.deps.adapter.write(skill, input.path, input.content);
+ }
+
+ async removeSkillFile(input: { path: string; skillRef: string }) {
+ const skill = await this.deps.resolver.resolve(input.skillRef);
+
+ await this.deps.adapter.delete(skill, input.path);
+ }
+}
diff --git a/src/server/services/skillMaintainer/SkillReferenceResolver.ts b/src/server/services/skillMaintainer/SkillReferenceResolver.ts
new file mode 100644
index 00000000000..25dac54d9a5
--- /dev/null
+++ b/src/server/services/skillMaintainer/SkillReferenceResolver.ts
@@ -0,0 +1,41 @@
+import type { ManagedSkillReference } from './types';
+
+/**
+ * Dependencies used to resolve external skill references.
+ */
+export interface SkillReferenceResolverDeps {
+ /** Finds a promoted agent-level skill by id. */
+ findAgentSkillById: (id: string) => Promise<{ id: string } | undefined>;
+}
+
+/**
+ * Resolves skill references into package roots and mutability metadata.
+ *
+ * Use when:
+ * - A tool call passes a skill id that points at managed agent storage
+ * - Services need a single reference shape before reading or writing files
+ *
+ * Expects:
+ * - Dependency lookups return at most one match per backing store
+ *
+ * Returns:
+ * - A managed skill reference with VFS root and scope information
+ */
+export class SkillReferenceResolver {
+ constructor(private deps: SkillReferenceResolverDeps) {}
+
+ async resolve(skillRef: string): Promise<ManagedSkillReference> {
+ const agentSkill = await this.deps.findAgentSkillById(skillRef);
+ if (agentSkill) {
+ return {
+ id: agentSkill.id,
+ kind: 'agent-skill',
+ rootPath: `./lobe/skills/agent/skills/${agentSkill.id}`,
+ scope: 'agent',
+ writable: true,
+ };
+ }
+
+ throw new Error(`Unknown skill reference: ${skillRef}`);
+ }
+}
diff --git a/src/server/services/skillMaintainer/VfsSkillPackageAdapter.ts b/src/server/services/skillMaintainer/VfsSkillPackageAdapter.ts
new file mode 100644
index 00000000000..538a56087c6
--- /dev/null
+++ b/src/server/services/skillMaintainer/VfsSkillPackageAdapter.ts
@@ -0,0 +1,72 @@
+import { assertPackageRelativePath } from './pathSafety';
+import type { ManagedSkillReference } from './types';
+
+/**
+ * Minimal VFS interface required by the skill package adapter.
+ */
+export interface VfsLike {
+ /** Deletes one VFS path. */
+ delete: (path: string) => Promise<void>;
+ /** Lists one VFS directory path. */
+ list: (path: string) => Promise<unknown>;
+ /** Reads one VFS file path as text. */
+ read: (path: string) => Promise<string>;
+ /** Writes text content to one VFS file path. */
+ write: (path: string, content: string) => Promise<void>;
+}
+
+/**
+ * Routes package-relative skill file operations through a VFS-like backend.
+ *
+ * Use when:
+ * - Skill services need path-safe file operations
+ * - The concrete VFS backend may change independently
+ *
+ * Expects:
+ * - Skill references contain a normalized root path
+ *
+ * Returns:
+ * - VFS calls scoped under the skill package root
+ */
+export class VfsSkillPackageAdapter {
+ constructor(private vfs: VfsLike) {}
+
+ /**
+ * Resolves a package-relative path under the skill root.
+ *
+ * Use when:
+ * - Converting tool input paths into VFS paths
+ * - Normalizing "." to the package root
+ *
+ * Expects:
+ * - Non-root paths are package-relative and traversal-free
+ *
+ * Returns:
+ * - A VFS path under the managed skill root
+ */
+ resolvePath(skill: ManagedSkillReference, path = '.') {
+ const relativePath = path === '.' ? '' : assertPackageRelativePath(path);
+
+ return relativePath ? `${skill.rootPath}/${relativePath}` : skill.rootPath;
+ }
+
+ async list(skill: ManagedSkillReference, path = '.') {
+ return this.vfs.list(this.resolvePath(skill, path));
+ }
+
+ async read(skill: ManagedSkillReference, path: string) {
+ return this.vfs.read(this.resolvePath(skill, path));
+ }
+
+ async write(skill: ManagedSkillReference, path: string, content: string) {
+ if (!skill.writable) throw new Error('skill is not writable');
+
+ await this.vfs.write(this.resolvePath(skill, path), content);
+ }
+
+ async delete(skill: ManagedSkillReference, path: string) {
+ if (!skill.writable) throw new Error('skill is not writable');
+
+ await this.vfs.delete(this.resolvePath(skill, path));
+ }
+}
diff --git a/src/server/services/skillMaintainer/pathSafety.test.ts b/src/server/services/skillMaintainer/pathSafety.test.ts
new file mode 100644
index 00000000000..fa7f6397600
--- /dev/null
+++ b/src/server/services/skillMaintainer/pathSafety.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+
+import { assertPackageRelativePath } from './pathSafety';
+
+describe('assertPackageRelativePath', () => {
+ it('accepts package-relative paths', () => {
+ expect(assertPackageRelativePath('SKILL.md')).toBe('SKILL.md');
+ expect(assertPackageRelativePath('references/checklist.md')).toBe('references/checklist.md');
+ });
+
+ it('rejects unsafe paths', () => {
+ expect(() => assertPackageRelativePath('/etc/passwd')).toThrow(
+ 'absolute paths are not allowed',
+ );
+ expect(() => assertPackageRelativePath('../SKILL.md')).toThrow('path traversal is not allowed');
+ expect(() => assertPackageRelativePath('references/../../SKILL.md')).toThrow(
+ 'path traversal is not allowed',
+ );
+ });
+});
diff --git a/src/server/services/skillMaintainer/pathSafety.ts b/src/server/services/skillMaintainer/pathSafety.ts
new file mode 100644
index 00000000000..abaa2168ac3
--- /dev/null
+++ b/src/server/services/skillMaintainer/pathSafety.ts
@@ -0,0 +1,19 @@
+/**
+ * Normalizes package-relative skill paths and rejects unsafe path forms.
+ *
+ * Before:
+ * - "references/../SKILL.md"
+ *
+ * After:
+ * - Throws "path traversal is not allowed"
+ */
+export const assertPackageRelativePath = (path: string) => {
+ if (path.startsWith('/')) throw new Error('absolute paths are not allowed');
+
+ const segments = path.split('/').filter(Boolean);
+ if (segments.includes('..')) {
+ throw new Error('path traversal is not allowed');
+ }
+
+ return segments.join('/');
+};
diff --git a/src/server/services/skillMaintainer/types.ts b/src/server/services/skillMaintainer/types.ts
new file mode 100644
index 00000000000..fe60da110e1
--- /dev/null
+++ b/src/server/services/skillMaintainer/types.ts
@@ -0,0 +1,18 @@
+/** Scope where a managed skill currently lives. */
+export type ManagedSkillScope = 'agent' | 'builtin' | 'installed';
+
+/**
+ * Reference to a skill package resolved from an external skill identifier.
+ */
+export interface ManagedSkillReference {
+ /** Stable skill or document id. */
+ id: string;
+ /** Backing source for package reads and writes. */
+ kind: 'agent-skill' | 'builtin' | 'installed';
+ /** VFS root path for the package. */
+ rootPath: string;
+ /** Lifecycle scope used by policy checks. */
+ scope: ManagedSkillScope;
+ /** Whether package content can be mutated directly. */
+ writable: boolean;
+}
diff --git a/src/server/workflows/agentSignal/__tests__/run.test.ts b/src/server/workflows/agentSignal/__tests__/run.test.ts
index 7fbb3b8f808..9377597e5ae 100644
--- a/src/server/workflows/agentSignal/__tests__/run.test.ts
+++ b/src/server/workflows/agentSignal/__tests__/run.test.ts
@@ -14,6 +14,10 @@ import {
} from '@/server/workflows/agentSignal/run';
import { uuid } from '@/utils/uuid';
+vi.mock('@/server/services/agentSignal/featureGate', () => ({
+ isAgentSignalEnabledForUser: vi.fn().mockResolvedValue(true),
+}));
+
const createWorkflowContext = <TPayload>(requestPayload: TPayload) => {
return {
requestPayload,
@@ -209,6 +213,17 @@ describe('runAgentSignalWorkflow', () => {
}),
);
expect(executeSourceEvent).toHaveBeenCalledTimes(1);
+ expect(executeSourceEvent).toHaveBeenCalledWith(
+ expect.any(Object),
+ expect.any(Object),
+ expect.objectContaining({
+ policyOptions: {
+ skillManagement: {
+ selfIterationEnabled: true,
+ },
+ },
+ }),
+ );
expect(capturedSourceEvent?.sourceType).toBe('agent.user.message');
expect(capturedSourceEvent?.payload.serializedContext).toContain('<feedback_analysis_context>');
expect(capturedSourceEvent?.payload.serializedContext).not.toContain(
diff --git a/src/server/workflows/agentSignal/run.ts b/src/server/workflows/agentSignal/run.ts
index 45d78b7e9c1..0d89f67d6cd 100644
--- a/src/server/workflows/agentSignal/run.ts
+++ b/src/server/workflows/agentSignal/run.ts
@@ -13,6 +13,7 @@ import { and, desc, eq, isNull, lte } from 'drizzle-orm';
import { MessageModel } from '@/database/models/message';
import { getServerDB } from '@/database/server';
import { extractTraceContext } from '@/libs/observability/traceparent';
+import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';
import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';
import type { GeneratedAgentSignalEmissionResult } from '@/server/services/agentSignal/orchestrator';
import { executeAgentSignalSourceEvent } from '@/server/services/agentSignal/orchestrator';
@@ -442,12 +443,14 @@ export const runAgentSignalWorkflow = async (
const createGuardBackend =
deps.createRuntimeGuardBackend ?? createRedisRuntimeGuardBackend;
const snapshotStore = (deps.createSnapshotStore ?? createDefaultSnapshotStore)();
+ let selfIterationEnabled = false;
const db = await getDb();
const normalizedSourceEvent = await tracer.startActiveSpan(
'agent_signal.workflow.normalize',
async (normalizeSpan) => {
try {
+ selfIterationEnabled = await isAgentSignalEnabledForUser(db, payload.userId);
const result = await normalizeWorkflowSourceEvent(payload.sourceEvent, {
db,
userId: payload.userId,
@@ -485,6 +488,11 @@ export const runAgentSignalWorkflow = async (
userId: payload.userId,
},
{
+ policyOptions: {
+ skillManagement: {
+ selfIterationEnabled,
+ },
+ },
runtimeGuardBackend: createGuardBackend(),
},
),