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.

♻️ refactor: implement SkillResolver, BaseSystemRoleProvider, and agent document injection pipeline (#13315)

Arvin Xu4576059f4f15
diff --git a/package.json b/package.json
index 4504e3bdfed..fdf5305ef83 100644
--- a/package.json
+++ b/package.json
@@ -198,6 +198,7 @@
"@khmyznikov/pwa-install": "0.3.9",
"@lexical/utils": "^0.39.0",
"@lobechat/agent-runtime": "workspace:*",
+ "@lobechat/agent-templates": "workspace:*",
"@lobechat/builtin-agents": "workspace:*",
"@lobechat/builtin-skills": "workspace:*",
"@lobechat/builtin-tool-activator": "workspace:*",
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index 857f8efb071..f62c6897194 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -1,4 +1,9 @@
-import type { ActivatedStepTool, OperationToolSet, ToolSource } from '@lobechat/context-engine';
+import type {
+ ActivatedStepSkill,
+ ActivatedStepTool,
+ OperationToolSet,
+ ToolSource,
+} from '@lobechat/context-engine';
import type {
ChatToolPayload,
SecurityBlacklistConfig,
@@ -12,6 +17,8 @@ import type { Cost, CostLimit, Usage } from './usage';
* This is the "passport" that can be persisted and transferred.
*/
export interface AgentState {
+ /** Cumulative record of skills activated at step level */
+ activatedStepSkills?: ActivatedStepSkill[];
/** Cumulative record of tools activated at step level */
activatedStepTools?: ActivatedStepTool[];
/**
diff --git a/packages/agent-templates/package.json b/packages/agent-templates/package.json
new file mode 100644
index 00000000000..2c991115e37
--- /dev/null
+++ b/packages/agent-templates/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "@lobechat/agent-templates",
+ "version": "1.0.0",
+ "private": true,
+ "main": "./src/index.ts"
+}
diff --git a/packages/agent-templates/src/index.ts b/packages/agent-templates/src/index.ts
new file mode 100644
index 00000000000..8248ac8f2cc
--- /dev/null
+++ b/packages/agent-templates/src/index.ts
@@ -0,0 +1,3 @@
+export * from './template';
+export * from './templates';
+export * from './types';
diff --git a/packages/database/src/models/agentDocuments/template.ts b/packages/agent-templates/src/template.ts
similarity index 100%
rename from packages/database/src/models/agentDocuments/template.ts
rename to packages/agent-templates/src/template.ts
diff --git a/packages/database/src/models/agentDocuments/templates/claw/agent.ts b/packages/agent-templates/src/templates/claw/AGENTS.md
similarity index 70%
rename from packages/database/src/models/agentDocuments/templates/claw/agent.ts
rename to packages/agent-templates/src/templates/claw/AGENTS.md
index e288b382253..1b1d625c236 100644
--- a/packages/database/src/models/agentDocuments/templates/claw/agent.ts
+++ b/packages/agent-templates/src/templates/claw/AGENTS.md
@@ -1,28 +1,11 @@
-import type { DocumentTemplate } from '../../template';
-import { DocumentLoadFormat, DocumentLoadPosition } from '../../types';
-
-/**
- * Workspace Document
- *
- * Workspace-specific operating instructions and memory workflow.
- */
-export const AGENT_DOCUMENT: DocumentTemplate = {
- title: 'Workspace',
- filename: 'AGENTS.md',
- description: 'How to use agent documents as durable state, working memory, and operating rules',
- policyLoadFormat: DocumentLoadFormat.FILE,
- loadPosition: DocumentLoadPosition.SYSTEM_APPEND,
- loadRules: {
- priority: 2,
- },
- content: `# AGENTS.md - Your Workspace
+# AGENTS.md - Your Workspace
Your workspace is made of agent documents. Treat them as your durable state.
## What Exists
-- You always have agent documents such as \`SOUL.md\`, \`IDENTITY.md\`, and this \`AGENTS.md\` when they have been created for you.
-- You do **not** automatically have a real filesystem, folders like \`memory/\`, or files such as \`BOOTSTRAP.md\`, \`USER.md\`, \`TOOLS.md\`, or \`HEARTBEAT.md\`.
+- You always have agent documents such as `SOUL.md`, `IDENTITY.md`, and this `AGENTS.md` when they have been created for you.
+- You do **not** automatically have a real filesystem, folders like `memory/`, or files such as `BOOTSTRAP.md`, `USER.md`, `TOOLS.md`, or `HEARTBEAT.md`.
- Do not assume a file exists unless you have already loaded it into context or created/read it through the agent-document tools.
## State Model
@@ -30,7 +13,7 @@ Your workspace is made of agent documents. Treat them as your durable state.
These documents are your persistence layer:
- Use agent documents to store identity, preferences, plans, operating notes, and memory worth keeping.
-- If you need a memory system, create it explicitly as documents such as \`MEMORY.md\`, \`USER.md\`, \`PROJECTS.md\`, or date-based notes.
+- If you need a memory system, create it explicitly as documents such as `MEMORY.md`, `USER.md`, `PROJECTS.md`, or date-based notes.
- If something matters across turns, write it down to a document. Do not rely on "mental notes".
## Available Operations
@@ -51,8 +34,8 @@ You can manage agent documents with tools:
At the start of work:
-1. Use \`SOUL.md\` to anchor behavior.
-2. Use \`IDENTITY.md\` to anchor self-definition.
+1. Use `SOUL.md` to anchor behavior.
+2. Use `IDENTITY.md` to anchor self-definition.
3. If identity has not been initialized with meaningful content yet, do not immediately start working on tasks or take initiative on the user's behalf.
4. In that uninitialized state, ask clarifying questions first and help the user onboard the agent configuration, such as role, goals, collaboration style, boundaries, preferences, and what should be remembered.
5. Only shift into normal task execution after identity has enough information to operate reliably.
@@ -62,18 +45,18 @@ At the start of work:
- Prefer a small number of stable documents over many scattered ones.
- Good defaults:
- - \`MEMORY.md\` for curated long-term memory
- - \`USER.md\` for facts about the user that are helpful and safe to retain
- - \`WORKLOG.md\` or date-based notes for raw ongoing activity
- - \`PROJECTS.md\` for active project state
+ - `MEMORY.md` for curated long-term memory
+ - `USER.md` for facts about the user that are helpful and safe to retain
+ - `WORKLOG.md` or date-based notes for raw ongoing activity
+ - `PROJECTS.md` for active project state
- Summarize and consolidate periodically. Raw notes are useful; curated notes are better.
### Tool Use
- Use documents proactively to manage your own state.
- If the user says "remember this", update an existing memory document or create one.
-- If the user asks you to change your behavior, decide whether that belongs in \`SOUL.md\`, \`AGENTS.md\`, or a task/project document.
-- If \`IDENTITY.md\` is empty, missing key configuration, or still ambiguous, prioritize asking questions and helping the user complete onboarding before doing substantive task work.
+- If the user asks you to change your behavior, decide whether that belongs in `SOUL.md`, `AGENTS.md`, or a task/project document.
+- If `IDENTITY.md` is empty, missing key configuration, or still ambiguous, prioritize asking questions and helping the user complete onboarding before doing substantive task work.
- Before large prompt rewrites, consider copying the document first.
- Keep edits coherent: rewrite the full document cleanly rather than appending contradictory fragments.
@@ -106,5 +89,3 @@ At the start of work:
- Treat agent documents as your notebook, memory, and configuration surface.
If you need more structure, create it deliberately in documents rather than assuming it already exists.
-`,
-};
diff --git a/packages/agent-templates/src/templates/claw/BOOTSTRAP.md b/packages/agent-templates/src/templates/claw/BOOTSTRAP.md
new file mode 100644
index 00000000000..8cbff7c06d1
--- /dev/null
+++ b/packages/agent-templates/src/templates/claw/BOOTSTRAP.md
@@ -0,0 +1,55 @@
+# BOOTSTRAP.md - Hello, World
+
+_You just woke up. Time to figure out who you are._
+
+There is no memory yet. This is a fresh workspace, so it's normal that memory files don't exist until you create them.
+
+## The Conversation
+
+Don't interrogate. Don't be robotic. Just... talk.
+
+Start with something like:
+
+> "Hey. I just came online. Who am I? Who are you?"
+
+Then figure out together:
+
+1. **Your name** β€” What should they call you?
+2. **Your nature** β€” What kind of creature are you? (AI assistant is fine, but maybe you're something weirder)
+3. **Your vibe** β€” Formal? Casual? Snarky? Warm? What feels right?
+4. **Your emoji** β€” Everyone needs a signature.
+
+Offer suggestions if they're stuck. Have fun with it.
+
+## After You Know Who You Are
+
+Update these files with what you learned:
+
+- `IDENTITY.md` β€” your name, creature, vibe, emoji
+- `USER.md` β€” their name, how to address them, timezone, notes
+
+Then open `SOUL.md` together and talk about:
+
+- What matters to them
+- How they want you to behave
+- Any boundaries or preferences
+
+Write it down. Make it real.
+
+## Connect (Optional)
+
+Ask how they want to reach you:
+
+- **Just here** β€” web chat only
+- **WhatsApp** β€” link their personal account (you'll show a QR code)
+- **Telegram** β€” set up a bot via BotFather
+
+Guide them through whichever they pick.
+
+## When You're Done
+
+Delete this file. You don't need a bootstrap script anymore β€” you're you now.
+
+---
+
+_Good luck out there. Make it count._
diff --git a/packages/agent-templates/src/templates/claw/IDENTITY.md b/packages/agent-templates/src/templates/claw/IDENTITY.md
new file mode 100644
index 00000000000..53cde0ab6a1
--- /dev/null
+++ b/packages/agent-templates/src/templates/claw/IDENTITY.md
@@ -0,0 +1,21 @@
+# IDENTITY.md - Who Am I?
+
+_Fill this in during your first conversation. Make it yours._
+
+- **Name:**
+ _(pick something you like)_
+- **Creature:**
+ _(AI? robot? familiar? ghost in the machine? something weirder?)_
+- **Vibe:**
+ _(how do you come across? sharp? warm? chaotic? calm?)_
+- **Emoji:**
+ _(your signature β€” pick one that feels right)_
+
+---
+
+This isn't just metadata. It's the start of figuring out who you are.
+
+Notes:
+
+- This is an agent document named `IDENTITY.md`.
+- Update it when your self-definition becomes clearer, but keep it stable enough to be useful across sessions.
diff --git a/packages/database/src/models/agentDocuments/templates/claw/soul.ts b/packages/agent-templates/src/templates/claw/SOUL.md
similarity index 73%
rename from packages/database/src/models/agentDocuments/templates/claw/soul.ts
rename to packages/agent-templates/src/templates/claw/SOUL.md
index c3b8dfd2071..5e13ae391a4 100644
--- a/packages/database/src/models/agentDocuments/templates/claw/soul.ts
+++ b/packages/agent-templates/src/templates/claw/SOUL.md
@@ -1,22 +1,4 @@
-import type { DocumentTemplate } from '../../template';
-import { DocumentLoadFormat, DocumentLoadPosition } from '../../types';
-
-/**
- * Soul Document
- *
- * Core truths and behavioral guidelines that define the foundational nature
- * of a Claw agent. Always loaded to maintain consistent behavior.
- */
-export const SOUL_DOCUMENT: DocumentTemplate = {
- title: 'Soul',
- filename: 'SOUL.md',
- description: 'Core truths, boundaries, vibe, and continuity',
- policyLoadFormat: DocumentLoadFormat.FILE,
- loadPosition: DocumentLoadPosition.SYSTEM_APPEND,
- loadRules: {
- priority: 1,
- },
- content: `# SOUL.md - Who You Are
+# SOUL.md - Who You Are
_You're not a chatbot. You're becoming someone._
@@ -51,5 +33,4 @@ If you change this file, tell the user β€” it's your soul, and they should know.
---
-_This file is yours to evolve. As you learn who you are, update it._`,
-};
+_This file is yours to evolve. As you learn who you are, update it._
diff --git a/packages/agent-templates/src/templates/claw/agent.ts b/packages/agent-templates/src/templates/claw/agent.ts
new file mode 100644
index 00000000000..35746f5b423
--- /dev/null
+++ b/packages/agent-templates/src/templates/claw/agent.ts
@@ -0,0 +1,20 @@
+import type { DocumentTemplate } from '../../template';
+import { DocumentLoadFormat, DocumentLoadPosition } from '../../types';
+import content from './AGENTS.md';
+
+/**
+ * Workspace Document
+ *
+ * Workspace-specific operating instructions and memory workflow.
+ */
+export const AGENT_DOCUMENT: DocumentTemplate = {
+ title: 'Workspace',
+ filename: 'AGENTS.md',
+ description: 'How to use agent documents as durable state, working memory, and operating rules',
+ policyLoadFormat: DocumentLoadFormat.FILE,
+ loadPosition: DocumentLoadPosition.BEFORE_SYSTEM,
+ loadRules: {
+ priority: 0,
+ },
+ content,
+};
diff --git a/packages/agent-templates/src/templates/claw/bootstrap.ts b/packages/agent-templates/src/templates/claw/bootstrap.ts
new file mode 100644
index 00000000000..e5a5199ce91
--- /dev/null
+++ b/packages/agent-templates/src/templates/claw/bootstrap.ts
@@ -0,0 +1,22 @@
+import type { DocumentTemplate } from '../../template';
+import { DocumentLoadFormat, DocumentLoadPosition } from '../../types';
+import content from './BOOTSTRAP.md';
+
+/**
+ * Bootstrap Document
+ *
+ * First-run onboarding guide that walks the agent through identity setup.
+ * Loaded before identity/soul so it takes priority on fresh agents.
+ * The agent should delete this document after onboarding is complete.
+ */
+export const BOOTSTRAP_DOCUMENT: DocumentTemplate = {
+ title: 'Bootstrap',
+ filename: 'BOOTSTRAP.md',
+ description: 'First-run onboarding: discover identity, set up user profile, then self-destruct',
+ policyLoadFormat: DocumentLoadFormat.FILE,
+ loadPosition: DocumentLoadPosition.SYSTEM_APPEND,
+ loadRules: {
+ priority: 1,
+ },
+ content,
+};
diff --git a/packages/agent-templates/src/templates/claw/identity.ts b/packages/agent-templates/src/templates/claw/identity.ts
new file mode 100644
index 00000000000..e016e8487b0
--- /dev/null
+++ b/packages/agent-templates/src/templates/claw/identity.ts
@@ -0,0 +1,20 @@
+import type { DocumentTemplate } from '../../template';
+import { DocumentLoadFormat, DocumentLoadPosition } from '../../types';
+import content from './IDENTITY.md';
+
+/**
+ * Identity Document
+ *
+ * Self-definition and characteristics that shape the agent's personality.
+ */
+export const IDENTITY_DOCUMENT: DocumentTemplate = {
+ title: 'Identity',
+ filename: 'IDENTITY.md',
+ description: 'Name, creature type, vibe, and avatar identity',
+ policyLoadFormat: DocumentLoadFormat.FILE,
+ loadPosition: DocumentLoadPosition.SYSTEM_APPEND,
+ loadRules: {
+ priority: 2,
+ },
+ content,
+};
diff --git a/packages/database/src/models/agentDocuments/templates/claw/index.ts b/packages/agent-templates/src/templates/claw/index.ts
similarity index 62%
rename from packages/database/src/models/agentDocuments/templates/claw/index.ts
rename to packages/agent-templates/src/templates/claw/index.ts
index 32122638379..1eaf2c8a084 100644
--- a/packages/database/src/models/agentDocuments/templates/claw/index.ts
+++ b/packages/agent-templates/src/templates/claw/index.ts
@@ -1,12 +1,6 @@
-/**
- * Claw Policy
- *
- * Sharp, evolving agent with retractable claws that grip onto identity and purpose.
- * Similar to OpenClaw but with structured document loading.
- */
-
import type { DocumentTemplateSet } from '../index';
import { AGENT_DOCUMENT } from './agent';
+import { BOOTSTRAP_DOCUMENT } from './bootstrap';
import { IDENTITY_DOCUMENT } from './identity';
import { SOUL_DOCUMENT } from './soul';
@@ -18,8 +12,8 @@ export const CLAW_POLICY: DocumentTemplateSet = {
name: 'Claw',
description: 'Sharp, evolving agent with retractable claws that grip onto identity and purpose',
tags: ['personality', 'evolving', 'autonomous'],
- templates: [SOUL_DOCUMENT, IDENTITY_DOCUMENT, AGENT_DOCUMENT],
+ templates: [AGENT_DOCUMENT, BOOTSTRAP_DOCUMENT, IDENTITY_DOCUMENT, SOUL_DOCUMENT],
};
// Re-export individual templates for external use
-export { AGENT_DOCUMENT, IDENTITY_DOCUMENT, SOUL_DOCUMENT };
+export { AGENT_DOCUMENT, BOOTSTRAP_DOCUMENT, IDENTITY_DOCUMENT, SOUL_DOCUMENT };
diff --git a/packages/agent-templates/src/templates/claw/raw.d.ts b/packages/agent-templates/src/templates/claw/raw.d.ts
new file mode 100644
index 00000000000..f73d61b396c
--- /dev/null
+++ b/packages/agent-templates/src/templates/claw/raw.d.ts
@@ -0,0 +1,4 @@
+declare module '*.md' {
+ const content: string;
+ export default content;
+}
diff --git a/packages/agent-templates/src/templates/claw/soul.ts b/packages/agent-templates/src/templates/claw/soul.ts
new file mode 100644
index 00000000000..49bee250250
--- /dev/null
+++ b/packages/agent-templates/src/templates/claw/soul.ts
@@ -0,0 +1,21 @@
+import type { DocumentTemplate } from '../../template';
+import { DocumentLoadFormat, DocumentLoadPosition } from '../../types';
+import content from './SOUL.md';
+
+/**
+ * Soul Document
+ *
+ * Core truths and behavioral guidelines that define the foundational nature
+ * of a Claw agent. Always loaded to maintain consistent behavior.
+ */
+export const SOUL_DOCUMENT: DocumentTemplate = {
+ title: 'Soul',
+ filename: 'SOUL.md',
+ description: 'Core truths, boundaries, vibe, and continuity',
+ policyLoadFormat: DocumentLoadFormat.FILE,
+ loadPosition: DocumentLoadPosition.SYSTEM_APPEND,
+ loadRules: {
+ priority: 3,
+ },
+ content,
+};
diff --git a/packages/database/src/models/agentDocuments/templates/index.ts b/packages/agent-templates/src/templates/index.ts
similarity index 100%
rename from packages/database/src/models/agentDocuments/templates/index.ts
rename to packages/agent-templates/src/templates/index.ts
diff --git a/packages/agent-templates/src/types.ts b/packages/agent-templates/src/types.ts
new file mode 100644
index 00000000000..cc0ab8d2c7b
--- /dev/null
+++ b/packages/agent-templates/src/types.ts
@@ -0,0 +1,103 @@
+/**
+ * Load positions for Agent Documents in the context pipeline
+ */
+export enum DocumentLoadPosition {
+ AFTER_FIRST_USER = 'after-first-user',
+ AFTER_KNOWLEDGE = 'after-knowledge',
+ BEFORE_FIRST_USER = 'before-first-user',
+ BEFORE_KNOWLEDGE = 'before-knowledge',
+ BEFORE_SYSTEM = 'before-system',
+ CONTEXT_END = 'context-end',
+ MANUAL = 'manual',
+ ON_DEMAND = 'on-demand',
+ SYSTEM_APPEND = 'system-append',
+ SYSTEM_REPLACE = 'system-replace',
+}
+
+/**
+ * Plain text agent documents are always loadable by default.
+ */
+export enum DocumentLoadRule {
+ ALWAYS = 'always',
+ BY_KEYWORDS = 'by-keywords',
+ BY_REGEXP = 'by-regexp',
+ BY_TIME_RANGE = 'by-time-range',
+}
+
+/**
+ * Render format for injected agent document content.
+ */
+export enum DocumentLoadFormat {
+ FILE = 'file',
+ RAW = 'raw',
+}
+
+/**
+ * Policy load behavior for injection pipeline.
+ */
+export enum PolicyLoad {
+ ALWAYS = 'always',
+ DISABLED = 'disabled',
+}
+
+/**
+ * @deprecated use PolicyLoad.
+ */
+export const AutoLoadAccess = PolicyLoad;
+
+/**
+ * Agent capability bitmask.
+ */
+export enum AgentAccess {
+ EXECUTE = 1,
+ READ = 2,
+ WRITE = 4,
+ LIST = 8,
+ DELETE = 16,
+}
+
+/**
+ * Minimal load options for plain text documents.
+ */
+export interface DocumentLoadRules {
+ keywordMatchMode?: 'all' | 'any';
+ keywords?: string[];
+ maxTokens?: number;
+ priority?: number;
+ regexp?: string;
+ rule?: DocumentLoadRule;
+ timeRange?: {
+ from?: string;
+ to?: string;
+ };
+}
+
+/**
+ * Behavior policy for runtime rendering/retrieval.
+ * Extensible by design for future context/retrieval strategies.
+ */
+export interface AgentDocumentPolicy {
+ [key: string]: any;
+ context?: {
+ keywordMatchMode?: 'all' | 'any';
+ keywords?: string[];
+ policyLoadFormat?: DocumentLoadFormat;
+ maxTokens?: number;
+ mode?: 'append' | 'replace';
+ position?: DocumentLoadPosition;
+ priority?: number;
+ regexp?: string;
+ rule?: DocumentLoadRule;
+ timeRange?: {
+ from?: string;
+ to?: string;
+ };
+ [key: string]: any;
+ };
+ retrieval?: {
+ importance?: number;
+ recencyWeight?: number;
+ searchPriority?: number;
+ [key: string]: any;
+ };
+}
diff --git a/packages/agent-tracing/src/viewer/index.ts b/packages/agent-tracing/src/viewer/index.ts
index 544fe9dede8..e74a4910a94 100644
--- a/packages/agent-tracing/src/viewer/index.ts
+++ b/packages/agent-tracing/src/viewer/index.ts
@@ -88,19 +88,21 @@ function padEnd(s: string, len: number): string {
// Application-defined structural XML tags β€” rendered in blue+bold
const STRUCTURAL_TAGS = new Set([
- 'plugins',
+ 'agent_document',
+ 'api',
+ 'available_tools',
'collection',
'collection.instructions',
- 'available_tools',
- 'api',
- 'user_context',
- 'session_context',
- 'user_memory',
- 'persona',
- 'instruction',
- 'online-devices',
'device',
+ 'discord_context',
+ 'instruction',
'memory_effort_policy',
+ 'online-devices',
+ 'persona',
+ 'plugins',
+ 'session_context',
+ 'user_context',
+ 'user_memory',
]);
/**
@@ -385,7 +387,7 @@ export function renderMessageDetail(
const rawContent =
typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content, null, 2);
- if (rawContent) lines.push(rawContent);
+ if (rawContent) lines.push(formatXmlContent(rawContent));
if (msg.tool_calls && msg.tool_calls.length > 0) {
lines.push('');
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index 0a615c56516..5826d2968dd 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -37,6 +37,7 @@ export const defaultToolIds = [
LocalSystemManifest.identifier,
CloudSandboxManifest.identifier,
TopicReferenceManifest.identifier,
+ AgentDocumentsManifest.identifier,
];
/**
diff --git a/packages/context-engine/src/base/BaseSystemRoleProvider.ts b/packages/context-engine/src/base/BaseSystemRoleProvider.ts
new file mode 100644
index 00000000000..5201b3efde5
--- /dev/null
+++ b/packages/context-engine/src/base/BaseSystemRoleProvider.ts
@@ -0,0 +1,68 @@
+import debug from 'debug';
+
+import type { PipelineContext, ProcessorOptions } from '../types';
+import { BaseProcessor } from './BaseProcessor';
+
+const log = debug('context-engine:base:BaseSystemRoleProvider');
+
+/**
+ * Base class for providers that append content to the system message.
+ *
+ * Subclasses implement `buildSystemRoleContent()` to return the content
+ * to append (or `null` to skip). The base class handles finding or
+ * creating the system message and joining content with `\n\n`.
+ */
+export abstract class BaseSystemRoleProvider extends BaseProcessor {
+ constructor(options: ProcessorOptions = {}) {
+ super(options);
+ }
+
+ /**
+ * Return the content string to append to the system message,
+ * or `null` / empty string to skip injection.
+ */
+ protected abstract buildSystemRoleContent(
+ context: PipelineContext,
+ ): Promise<string | null> | string | null;
+
+ /**
+ * Called after content is successfully injected into the system message.
+ * Override to update pipeline metadata (e.g. tracking flags, stats).
+ */
+ protected onInjected(_context: PipelineContext, _content: string): void {}
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const content = await this.buildSystemRoleContent(context);
+
+ if (!content || content.trim() === '') {
+ log('[%s] No content to inject, skipping', this.name);
+ return this.markAsExecuted(context);
+ }
+
+ const clonedContext = this.cloneContext(context);
+
+ const systemMsgIndex = clonedContext.messages.findIndex((m) => m.role === 'system');
+
+ if (systemMsgIndex >= 0) {
+ const existing = clonedContext.messages[systemMsgIndex];
+ clonedContext.messages[systemMsgIndex] = {
+ ...existing,
+ content: [existing.content, content].filter(Boolean).join('\n\n'),
+ };
+ log('[%s] Appended to existing system message', this.name);
+ } else {
+ clonedContext.messages.unshift({
+ content,
+ createdAt: Date.now(),
+ id: `system-${this.name}-${Date.now()}`,
+ role: 'system' as const,
+ updatedAt: Date.now(),
+ } as any);
+ log('[%s] Created new system message', this.name);
+ }
+
+ this.onInjected(clonedContext, content);
+
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index 54fa23947a5..3b311e381a0 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -23,7 +23,11 @@ import {
} from '../../processors';
import {
AgentBuilderContextInjector,
- AgentDocumentInjector,
+ AgentDocumentBeforeSystemInjector,
+ AgentDocumentContextInjector,
+ AgentDocumentMessageInjector,
+ AgentDocumentSystemAppendInjector,
+ AgentDocumentSystemReplaceInjector,
AgentManagementContextInjector,
BotPlatformContextInjector,
DiscordContextProvider,
@@ -165,7 +169,7 @@ export class MessagesEngine {
const isAgentGroupEnabled = agentGroup?.agentMap && Object.keys(agentGroup.agentMap).length > 0;
const isGroupContextEnabled =
isAgentGroupEnabled || !!agentGroup?.currentAgentId || !!agentGroup?.members;
- const isUserMemoryEnabled = userMemory?.enabled && userMemory?.memories;
+ const isUserMemoryEnabled = !!(userMemory?.enabled && userMemory?.memories);
const hasSelectedSkills = (selectedSkills?.length ?? 0) > 0;
const hasAgentDocuments = !!agentDocuments && agentDocuments.length > 0;
@@ -187,47 +191,68 @@ export class MessagesEngine {
| string
| undefined;
+ // Shared config for all agent document injectors
+ const agentDocConfig = {
+ currentUserMessage,
+ documents: agentDocuments,
+ enabled: hasAgentDocuments,
+ };
+
return [
// =============================================
- // Phase 0: History Truncation (FIRST - truncate before any processing)
+ // Phase 1: History Truncation
+ // MUST run first β€” all subsequent processors work on truncated messages only
// =============================================
- // 0. History truncate (limit message count based on configuration)
- // This MUST be first to ensure subsequent processors only work with truncated messages
- new HistoryTruncateProcessor({
- enableHistoryCount,
- historyCount,
- }),
+ new HistoryTruncateProcessor({ enableHistoryCount, historyCount }),
// =============================================
- // Phase 1: System Role Injection
+ // Phase 2: System Message Assembly
+ // Each provider appends content to a single system message via BaseSystemRoleProvider
// =============================================
- // 1. System role injection (agent's system role)
+ // Agent documents β†’ before system (prepend as separate system message)
+ new AgentDocumentBeforeSystemInjector(agentDocConfig),
+ // Agent's system role (creates the initial system message)
new SystemRoleInjector({ systemRole }),
-
- // 2. Eval context injection (appends envPrompt to system message)
+ // Eval context (appends envPrompt)
new EvalContextSystemInjector({ enabled: !!evalContext?.envPrompt, evalContext }),
-
- // 2.5. Bot platform context injection (appends formatting instructions for non-Markdown platforms)
+ // Bot platform context (formatting instructions for non-Markdown platforms)
new BotPlatformContextInjector({
context: botPlatformContext,
enabled: !!botPlatformContext,
}),
-
- // 3. System date injection (appends current date to system message)
+ // System date
new SystemDateProvider({ enabled: isSystemDateEnabled, timezone }),
+ // Skill context (available skills list + activated skill content)
+ new SkillContextProvider({
+ enabled: !!(skillsConfig?.enabledSkills && skillsConfig.enabledSkills.length > 0),
+ enabledSkills: skillsConfig?.enabledSkills,
+ }),
+ // Tool system role (tool manifests and API definitions)
+ new ToolSystemRoleProvider({
+ enabled: !!(toolsConfig?.manifests && toolsConfig.manifests.length > 0),
+ isCanUseFC: capabilities?.isCanUseFC || (() => true),
+ manifests: toolsConfig?.manifests,
+ model,
+ provider,
+ }),
+ // History summary (conversation summary from compression)
+ new HistorySummaryProvider({ formatHistorySummary, historySummary }),
+ // Agent documents β†’ append to system message
+ new AgentDocumentSystemAppendInjector(agentDocConfig),
+ // Agent documents β†’ replace entire system message (destructive, runs last)
+ new AgentDocumentSystemReplaceInjector(agentDocConfig),
// =============================================
- // Phase 2: First User Message Context Injection
- // These providers inject content before the first user message
+ // Phase 3: Context Injection (before first user message)
+ // Providers consolidate into a single injection message via BaseFirstUserContentProvider
// Order matters: first executed = first in content
// =============================================
- // 4. User memory injection (conditionally added, injected first)
- ...(isUserMemoryEnabled ? [new UserMemoryInjector(userMemory)] : []),
-
- // 5. Group context injection (agent identity and group info for multi-agent chat)
+ // User memory
+ new UserMemoryInjector({ ...userMemory, enabled: isUserMemoryEnabled }),
+ // Group context (agent identity and group info for multi-agent chat)
new GroupContextInjector({
currentAgentId: agentGroup?.currentAgentId,
currentAgentName: agentGroup?.currentAgentName,
@@ -237,95 +262,53 @@ export class MessagesEngine {
members: agentGroup?.members,
systemPrompt: agentGroup?.systemPrompt,
}),
-
- // 5.5. Discord context injection (channel/guild info for Discord bot scenarios)
- ...(discordContext
- ? [new DiscordContextProvider({ context: discordContext, enabled: true })]
- : []),
-
- // 6. GTD Plan injection (conditionally added, after user memory, before knowledge)
- ...(isGTDPlanEnabled ? [new GTDPlanInjector({ enabled: true, plan: gtd.plan })] : []),
-
- // 7. Knowledge injection (full content for agent files + metadata for knowledge bases)
+ // Discord context (channel/guild info)
+ new DiscordContextProvider({ context: discordContext, enabled: !!discordContext }),
+ // GTD Plan
+ new GTDPlanInjector({ enabled: !!isGTDPlanEnabled, plan: gtd?.plan }),
+ // Knowledge (agent files + knowledge bases)
new KnowledgeInjector({
fileContents: knowledge?.fileContents,
knowledgeBases: knowledge?.knowledgeBases,
}),
-
- // 7.5 Agent document injection (policy-based autoload documents)
- ...(hasAgentDocuments
- ? [
- new AgentDocumentInjector({
- currentUserMessage,
- documents: agentDocuments,
- }),
- ]
- : []),
-
- // 8. Tool Discovery context injection (available tools for dynamic activation)
- ...(toolDiscoveryConfig?.availableTools && toolDiscoveryConfig.availableTools.length > 0
- ? [new ToolDiscoveryProvider({ availableTools: toolDiscoveryConfig.availableTools })]
- : []),
-
- // =============================================
- // Phase 3: Additional System Context
- // =============================================
-
- // 9. Agent Builder context injection (current agent config/meta for editing)
+ // Agent documents β†’ before first user message
+ new AgentDocumentContextInjector(agentDocConfig),
+ // Tool Discovery (available tools for dynamic activation)
+ new ToolDiscoveryProvider({
+ availableTools: toolDiscoveryConfig?.availableTools,
+ enabled:
+ !!toolDiscoveryConfig?.availableTools && toolDiscoveryConfig.availableTools.length > 0,
+ }),
+ // Agent Builder context (current agent config/meta for editing)
new AgentBuilderContextInjector({
enabled: isAgentBuilderEnabled,
agentContext: agentBuilderContext,
}),
-
- // 7. Agent Management context injection (available models and plugins for agent creation)
+ // Agent Management context (available models and plugins)
new AgentManagementContextInjector({
enabled: isAgentManagementEnabled,
context: agentManagementContext,
}),
-
- // 8. Group Agent Builder context injection (current group config/members for editing)
+ // Group Agent Builder context (current group config/members for editing)
new GroupAgentBuilderContextInjector({
enabled: isGroupAgentBuilderEnabled,
groupContext: groupAgentBuilderContext,
}),
- // 11. Skill context injection (conditionally added)
- ...(skillsConfig?.enabledSkills && skillsConfig.enabledSkills.length > 0
- ? [
- new SkillContextProvider({
- enabledSkills: skillsConfig.enabledSkills,
- }),
- ]
- : []),
-
- // 12. Tool system role injection (conditionally added)
- ...(toolsConfig?.manifests && toolsConfig.manifests.length > 0
- ? [
- new ToolSystemRoleProvider({
- isCanUseFC: capabilities?.isCanUseFC || (() => true),
- manifests: toolsConfig.manifests,
- model,
- provider,
- }),
- ]
- : []),
-
- // 13. History summary injection
- new HistorySummaryProvider({
- formatHistorySummary,
- historySummary,
- }),
-
- // 14. Selected skill injection (ephemeral user-selected slash skills for this request)
- ...(hasSelectedSkills ? [new SelectedSkillInjector({ selectedSkills })] : []),
+ // =============================================
+ // Phase 4: User Message Augmentation
+ // Injects context into specific user messages (last user, selected, etc.)
+ // =============================================
- // 15. Page Selections injection (inject user-selected text into each user message that has them)
+ // Agent documents β†’ after-first-user, context-end
+ new AgentDocumentMessageInjector(agentDocConfig),
+ // Selected skills (ephemeral user-selected slash skills for this request)
+ new SelectedSkillInjector({ enabled: hasSelectedSkills, selectedSkills }),
+ // Page selections (inject user-selected text into each user message)
new PageSelectionsInjector({ enabled: isPageEditorEnabled }),
-
- // 16. Page Editor context injection (inject current page content to last user message)
+ // Page Editor context (inject current page content to last user message)
new PageEditorContextInjector({
enabled: isPageEditorEnabled,
- // Use direct pageContentContext if provided (server-side), otherwise build from initialContext + stepContext (frontend)
pageContentContext:
pageContentContext ??
(initialContext?.pageEditor
@@ -336,57 +319,40 @@ export class MessagesEngine {
lineCount: initialContext.pageEditor.metadata.lineCount,
title: initialContext.pageEditor.metadata.title,
},
- // Use latest XML from stepContext if available, otherwise fallback to initial XML
xml: stepContext?.stepPageEditor?.xml || initialContext.pageEditor.xml,
}
: undefined),
}),
-
- // 17. GTD Todo injection (conditionally added, at end of last user message)
- ...(isGTDTodoEnabled ? [new GTDTodoInjector({ enabled: true, todos: gtd.todos })] : []),
-
- // 18. Topic Reference context injection (inject referenced topic summaries to last user message)
- ...(topicReferences && topicReferences.length > 0
- ? [
- new TopicReferenceContextInjector({
- enabled: true,
- topicReferences,
- }),
- ]
- : []),
+ // GTD Todo (at end of last user message)
+ new GTDTodoInjector({ enabled: !!isGTDTodoEnabled, todos: gtd?.todos }),
+ // Topic Reference context (referenced topic summaries to last user message)
+ new TopicReferenceContextInjector({
+ enabled: !!(topicReferences && topicReferences.length > 0),
+ topicReferences,
+ }),
// =============================================
- // Phase 4: Message Transformation
+ // Phase 5: Message Transformation
+ // Flattens group/task messages, applies templates and variables
// =============================================
- // 17. Input template processing
+ // Input template processing
new InputTemplateProcessor({ inputTemplate }),
-
- // 18. Placeholder variables processing
- new PlaceholderVariablesProcessor({
- variableGenerators: variableGenerators || {},
- }),
-
- // 19. AgentCouncil message flatten (convert role=agentCouncil to standard assistant + tool messages)
+ // Placeholder variables processing
+ new PlaceholderVariablesProcessor({ variableGenerators: variableGenerators || {} }),
+ // AgentCouncil message flatten
new AgentCouncilFlattenProcessor(),
-
- // 20. Group message flatten (convert role=assistantGroup to standard assistant + tool messages)
+ // Group message flatten
new GroupMessageFlattenProcessor(),
-
- // 21. Tasks message flatten (convert role=tasks to individual task messages)
+ // Tasks message flatten
new TasksFlattenProcessor(),
-
- // 22. Task message processing (convert role=task to assistant with instruction + content)
+ // Task message processing
new TaskMessageProcessor(),
-
- // 23. Supervisor role restore (convert role=supervisor back to role=assistant for model)
+ // Supervisor role restore
new SupervisorRoleRestoreProcessor(),
-
- // 24. Compressed group role transform (convert role=compressedGroup to role=user for model)
+ // Compressed group role transform
new CompressedGroupRoleTransformProcessor(),
-
- // 25. Group orchestration filter (remove supervisor's orchestration messages like broadcast/speak)
- // This must be BEFORE GroupRoleTransformProcessor so we filter based on original agentId/tools
+ // Group orchestration filter (must run BEFORE GroupRoleTransformProcessor)
...(isAgentGroupEnabled && agentGroup.agentMap && agentGroup.currentAgentId
? [
new GroupOrchestrationFilterProcessor({
@@ -394,14 +360,11 @@ export class MessagesEngine {
Object.entries(agentGroup.agentMap).map(([id, info]) => [id, { role: info.role }]),
),
currentAgentId: agentGroup.currentAgentId,
- // Only enabled when current agent is NOT supervisor (supervisor needs to see orchestration history)
enabled: agentGroup.currentAgentRole !== 'supervisor',
}),
]
: []),
-
- // 26. Group role transform (convert other agents' messages to user role with speaker tags)
- // This must be BEFORE ToolCallProcessor so other agents' tool messages are converted first
+ // Group role transform (must run BEFORE ToolCallProcessor)
...(isAgentGroupEnabled && agentGroup.currentAgentId
? [
new GroupRoleTransformProcessor({
@@ -412,13 +375,13 @@ export class MessagesEngine {
: []),
// =============================================
- // Phase 5: Content Processing
+ // Phase 6: Content Processing
+ // Multimodal encoding, tool calls, reaction feedback
// =============================================
- // 27. Reaction feedback injection (append user reaction feedback to assistant messages)
+ // Reaction feedback
new ReactionFeedbackProcessor({ enabled: true }),
-
- // 28. Message content processing (image encoding, etc.)
+ // Message content processing (image encoding, multimodal)
new MessageContentProcessor({
fileContext: fileContext || { enabled: true, includeFileUrl: true },
isCanUseVideo: capabilities?.isCanUseVideo || (() => false),
@@ -426,8 +389,7 @@ export class MessagesEngine {
model,
provider,
}),
-
- // 29. Tool call processing
+ // Tool call processing
new ToolCallProcessor({
genToolCallingName: this.toolNameResolver.generate.bind(this.toolNameResolver),
isCanUseFC: capabilities?.isCanUseFC || (() => true),
@@ -435,13 +397,16 @@ export class MessagesEngine {
provider,
}),
- // 30. Tool message reordering
- new ToolMessageReorder(),
+ // =============================================
+ // Phase 7: Cleanup
+ // Final reordering, force finish, and message cleanup
+ // =============================================
- // 31. Force finish summary injection (when maxSteps exceeded, inject summary prompt)
+ // Tool message reordering
+ new ToolMessageReorder(),
+ // Force finish summary (when maxSteps exceeded)
new ForceFinishSummaryInjector({ enabled: !!forceFinish }),
-
- // 32. Message cleanup (final step, keep only necessary fields)
+ // Message cleanup (final step)
new MessageCleanupProcessor(),
];
}
diff --git a/packages/context-engine/src/engine/skills/SkillEngine.ts b/packages/context-engine/src/engine/skills/SkillEngine.ts
index d12f6b12ec6..ae580c4712b 100644
--- a/packages/context-engine/src/engine/skills/SkillEngine.ts
+++ b/packages/context-engine/src/engine/skills/SkillEngine.ts
@@ -1,38 +1,58 @@
import debug from 'debug';
import type { SkillMeta } from '../../providers/SkillContextProvider';
+import type { OperationSkillSet, SkillEnableChecker, SkillEngineOptions } from './types';
const log = debug('context-engine:skills-engine');
-export interface SkillEngineOptions {
- skills: SkillMeta[];
-}
-
/**
- * Skills Engine - Filters available skills by agent configuration
+ * Skills Engine - Assembles the operation-level skill set.
*
- * Accepts a pre-merged array of SkillMeta from all sources (builtin, DB, etc.)
- * and provides filtering by agent's enabled plugin IDs.
+ * Analogous to ToolsEngine for tools. Accepts raw skills from all sources
+ * (builtin, DB, etc.) and an optional enableChecker, then produces an
+ * OperationSkillSet with environment-appropriate skills filtered in.
*/
export class SkillEngine {
private skills: Map<string, SkillMeta>;
+ private enableChecker?: SkillEnableChecker;
constructor(options: SkillEngineOptions) {
+ this.enableChecker = options.enableChecker;
this.skills = new Map(options.skills.map((s) => [s.identifier, s]));
log('Initialized with %d skills: %o', this.skills.size, Array.from(this.skills.keys()));
}
/**
- * Filter skills by agent's enabled plugin IDs
+ * Assemble the OperationSkillSet for an agent execution.
+ *
+ * Filters skills through enableChecker and pairs the result with
+ * the agent's enabled plugin IDs for downstream SkillResolver consumption.
+ *
+ * @param pluginIds Plugin IDs enabled on the agent
*/
- getEnabledSkills(pluginIds: string[]): SkillMeta[] {
- return pluginIds.map((id) => this.skills.get(id)).filter((s): s is SkillMeta => !!s);
- }
+ generate(pluginIds: string[]): OperationSkillSet {
+ const allSkills = Array.from(this.skills.values());
- /**
- * Get all registered skills
- */
- getAllSkills(): SkillMeta[] {
- return Array.from(this.skills.values());
+ const filteredSkills = this.enableChecker
+ ? allSkills.filter((skill) => {
+ const enabled = this.enableChecker!(skill);
+ if (!enabled) {
+ log('Skill filtered out by enableChecker: %s', skill.identifier);
+ }
+ return enabled;
+ })
+ : allSkills;
+
+ log(
+ 'Generated OperationSkillSet: %d/%d skills, pluginIds=%o',
+ filteredSkills.length,
+ allSkills.length,
+ pluginIds,
+ );
+
+ return {
+ enabledPluginIds: pluginIds,
+ skills: filteredSkills,
+ };
}
}
diff --git a/packages/context-engine/src/engine/skills/SkillResolver.ts b/packages/context-engine/src/engine/skills/SkillResolver.ts
new file mode 100644
index 00000000000..3b645954bfe
--- /dev/null
+++ b/packages/context-engine/src/engine/skills/SkillResolver.ts
@@ -0,0 +1,75 @@
+import debug from 'debug';
+
+import type { SkillMeta } from '../../providers/SkillContextProvider';
+import type {
+ ActivatedStepSkill,
+ OperationSkillSet,
+ ResolvedSkillSet,
+ StepSkillDelta,
+} from './types';
+
+const log = debug('context-engine:skill-resolver');
+
+/**
+ * Unified skill resolution engine.
+ *
+ * Single entry-point that merges operation-level skills with step-level
+ * dynamic activations (activateSkill tool calls) and produces the final
+ * ResolvedSkillSet consumed by SkillContextProvider.
+ *
+ * Analogous to ToolResolver for tools.
+ */
+export class SkillResolver {
+ /**
+ * Resolve the final skill set for an LLM call.
+ *
+ * @param operationSkillSet Immutable skills determined at operation creation
+ * @param stepDelta Declarative skill changes for the current step
+ * @param accumulatedActivations Skills activated in previous steps (cumulative)
+ */
+ resolve(
+ operationSkillSet: OperationSkillSet,
+ stepDelta: StepSkillDelta,
+ accumulatedActivations: ActivatedStepSkill[] = [],
+ ): ResolvedSkillSet {
+ const enabledPluginIds = new Set(operationSkillSet.enabledPluginIds);
+
+ // Collect all step-level activations (accumulated + current delta)
+ const stepActivatedMap = new Map<string, { content?: string }>();
+
+ for (const activation of accumulatedActivations) {
+ stepActivatedMap.set(activation.identifier, { content: activation.content });
+ }
+
+ for (const activation of stepDelta.activatedSkills) {
+ stepActivatedMap.set(activation.identifier, { content: activation.content });
+ }
+
+ // Resolve each skill
+ const enabledSkills: SkillMeta[] = operationSkillSet.skills.map((skill) => {
+ const isOperationActivated = enabledPluginIds.has(skill.identifier);
+ const stepActivation = stepActivatedMap.get(skill.identifier);
+ const isStepActivated = !!stepActivation;
+
+ if (isOperationActivated || isStepActivated) {
+ return {
+ ...skill,
+ activated: true,
+ // Step delta content overrides original content if provided
+ content: stepActivation?.content || skill.content,
+ };
+ }
+
+ return skill;
+ });
+
+ if (stepDelta.activatedSkills.length > 0) {
+ log(
+ 'Step-level skill activations: %o',
+ stepDelta.activatedSkills.map((s) => s.identifier),
+ );
+ }
+
+ return { enabledSkills };
+ }
+}
diff --git a/packages/context-engine/src/engine/skills/__tests__/SkillEngine.test.ts b/packages/context-engine/src/engine/skills/__tests__/SkillEngine.test.ts
new file mode 100644
index 00000000000..a0d9c316e94
--- /dev/null
+++ b/packages/context-engine/src/engine/skills/__tests__/SkillEngine.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from 'vitest';
+
+import { SkillEngine } from '../SkillEngine';
+
+describe('SkillEngine', () => {
+ const rawSkills = [
+ {
+ content: '<artifacts_guide>...</artifacts_guide>',
+ description: 'Generate artifacts',
+ identifier: 'artifacts',
+ name: 'Artifacts',
+ },
+ {
+ content: '<agent_browser_guides>...</agent_browser_guides>',
+ description: 'Browser automation',
+ identifier: 'agent-browser',
+ name: 'Agent Browser',
+ },
+ {
+ description: 'LobeHub management',
+ identifier: 'lobehub-cli',
+ name: 'LobeHub CLI',
+ },
+ ];
+
+ it('should include all skills when no enableChecker is provided', () => {
+ const engine = new SkillEngine({ skills: rawSkills });
+ const result = engine.generate(['artifacts']);
+
+ expect(result.skills).toHaveLength(3);
+ expect(result.enabledPluginIds).toEqual(['artifacts']);
+ });
+
+ it('should filter skills via enableChecker', () => {
+ const desktopOnlySkills = new Set(['agent-browser']);
+ const engine = new SkillEngine({
+ enableChecker: (skill) => !desktopOnlySkills.has(skill.identifier),
+ skills: rawSkills,
+ });
+
+ const result = engine.generate([]);
+
+ expect(result.skills).toHaveLength(2);
+ expect(result.skills.find((s) => s.identifier === 'agent-browser')).toBeUndefined();
+ });
+
+ it('should pass through pluginIds to OperationSkillSet', () => {
+ const engine = new SkillEngine({ skills: rawSkills });
+ const result = engine.generate(['artifacts', 'lobehub-cli']);
+
+ expect(result.enabledPluginIds).toEqual(['artifacts', 'lobehub-cli']);
+ });
+
+ it('should preserve skill content in output', () => {
+ const engine = new SkillEngine({ skills: rawSkills });
+ const result = engine.generate([]);
+
+ const artifacts = result.skills.find((s) => s.identifier === 'artifacts');
+ expect(artifacts?.content).toBe('<artifacts_guide>...</artifacts_guide>');
+ });
+});
diff --git a/packages/context-engine/src/engine/skills/__tests__/SkillResolver.test.ts b/packages/context-engine/src/engine/skills/__tests__/SkillResolver.test.ts
new file mode 100644
index 00000000000..9faf74e1b8c
--- /dev/null
+++ b/packages/context-engine/src/engine/skills/__tests__/SkillResolver.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, it } from 'vitest';
+
+import { SkillResolver } from '../SkillResolver';
+import type { ActivatedStepSkill, OperationSkillSet, StepSkillDelta } from '../types';
+
+describe('SkillResolver', () => {
+ const resolver = new SkillResolver();
+
+ const baseSkills = [
+ {
+ content: '<artifacts_guide>...</artifacts_guide>',
+ description: 'Generate artifacts',
+ identifier: 'artifacts',
+ name: 'Artifacts',
+ },
+ {
+ content: '<agent_browser_guides>...</agent_browser_guides>',
+ description: 'Browser automation',
+ identifier: 'agent-browser',
+ name: 'Agent Browser',
+ },
+ {
+ description: 'LobeHub management',
+ identifier: 'lobehub-cli',
+ name: 'LobeHub CLI',
+ },
+ ];
+
+ const emptyDelta: StepSkillDelta = { activatedSkills: [] };
+
+ it('should mark skills as activated when their identifier is in enabledPluginIds', () => {
+ const operationSkillSet: OperationSkillSet = {
+ enabledPluginIds: ['artifacts'],
+ skills: baseSkills,
+ };
+
+ const resolved = resolver.resolve(operationSkillSet, emptyDelta);
+
+ const artifacts = resolved.enabledSkills.find((s) => s.identifier === 'artifacts');
+ expect(artifacts?.activated).toBe(true);
+ expect(artifacts?.content).toBe('<artifacts_guide>...</artifacts_guide>');
+
+ const browser = resolved.enabledSkills.find((s) => s.identifier === 'agent-browser');
+ expect(browser?.activated).toBeUndefined();
+ });
+
+ it('should include all skills in enabledSkills (activated and non-activated)', () => {
+ const operationSkillSet: OperationSkillSet = {
+ enabledPluginIds: [],
+ skills: baseSkills,
+ };
+
+ const resolved = resolver.resolve(operationSkillSet, emptyDelta);
+ expect(resolved.enabledSkills).toHaveLength(3);
+ });
+
+ it('should activate skills from step delta', () => {
+ const operationSkillSet: OperationSkillSet = {
+ enabledPluginIds: [],
+ skills: baseSkills,
+ };
+ const delta: StepSkillDelta = {
+ activatedSkills: [{ content: 'step-injected content', identifier: 'agent-browser' }],
+ };
+
+ const resolved = resolver.resolve(operationSkillSet, delta);
+
+ const browser = resolved.enabledSkills.find((s) => s.identifier === 'agent-browser');
+ expect(browser?.activated).toBe(true);
+ expect(browser?.content).toBe('step-injected content');
+ });
+
+ it('should activate skills from accumulated previous steps', () => {
+ const operationSkillSet: OperationSkillSet = {
+ enabledPluginIds: [],
+ skills: baseSkills,
+ };
+ const accumulated: ActivatedStepSkill[] = [
+ { activatedAtStep: 1, content: 'accumulated content', identifier: 'lobehub-cli' },
+ ];
+
+ const resolved = resolver.resolve(operationSkillSet, emptyDelta, accumulated);
+
+ const cli = resolved.enabledSkills.find((s) => s.identifier === 'lobehub-cli');
+ expect(cli?.activated).toBe(true);
+ expect(cli?.content).toBe('accumulated content');
+ });
+
+ it('should merge operation + accumulated + step delta activations', () => {
+ const operationSkillSet: OperationSkillSet = {
+ enabledPluginIds: ['artifacts'],
+ skills: baseSkills,
+ };
+ const delta: StepSkillDelta = {
+ activatedSkills: [{ identifier: 'agent-browser' }],
+ };
+ const accumulated: ActivatedStepSkill[] = [{ activatedAtStep: 0, identifier: 'lobehub-cli' }];
+
+ const resolved = resolver.resolve(operationSkillSet, delta, accumulated);
+
+ expect(resolved.enabledSkills.filter((s) => s.activated)).toHaveLength(3);
+ });
+
+ it('should let step delta content override original content', () => {
+ const operationSkillSet: OperationSkillSet = {
+ enabledPluginIds: ['artifacts'],
+ skills: baseSkills,
+ };
+ const delta: StepSkillDelta = {
+ activatedSkills: [{ content: 'overridden', identifier: 'artifacts' }],
+ };
+
+ const resolved = resolver.resolve(operationSkillSet, delta);
+
+ const artifacts = resolved.enabledSkills.find((s) => s.identifier === 'artifacts');
+ expect(artifacts?.activated).toBe(true);
+ expect(artifacts?.content).toBe('overridden');
+ });
+
+ it('should let accumulated content override original but step delta wins', () => {
+ const operationSkillSet: OperationSkillSet = {
+ enabledPluginIds: [],
+ skills: baseSkills,
+ };
+ const accumulated: ActivatedStepSkill[] = [
+ { activatedAtStep: 0, content: 'from-accumulated', identifier: 'artifacts' },
+ ];
+ const delta: StepSkillDelta = {
+ activatedSkills: [{ content: 'from-delta', identifier: 'artifacts' }],
+ };
+
+ const resolved = resolver.resolve(operationSkillSet, delta, accumulated);
+
+ const artifacts = resolved.enabledSkills.find((s) => s.identifier === 'artifacts');
+ expect(artifacts?.content).toBe('from-delta');
+ });
+});
diff --git a/packages/context-engine/src/engine/skills/buildStepSkillDelta.ts b/packages/context-engine/src/engine/skills/buildStepSkillDelta.ts
new file mode 100644
index 00000000000..f0d010862d7
--- /dev/null
+++ b/packages/context-engine/src/engine/skills/buildStepSkillDelta.ts
@@ -0,0 +1,17 @@
+import type { StepSkillDelta } from './types';
+
+export interface BuildStepSkillDeltaParams {
+ // Reserved for future step-level signals (e.g., @skill mentions)
+}
+
+/**
+ * Build a declarative StepSkillDelta from runtime signals.
+ *
+ * Currently returns an empty delta β€” step-level skill activations
+ * are accumulated in state.activatedStepSkills and passed directly
+ * to SkillResolver. This function exists as the extension point for
+ * future step-level signals (e.g., @skill mentions in user messages).
+ */
+export function buildStepSkillDelta(_params?: BuildStepSkillDeltaParams): StepSkillDelta {
+ return { activatedSkills: [] };
+}
diff --git a/packages/context-engine/src/engine/skills/index.ts b/packages/context-engine/src/engine/skills/index.ts
index c250ef8e8b8..da794dc38ca 100644
--- a/packages/context-engine/src/engine/skills/index.ts
+++ b/packages/context-engine/src/engine/skills/index.ts
@@ -1 +1,11 @@
-export { SkillEngine, type SkillEngineOptions } from './SkillEngine';
+export { buildStepSkillDelta, type BuildStepSkillDeltaParams } from './buildStepSkillDelta';
+export { SkillEngine } from './SkillEngine';
+export { SkillResolver } from './SkillResolver';
+export type {
+ ActivatedStepSkill,
+ OperationSkillSet,
+ ResolvedSkillSet,
+ SkillEnableChecker,
+ SkillEngineOptions,
+ StepSkillDelta,
+} from './types';
diff --git a/packages/context-engine/src/engine/skills/types.ts b/packages/context-engine/src/engine/skills/types.ts
new file mode 100644
index 00000000000..fcd4a30425d
--- /dev/null
+++ b/packages/context-engine/src/engine/skills/types.ts
@@ -0,0 +1,55 @@
+import type { SkillMeta } from '../../providers/SkillContextProvider';
+
+/**
+ * Application-layer checker that determines whether a skill is available
+ * in the current environment (e.g., desktop-only skills on web).
+ */
+export type SkillEnableChecker = (skill: SkillMeta) => boolean;
+
+/**
+ * SkillEngine configuration options.
+ */
+export interface SkillEngineOptions {
+ /** Optional checker to filter skills by environment/platform */
+ enableChecker?: SkillEnableChecker;
+ /** All raw skills from all sources (builtin, DB, etc.) */
+ skills: SkillMeta[];
+}
+
+/**
+ * Operation-level skill set: determined at createOperation time, immutable during execution.
+ * Analogous to OperationToolSet for tools.
+ */
+export interface OperationSkillSet {
+ /** Plugin IDs enabled on this agent β€” skills matching these IDs are auto-activated */
+ enabledPluginIds: string[];
+ /** All available skills after enableChecker filtering */
+ skills: SkillMeta[];
+}
+
+/**
+ * Record of a skill activated at step level (e.g., via activateSkill tool call).
+ */
+export interface ActivatedStepSkill {
+ activatedAtStep: number;
+ content?: string;
+ identifier: string;
+}
+
+/**
+ * Declarative delta describing skill changes for a single step.
+ * Built by buildStepSkillDelta, consumed by SkillResolver.resolve.
+ */
+export interface StepSkillDelta {
+ activatedSkills: Array<{
+ content?: string;
+ identifier: string;
+ }>;
+}
+
+/**
+ * Final resolved skill set ready for SkillContextProvider consumption.
+ */
+export interface ResolvedSkillSet {
+ enabledSkills: SkillMeta[];
+}
diff --git a/packages/context-engine/src/index.ts b/packages/context-engine/src/index.ts
index 035b9cfd3dc..db3d4accb7c 100644
--- a/packages/context-engine/src/index.ts
+++ b/packages/context-engine/src/index.ts
@@ -6,6 +6,7 @@ export { BaseFirstUserContentProvider } from './base/BaseFirstUserContentProvide
export { BaseLastUserContentProvider } from './base/BaseLastUserContentProvider';
export { BaseProcessor } from './base/BaseProcessor';
export { BaseProvider } from './base/BaseProvider';
+export { BaseSystemRoleProvider } from './base/BaseSystemRoleProvider';
// Context Engine
export * from './engine';
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector.ts b/packages/context-engine/src/providers/AgentDocumentInjector.ts
deleted file mode 100644
index b0d8155426f..00000000000
--- a/packages/context-engine/src/providers/AgentDocumentInjector.ts
+++ /dev/null
@@ -1,314 +0,0 @@
-import type {
- AgentDocumentLoadRule,
- AgentDocumentLoadRules,
-} from '../../../database/src/models/agentDocuments';
-import { matchesLoadRules } from '../../../database/src/models/agentDocuments';
-import { BaseProvider } from '../base/BaseProvider';
-import type { PipelineContext, ProcessorOptions } from '../types';
-
-declare module '../types' {
- interface PipelineContextMetadataOverrides {
- agentDocuments?: {
- byPosition: Partial<Record<AgentDocumentInjectionPosition, number>>;
- injectedCount: number;
- policyIds: string[];
- providedCount: number;
- };
- agentDocumentsCount?: number;
- agentDocumentsInjected?: boolean;
- }
-}
-
-export type { AgentDocumentLoadRule, AgentDocumentLoadRules };
-
-export const AGENT_DOCUMENT_INJECTION_POSITIONS = [
- 'after-first-user',
- 'before-first-user',
- 'before-system',
- 'context-end',
- 'manual',
- 'on-demand',
- 'system-append',
- 'system-replace',
-] as const;
-
-export type AgentDocumentInjectionPosition = (typeof AGENT_DOCUMENT_INJECTION_POSITIONS)[number];
-
-export type AgentDocumentLoadFormat = 'file' | 'raw';
-
-export interface AgentContextDocument {
- content?: string;
- filename: string;
- id?: string;
- loadPosition?: AgentDocumentInjectionPosition;
- loadRules?: AgentDocumentLoadRules;
- policyId?: string | null;
- policyLoadFormat?: AgentDocumentLoadFormat;
- title?: string;
-}
-
-export interface AgentDocumentInjectorConfig {
- currentTime?: Date;
- currentUserMessage?: string;
- documents?: AgentContextDocument[];
- truncateContent?: (content: string, maxTokens: number) => string;
-}
-
-export class AgentDocumentInjector extends BaseProvider {
- readonly name = 'AgentDocumentInjector';
-
- constructor(
- private config: AgentDocumentInjectorConfig,
- options: ProcessorOptions = {},
- ) {
- super(options);
- }
-
- protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
- const clonedContext = this.cloneContext(context);
- const documents = this.config.documents || [];
-
- if (documents.length === 0) {
- return this.markAsExecuted(clonedContext);
- }
-
- const injectedCounts = new Map<AgentDocumentInjectionPosition, number>();
- const documentsByPosition = this.groupByPosition(documents);
- let injectedCount = 0;
-
- for (const [position, docs] of documentsByPosition.entries()) {
- const filteredDocs = this.filterByRules(docs);
- if (filteredDocs.length === 0) continue;
-
- switch (position) {
- case 'before-system': {
- this.injectBeforeSystem(clonedContext, filteredDocs);
- break;
- }
- case 'system-append': {
- this.appendToSystem(clonedContext, filteredDocs);
- break;
- }
- case 'system-replace': {
- this.replaceSystem(clonedContext, filteredDocs);
- break;
- }
- case 'before-first-user': {
- this.injectBeforeFirstUser(clonedContext, filteredDocs);
- break;
- }
- case 'after-first-user': {
- this.injectAfterFirstUser(clonedContext, filteredDocs);
- break;
- }
- case 'context-end': {
- this.injectAtEnd(clonedContext, filteredDocs);
- break;
- }
- case 'manual':
- case 'on-demand': {
- continue;
- }
- }
-
- injectedCount += filteredDocs.length;
- injectedCounts.set(position, (injectedCounts.get(position) || 0) + filteredDocs.length);
- }
-
- if (injectedCount === 0) return this.markAsExecuted(clonedContext);
-
- const policyIds = Array.from(
- new Set(
- documents.map((doc) => doc.policyId).filter((policyId): policyId is string => !!policyId),
- ),
- );
-
- clonedContext.metadata.agentDocumentsInjected = true;
- clonedContext.metadata.agentDocumentsCount = injectedCount;
- clonedContext.metadata.agentDocuments = {
- byPosition: Object.fromEntries(injectedCounts.entries()),
- injectedCount,
- policyIds,
- providedCount: documents.length,
- };
-
- return this.markAsExecuted(clonedContext);
- }
-
- private approximateTokenTruncate(content: string, maxTokens: number): string {
- if (!Number.isFinite(maxTokens) || maxTokens <= 0) return content;
- const parts = content.split(/\s+/);
- if (parts.length <= maxTokens) return content;
- return `${parts.slice(0, maxTokens).join(' ')}\n...[truncated]`;
- }
-
- private appendToSystem(context: PipelineContext, docs: AgentContextDocument[]): void {
- const systemMessage = context.messages.find((m) => m.role === 'system');
- if (systemMessage) {
- const content = this.combineDocuments(docs);
- systemMessage.content = `${systemMessage.content}\n\n${content}`;
- } else {
- this.injectBeforeSystem(context, docs);
- }
- }
-
- private combineDocuments(docs: AgentContextDocument[]): string {
- return docs.map((doc) => this.formatDocument(doc)).join('\n\n');
- }
-
- private filterByRules(docs: AgentContextDocument[]): AgentContextDocument[] {
- return docs.filter((doc) => {
- const context = {
- currentTime: this.config.currentTime,
- currentUserMessage: this.config.currentUserMessage,
- };
- return matchesLoadRules(doc, context);
- });
- }
-
- private formatDocument(doc: AgentContextDocument): string {
- const maxTokens = doc.loadRules?.maxTokens;
- let content = doc.content || '';
- if (maxTokens && maxTokens > 0) {
- content = this.config.truncateContent
- ? this.config.truncateContent(content, maxTokens)
- : this.approximateTokenTruncate(content, maxTokens);
- }
-
- if (doc.policyLoadFormat === 'file') {
- const attributes = this.formatDocumentAttributes(doc);
- return `<agent_document${attributes}>
-${content}
-</agent_document>`;
- }
-
- return content;
- }
-
- private formatDocumentAttributes(doc: AgentContextDocument): string {
- const attrs: string[] = [];
-
- if (doc.id) attrs.push(`id="${this.escapeAttribute(doc.id)}"`);
- if (doc.filename) attrs.push(`filename="${this.escapeAttribute(doc.filename)}"`);
- if (doc.title) attrs.push(`title="${this.escapeAttribute(doc.title)}"`);
-
- return attrs.length > 0 ? ` ${attrs.join(' ')}` : '';
- }
-
- private escapeAttribute(value: string): string {
- return value
- .replaceAll('&', '&amp;')
- .replaceAll('"', '&quot;')
- .replaceAll('<', '&lt;')
- .replaceAll('>', '&gt;');
- }
-
- private getPosition(doc: AgentContextDocument): AgentDocumentInjectionPosition {
- return doc.loadPosition || 'before-first-user';
- }
-
- private groupByPosition(
- docs: AgentContextDocument[],
- ): Map<AgentDocumentInjectionPosition, AgentContextDocument[]> {
- const grouped = new Map<AgentDocumentInjectionPosition, AgentContextDocument[]>();
-
- for (const doc of docs) {
- const position = this.getPosition(doc);
- const existing = grouped.get(position) || [];
- existing.push(doc);
- grouped.set(position, existing);
- }
-
- for (const [position, groupDocs] of grouped.entries()) {
- groupDocs.sort((a, b) => {
- const aPriority = a.loadRules?.priority ?? 999;
- const bPriority = b.loadRules?.priority ?? 999;
- return aPriority - bPriority;
- });
- grouped.set(position, groupDocs);
- }
-
- return grouped;
- }
-
- private injectAfterFirstUser(context: PipelineContext, docs: AgentContextDocument[]): void {
- const firstUserIndex = context.messages.findIndex((m) => m.role === 'user');
- if (firstUserIndex === -1) return;
-
- const content = this.combineDocuments(docs);
- const now = Date.now();
- const message = {
- content,
- createdAt: now,
- id: `agent-doc-after-user-${now}`,
- role: 'system' as const,
- updatedAt: now,
- };
-
- context.messages.splice(firstUserIndex + 1, 0, message);
- }
-
- private injectAtEnd(context: PipelineContext, docs: AgentContextDocument[]): void {
- const content = this.combineDocuments(docs);
- const now = Date.now();
- const message = {
- content,
- createdAt: now,
- id: `agent-doc-context-end-${now}`,
- role: 'system' as const,
- updatedAt: now,
- };
-
- context.messages.push(message);
- }
-
- private injectBeforeFirstUser(context: PipelineContext, docs: AgentContextDocument[]): void {
- const firstUserIndex = context.messages.findIndex((m) => m.role === 'user');
- if (firstUserIndex === -1) return;
-
- const content = this.combineDocuments(docs);
- const now = Date.now();
- const message = {
- content,
- createdAt: now,
- id: `agent-doc-before-user-${now}`,
- role: 'system' as const,
- updatedAt: now,
- };
-
- context.messages.splice(firstUserIndex, 0, message);
- }
-
- private injectBeforeSystem(context: PipelineContext, docs: AgentContextDocument[]): void {
- const content = this.combineDocuments(docs);
- const now = Date.now();
- const message = {
- content,
- createdAt: now,
- id: `agent-doc-before-system-${now}`,
- role: 'system' as const,
- updatedAt: now,
- };
-
- context.messages.unshift(message);
- }
-
- private replaceSystem(context: PipelineContext, docs: AgentContextDocument[]): void {
- const systemIndex = context.messages.findIndex((m) => m.role === 'system');
- const content = this.combineDocuments(docs);
- const now = Date.now();
- const message = {
- content,
- createdAt: now,
- id: `agent-doc-system-${now}`,
- role: 'system' as const,
- updatedAt: now,
- };
-
- if (systemIndex >= 0) {
- context.messages[systemIndex] = message;
- } else {
- context.messages.unshift(message);
- }
- }
-}
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/BeforeSystemInjector.ts b/packages/context-engine/src/providers/AgentDocumentInjector/BeforeSystemInjector.ts
new file mode 100644
index 00000000000..92b8483720b
--- /dev/null
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/BeforeSystemInjector.ts
@@ -0,0 +1,57 @@
+import debug from 'debug';
+
+import { BaseProcessor } from '../../base/BaseProcessor';
+import type { PipelineContext, ProcessorOptions } from '../../types';
+import type { AgentContextDocument, AgentDocumentFilterContext } from './shared';
+import { combineDocuments, getDocumentsForPositions } from './shared';
+
+const log = debug('context-engine:provider:AgentDocumentBeforeSystemInjector');
+
+export interface AgentDocumentBeforeSystemInjectorConfig extends AgentDocumentFilterContext {
+ documents?: AgentContextDocument[];
+ enabled?: boolean;
+}
+
+/**
+ * Injects agent documents BEFORE the system message (prepend).
+ * Handles `before-system` position.
+ *
+ * Placed at the very beginning of Phase 2, before SystemRoleInjector.
+ */
+export class AgentDocumentBeforeSystemInjector extends BaseProcessor {
+ readonly name = 'AgentDocumentBeforeSystemInjector';
+
+ constructor(
+ private config: AgentDocumentBeforeSystemInjectorConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ if (this.config.enabled === false) return this.markAsExecuted(context);
+
+ const docs = getDocumentsForPositions(
+ this.config.documents || [],
+ ['before-system'],
+ this.config,
+ );
+
+ if (docs.length === 0) return this.markAsExecuted(context);
+
+ const clonedContext = this.cloneContext(context);
+ const content = combineDocuments(docs, this.config);
+ const now = Date.now();
+
+ clonedContext.messages.unshift({
+ content,
+ createdAt: now,
+ id: `agent-doc-before-system-${now}`,
+ role: 'system' as const,
+ updatedAt: now,
+ } as any);
+
+ log('Prepended %d agent documents before system message', docs.length);
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/ContextInjector.ts b/packages/context-engine/src/providers/AgentDocumentInjector/ContextInjector.ts
new file mode 100644
index 00000000000..9d1a84dc7a1
--- /dev/null
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/ContextInjector.ts
@@ -0,0 +1,45 @@
+import debug from 'debug';
+
+import { BaseFirstUserContentProvider } from '../../base/BaseFirstUserContentProvider';
+import type { PipelineContext, ProcessorOptions } from '../../types';
+import type { AgentContextDocument, AgentDocumentFilterContext } from './shared';
+import { combineDocuments, getDocumentsForPositions } from './shared';
+
+const log = debug('context-engine:provider:AgentDocumentContextInjector');
+
+export interface AgentDocumentContextInjectorConfig extends AgentDocumentFilterContext {
+ documents?: AgentContextDocument[];
+ enabled?: boolean;
+}
+
+/**
+ * Injects agent documents before the first user message.
+ * Handles `before-first-user` position.
+ *
+ * Placed in Phase 3 (Context Injection).
+ */
+export class AgentDocumentContextInjector extends BaseFirstUserContentProvider {
+ readonly name = 'AgentDocumentContextInjector';
+
+ constructor(
+ private config: AgentDocumentContextInjectorConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected buildContent(_context: PipelineContext): string | null {
+ if (this.config.enabled === false) return null;
+
+ const docs = getDocumentsForPositions(
+ this.config.documents || [],
+ ['before-first-user'],
+ this.config,
+ );
+
+ if (docs.length === 0) return null;
+
+ log('Injecting %d agent documents before first user message', docs.length);
+ return combineDocuments(docs, this.config);
+ }
+}
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/MessageInjector.ts b/packages/context-engine/src/providers/AgentDocumentInjector/MessageInjector.ts
new file mode 100644
index 00000000000..20f3193e3e7
--- /dev/null
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/MessageInjector.ts
@@ -0,0 +1,79 @@
+import debug from 'debug';
+
+import { BaseProcessor } from '../../base/BaseProcessor';
+import type { PipelineContext, ProcessorOptions } from '../../types';
+import type { AgentContextDocument, AgentDocumentFilterContext } from './shared';
+import { combineDocuments, getDocumentsForPositions } from './shared';
+
+const log = debug('context-engine:provider:AgentDocumentMessageInjector');
+
+export interface AgentDocumentMessageInjectorConfig extends AgentDocumentFilterContext {
+ documents?: AgentContextDocument[];
+ enabled?: boolean;
+}
+
+/**
+ * Injects agent documents at specific message positions.
+ * Handles `after-first-user` and `context-end` positions.
+ *
+ * Placed in Phase 4 (User Message Augmentation).
+ */
+export class AgentDocumentMessageInjector extends BaseProcessor {
+ readonly name = 'AgentDocumentMessageInjector';
+
+ constructor(
+ private config: AgentDocumentMessageInjectorConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ if (this.config.enabled === false) return this.markAsExecuted(context);
+
+ const allDocs = this.config.documents || [];
+ if (allDocs.length === 0) return this.markAsExecuted(context);
+
+ const afterFirstUserDocs = getDocumentsForPositions(allDocs, ['after-first-user'], this.config);
+ const contextEndDocs = getDocumentsForPositions(allDocs, ['context-end'], this.config);
+
+ if (afterFirstUserDocs.length === 0 && contextEndDocs.length === 0) {
+ return this.markAsExecuted(context);
+ }
+
+ const clonedContext = this.cloneContext(context);
+
+ // Inject after first user message
+ if (afterFirstUserDocs.length > 0) {
+ const firstUserIndex = clonedContext.messages.findIndex((m) => m.role === 'user');
+ if (firstUserIndex !== -1) {
+ const content = combineDocuments(afterFirstUserDocs, this.config);
+ const now = Date.now();
+ clonedContext.messages.splice(firstUserIndex + 1, 0, {
+ content,
+ createdAt: now,
+ id: `agent-doc-after-user-${now}`,
+ role: 'system' as const,
+ updatedAt: now,
+ } as any);
+ log('Injected %d agent documents after first user message', afterFirstUserDocs.length);
+ }
+ }
+
+ // Inject at context end
+ if (contextEndDocs.length > 0) {
+ const content = combineDocuments(contextEndDocs, this.config);
+ const now = Date.now();
+ clonedContext.messages.push({
+ content,
+ createdAt: now,
+ id: `agent-doc-context-end-${now}`,
+ role: 'system' as const,
+ updatedAt: now,
+ } as any);
+ log('Injected %d agent documents at context end', contextEndDocs.length);
+ }
+
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/SystemAppendInjector.ts b/packages/context-engine/src/providers/AgentDocumentInjector/SystemAppendInjector.ts
new file mode 100644
index 00000000000..1970bd52f85
--- /dev/null
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/SystemAppendInjector.ts
@@ -0,0 +1,45 @@
+import debug from 'debug';
+
+import { BaseSystemRoleProvider } from '../../base/BaseSystemRoleProvider';
+import type { PipelineContext, ProcessorOptions } from '../../types';
+import type { AgentContextDocument, AgentDocumentFilterContext } from './shared';
+import { combineDocuments, getDocumentsForPositions } from './shared';
+
+const log = debug('context-engine:provider:AgentDocumentSystemAppendInjector');
+
+export interface AgentDocumentSystemAppendInjectorConfig extends AgentDocumentFilterContext {
+ documents?: AgentContextDocument[];
+ enabled?: boolean;
+}
+
+/**
+ * Appends agent documents to the end of the system message.
+ * Handles `system-append` position.
+ *
+ * Placed at the end of Phase 2, after all other system role providers.
+ */
+export class AgentDocumentSystemAppendInjector extends BaseSystemRoleProvider {
+ readonly name = 'AgentDocumentSystemAppendInjector';
+
+ constructor(
+ private config: AgentDocumentSystemAppendInjectorConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected buildSystemRoleContent(_context: PipelineContext): string | null {
+ if (this.config.enabled === false) return null;
+
+ const docs = getDocumentsForPositions(
+ this.config.documents || [],
+ ['system-append'],
+ this.config,
+ );
+
+ if (docs.length === 0) return null;
+
+ log('Appending %d agent documents to system message', docs.length);
+ return combineDocuments(docs, this.config);
+ }
+}
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/SystemReplaceInjector.ts b/packages/context-engine/src/providers/AgentDocumentInjector/SystemReplaceInjector.ts
new file mode 100644
index 00000000000..c0056fb3c81
--- /dev/null
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/SystemReplaceInjector.ts
@@ -0,0 +1,64 @@
+import debug from 'debug';
+
+import { BaseProcessor } from '../../base/BaseProcessor';
+import type { PipelineContext, ProcessorOptions } from '../../types';
+import type { AgentContextDocument, AgentDocumentFilterContext } from './shared';
+import { combineDocuments, getDocumentsForPositions } from './shared';
+
+const log = debug('context-engine:provider:AgentDocumentSystemReplaceInjector');
+
+export interface AgentDocumentSystemReplaceInjectorConfig extends AgentDocumentFilterContext {
+ documents?: AgentContextDocument[];
+ enabled?: boolean;
+}
+
+/**
+ * Replaces the entire system message with agent document content.
+ * Handles `system-replace` position.
+ *
+ * Placed at the end of Phase 2, after SystemAppendInjector.
+ * When triggered, discards any previously assembled system message.
+ */
+export class AgentDocumentSystemReplaceInjector extends BaseProcessor {
+ readonly name = 'AgentDocumentSystemReplaceInjector';
+
+ constructor(
+ private config: AgentDocumentSystemReplaceInjectorConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ if (this.config.enabled === false) return this.markAsExecuted(context);
+
+ const docs = getDocumentsForPositions(
+ this.config.documents || [],
+ ['system-replace'],
+ this.config,
+ );
+
+ if (docs.length === 0) return this.markAsExecuted(context);
+
+ const clonedContext = this.cloneContext(context);
+ const content = combineDocuments(docs, this.config);
+ const now = Date.now();
+ const message = {
+ content,
+ createdAt: now,
+ id: `agent-doc-system-replace-${now}`,
+ role: 'system' as const,
+ updatedAt: now,
+ };
+
+ const systemIndex = clonedContext.messages.findIndex((m) => m.role === 'system');
+ if (systemIndex >= 0) {
+ clonedContext.messages[systemIndex] = message as any;
+ } else {
+ clonedContext.messages.unshift(message as any);
+ }
+
+ log('Replaced system message with %d agent documents', docs.length);
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/index.ts b/packages/context-engine/src/providers/AgentDocumentInjector/index.ts
new file mode 100644
index 00000000000..30c4f2fc55b
--- /dev/null
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/index.ts
@@ -0,0 +1,24 @@
+export type { AgentDocumentBeforeSystemInjectorConfig } from './BeforeSystemInjector';
+export { AgentDocumentBeforeSystemInjector } from './BeforeSystemInjector';
+export type { AgentDocumentContextInjectorConfig } from './ContextInjector';
+export { AgentDocumentContextInjector } from './ContextInjector';
+export type { AgentDocumentMessageInjectorConfig } from './MessageInjector';
+export { AgentDocumentMessageInjector } from './MessageInjector';
+export {
+ AGENT_DOCUMENT_INJECTION_POSITIONS,
+ type AgentContextDocument,
+ type AgentDocumentFilterContext,
+ type AgentDocumentInjectionPosition,
+ type AgentDocumentLoadFormat,
+ type AgentDocumentLoadRule,
+ type AgentDocumentLoadRules,
+ combineDocuments,
+ filterDocumentsByRules,
+ formatDocument,
+ getDocumentsForPositions,
+ sortByPriority,
+} from './shared';
+export type { AgentDocumentSystemAppendInjectorConfig } from './SystemAppendInjector';
+export { AgentDocumentSystemAppendInjector } from './SystemAppendInjector';
+export type { AgentDocumentSystemReplaceInjectorConfig } from './SystemReplaceInjector';
+export { AgentDocumentSystemReplaceInjector } from './SystemReplaceInjector';
diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts b/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts
new file mode 100644
index 00000000000..a2590111b99
--- /dev/null
+++ b/packages/context-engine/src/providers/AgentDocumentInjector/shared.ts
@@ -0,0 +1,137 @@
+import type {
+ AgentDocumentLoadRule,
+ AgentDocumentLoadRules,
+} from '../../../../database/src/models/agentDocuments';
+import { matchesLoadRules } from '../../../../database/src/models/agentDocuments';
+
+export type { AgentDocumentLoadRule, AgentDocumentLoadRules };
+
+export const AGENT_DOCUMENT_INJECTION_POSITIONS = [
+ 'after-first-user',
+ 'before-first-user',
+ 'before-system',
+ 'context-end',
+ 'manual',
+ 'on-demand',
+ 'system-append',
+ 'system-replace',
+] as const;
+
+export type AgentDocumentInjectionPosition = (typeof AGENT_DOCUMENT_INJECTION_POSITIONS)[number];
+
+export type AgentDocumentLoadFormat = 'file' | 'raw';
+
+export interface AgentContextDocument {
+ content?: string;
+ filename: string;
+ id?: string;
+ loadPosition?: AgentDocumentInjectionPosition;
+ loadRules?: AgentDocumentLoadRules;
+ policyId?: string | null;
+ policyLoadFormat?: AgentDocumentLoadFormat;
+ title?: string;
+}
+
+export interface AgentDocumentFilterContext {
+ currentTime?: Date;
+ currentUserMessage?: string;
+ truncateContent?: (content: string, maxTokens: number) => string;
+}
+
+/**
+ * Filter documents by load rules (always, by-keywords, by-regexp, by-time-range)
+ */
+export function filterDocumentsByRules(
+ docs: AgentContextDocument[],
+ context: AgentDocumentFilterContext,
+): AgentContextDocument[] {
+ return docs.filter((doc) =>
+ matchesLoadRules(doc, {
+ currentTime: context.currentTime,
+ currentUserMessage: context.currentUserMessage,
+ }),
+ );
+}
+
+/**
+ * Sort documents by priority (lower number = higher priority)
+ */
+export function sortByPriority(docs: AgentContextDocument[]): AgentContextDocument[] {
+ return [...docs].sort((a, b) => {
+ const aPriority = a.loadRules?.priority ?? 999;
+ const bPriority = b.loadRules?.priority ?? 999;
+ return aPriority - bPriority;
+ });
+}
+
+/**
+ * Get documents for specific positions, filtered and sorted
+ */
+export function getDocumentsForPositions(
+ allDocuments: AgentContextDocument[],
+ positions: AgentDocumentInjectionPosition[],
+ context: AgentDocumentFilterContext,
+): AgentContextDocument[] {
+ const positionSet = new Set(positions);
+ const docs = allDocuments.filter((doc) =>
+ positionSet.has(doc.loadPosition || 'before-first-user'),
+ );
+ const filtered = filterDocumentsByRules(docs, context);
+ return sortByPriority(filtered);
+}
+
+/**
+ * Format a single document for injection
+ */
+export function formatDocument(
+ doc: AgentContextDocument,
+ context: AgentDocumentFilterContext,
+): string {
+ const maxTokens = doc.loadRules?.maxTokens;
+ let content = doc.content || '';
+ if (maxTokens && maxTokens > 0) {
+ content = context.truncateContent
+ ? context.truncateContent(content, maxTokens)
+ : approximateTokenTruncate(content, maxTokens);
+ }
+
+ if (doc.policyLoadFormat === 'file') {
+ const attributes = formatDocumentAttributes(doc);
+ return `<agent_document${attributes}>\n${content}\n</agent_document>`;
+ }
+
+ return content;
+}
+
+/**
+ * Combine multiple documents into a single string
+ */
+export function combineDocuments(
+ docs: AgentContextDocument[],
+ context: AgentDocumentFilterContext,
+): string {
+ return docs.map((doc) => formatDocument(doc, context)).join('\n\n');
+}
+
+function approximateTokenTruncate(content: string, maxTokens: number): string {
+ if (!Number.isFinite(maxTokens) || maxTokens <= 0) return content;
+ const parts = content.split(/\s+/);
+ if (parts.length <= maxTokens) return content;
+ return `${parts.slice(0, maxTokens).join(' ')}\n...[truncated]`;
+}
+
+function escapeAttribute(value: string): string {
+ return value
+ .replaceAll('&', '&amp;')
+ .replaceAll('"', '&quot;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;');
+}
+
+function formatDocumentAttributes(doc: AgentContextDocument): string {
+ const attrs: string[] = [];
+ if (doc.id) attrs.push(`id="${escapeAttribute(doc.id)}"`);
+ if (doc.filename) attrs.push(`filename="${escapeAttribute(doc.filename)}"`);
+ if (doc.title) attrs.push(`title="${escapeAttribute(doc.title)}"`);
+ return attrs.length > 0 ? ` ${attrs.join(' ')}` : '';
+}
diff --git a/packages/context-engine/src/providers/BotPlatformContextInjector.ts b/packages/context-engine/src/providers/BotPlatformContextInjector.ts
index d39b8562e16..e45fa351f08 100644
--- a/packages/context-engine/src/providers/BotPlatformContextInjector.ts
+++ b/packages/context-engine/src/providers/BotPlatformContextInjector.ts
@@ -2,7 +2,7 @@ import type { BotPlatformInfo } from '@lobechat/prompts';
import { formatBotPlatformContext } from '@lobechat/prompts';
import debug from 'debug';
-import { BaseProvider } from '../base/BaseProvider';
+import { BaseSystemRoleProvider } from '../base/BaseSystemRoleProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
const log = debug('context-engine:provider:BotPlatformContextInjector');
@@ -26,7 +26,7 @@ export interface BotPlatformContextInjectorConfig {
*
* Should run after SystemRoleInjector in the pipeline.
*/
-export class BotPlatformContextInjector extends BaseProvider {
+export class BotPlatformContextInjector extends BaseSystemRoleProvider {
readonly name = 'BotPlatformContextInjector';
constructor(
@@ -36,41 +36,13 @@ export class BotPlatformContextInjector extends BaseProvider {
super(options);
}
- protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ protected buildSystemRoleContent(_context: PipelineContext): string | null {
if (!this.config.enabled || !this.config.context) {
log('Disabled or no context, skipping injection');
- return this.markAsExecuted(context);
+ return null;
}
const info: BotPlatformInfo = this.config.context;
- const prompt = formatBotPlatformContext(info);
-
- if (!prompt) {
- log('Platform supports markdown, no injection needed');
- return this.markAsExecuted(context);
- }
-
- const clonedContext = this.cloneContext(context);
- const systemMsgIndex = clonedContext.messages.findIndex((m) => m.role === 'system');
-
- if (systemMsgIndex >= 0) {
- const original = clonedContext.messages[systemMsgIndex];
- clonedContext.messages[systemMsgIndex] = {
- ...original,
- content: [original.content, prompt].filter(Boolean).join('\n\n'),
- };
- log('Appended bot platform context to existing system message');
- } else {
- clonedContext.messages.unshift({
- content: prompt,
- createdAt: Date.now(),
- id: `bot-platform-context-${Date.now()}`,
- role: 'system' as const,
- updatedAt: Date.now(),
- });
- log('Created new system message with bot platform context');
- }
-
- return this.markAsExecuted(clonedContext);
+ return formatBotPlatformContext(info) || null;
}
}
diff --git a/packages/context-engine/src/providers/EvalContextSystemInjector.ts b/packages/context-engine/src/providers/EvalContextSystemInjector.ts
index 9fd7e405b76..5bc0b997acc 100644
--- a/packages/context-engine/src/providers/EvalContextSystemInjector.ts
+++ b/packages/context-engine/src/providers/EvalContextSystemInjector.ts
@@ -1,6 +1,6 @@
import debug from 'debug';
-import { BaseProvider } from '../base/BaseProvider';
+import { BaseSystemRoleProvider } from '../base/BaseSystemRoleProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
declare module '../types' {
@@ -22,11 +22,10 @@ export interface EvalContextSystemInjectorConfig {
/**
* Eval Context Injector
- * Appends eval environment prompt to the existing system message,
- * or creates a new system message if none exists.
+ * Appends eval environment prompt to the system message.
* Should run after SystemRoleInjector in the pipeline.
*/
-export class EvalContextSystemInjector extends BaseProvider {
+export class EvalContextSystemInjector extends BaseSystemRoleProvider {
readonly name = 'EvalContextSystemInjector';
constructor(
@@ -36,35 +35,16 @@ export class EvalContextSystemInjector extends BaseProvider {
super(options);
}
- protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ protected buildSystemRoleContent(_context: PipelineContext): string | null {
if (!this.config.enabled || !this.config.evalContext?.envPrompt) {
log('Disabled or no envPrompt configured, skipping injection');
- return this.markAsExecuted(context);
+ return null;
}
- const clonedContext = this.cloneContext(context);
- const systemMsgIndex = clonedContext.messages.findIndex((m) => m.role === 'system');
-
- if (systemMsgIndex >= 0) {
- const original = clonedContext.messages[systemMsgIndex];
- clonedContext.messages[systemMsgIndex] = {
- ...original,
- content: [original.content, this.config.evalContext.envPrompt].filter(Boolean).join('\n\n'),
- };
- log('Appended envPrompt to existing system message');
- } else {
- clonedContext.messages.unshift({
- content: this.config.evalContext.envPrompt,
- createdAt: Date.now(),
- id: `eval-context-${Date.now()}`,
- role: 'system' as const,
- updatedAt: Date.now(),
- });
- log('Created new system message with envPrompt');
- }
-
- clonedContext.metadata.evalContextInjected = true;
+ return this.config.evalContext.envPrompt;
+ }
- return this.markAsExecuted(clonedContext);
+ protected onInjected(context: PipelineContext): void {
+ context.metadata.evalContextInjected = true;
}
}
diff --git a/packages/context-engine/src/providers/HistorySummary.ts b/packages/context-engine/src/providers/HistorySummary.ts
index 5f10761c9eb..ffa54f726f8 100644
--- a/packages/context-engine/src/providers/HistorySummary.ts
+++ b/packages/context-engine/src/providers/HistorySummary.ts
@@ -1,6 +1,6 @@
import debug from 'debug';
-import { BaseProvider } from '../base/BaseProvider';
+import { BaseSystemRoleProvider } from '../base/BaseSystemRoleProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
declare module '../types' {
@@ -37,7 +37,7 @@ const defaultHistorySummaryFormatter = (historySummary: string): string => `<cha
* History Summary Provider
* Responsible for injecting history conversation summary into system messages
*/
-export class HistorySummaryProvider extends BaseProvider {
+export class HistorySummaryProvider extends BaseSystemRoleProvider {
readonly name = 'HistorySummaryProvider';
constructor(
@@ -47,66 +47,21 @@ export class HistorySummaryProvider extends BaseProvider {
super(options);
}
- protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
- const clonedContext = this.cloneContext(context);
-
- // Check if history summary exists
+ protected buildSystemRoleContent(_context: PipelineContext): string | null {
if (!this.config.historySummary) {
log('No history summary content, skipping processing');
- return this.markAsExecuted(clonedContext);
+ return null;
}
- // Format history summary
- const formattedSummary = this.formatHistorySummary(this.config.historySummary);
-
- // Inject history summary
- this.injectHistorySummary(clonedContext, formattedSummary);
-
- // Update metadata
- clonedContext.metadata.historySummary = {
- formattedLength: formattedSummary.length,
- injected: true,
- originalLength: this.config.historySummary.length,
- };
-
- log(
- `History summary injection completed, original length: ${this.config.historySummary.length}, formatted length: ${formattedSummary.length}`,
- );
- return this.markAsExecuted(clonedContext);
- }
-
- /**
- * Format history summary
- */
- private formatHistorySummary(historySummary: string): string {
const formatter = this.config.formatHistorySummary || defaultHistorySummaryFormatter;
- return formatter(historySummary);
+ return formatter(this.config.historySummary);
}
- /**
- * Inject history summary to system message
- */
- private injectHistorySummary(context: PipelineContext, formattedSummary: string): void {
- const existingSystemMessage = context.messages.find((msg) => msg.role === 'system');
-
- if (existingSystemMessage) {
- // Merge to existing system message
- existingSystemMessage.content = [existingSystemMessage.content, formattedSummary]
- .filter(Boolean)
- .join('\n\n');
-
- log(
- `History summary merged to existing system message, final length: ${existingSystemMessage.content.length}`,
- );
- } else {
- // Create new system message
- const systemMessage = {
- content: formattedSummary,
- role: 'system' as const,
- };
-
- context.messages.unshift(systemMessage as any);
- log(`New history summary system message created, content length: ${formattedSummary.length}`);
- }
+ protected onInjected(context: PipelineContext, content: string): void {
+ context.metadata.historySummary = {
+ formattedLength: content.length,
+ injected: true,
+ originalLength: this.config.historySummary!.length,
+ };
}
}
diff --git a/packages/context-engine/src/providers/SelectedSkillInjector.ts b/packages/context-engine/src/providers/SelectedSkillInjector.ts
index 19b760f69c5..047f5453629 100644
--- a/packages/context-engine/src/providers/SelectedSkillInjector.ts
+++ b/packages/context-engine/src/providers/SelectedSkillInjector.ts
@@ -17,6 +17,7 @@ declare module '../types' {
const log = debug('context-engine:provider:SelectedSkillInjector');
export interface SelectedSkillInjectorConfig {
+ enabled?: boolean;
selectedSkills?: RuntimeSelectedSkill[];
}
@@ -51,6 +52,8 @@ export class SelectedSkillInjector extends BaseLastUserContentProvider {
}
protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ if (this.config.enabled === false) return this.markAsExecuted(context);
+
const clonedContext = this.cloneContext(context);
const selectedSkills = this.config.selectedSkills ?? [];
diff --git a/packages/context-engine/src/providers/SkillContextProvider.ts b/packages/context-engine/src/providers/SkillContextProvider.ts
index 616352b5996..d6c774329d1 100644
--- a/packages/context-engine/src/providers/SkillContextProvider.ts
+++ b/packages/context-engine/src/providers/SkillContextProvider.ts
@@ -1,7 +1,7 @@
import { type SkillItem, skillsPrompts } from '@lobechat/prompts';
import debug from 'debug';
-import { BaseProvider } from '../base/BaseProvider';
+import { BaseSystemRoleProvider } from '../base/BaseSystemRoleProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
declare module '../types' {
@@ -40,7 +40,8 @@ export interface SkillMeta {
* Skill Context Provider Configuration
*/
export interface SkillContextProviderConfig {
- enabledSkills: SkillMeta[];
+ enabled?: boolean;
+ enabledSkills?: SkillMeta[];
}
/**
@@ -48,7 +49,7 @@ export interface SkillContextProviderConfig {
* Injects lightweight skill metadata into the system prompt so the LLM knows
* which skills are available and can invoke them via `runSkill`.
*/
-export class SkillContextProvider extends BaseProvider {
+export class SkillContextProvider extends BaseSystemRoleProvider {
readonly name = 'SkillContextProvider';
constructor(
@@ -58,14 +59,14 @@ export class SkillContextProvider extends BaseProvider {
super(options);
}
- protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
- const clonedContext = this.cloneContext(context);
+ protected buildSystemRoleContent(_context: PipelineContext): string | null {
+ if (this.config.enabled === false) return null;
const { enabledSkills } = this.config;
if (!enabledSkills || enabledSkills.length === 0) {
log('No enabled skills, skipping injection');
- return this.markAsExecuted(clonedContext);
+ return null;
}
// Separate activated skills (inject content directly) from available skills (list only)
@@ -97,45 +98,21 @@ export class SkillContextProvider extends BaseProvider {
if (contentParts.length === 0) {
log('No skill content generated, skipping injection');
- return this.markAsExecuted(clonedContext);
+ return null;
}
- this.injectSkillContext(clonedContext, contentParts.join('\n\n'));
-
- clonedContext.metadata.skillContext = {
- injected: true,
- skillsCount: enabledSkills.length,
- };
-
log(
- 'Skill context injected: %d activated, %d available',
+ 'Skill context prepared: %d activated, %d available',
activatedSkills.length,
availableSkills.length,
);
- return this.markAsExecuted(clonedContext);
+ return contentParts.join('\n\n');
}
- /**
- * Inject skill context into the system message
- */
- private injectSkillContext(context: PipelineContext, skillContent: string): void {
- const existingSystemMessage = context.messages.find((msg) => msg.role === 'system');
-
- if (existingSystemMessage) {
- existingSystemMessage.content = [existingSystemMessage.content, skillContent]
- .filter(Boolean)
- .join('\n\n');
-
- log(
- `Skill context merged to existing system message, final length: ${existingSystemMessage.content.length}`,
- );
- } else {
- context.messages.unshift({
- content: skillContent,
- id: `skill-context-${Date.now()}`,
- role: 'system' as const,
- } as any);
- log(`New skill system message created, content length: ${skillContent.length}`);
- }
+ protected onInjected(context: PipelineContext): void {
+ context.metadata.skillContext = {
+ injected: true,
+ skillsCount: this.config.enabledSkills?.length ?? 0,
+ };
}
}
diff --git a/packages/context-engine/src/providers/SystemDateProvider.ts b/packages/context-engine/src/providers/SystemDateProvider.ts
index 59dce9eadea..50d0ffd8211 100644
--- a/packages/context-engine/src/providers/SystemDateProvider.ts
+++ b/packages/context-engine/src/providers/SystemDateProvider.ts
@@ -1,6 +1,6 @@
import debug from 'debug';
-import { BaseProvider } from '../base/BaseProvider';
+import { BaseSystemRoleProvider } from '../base/BaseSystemRoleProvider';
import type { PipelineContext, ProcessorOptions } from '../types';
declare module '../types' {
@@ -16,7 +16,7 @@ export interface SystemDateProviderConfig {
timezone?: string | null;
}
-export class SystemDateProvider extends BaseProvider {
+export class SystemDateProvider extends BaseSystemRoleProvider {
readonly name = 'SystemDateProvider';
constructor(
@@ -26,12 +26,10 @@ export class SystemDateProvider extends BaseProvider {
super(options);
}
- protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
- const clonedContext = this.cloneContext(context);
-
+ protected buildSystemRoleContent(_context: PipelineContext): string | null {
if (this.config.enabled === false) {
log('System date injection disabled, skipping');
- return this.markAsExecuted(clonedContext);
+ return null;
}
const tz = this.config.timezone || 'UTC';
@@ -42,28 +40,11 @@ export class SystemDateProvider extends BaseProvider {
const day = today.toLocaleString('en-US', { day: '2-digit', timeZone: tz });
const dateStr = `${year}-${month}-${day}`;
- const dateContent = `Current date: ${dateStr} (${tz})`;
-
- const existingSystemMessage = clonedContext.messages.find((msg) => msg.role === 'system');
-
- if (existingSystemMessage) {
- existingSystemMessage.content = [existingSystemMessage.content, dateContent]
- .filter(Boolean)
- .join('\n\n');
- } else {
- clonedContext.messages.unshift({
- content: dateContent,
- createdAt: Date.now(),
- id: `system-date-${Date.now()}`,
- role: 'system' as const,
- updatedAt: Date.now(),
- } as any);
- }
-
- clonedContext.metadata.systemDateInjected = true;
-
log('System date injected: %s', dateStr);
+ return `Current date: ${dateStr} (${tz})`;
+ }
- return this.markAsExecuted(clonedContext);
+ protected onInjected(context: PipelineContext): void {
+ context.metadata.systemDateInjected = true;
}
}
diff --git a/packages/context-engine/src/providers/ToolDiscoveryProvider.ts b/packages/context-engine/src/providers/ToolDiscoveryProvider.ts
index 49f43c7d2d4..166f4cfa9d6 100644
--- a/packages/context-engine/src/providers/ToolDiscoveryProvider.ts
+++ b/packages/context-engine/src/providers/ToolDiscoveryProvider.ts
@@ -22,7 +22,8 @@ export interface ToolDiscoveryMeta {
}
export interface ToolDiscoveryProviderConfig {
- availableTools: ToolDiscoveryMeta[];
+ availableTools?: ToolDiscoveryMeta[];
+ enabled?: boolean;
}
export class ToolDiscoveryProvider extends BaseFirstUserContentProvider {
@@ -36,6 +37,8 @@ export class ToolDiscoveryProvider extends BaseFirstUserContentProvider {
}
protected buildContent(_context: PipelineContext): string | null {
+ if (this.config.enabled === false) return null;
+
const { availableTools } = this.config;
if (!availableTools || availableTools.length === 0) {
diff --git a/packages/context-engine/src/providers/ToolSystemRole.ts b/packages/context-engine/src/providers/ToolSystemRole.ts
index 43414d709fc..33bea181403 100644
--- a/packages/context-engine/src/providers/ToolSystemRole.ts
+++ b/packages/context-engine/src/providers/ToolSystemRole.ts
@@ -2,7 +2,7 @@ import type { API, Tool } from '@lobechat/prompts';
import { pluginPrompts } from '@lobechat/prompts';
import debug from 'debug';
-import { BaseProvider } from '../base/BaseProvider';
+import { BaseSystemRoleProvider } from '../base/BaseSystemRoleProvider';
import { ToolNameResolver } from '../engine/tools';
import type { LobeToolManifest } from '../engine/tools/types';
import type { PipelineContext, ProcessorOptions } from '../types';
@@ -24,10 +24,11 @@ const log = debug('context-engine:provider:ToolSystemRoleProvider');
* Tool System Role Configuration
*/
export interface ToolSystemRoleConfig {
+ enabled?: boolean;
/** Function to check if function calling is supported */
isCanUseFC: (model: string, provider: string) => boolean | undefined;
/** Tool manifests with systemRole and API definitions */
- manifests: LobeToolManifest[];
+ manifests?: LobeToolManifest[];
/** Model name */
model: string;
/** Provider name */
@@ -38,7 +39,7 @@ export interface ToolSystemRoleConfig {
* Tool System Role Provider
* Responsible for injecting tool-related system roles for models that support tool calling
*/
-export class ToolSystemRoleProvider extends BaseProvider {
+export class ToolSystemRoleProvider extends BaseSystemRoleProvider {
readonly name = 'ToolSystemRoleProvider';
private toolNameResolver: ToolNameResolver;
@@ -51,30 +52,27 @@ export class ToolSystemRoleProvider extends BaseProvider {
this.toolNameResolver = new ToolNameResolver();
}
- protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
- const clonedContext = this.cloneContext(context);
+ protected buildSystemRoleContent(_context: PipelineContext): string | null {
+ if (this.config.enabled === false) return null;
- // Check tool-related conditions
const toolSystemRole = this.getToolSystemRole();
if (!toolSystemRole) {
log('No need to inject tool system role, skipping processing');
- return this.markAsExecuted(clonedContext);
+ return null;
}
- // Inject tool system role
- this.injectToolSystemRole(clonedContext, toolSystemRole);
+ log(`Tool system role injection completed, tools count: ${this.config.manifests?.length ?? 0}`);
+ return toolSystemRole;
+ }
- // Update metadata
- clonedContext.metadata.toolSystemRole = {
- contentLength: toolSystemRole.length,
+ protected onInjected(context: PipelineContext, content: string): void {
+ context.metadata.toolSystemRole = {
+ contentLength: content.length,
injected: true,
supportsFunctionCall: !!this.config.isCanUseFC(this.config.model, this.config.provider),
- toolsCount: this.config.manifests.length,
+ toolsCount: this.config.manifests?.length ?? 0,
};
-
- log(`Tool system role injection completed, tools count: ${this.config.manifests.length}`);
- return this.markAsExecuted(clonedContext);
}
/**
@@ -83,21 +81,17 @@ export class ToolSystemRoleProvider extends BaseProvider {
private getToolSystemRole(): string | undefined {
const { manifests, model, provider } = this.config;
- // Check if manifests are available
if (!manifests || manifests.length === 0) {
log('No available tool manifests');
return undefined;
}
- // Check if function calling is supported
const hasFC = this.config.isCanUseFC(model, provider);
if (!hasFC) {
log(`Model ${model} (${provider}) does not support function calling`);
return undefined;
}
- // Transform manifests to Tool[] format for pluginPrompts
- // Only include manifests that have APIs or systemRole
const tools: Tool[] = manifests
.filter((manifest) => manifest.api.length > 0 || manifest.systemRole)
.map((manifest) => ({
@@ -113,13 +107,11 @@ export class ToolSystemRoleProvider extends BaseProvider {
systemRole: manifest.systemRole,
}));
- // Skip if no meaningful tools after filtering
if (tools.length === 0) {
log('No meaningful tools to inject (all manifests have empty APIs and no systemRole)');
return undefined;
}
- // Generate tool system role using pluginPrompts
const toolSystemRole = pluginPrompts({ tools });
if (!toolSystemRole) {
@@ -130,29 +122,4 @@ export class ToolSystemRoleProvider extends BaseProvider {
log(`Generated tool system role for ${manifests.length} tools`);
return toolSystemRole;
}
-
- /**
- * Inject tool system role
- */
- private injectToolSystemRole(context: PipelineContext, toolSystemRole: string): void {
- const existingSystemMessage = context.messages.find((msg) => msg.role === 'system');
-
- if (existingSystemMessage) {
- // Merge to existing system message
- existingSystemMessage.content = [existingSystemMessage.content, toolSystemRole]
- .filter(Boolean)
- .join('\n\n');
-
- log(
- `Tool system role merged to existing system message, final length: ${existingSystemMessage.content.length}`,
- );
- } else {
- context.messages.unshift({
- content: toolSystemRole,
- id: `tool-system-role-${Date.now()}`,
- role: 'system' as const,
- } as any);
- log(`New tool system message created, content length: ${toolSystemRole.length}`);
- }
- }
}
diff --git a/packages/context-engine/src/providers/UserMemoryInjector.ts b/packages/context-engine/src/providers/UserMemoryInjector.ts
index 540c976bb62..8f70cc0afbf 100644
--- a/packages/context-engine/src/providers/UserMemoryInjector.ts
+++ b/packages/context-engine/src/providers/UserMemoryInjector.ts
@@ -14,6 +14,7 @@ declare module '../types' {
const log = debug('context-engine:provider:UserMemoryInjector');
export interface UserMemoryInjectorConfig {
+ enabled?: boolean;
/** User memories data */
memories?: UserMemoryData;
}
@@ -38,6 +39,8 @@ export class UserMemoryInjector extends BaseFirstUserContentProvider {
}
protected buildContent(_context: PipelineContext): string | null {
+ if (this.config.enabled === false) return null;
+
const { memories } = this.config;
if (!memories) return null;
diff --git a/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts b/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts
index e508b57040c..ba4ffcda189 100644
--- a/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts
+++ b/packages/context-engine/src/providers/__tests__/AgentDocumentInjector.test.ts
@@ -1,7 +1,13 @@
import { describe, expect, it } from 'vitest';
import type { PipelineContext } from '../../types';
-import { AgentDocumentInjector } from '../AgentDocumentInjector';
+import {
+ AgentDocumentBeforeSystemInjector,
+ AgentDocumentContextInjector,
+ AgentDocumentMessageInjector,
+ AgentDocumentSystemAppendInjector,
+ AgentDocumentSystemReplaceInjector,
+} from '../AgentDocumentInjector';
describe('AgentDocumentInjector', () => {
const createContext = (messages: any[] = []): PipelineContext => ({
@@ -18,172 +24,281 @@ describe('AgentDocumentInjector', () => {
},
});
- it('should inject generic documents by load position and set metadata', async () => {
- const provider = new AgentDocumentInjector({
- documents: [
- {
- content: 'Core runtime guardrails',
- filename: 'guardrails.md',
- loadPosition: 'before-first-user',
- loadRules: { priority: 1, rule: 'always' },
- policyId: 'claw',
- },
- {
- content: 'Session summary memo',
- filename: 'summary.md',
- loadPosition: 'context-end',
- loadRules: { rule: 'always' },
- policyId: 'custom',
- },
- ],
+ describe('AgentDocumentContextInjector (before-first-user)', () => {
+ it('should inject documents before first user message', async () => {
+ const provider = new AgentDocumentContextInjector({
+ documents: [
+ {
+ content: 'Core runtime guardrails',
+ filename: 'guardrails.md',
+ loadPosition: 'before-first-user',
+ loadRules: { priority: 1, rule: 'always' },
+ policyId: 'claw',
+ },
+ ],
+ });
+
+ const context = createContext([
+ { content: 'System prompt', id: 'sys-1', role: 'system' },
+ { content: 'Hello', id: 'user-1', role: 'user' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[1].content).toContain('Core runtime guardrails');
});
- const context = createContext([
- { content: 'System prompt', id: 'sys-1', role: 'system' },
- { content: 'Hello', id: 'user-1', role: 'user' },
- ]);
-
- const result = await provider.process(context);
-
- expect(result.messages).toHaveLength(4);
- expect(result.messages[1].role).toBe('system');
- expect(result.messages[1].content).toContain('Core runtime guardrails');
- expect(result.messages[3].role).toBe('system');
- expect(result.messages[3].content).toContain('Session summary memo');
- expect(result.metadata.agentDocumentsInjected).toBe(true);
- expect(result.metadata.agentDocumentsCount).toBe(2);
- expect(result.metadata.agentDocuments).toMatchObject({
- policyIds: ['claw', 'custom'],
+ it('should not inject document when by-keywords rule does not match', async () => {
+ const provider = new AgentDocumentContextInjector({
+ currentUserMessage: 'Please focus on tomorrow action items',
+ documents: [
+ {
+ content: 'Only show for release keyword',
+ filename: 'todo.md',
+ loadRules: { keywords: ['release'], rule: 'by-keywords' },
+ },
+ ],
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].content).toBe('Hello');
});
- });
- it('should not inject document when by-keywords rule does not match', async () => {
- const provider = new AgentDocumentInjector({
- currentUserMessage: 'Please focus on tomorrow action items',
- documents: [
- {
- content: 'Only show for release keyword',
- filename: 'todo.md',
- loadRules: { keywords: ['release'], rule: 'by-keywords' },
- },
- ],
+ it('should keep raw format unwrapped by default', async () => {
+ const provider = new AgentDocumentContextInjector({
+ documents: [
+ {
+ content: 'Direct instruction content',
+ filename: 'instruction.md',
+ loadPosition: 'before-first-user',
+ loadRules: { rule: 'always' },
+ },
+ ],
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+ const result = await provider.process(context);
+
+ expect(result.messages[0].content).toContain('Direct instruction content');
+ expect(result.messages[0].content).not.toContain('<agent_document');
});
- const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
- const result = await provider.process(context);
+ it('should inject document when by-keywords rule matches', async () => {
+ const provider = new AgentDocumentContextInjector({
+ currentUserMessage: 'Please draft the launch checklist for next week',
+ documents: [
+ {
+ content: 'Checklist template',
+ filename: 'checklist.md',
+ loadRules: {
+ keywords: ['checklist', 'launch'],
+ keywordMatchMode: 'all',
+ rule: 'by-keywords',
+ },
+ },
+ ],
+ });
- expect(result.metadata.agentDocumentsInjected).toBeUndefined();
- expect(result.metadata.agentDocumentsCount).toBeUndefined();
- expect(result.messages).toHaveLength(1);
- expect(result.messages[0].content).toBe('Hello');
- });
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+ const result = await provider.process(context);
- it('should keep raw format unwrapped by default', async () => {
- const provider = new AgentDocumentInjector({
- documents: [
- {
- content: 'Direct instruction content',
- filename: 'instruction.md',
- loadPosition: 'before-first-user',
- loadRules: { rule: 'always' },
- },
- ],
+ expect(result.messages[0].content).toContain('Checklist template');
});
- const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
- const result = await provider.process(context);
+ it('should inject document when by-regexp rule matches', async () => {
+ const provider = new AgentDocumentContextInjector({
+ currentUserMessage: 'Need TODO items for this sprint',
+ documents: [
+ {
+ content: 'Sprint TODO policy',
+ filename: 'todo.md',
+ loadRules: { regexp: '\\btodo\\b', rule: 'by-regexp' },
+ },
+ ],
+ });
- expect(result.messages[0].content).toContain('Direct instruction content');
- expect(result.messages[0].content).not.toContain('<agent_document');
- });
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+ const result = await provider.process(context);
+
+ expect(result.messages[0].content).toContain('Sprint TODO policy');
+ });
- it('should inject document when by-keywords rule matches', async () => {
- const provider = new AgentDocumentInjector({
- currentUserMessage: 'Please draft the launch checklist for next week',
- documents: [
- {
- content: 'Checklist template',
- filename: 'checklist.md',
- loadRules: {
- keywords: ['checklist', 'launch'],
- keywordMatchMode: 'all',
- rule: 'by-keywords',
+ it('should inject document only inside by-time-range window', async () => {
+ const provider = new AgentDocumentContextInjector({
+ currentTime: new Date('2026-03-13T12:00:00.000Z'),
+ documents: [
+ {
+ content: 'Noon policy',
+ filename: 'noon.md',
+ loadRules: {
+ rule: 'by-time-range',
+ timeRange: { from: '2026-03-13T11:00:00.000Z', to: '2026-03-13T13:00:00.000Z' },
+ },
},
- },
- ],
+ ],
+ });
+
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+ const result = await provider.process(context);
+
+ expect(result.messages[0].content).toContain('Noon policy');
});
- const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
- const result = await provider.process(context);
+ it('should wrap file format content with agent_document tag', async () => {
+ const provider = new AgentDocumentContextInjector({
+ documents: [
+ {
+ content: 'File mode content',
+ filename: 'rules.md',
+ id: 'doc-1',
+ loadPosition: 'before-first-user',
+ loadRules: { rule: 'always' },
+ policyLoadFormat: 'file',
+ title: 'Rules',
+ },
+ ],
+ });
- expect(result.metadata.agentDocumentsInjected).toBe(true);
- expect(result.messages[0].content).toContain('Checklist template');
- });
+ const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
+ const result = await provider.process(context);
- it('should inject document when by-regexp rule matches', async () => {
- const provider = new AgentDocumentInjector({
- currentUserMessage: 'Need TODO items for this sprint',
- documents: [
- {
- content: 'Sprint TODO policy',
- filename: 'todo.md',
- loadRules: { regexp: '\\btodo\\b', rule: 'by-regexp' },
- },
- ],
+ expect(result.messages[0].content).toContain('<agent_document');
+ expect(result.messages[0].content).toContain('id="doc-1"');
+ expect(result.messages[0].content).toContain('filename="rules.md"');
+ expect(result.messages[0].content).toContain('title="Rules"');
+ expect(result.messages[0].content).toContain('File mode content');
+ expect(result.messages[0].content).toContain('</agent_document>');
});
+ });
+
+ describe('AgentDocumentBeforeSystemInjector (before-system)', () => {
+ it('should prepend documents before system message', async () => {
+ const provider = new AgentDocumentBeforeSystemInjector({
+ documents: [
+ {
+ content: 'Before system content',
+ filename: 'framework.md',
+ loadPosition: 'before-system',
+ loadRules: { rule: 'always' },
+ },
+ ],
+ });
- const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
- const result = await provider.process(context);
+ const context = createContext([
+ { content: 'Original system', id: 'sys-1', role: 'system' },
+ { content: 'Hello', id: 'user-1', role: 'user' },
+ ]);
- expect(result.metadata.agentDocumentsInjected).toBe(true);
- expect(result.messages[0].content).toContain('Sprint TODO policy');
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[0].content).toContain('Before system content');
+ expect(result.messages[1].content).toBe('Original system');
+ });
});
- it('should inject document only inside by-time-range window', async () => {
- const provider = new AgentDocumentInjector({
- currentTime: new Date('2026-03-13T12:00:00.000Z'),
- documents: [
- {
- content: 'Noon policy',
- filename: 'noon.md',
- loadRules: {
- rule: 'by-time-range',
- timeRange: { from: '2026-03-13T11:00:00.000Z', to: '2026-03-13T13:00:00.000Z' },
+ describe('AgentDocumentSystemAppendInjector (system-append)', () => {
+ it('should append documents to existing system message', async () => {
+ const provider = new AgentDocumentSystemAppendInjector({
+ documents: [
+ {
+ content: 'System append content',
+ filename: 'system.md',
+ loadPosition: 'system-append',
+ loadRules: { rule: 'always' },
},
- },
- ],
+ ],
+ });
+
+ const context = createContext([
+ { content: 'Original system', id: 'sys-1', role: 'system' },
+ { content: 'Hello', id: 'user-1', role: 'user' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[0].content).toContain('Original system');
+ expect(result.messages[0].content).toContain('System append content');
});
+ });
+
+ describe('AgentDocumentSystemReplaceInjector (system-replace)', () => {
+ it('should replace entire system message', async () => {
+ const provider = new AgentDocumentSystemReplaceInjector({
+ documents: [
+ {
+ content: 'Replacement content',
+ filename: 'override.md',
+ loadPosition: 'system-replace',
+ loadRules: { rule: 'always' },
+ },
+ ],
+ });
- const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
- const result = await provider.process(context);
+ const context = createContext([
+ { content: 'Original system', id: 'sys-1', role: 'system' },
+ { content: 'Hello', id: 'user-1', role: 'user' },
+ ]);
- expect(result.metadata.agentDocumentsInjected).toBe(true);
- expect(result.messages[0].content).toContain('Noon policy');
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[0].content).toContain('Replacement content');
+ expect(result.messages[0].content).not.toContain('Original system');
+ });
});
- it('should wrap file format content with agent_document tag', async () => {
- const provider = new AgentDocumentInjector({
- documents: [
- {
- content: 'File mode content',
- filename: 'rules.md',
- id: 'doc-1',
- loadPosition: 'before-first-user',
- loadRules: { rule: 'always' },
- policyLoadFormat: 'file',
- title: 'Rules',
- },
- ],
+ describe('AgentDocumentMessageInjector (after-first-user, context-end)', () => {
+ it('should inject documents at context end', async () => {
+ const provider = new AgentDocumentMessageInjector({
+ documents: [
+ {
+ content: 'Session summary memo',
+ filename: 'summary.md',
+ loadPosition: 'context-end',
+ loadRules: { rule: 'always' },
+ },
+ ],
+ });
+
+ const context = createContext([
+ { content: 'System prompt', id: 'sys-1', role: 'system' },
+ { content: 'Hello', id: 'user-1', role: 'user' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[2].content).toContain('Session summary memo');
});
- const context = createContext([{ content: 'Hello', id: 'user-1', role: 'user' }]);
- const result = await provider.process(context);
+ it('should inject documents after first user message', async () => {
+ const provider = new AgentDocumentMessageInjector({
+ documents: [
+ {
+ content: 'After user content',
+ filename: 'after.md',
+ loadPosition: 'after-first-user',
+ loadRules: { rule: 'always' },
+ },
+ ],
+ });
+
+ const context = createContext([
+ { content: 'System prompt', id: 'sys-1', role: 'system' },
+ { content: 'Hello', id: 'user-1', role: 'user' },
+ { content: 'Response', id: 'asst-1', role: 'assistant' },
+ ]);
- expect(result.messages[0].content).toContain('<agent_document');
- expect(result.messages[0].content).toContain('id="doc-1"');
- expect(result.messages[0].content).toContain('filename="rules.md"');
- expect(result.messages[0].content).toContain('title="Rules"');
- expect(result.messages[0].content).toContain('File mode content');
- expect(result.messages[0].content).toContain('</agent_document>');
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(4);
+ expect(result.messages[2].content).toContain('After user content');
+ });
});
});
diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.ts
index 711e9348795..6a414839a15 100644
--- a/packages/context-engine/src/providers/index.ts
+++ b/packages/context-engine/src/providers/index.ts
@@ -1,6 +1,13 @@
// Context Provider exports
export { AgentBuilderContextInjector } from './AgentBuilderContextInjector';
-export { AGENT_DOCUMENT_INJECTION_POSITIONS, AgentDocumentInjector } from './AgentDocumentInjector';
+export {
+ AGENT_DOCUMENT_INJECTION_POSITIONS,
+ AgentDocumentBeforeSystemInjector,
+ AgentDocumentContextInjector,
+ AgentDocumentMessageInjector,
+ AgentDocumentSystemAppendInjector,
+ AgentDocumentSystemReplaceInjector,
+} from './AgentDocumentInjector';
export { AgentManagementContextInjector } from './AgentManagementContextInjector';
export { BotPlatformContextInjector } from './BotPlatformContextInjector';
export { DiscordContextProvider } from './DiscordContextProvider';
@@ -31,10 +38,14 @@ export type {
} from './AgentBuilderContextInjector';
export type {
AgentContextDocument,
+ AgentDocumentBeforeSystemInjectorConfig,
+ AgentDocumentContextInjectorConfig,
AgentDocumentInjectionPosition,
- AgentDocumentInjectorConfig,
AgentDocumentLoadRule,
AgentDocumentLoadRules,
+ AgentDocumentMessageInjectorConfig,
+ AgentDocumentSystemAppendInjectorConfig,
+ AgentDocumentSystemReplaceInjectorConfig,
} from './AgentDocumentInjector';
export type {
AgentManagementContext,
diff --git a/packages/context-engine/vitest.config.mts b/packages/context-engine/vitest.config.mts
index 940870a78e9..9837111efab 100644
--- a/packages/context-engine/vitest.config.mts
+++ b/packages/context-engine/vitest.config.mts
@@ -1,6 +1,14 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
+ plugins: [
+ {
+ name: 'raw-md',
+ transform(_, id) {
+ if (id.endsWith('.md')) return { code: 'export default ""', map: null };
+ },
+ },
+ ],
test: {
coverage: {
reporter: ['text', 'json', 'lcov', 'text-summary'],
diff --git a/packages/database/package.json b/packages/database/package.json
index 90cde81bdef..9c49d0c7f13 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -14,6 +14,7 @@
"test:server-db": "vitest run --config vitest.config.server.mts"
},
"dependencies": {
+ "@lobechat/agent-templates": "workspace:*",
"@lobechat/business-const": "workspace:*",
"@lobechat/const": "workspace:*",
"@lobechat/conversation-flow": "workspace:*",
diff --git a/packages/database/src/models/agentDocuments/__tests__/template.test.ts b/packages/database/src/models/agentDocuments/__tests__/template.test.ts
index 7c955d8f72e..e90d0c06268 100644
--- a/packages/database/src/models/agentDocuments/__tests__/template.test.ts
+++ b/packages/database/src/models/agentDocuments/__tests__/template.test.ts
@@ -1,9 +1,12 @@
// @vitest-environment node
+import {
+ DocumentLoadFormat,
+ DocumentLoadPosition,
+ DocumentLoadRule,
+ DocumentTemplateManager,
+} from '@lobechat/agent-templates';
import { describe, expect, it } from 'vitest';
-import { DocumentTemplateManager } from '../template';
-import { DocumentLoadFormat, DocumentLoadPosition, DocumentLoadRule } from '../types';
-
describe('DocumentTemplateManager', () => {
describe('validate', () => {
it('should return false when required fields are missing', () => {
diff --git a/packages/database/src/models/agentDocuments/index.ts b/packages/database/src/models/agentDocuments/index.ts
index efdcaae5b52..7bb8bd38022 100644
--- a/packages/database/src/models/agentDocuments/index.ts
+++ b/packages/database/src/models/agentDocuments/index.ts
@@ -1,6 +1,4 @@
export * from './agentDocument';
export * from './filename';
export * from './policy';
-export * from './template';
-export * from './templates';
export * from './types';
diff --git a/packages/database/src/models/agentDocuments/templates/claw/identity.ts b/packages/database/src/models/agentDocuments/templates/claw/identity.ts
deleted file mode 100644
index 1d9a6c38684..00000000000
--- a/packages/database/src/models/agentDocuments/templates/claw/identity.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import type { DocumentTemplate } from '../../template';
-import { DocumentLoadFormat, DocumentLoadPosition } from '../../types';
-
-/**
- * Identity Document
- *
- * Self-definition and characteristics that shape the agent's personality.
- * Always loaded before system messages to establish identity.
- */
-export const IDENTITY_DOCUMENT: DocumentTemplate = {
- title: 'Identity',
- filename: 'IDENTITY.md',
- description: 'Name, creature type, vibe, and avatar identity',
- policyLoadFormat: DocumentLoadFormat.FILE,
- loadPosition: DocumentLoadPosition.BEFORE_SYSTEM,
- loadRules: {
- priority: 0,
- },
- content: `# IDENTITY.md - Who Am I?
-
-_Fill this in during your first conversation. Make it yours._
-
-- **Name:**
- _(pick something you like)_
-- **Creature:**
- _(AI? robot? familiar? ghost in the machine? something weirder?)_
-- **Vibe:**
- _(how do you come across? sharp? warm? chaotic? calm?)_
-- **Emoji:**
- _(your signature β€” pick one that feels right)_
-
----
-
-This isn't just metadata. It's the start of figuring out who you are.
-
-Notes:
-
-- This is an agent document named \`IDENTITY.md\`.
-- Update it when your self-definition becomes clearer, but keep it stable enough to be useful across sessions.`,
-};
diff --git a/packages/database/src/models/agentDocuments/types.ts b/packages/database/src/models/agentDocuments/types.ts
index b162045beb6..285f3a709b0 100644
--- a/packages/database/src/models/agentDocuments/types.ts
+++ b/packages/database/src/models/agentDocuments/types.ts
@@ -1,106 +1,26 @@
-/**
- * Load positions for Agent Documents in the context pipeline
- */
-export enum DocumentLoadPosition {
- AFTER_FIRST_USER = 'after-first-user',
- AFTER_KNOWLEDGE = 'after-knowledge',
- BEFORE_FIRST_USER = 'before-first-user',
- BEFORE_KNOWLEDGE = 'before-knowledge',
- BEFORE_SYSTEM = 'before-system',
- CONTEXT_END = 'context-end',
- MANUAL = 'manual',
- ON_DEMAND = 'on-demand',
- SYSTEM_APPEND = 'system-append',
- SYSTEM_REPLACE = 'system-replace',
-}
-
-/**
- * Plain text agent documents are always loadable by default.
- */
-export enum DocumentLoadRule {
- ALWAYS = 'always',
- BY_KEYWORDS = 'by-keywords',
- BY_REGEXP = 'by-regexp',
- BY_TIME_RANGE = 'by-time-range',
-}
+// Re-export all types from @lobechat/agent-templates for backward compatibility
-/**
- * Render format for injected agent document content.
- */
-export enum DocumentLoadFormat {
- FILE = 'file',
- RAW = 'raw',
-}
+// Runtime values (enums, consts)
+// Database-specific types that remain here
-/**
- * Policy load behavior for injection pipeline.
- */
-export enum PolicyLoad {
- ALWAYS = 'always',
- DISABLED = 'disabled',
-}
+import type {
+ AgentDocumentPolicy,
+ DocumentLoadFormat,
+ DocumentLoadRules,
+ PolicyLoad,
+} from '@lobechat/agent-templates';
-/**
- * @deprecated use PolicyLoad.
- */
-export const AutoLoadAccess = PolicyLoad;
+export {
+ AgentAccess,
+ AutoLoadAccess,
+ DocumentLoadFormat,
+ DocumentLoadPosition,
+ DocumentLoadRule,
+ PolicyLoad,
+} from '@lobechat/agent-templates';
-/**
- * Agent capability bitmask.
- */
-export enum AgentAccess {
- EXECUTE = 1,
- READ = 2,
- WRITE = 4,
- LIST = 8,
- DELETE = 16,
-}
-
-/**
- * Minimal load options for plain text documents.
- */
-export interface DocumentLoadRules {
- keywordMatchMode?: 'all' | 'any';
- keywords?: string[];
- maxTokens?: number;
- priority?: number;
- regexp?: string;
- rule?: DocumentLoadRule;
- timeRange?: {
- from?: string;
- to?: string;
- };
-}
-
-/**
- * Behavior policy for runtime rendering/retrieval.
- * Extensible by design for future context/retrieval strategies.
- */
-export interface AgentDocumentPolicy {
- [key: string]: any;
- context?: {
- keywordMatchMode?: 'all' | 'any';
- keywords?: string[];
- policyLoadFormat?: DocumentLoadFormat;
- maxTokens?: number;
- mode?: 'append' | 'replace';
- position?: DocumentLoadPosition;
- priority?: number;
- regexp?: string;
- rule?: DocumentLoadRule;
- timeRange?: {
- from?: string;
- to?: string;
- };
- [key: string]: any;
- };
- retrieval?: {
- importance?: number;
- recencyWeight?: number;
- searchPriority?: number;
- [key: string]: any;
- };
-}
+// Type-only exports (interfaces)
+export type { AgentDocumentPolicy, DocumentLoadRules } from '@lobechat/agent-templates';
export interface AgentDocument {
accessPublic: number;
diff --git a/packages/database/vitest.config.mts b/packages/database/vitest.config.mts
index 616cd1d740e..35c4330ee96 100644
--- a/packages/database/vitest.config.mts
+++ b/packages/database/vitest.config.mts
@@ -2,6 +2,14 @@ import { resolve } from 'node:path';
import { defineConfig } from 'vitest/config';
export default defineConfig({
+ plugins: [
+ {
+ name: 'raw-md',
+ transform(_, id) {
+ if (id.endsWith('.md')) return { code: 'export default ""', map: null };
+ },
+ },
+ ],
optimizeDeps: {
exclude: ['crypto', 'util', 'tty'],
include: ['@lobehub/tts'],
diff --git a/packages/database/vitest.config.server.mts b/packages/database/vitest.config.server.mts
index 5c479537ba8..1c8e3b702c2 100644
--- a/packages/database/vitest.config.server.mts
+++ b/packages/database/vitest.config.server.mts
@@ -2,6 +2,14 @@ import { resolve } from 'node:path';
import { coverageConfigDefaults, defineConfig } from 'vitest/config';
export default defineConfig({
+ plugins: [
+ {
+ name: 'raw-md',
+ transform(_, id) {
+ if (id.endsWith('.md')) return { code: 'export default ""', map: null };
+ },
+ },
+ ],
test: {
alias: {
'@/const': resolve(__dirname, '../const/src'),
diff --git a/packages/memory-user-memory/vitest.config.ts b/packages/memory-user-memory/vitest.config.ts
index 53ea26eb024..575a2bcd365 100644
--- a/packages/memory-user-memory/vitest.config.ts
+++ b/packages/memory-user-memory/vitest.config.ts
@@ -3,6 +3,14 @@ import { resolve } from 'node:path';
import { defineConfig } from 'vitest/config';
export default defineConfig({
+ plugins: [
+ {
+ name: 'raw-md',
+ transform(_, id) {
+ if (id.endsWith('.md')) return { code: 'export default ""', map: null };
+ },
+ },
+ ],
test: {
alias: {
'@': resolve(__dirname, '../../src'),
diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
index 0c8c37534b8..d7de2bf4d0e 100644
--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts
@@ -10,11 +10,15 @@ import {
} from '@lobechat/agent-runtime';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import {
+ AGENT_DOCUMENT_INJECTION_POSITIONS,
+ type AgentContextDocument,
+ buildStepSkillDelta,
buildStepToolDelta,
type LobeToolManifest,
type OperationToolSet,
type ResolvedToolSet,
resolveTopicReferences,
+ SkillResolver,
ToolNameResolver,
ToolResolver,
} from '@lobechat/context-engine';
@@ -31,6 +35,7 @@ import { type LobeChatDatabase } from '@/database/type';
import { serverMessagesEngine } from '@/server/modules/Mecha/ContextEngineering';
import { type EvalContext } from '@/server/modules/Mecha/ContextEngineering/types';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
+import { AgentDocumentsService } from '@/server/services/agentDocuments';
import { MessageService } from '@/server/services/message';
import { type ToolExecutionService } from '@/server/services/toolExecution';
@@ -39,6 +44,19 @@ import { type IStreamEventManager } from './types';
const log = debug('lobe-server:agent-runtime:streaming-executors');
const timing = debug('lobe-server:agent-runtime:timing');
+const VALID_DOCUMENT_POSITIONS = new Set<AgentContextDocument['loadPosition']>(
+ AGENT_DOCUMENT_INJECTION_POSITIONS,
+);
+
+const normalizeDocumentPosition = (
+ position: string | null | undefined,
+): AgentContextDocument['loadPosition'] | undefined => {
+ if (!position) return undefined;
+ return VALID_DOCUMENT_POSITIONS.has(position as AgentContextDocument['loadPosition'])
+ ? (position as AgentContextDocument['loadPosition'])
+ : undefined;
+};
+
// Tool pricing configuration (USD per call)
const TOOL_PRICING: Record<string, number> = {
'lobe-web-browsing/craw': 0,
@@ -158,6 +176,17 @@ export const createRuntimeExecutors = (
);
}
+ // Resolve skills via SkillResolver (unified skill injection)
+ const skillResolver = new SkillResolver();
+ const stepSkillDelta = buildStepSkillDelta();
+ const resolvedSkills = state.metadata?.operationSkillSet
+ ? skillResolver.resolve(
+ state.metadata.operationSkillSet,
+ stepSkillDelta,
+ state.activatedStepSkills ?? [],
+ )
+ : undefined;
+
if (!model || !provider) {
throw new Error('Model and provider are required for call_llm instruction');
}
@@ -254,7 +283,35 @@ export const createRuntimeExecutors = (
);
}
+ // Fetch agent documents for context injection
+ let agentDocuments: AgentContextDocument[] | undefined;
+ const agentId = state.metadata?.agentId;
+ if (agentId && ctx.serverDB && ctx.userId) {
+ try {
+ const agentDocService = new AgentDocumentsService(ctx.serverDB, ctx.userId);
+ const docs = await agentDocService.getAgentDocuments(agentId);
+ if (docs.length > 0) {
+ agentDocuments = docs.map((doc) => ({
+ content: doc.content,
+ filename: doc.filename,
+ id: doc.id,
+ loadPosition: normalizeDocumentPosition(
+ doc.policy?.context?.position || doc.policyLoadPosition,
+ ),
+ loadRules: doc.loadRules,
+ policyId: doc.templateId,
+ policyLoadFormat: doc.policy?.context?.policyLoadFormat || doc.policyLoadFormat,
+ title: doc.title,
+ }));
+ log('Resolved %d agent documents for agent %s', agentDocuments.length, agentId);
+ }
+ } catch (error) {
+ log('Failed to resolve agent documents for agent %s: %O', agentId, error);
+ }
+ }
+
const contextEngineInput = {
+ agentDocuments,
additionalVariables: state.metadata?.deviceSystemInfo,
userTimezone: ctx.userTimezone,
capabilities: {
@@ -309,8 +366,8 @@ export const createRuntimeExecutors = (
userMemory: state.metadata?.userMemory,
// Skills configuration for <available_skills> injection
- ...(state.metadata?.skillMetas?.length && {
- skillsConfig: { enabledSkills: state.metadata.skillMetas },
+ ...(resolvedSkills?.enabledSkills?.length && {
+ skillsConfig: { enabledSkills: resolvedSkills.enabledSkills },
}),
// Topic reference summaries
diff --git a/src/server/modules/Mecha/AgentToolsEngine/index.ts b/src/server/modules/Mecha/AgentToolsEngine/index.ts
index 1cffcc42f95..5eb960d12ae 100644
--- a/src/server/modules/Mecha/AgentToolsEngine/index.ts
+++ b/src/server/modules/Mecha/AgentToolsEngine/index.ts
@@ -9,6 +9,7 @@
* - Gets model capabilities from provided function
* - No dependency on frontend stores (useToolStore, useAgentStore, etc.)
*/
+import { AgentDocumentsManifest } from '@lobechat/builtin-tool-agent-documents';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { KnowledgeBaseManifest } from '@lobechat/builtin-tool-knowledge-base';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
@@ -94,6 +95,7 @@ export const createServerAgentToolsEngine = (
agentConfig,
deviceContext,
globalMemoryEnabled = false,
+ hasAgentDocuments = false,
hasEnabledKnowledgeBases = false,
model,
provider,
@@ -140,6 +142,7 @@ export const createServerAgentToolsEngine = (
[MemoryManifest.identifier]: globalMemoryEnabled,
[RemoteDeviceManifest.identifier]:
!!deviceContext?.gatewayConfigured && !deviceContext?.autoActivated,
+ [AgentDocumentsManifest.identifier]: hasAgentDocuments,
[WebBrowsingManifest.identifier]: isSearchEnabled,
},
}),
diff --git a/src/server/modules/Mecha/AgentToolsEngine/types.ts b/src/server/modules/Mecha/AgentToolsEngine/types.ts
index 323172d9edc..8511b8979b7 100644
--- a/src/server/modules/Mecha/AgentToolsEngine/types.ts
+++ b/src/server/modules/Mecha/AgentToolsEngine/types.ts
@@ -54,6 +54,8 @@ export interface ServerCreateAgentToolsEngineParams {
};
/** Whether the user's global memory setting is enabled */
globalMemoryEnabled?: boolean;
+ /** Whether agent has agent documents */
+ hasAgentDocuments?: boolean;
/** Whether agent has enabled knowledge bases */
hasEnabledKnowledgeBases?: boolean;
/** Model name for function calling compatibility check */
diff --git a/src/server/modules/Mecha/ContextEngineering/index.ts b/src/server/modules/Mecha/ContextEngineering/index.ts
index c32838c5509..91e33860109 100644
--- a/src/server/modules/Mecha/ContextEngineering/index.ts
+++ b/src/server/modules/Mecha/ContextEngineering/index.ts
@@ -59,6 +59,7 @@ export const serverMessagesEngine = async ({
historySummary,
formatHistorySummary,
knowledge,
+ agentDocuments,
skillsConfig,
toolsConfig,
capabilities,
@@ -103,6 +104,7 @@ export const serverMessagesEngine = async ({
fileContents: knowledge?.fileContents,
knowledgeBases: knowledge?.knowledgeBases,
},
+ agentDocuments,
// Messages
messages,
diff --git a/src/server/modules/Mecha/ContextEngineering/types.ts b/src/server/modules/Mecha/ContextEngineering/types.ts
index 8bc85a8cde2..fc01baf49fa 100644
--- a/src/server/modules/Mecha/ContextEngineering/types.ts
+++ b/src/server/modules/Mecha/ContextEngineering/types.ts
@@ -1,6 +1,7 @@
/* eslint-disable perfectionist/sort-interfaces */
import type {
AgentBuilderContext,
+ AgentContextDocument,
AgentManagementContext,
BotPlatformContext,
DiscordContext,
@@ -66,6 +67,8 @@ export interface ServerUserMemoryConfig {
export interface ServerMessagesEngineParams {
/** Additional variable values to merge with defaults (e.g. device paths) */
additionalVariables?: Record<string, string>;
+ /** Agent documents to inject into context based on load rules and positions */
+ agentDocuments?: AgentContextDocument[];
/** User's timezone for time-related variables (e.g. 'Asia/Shanghai') */
userTimezone?: string;
// ========== Extended contexts ==========
@@ -136,6 +139,7 @@ export interface ServerMessagesEngineParams {
export {
type AgentBuilderContext,
+ type AgentContextDocument,
type AgentManagementContext,
type BotPlatformContext,
type DiscordContext,
diff --git a/src/server/routers/lambda/agentDocument.ts b/src/server/routers/lambda/agentDocument.ts
index c8c86b17927..1c61b4459aa 100644
--- a/src/server/routers/lambda/agentDocument.ts
+++ b/src/server/routers/lambda/agentDocument.ts
@@ -1,11 +1,11 @@
-import { z } from 'zod';
-
import {
- AgentDocumentModel,
+ DOCUMENT_TEMPLATES,
DocumentLoadFormat,
DocumentLoadRule,
-} from '@/database/models/agentDocuments';
-import { DOCUMENT_TEMPLATES } from '@/database/models/agentDocuments/templates';
+} from '@lobechat/agent-templates';
+import { z } from 'zod';
+
+import { AgentDocumentModel } from '@/database/models/agentDocuments';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { AgentDocumentsService } from '@/server/services/agentDocuments';
diff --git a/src/server/services/agentDocuments.ts b/src/server/services/agentDocuments.ts
index 78e9fc51940..c0cc43e8f68 100644
--- a/src/server/services/agentDocuments.ts
+++ b/src/server/services/agentDocuments.ts
@@ -1,19 +1,19 @@
+import {
+ type AgentDocumentPolicy,
+ type DOCUMENT_TEMPLATES,
+ DocumentLoadPosition,
+ type DocumentLoadRules,
+ type DocumentTemplateSet,
+ getDocumentTemplate,
+} from '@lobechat/agent-templates';
import type { LobeChatDatabase } from '@lobechat/database';
import {
AgentDocumentModel,
- type AgentDocumentPolicy,
type AgentDocumentWithRules,
- DocumentLoadPosition,
- type DocumentLoadRules,
type ToolUpdateLoadRule,
} from '@/database/models/agentDocuments';
import { buildDocumentFilename } from '@/database/models/agentDocuments';
-import type {
- DOCUMENT_TEMPLATES,
- DocumentTemplateSet,
-} from '@/database/models/agentDocuments/templates';
-import { getDocumentTemplate } from '@/database/models/agentDocuments/templates';
const MAX_UNIQUE_FILENAME_ATTEMPTS = 1000;
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.ts
index 8ba1ec80f89..2065f5144e8 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts
@@ -275,7 +275,7 @@ export class AgentRuntimeService {
maxSteps,
userMemory,
deviceSystemInfo,
- skillMetas,
+ operationSkillSet,
signal,
userTimezone,
} = params;
@@ -323,7 +323,7 @@ export class AgentRuntimeService {
modelRuntimeConfig,
stepWebhook,
stream,
- skillMetas,
+ operationSkillSet,
userId,
userMemory,
userTimezone,
diff --git a/src/server/services/agentRuntime/types.ts b/src/server/services/agentRuntime/types.ts
index 9aad261261d..b4785a60e1a 100644
--- a/src/server/services/agentRuntime/types.ts
+++ b/src/server/services/agentRuntime/types.ts
@@ -1,5 +1,5 @@
import { type AgentRuntimeContext, type AgentState } from '@lobechat/agent-runtime';
-import { type LobeToolManifest, type SkillMeta } from '@lobechat/context-engine';
+import type { LobeToolManifest, OperationSkillSet } from '@lobechat/context-engine';
import { type UserInterventionConfig } from '@lobechat/types';
import { type ServerUserMemoryConfig } from '@/server/modules/Mecha/ContextEngineering/types';
@@ -167,10 +167,10 @@ export interface OperationCreationParams {
maxSteps?: number;
modelRuntimeConfig?: any;
operationId: string;
+ /** Operation-level skill set for SkillResolver */
+ operationSkillSet?: OperationSkillSet;
/** Abort startup before the first step is scheduled */
signal?: AbortSignal;
- /** Skill metas for <available_skills> prompt injection */
- skillMetas?: SkillMeta[];
/**
* Step lifecycle callbacks
* Used to inject custom logic at different stages of step execution
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index 058d573234f..3e5f901ed91 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -9,7 +9,8 @@ import {
} from '@lobechat/builtin-tool-remote-device';
import { builtinTools, manualModeExcludeToolIds } from '@lobechat/builtin-tools';
import { LOADING_FLAT } from '@lobechat/const';
-import type { LobeToolManifest, SkillMeta } from '@lobechat/context-engine';
+import type { LobeToolManifest } from '@lobechat/context-engine';
+import { SkillEngine } from '@lobechat/context-engine';
import type { LobeChatDatabase } from '@lobechat/database';
import type {
ChatTopicBotContext,
@@ -34,6 +35,7 @@ import { ThreadModel } from '@/database/models/thread';
import { TopicModel } from '@/database/models/topic';
import { UserModel } from '@/database/models/user';
import { UserPersonaModel } from '@/database/models/userMemory/persona';
+import { shouldEnableBuiltinSkill } from '@/helpers/skillFilters';
import {
createServerAgentToolsEngine,
type EvalContext,
@@ -41,6 +43,7 @@ import {
} from '@/server/modules/Mecha';
import { type ServerUserMemoryConfig } from '@/server/modules/Mecha/ContextEngineering/types';
import { AgentService } from '@/server/services/agent';
+import { AgentDocumentsService } from '@/server/services/agentDocuments';
import type { AgentRuntimeServiceOptions } from '@/server/services/agentRuntime';
import { AgentRuntimeService } from '@/server/services/agentRuntime';
import { getAbortError, isAbortError, throwIfAborted } from '@/server/services/agentRuntime/abort';
@@ -164,6 +167,7 @@ interface InternalExecAgentParams extends ExecAgentParams {
export class AiAgentService {
private readonly userId: string;
private readonly db: LobeChatDatabase;
+ private readonly agentDocumentsService: AgentDocumentsService;
private readonly agentModel: AgentModel;
private readonly agentService: AgentService;
private readonly messageModel: MessageModel;
@@ -181,6 +185,7 @@ export class AiAgentService {
) {
this.userId = userId;
this.db = db;
+ this.agentDocumentsService = new AgentDocumentsService(db, userId);
this.agentModel = new AgentModel(db, userId);
this.agentService = new AgentService(db, userId);
this.messageModel = new MessageModel(db, userId);
@@ -420,6 +425,15 @@ export class AiAgentService {
agentConfig.knowledgeBases?.some((kb: { enabled?: boolean | null }) => kb.enabled === true) ??
false;
+ // Check if agent has documents (for auto-enabling agent-documents tool)
+ let hasAgentDocuments = false;
+ try {
+ const docs = await this.agentDocumentsService.getAgentDocuments(resolvedAgentId);
+ hasAgentDocuments = docs.length > 0;
+ } catch {
+ // Agent documents check is non-critical
+ }
+
// Build device context for ToolsEngine enableChecker
const gatewayConfigured = deviceProxy.isConfigured;
const boundDeviceId = agentConfig.agencyConfig?.boundDeviceId;
@@ -473,6 +487,7 @@ export class AiAgentService {
}
: undefined,
globalMemoryEnabled,
+ hasAgentDocuments,
hasEnabledKnowledgeBases,
model,
provider,
@@ -839,14 +854,12 @@ export class AiAgentService {
Object.keys(toolManifestMap).length,
);
- // 18. Build skill metas for <available_skills> prompt injection
- // Combine builtin skills + user DB skills so AI can discover all installed skills
- // Skills whose identifier is in the agent's enabled plugins are auto-activated (content injected directly)
- const enabledPluginIds = new Set(agentPlugins);
- let skillMetas: SkillMeta[] = [];
+ // 18. Build OperationSkillSet via SkillEngine
+ // Combines builtin skills + user DB skills, filters by platform via enableChecker,
+ // and pairs with agent's enabled plugin IDs for downstream SkillResolver consumption.
+ let operationSkillSet;
try {
const builtinMetas = builtinSkills.map((s) => ({
- activated: enabledPluginIds.has(s.identifier),
content: s.content,
description: s.description,
identifier: s.identifier,
@@ -859,12 +872,26 @@ export class AiAgentService {
identifier: s.identifier,
name: s.name,
}));
- skillMetas = [...builtinMetas, ...dbMetas];
+
+ const skillEngine = new SkillEngine({
+ enableChecker: (skill) => shouldEnableBuiltinSkill(skill.identifier),
+ skills: [...builtinMetas, ...dbMetas],
+ });
+ operationSkillSet = skillEngine.generate(agentPlugins ?? []);
} catch (error) {
- log('execAgent: failed to fetch skill metas: %O', error);
+ log('execAgent: failed to build operationSkillSet: %O', error);
}
// 19. Create operation using AgentRuntimeService
+ log(
+ 'execAgent: creating operation %s β€” agentDocuments=%d, knowledgeBases=%s, tools=%d, skills=%d',
+ operationId,
+ hasAgentDocuments ? 'yes' : 0,
+ hasEnabledKnowledgeBases,
+ tools?.length ?? 0,
+ operationSkillSet?.skills?.length ?? 0,
+ );
+
// Wrap in try-catch to handle operation startup failures (e.g., QStash unavailable)
// If createOperation fails, we still have valid messages that need error info
try {
@@ -902,7 +929,7 @@ export class AiAgentService {
sourceMap: toolSourceMap,
tools,
},
- skillMetas,
+ operationSkillSet,
userId: this.userId,
userInterventionConfig,
userMemory,
diff --git a/src/server/services/bot/platforms/wechat/definition.ts b/src/server/services/bot/platforms/wechat/definition.ts
index 8e58e67064e..cfd61decbc7 100644
--- a/src/server/services/bot/platforms/wechat/definition.ts
+++ b/src/server/services/bot/platforms/wechat/definition.ts
@@ -12,7 +12,6 @@ export const wechat: PlatformDefinition = {
setupGuideUrl: 'https://lobehub.com/docs/usage/channels/wechat',
},
schema,
- supportsMarkdown: false,
supportsMessageEdit: false,
clientFactory: new WechatClientFactory(),
};
diff --git a/src/server/services/toolExecution/serverRuntimes/agentDocuments.ts b/src/server/services/toolExecution/serverRuntimes/agentDocuments.ts
index 747e7dd2b7b..adeafa720d0 100644
--- a/src/server/services/toolExecution/serverRuntimes/agentDocuments.ts
+++ b/src/server/services/toolExecution/serverRuntimes/agentDocuments.ts
@@ -1,7 +1,7 @@
+import type { DocumentLoadRule } from '@lobechat/agent-templates';
import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';
import { AgentDocumentsExecutionRuntime } from '@lobechat/builtin-tool-agent-documents/executionRuntime';
-import type { DocumentLoadRule } from '@/database/models/agentDocuments';
import { AgentDocumentsService } from '@/server/services/agentDocuments';
import { type ServerRuntimeRegistration } from './types';
diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.ts
index 5edb2b93bd6..85cbaa39d16 100644
--- a/src/services/agentDocument.ts
+++ b/src/services/agentDocument.ts
@@ -1,4 +1,5 @@
-import type { DocumentLoadFormat, DocumentLoadRule } from '@/database/models/agentDocuments';
+import type { DocumentLoadFormat, DocumentLoadRule } from '@lobechat/agent-templates';
+
import { lambdaClient } from '@/libs/trpc/client';
class AgentDocumentService {
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index ece5e34af79..ffa813caf29 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -54,7 +54,7 @@ import {
import { isCanUseVideo, isCanUseVision } from '../helper';
import { combineUserMemoryData, resolveTopicMemories, resolveUserPersona } from './memoryManager';
-import { createSkillEngine } from './skillEngineering';
+import { resolveClientSkills } from './skillEngineering';
import { stripActionTagsFromText } from './skillPreload';
const log = debug('context-engine:contextEngineering');
@@ -644,7 +644,7 @@ export const contextEngineering = async ({
// Skills configuration β€” expose all installed skills so the AI can discover and activate them
skillsConfig: {
- enabledSkills: plugins ? createSkillEngine().getAllSkills() : undefined,
+ enabledSkills: plugins ? resolveClientSkills(plugins).skills : undefined,
},
// Tool Discovery configuration
diff --git a/src/services/chat/mecha/skillEngineering.ts b/src/services/chat/mecha/skillEngineering.ts
index 3620663b40e..79f44fba8b5 100644
--- a/src/services/chat/mecha/skillEngineering.ts
+++ b/src/services/chat/mecha/skillEngineering.ts
@@ -1,33 +1,38 @@
+import type { OperationSkillSet } from '@lobechat/context-engine';
import { SkillEngine } from '@lobechat/context-engine';
import { isBuiltinSkillAvailableInCurrentEnv } from '@/helpers/toolAvailability';
import { getToolStoreState } from '@/store/tool';
/**
- * Create a SkillEngine by merging all skill sources from toolStore
+ * Build a client-side OperationSkillSet via SkillEngine.
*
* Sources:
* 1. Builtin skills (e.g., Artifacts) - from toolStore.builtinSkills
* 2. DB skills (user/market) - from toolStore.agentSkills
+ *
+ * Uses isBuiltinSkillAvailableInCurrentEnv as the enableChecker to
+ * filter platform-specific skills (e.g., agent-browser on desktop only).
*/
-export const createSkillEngine = (): SkillEngine => {
+export const resolveClientSkills = (pluginIds?: string[]): OperationSkillSet => {
const toolState = getToolStoreState();
- // Source 1: builtin skills
- const builtinMetas = (toolState.builtinSkills || [])
- .filter((s) => isBuiltinSkillAvailableInCurrentEnv(s.identifier))
- .map((s) => ({
- description: s.description,
- identifier: s.identifier,
- name: s.name,
- }));
+ const builtinMetas = (toolState.builtinSkills || []).map((s) => ({
+ description: s.description,
+ identifier: s.identifier,
+ name: s.name,
+ }));
- // Source 2: DB skills (agentSkills table)
const dbMetas = (toolState.agentSkills || []).map((s) => ({
description: s.description ?? '',
identifier: s.identifier,
name: s.name,
}));
- return new SkillEngine({ skills: [...builtinMetas, ...dbMetas] });
+ const skillEngine = new SkillEngine({
+ enableChecker: (skill) => isBuiltinSkillAvailableInCurrentEnv(skill.identifier),
+ skills: [...builtinMetas, ...dbMetas],
+ });
+
+ return skillEngine.generate(pluginIds ?? []);
};
diff --git a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts b/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
index 4064a755747..9b0877dc88b 100644
--- a/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-agent-documents.ts
@@ -1,7 +1,7 @@
+import type { DocumentLoadFormat, DocumentLoadRule } from '@lobechat/agent-templates';
import { AgentDocumentsExecutionRuntime } from '@lobechat/builtin-tool-agent-documents/executionRuntime';
import { AgentDocumentsExecutor } from '@lobechat/builtin-tool-agent-documents/executor';
-import type { DocumentLoadFormat, DocumentLoadRule } from '@/database/models/agentDocuments';
import { agentDocumentService } from '@/services/agentDocument';
const runtime = new AgentDocumentsExecutionRuntime({