@@ -14,6 +14,7 @@ import { IAgentToolService } from "../../AgentTool";
1414import { ILoggerService } from "../../Logger" ;
1515import { normalizeToMCPResult , truncateMCPToolResult , MCPContentType } from '../../Tools' ;
1616import { AgentServiceBase , GraphNodeType , ToolApproval , IAgentCallback , AgentCancelledError , DEFAULT_MAX_HISTORY_TOKENS , ChatMessage , ChatToolCall , MessageRole , type TokenUsage , type OnCreateThinkFn } from "../AgentServiceBase" ;
17+ import { IAgentPlugin , AgentPluginPromptKind , type AgentPluginContext , type AgentTurn } from "../Plugins" ;
1718import { ContentPartType , MessageKind , type MessageContent , type ContentPart } from "../../Saver/IAgentSaverService" ;
1819import { contentToString , truncateForLog } from "../../Utils/contentUtils" ;
1920import { v4 as uuidv4 } from "uuid" ;
@@ -88,6 +89,9 @@ export class SingleAgentService extends AgentServiceBase {
8889 * 与 extractFromConversation 入队 pending job 的 channelSessionId 都用它。
8990 * 必传——caller(AgentRunner / ReActAgentService 子任务路径)务必把 T_ChannelSessionId 注册进容器。 */
9091 protected channelSessionId : number ;
92+ /** 能力插件:把 system prompt + 工具 + turn 末尾副作用打包成可插拔单元,注册进容器即生效。
93+ * 新子系统走这条路接入,无需再改本类。生命周期归注册方,本类只消费不 dispose。 */
94+ protected plugins : IAgentPlugin [ ] ;
9195
9296 constructor (
9397 @inject ( IModelService ) modelService : IModelService ,
@@ -105,6 +109,7 @@ export class SingleAgentService extends AgentServiceBase {
105109 @inject ( IWikiService , { optional : true } ) wikiServices ?: IWikiService [ ] ,
106110 @inject ( T_ModelCallTimeout , { optional : true } ) modelCallTimeout ?: number ,
107111 @inject ( IConversationCompactor , { optional : true } ) compactor ?: ConversationCompactor ,
112+ @inject ( IAgentPlugin , { optional : true } ) plugins ?: IAgentPlugin [ ] ,
108113 ) {
109114 super ( loggerService , agentSaver , noteServices , wikiServices ) ;
110115 this . modelService = modelService ;
@@ -118,6 +123,7 @@ export class SingleAgentService extends AgentServiceBase {
118123 this . compactor = compactor ;
119124 this . toolOverflowDir = toolOverflowDir ;
120125 this . channelSessionId = channelSessionId ;
126+ this . plugins = plugins ?? [ ] ;
121127 }
122128
123129 override addStaticSystemPrompts ( prompts : string [ ] ) : void {
@@ -128,11 +134,64 @@ export class SingleAgentService extends AgentServiceBase {
128134 this . dynamicSystemPrompts . push ( ...prompts ) ;
129135 }
130136
131- protected async buildSystemMessage ( query : MessageContent ) : Promise < ChatMessage | undefined > {
137+ /**
138+ * 构造本轮的插件上下文。stream 入口造一份贯穿 buildSystemMessage / buildTools / onTurnCompleted,
139+ * 保证同一轮内各钩子看到的 query 与 saver 一致。
140+ */
141+ protected buildPluginContext ( query : MessageContent ) : AgentPluginContext {
142+ return {
143+ query : contentToString ( query ) ,
144+ channelSessionId : this . channelSessionId ,
145+ saver : this . saverService ,
146+ logger : this . loggerService ?. getLogger ( 'AgentPlugin' ) ,
147+ } ;
148+ }
149+
150+ /**
151+ * 收集插件的 system prompt。并发取、按插件声明顺序保序拼接;
152+ * 单个插件抛错降级为日志告警并跳过——插件是可选扩展,不该因一个实现出错整轮失败。
153+ */
154+ protected async collectPluginPrompts ( kind : AgentPluginPromptKind , ctx : AgentPluginContext ) : Promise < string [ ] > {
155+ if ( this . plugins . length === 0 ) return [ ] ;
156+ const results = await Promise . all ( this . plugins . map ( async plugin => {
157+ const fn = kind === AgentPluginPromptKind . Static ? plugin . getStaticSystemPrompt : plugin . getDynamicSystemPrompt ;
158+ if ( ! fn ) return undefined ;
159+ try {
160+ return await fn . call ( plugin , ctx ) ;
161+ } catch ( err : any ) {
162+ this . logger ?. warn ( `插件 ${ plugin . name } 生成 ${ kind } system prompt 失败,已跳过: ${ formatError ( err , true ) } ` ) ;
163+ return undefined ;
164+ }
165+ } ) ) ;
166+ return results . filter ( ( text ) : text is string => ! ! text ?. trim ( ) ) ;
167+ }
168+
169+ /** 收集插件工具。单个插件抛错降级为日志告警并跳过,其余插件照常生效。 */
170+ protected async collectPluginTools ( ctx : AgentPluginContext ) : Promise < StructuredToolInterface [ ] > {
171+ if ( this . plugins . length === 0 ) return [ ] ;
172+ const results = await Promise . all ( this . plugins . map ( async plugin => {
173+ if ( ! plugin . getTools ) return [ ] ;
174+ try {
175+ return await plugin . getTools ( ctx ) ;
176+ } catch ( err : any ) {
177+ this . logger ?. warn ( `插件 ${ plugin . name } 生成工具失败,已跳过: ${ formatError ( err , true ) } ` ) ;
178+ return [ ] ;
179+ }
180+ } ) ) ;
181+ return results . flat ( ) ;
182+ }
183+
184+ /**
185+ * 构建本轮 system message(静态块 + 动态块两个 content part)
186+ *
187+ * ctx 统一排在首位,与 buildTools / collectPlugin* / notifyPluginsTurnCompleted 一致。
188+ */
189+ protected async buildSystemMessage ( ctx : AgentPluginContext , query : MessageContent ) : Promise < ChatMessage | undefined > {
132190 // ── 静态部分(跨请求不变,可被 prompt caching 缓存) ──
133191 const staticParts : string [ ] = [ ...this . staticSystemPrompts ] ;
134192 const skillMessage = await this . skillService . getSystemMessage ( ) ;
135193 if ( skillMessage ) staticParts . push ( skillMessage ) ;
194+ staticParts . push ( ...await this . collectPluginPrompts ( AgentPluginPromptKind . Static , ctx ) ) ;
136195
137196 // ── 动态部分(每次请求可能变化) ──
138197 const dynamicParts : string [ ] = [ ...this . dynamicSystemPrompts ] ;
@@ -158,6 +217,8 @@ export class SingleAgentService extends AgentServiceBase {
158217 if ( msg ) dynamicParts . push ( msg ) ;
159218 }
160219 }
220+ dynamicParts . push ( ...await this . collectPluginPrompts ( AgentPluginPromptKind . Dynamic , ctx ) ) ;
221+
161222 const contentBlocks : Array < { type : string ; text : string } > = [ ] ;
162223 const staticContent = staticParts . join ( "\n\n" ) . trim ( ) ;
163224 if ( staticContent ) contentBlocks . push ( { type : ContentPartType . Text , text : staticContent } ) ;
@@ -168,9 +229,12 @@ export class SingleAgentService extends AgentServiceBase {
168229 }
169230
170231 /**
171- * 构建本轮所有可用工具(toolService + 笔记 + skill)
232+ * 构建本轮所有可用工具(toolService + 笔记 + skill + 插件)
233+ *
234+ * 插件工具追加在最末:同名去重时框架自有工具胜出,maxTools 截断也优先砍插件工具。
235+ * ctx 统一排在首位(也是必需参数唯一能放的位置——不能跟在可选的 callback / signal 之后)。
172236 */
173- protected async buildTools ( _callback ?: IAgentCallback , _signal ?: AbortSignal ) : Promise < StructuredToolInterface [ ] > {
237+ protected async buildTools ( ctx : AgentPluginContext , _callback ?: IAgentCallback , _signal ?: AbortSignal ) : Promise < StructuredToolInterface [ ] > {
174238 const tools : StructuredToolInterface [ ] = await this . toolService ?. getAllTools ( ) ?? [ ] ;
175239 if ( this . skillService ) tools . push ( ...this . skillService . getTools ( ) ) ;
176240 if ( this . noteServices . length > 0 ) {
@@ -185,6 +249,9 @@ export class SingleAgentService extends AgentServiceBase {
185249 if ( this . memoryService ) {
186250 tools . push ( ...MemoryToolProvider . getTools ( this . memoryService ) ) ;
187251 }
252+ if ( this . plugins . length > 0 ) {
253+ tools . push ( ...await this . collectPluginTools ( ctx ) ) ;
254+ }
188255
189256 // 同名工具会被 OpenAI 兼容端点判为非法请求(400),按首次出现去重
190257 const unique = new Map < string , StructuredToolInterface > ( ) ;
@@ -519,11 +586,13 @@ export class SingleAgentService extends AgentServiceBase {
519586 await this . saverService . pushMessage ( { role : MessageRole . Human , content : query } ) ;
520587
521588 const outputMessages : ChatMessage [ ] = [ ] ;
589+ // 本轮插件上下文造一份,贯穿 prompt / 工具 / turn 末尾三个钩子,保证各钩子看到同一份 query。
590+ const ctx = this . buildPluginContext ( query ) ;
522591
523592 try {
524593 const [ systemMessage , tools ] = await Promise . all ( [
525- this . buildSystemMessage ( query ) ,
526- this . buildTools ( callback , signal ) ,
594+ this . buildSystemMessage ( ctx , query ) ,
595+ this . buildTools ( ctx , callback , signal ) ,
527596 ] ) ;
528597
529598 const graph = new StateGraph < SingleAgentState > ( )
@@ -585,9 +654,31 @@ export class SingleAgentService extends AgentServiceBase {
585654 if ( this . agendaService ) {
586655 this . agendaService . extractFromConversation ( conversation , this . channelSessionId ) ;
587656 }
657+ this . notifyPluginsTurnCompleted ( ctx , conversation ) ;
588658
589659 // Memory 反馈走 read_memory 工具调用累加 read_count,不再需要 citation 钩子。
590660
591661 return outputMessages ;
592662 }
663+
664+ /**
665+ * turn 末尾通知各插件(fire-and-forget,与 memory / agenda 的抽取同一语义):
666+ * 不 await 返回的 promise,同步抛错与 reject 都只降级为日志,不影响本轮响应。
667+ */
668+ protected notifyPluginsTurnCompleted ( ctx : AgentPluginContext , conversation : ChatMessage [ ] ) : void {
669+ if ( this . plugins . length === 0 ) return ;
670+
671+ const turn : AgentTurn = { conversation } ;
672+
673+ for ( const plugin of this . plugins ) {
674+ if ( ! plugin . onTurnCompleted ) continue ;
675+ try {
676+ Promise . resolve ( plugin . onTurnCompleted ( turn , ctx ) ) . catch ( ( err : any ) => {
677+ this . logger ?. warn ( `插件 ${ plugin . name } onTurnCompleted 异步失败: ${ formatError ( err , true ) } ` ) ;
678+ } ) ;
679+ } catch ( err : any ) {
680+ this . logger ?. warn ( `插件 ${ plugin . name } onTurnCompleted 失败: ${ formatError ( err , true ) } ` ) ;
681+ }
682+ }
683+ }
593684}
0 commit comments