Skip to content

Commit 81059d8

Browse files
author
linyuan.yang
committed
添加 IAgentPlugin
1 parent 17084d2 commit 81059d8

6 files changed

Lines changed: 218 additions & 10 deletions

File tree

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import { type StructuredToolInterface } from "@langchain/core/tools";
2+
import type { ILogger } from "../../Logger";
3+
import type { ChatMessage, IAgentSaverService } from "../../Saver";
4+
5+
/**
6+
* Agent 能力插件的运行上下文。每次 stream 构造一份,不跨轮复用。
7+
*
8+
* 字段对齐现有硬编码子系统各自需要的入参:query 对应 note / wiki 的 queryText,
9+
* channelSessionId 对应 agenda 写 trigger / pending job 的会话归属。
10+
*/
11+
export interface AgentPluginContext {
12+
/** 本轮用户输入的纯文本形式(多模态 content 已拍平),供检索类插件构造查询。 */
13+
readonly query: string;
14+
/** 本轮归属的 channel session db id,供需要会话归属的插件使用。 */
15+
readonly channelSessionId: number;
16+
/** 本轮历史存储器,插件可读完整对话与 metadata。 */
17+
readonly saver: IAgentSaverService;
18+
/** 以插件 name 派生的 logger。 */
19+
readonly logger?: ILogger;
20+
}
21+
22+
/**
23+
* system prompt 的注入分区,与 system message 的两个 content block 一一对应。
24+
*/
25+
export enum AgentPluginPromptKind {
26+
/** 静态块:跨请求不变,可命中 prompt caching。取自 {@link IAgentPlugin.getStaticSystemPrompt}。 */
27+
Static = 'static',
28+
/** 动态块:每轮可变。取自 {@link IAgentPlugin.getDynamicSystemPrompt}。 */
29+
Dynamic = 'dynamic',
30+
}
31+
32+
/**
33+
* 一轮对话结束时的结果快照,作为 {@link IAgentPlugin.onTurnCompleted} 的第一个参数。
34+
*
35+
* 只装本轮结果,不含运行上下文——ctx 作为独立的第二个参数传入,
36+
* 两者职责分开:turn 是「这一轮产出了什么」,ctx 是「这一轮在什么环境里跑」。
37+
*/
38+
export interface AgentTurn {
39+
/** 本轮完整对话:首条为 human 消息,其后是 agent 的全部输出(AI / tool 消息)。 */
40+
readonly conversation: ChatMessage[];
41+
}
42+
43+
/**
44+
* Agent 能力插件:把一套子系统(system prompt + 工具 + turn 末尾副作用)打包成
45+
* 可插拔单元,注册进容器即生效,无需再改 SingleAgentService。
46+
*
47+
* 与 Wiki 数据源插件(`WikiPlugin`)、Channel 插件不是同一层概念——那两者是「某类
48+
* 数据源/渠道的具体实现」,本接口是「挂到 agent 生命周期上的扩展点」。
49+
*
50+
* **生命周期不在本接口内**:插件由注册方创建并负责释放(memory / agenda 那类走 pool +
51+
* refCount 的服务,由 acquire 方在 finally 里 release)。agent 只消费插件、不 dispose,
52+
* 否则 pool 化服务会被双重释放。
53+
*
54+
* 所有钩子均为可选:只出工具的插件只实现 getTools,只注入 prompt 的只实现 getDynamicSystemPrompt。
55+
* 单个钩子抛错由框架捕获并降级为日志告警,不会中断本轮请求。
56+
*/
57+
export interface IAgentPlugin {
58+
/** 唯一标识,用于日志定位。 */
59+
readonly name: string;
60+
61+
/**
62+
* ReAct 派发子 agent 时是否随子容器下传。默认 false。
63+
*
64+
* 抽取类插件(memory / agenda 风格)应保持 false:子 agent 的 human 消息是编排者
65+
* 合成的 task 指令而非真实用户输入,参与抽取会污染数据。纯检索类(note / wiki 风格)
66+
* 置 true 让子 agent 也能用。
67+
*/
68+
readonly inheritToSubAgent?: boolean;
69+
70+
/**
71+
* 静态 system prompt:跨请求不变,拼进 system message 的第一个 content block,
72+
* 可命中 prompt caching。返回随请求变化的内容会让缓存持续失效——那种内容用
73+
* {@link getDynamicSystemPrompt}。返回 undefined / 空串表示本轮不注入。
74+
*/
75+
getStaticSystemPrompt?(ctx: AgentPluginContext): Promise<string | undefined> | string | undefined;
76+
77+
/**
78+
* 动态 system prompt:每轮可变(如按 query 检索出的片段),拼进第二个 content block。
79+
* 返回 undefined / 空串表示本轮不注入。
80+
*/
81+
getDynamicSystemPrompt?(ctx: AgentPluginContext): Promise<string | undefined> | string | undefined;
82+
83+
/**
84+
* 本轮暴露给模型的工具。插件工具排在框架自有工具之后:同名时框架工具胜出,
85+
* 模型 maxTools 截断也优先砍插件工具。
86+
*/
87+
getTools?(ctx: AgentPluginContext): Promise<StructuredToolInterface[]> | StructuredToolInterface[];
88+
89+
/**
90+
* 一轮对话结束后触发的副作用钩子(后台抽取、统计、清理等)。
91+
*
92+
* turn 是本轮产出的快照,ctx 是与其他钩子同一份的运行上下文。
93+
* fire-and-forget:框架不 await 返回的 promise,实现方应只做同步入队之类的轻量动作,
94+
* 重活自行放后台。同步抛错与 promise reject 都会被捕获并写日志。
95+
* 命名不用 extractFromConversation 是因为用途不限于抽取。
96+
*/
97+
onTurnCompleted?(turn: AgentTurn, ctx: AgentPluginContext): void | Promise<void>;
98+
}
99+
100+
/**
101+
* IAgentPlugin 的依赖注入 token。注册值为**插件数组**(与 INoteService / IWikiService 同套路):
102+
* `container.registerInstance(IAgentPlugin, [pluginA, pluginB])`。
103+
*/
104+
export const IAgentPlugin = Symbol("IAgentPlugin");
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from './IAgentPlugin';

‎packages/scorpio.ai/src/Agents/ReAct/ReActAgentService.ts‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { IAgentSaverService, TaskBackedSaver, ConversationCompactor, IConversati
77
import { ILoggerService } from "../../Logger";
88
import { IModelService } from "../../Model";
99
import { type AgentServiceBase, IAgentCallback, AgentSubNode, CreateAgentFn, T_CreateAgent, MessageRole, ChatMessage } from "../AgentServiceBase";
10+
import { IAgentPlugin, type AgentPluginContext } from "../Plugins";
1011
import { ISkillService } from "../../Skills";
1112
import { IMemoryService } from "../../Memory";
1213
import { IAgendaService } from "../../Agenda";
@@ -78,23 +79,24 @@ export class ReActAgentService extends SingleAgentService {
7879
@inject(T_ModelCallTimeout, { optional: true }) modelCallTimeout?: number,
7980
@inject(IConversationCompactor, { optional: true }) compactor?: ConversationCompactor,
8081
@inject(T_SpawnDepth, { optional: true }) spawnDepth?: number,
82+
@inject(IAgentPlugin, { optional: true }) plugins?: IAgentPlugin[],
8183
) {
82-
super(thinkModelService, skillService, toolOverflowDir, channelSessionId, staticSystemPrompts, dynamicSystemPrompts, loggerService, agentSaver, memoryService, agendaService, toolService, noteServices, wikiServices, modelCallTimeout, compactor);
84+
super(thinkModelService, skillService, toolOverflowDir, channelSessionId, staticSystemPrompts, dynamicSystemPrompts, loggerService, agentSaver, memoryService, agendaService, toolService, noteServices, wikiServices, modelCallTimeout, compactor, plugins);
8385
this.agentSubNodes = agentSubNodes;
8486
this.agentFactory = agentFactory;
8587
this.spawnDepth = spawnDepth ?? 0;
8688
}
8789

8890
// ── Overrides ────────────────────────────────────────────────
8991

90-
protected override async buildSystemMessage(query: MessageContent): Promise<ChatMessage | undefined> {
92+
protected override async buildSystemMessage(ctx: AgentPluginContext, query: MessageContent): Promise<ChatMessage | undefined> {
9193
const agentsDesc = this.agentSubNodes.map(a => {
9294
const nameAttr = a.name ? ` name="${a.name}"` : '';
9395
return ` <agent id="${a.id}"${nameAttr}>${a.desc}</agent>`;
9496
}).join('\n');
9597
const reactPrompt = this.systemPromptTemplate.replace('{agents}', agentsDesc);
9698

97-
const parentMsg = await super.buildSystemMessage(query);
99+
const parentMsg = await super.buildSystemMessage(ctx, query);
98100
if (!parentMsg) {
99101
return { role: MessageRole.System, content: [{ type: ContentPartType.Text, text: reactPrompt }] };
100102
}
@@ -109,7 +111,7 @@ export class ReActAgentService extends SingleAgentService {
109111
};
110112
}
111113

112-
protected override async buildTools(callback?: IAgentCallback, signal?: AbortSignal): Promise<StructuredToolInterface[]> {
114+
protected override async buildTools(ctx: AgentPluginContext, callback?: IAgentCallback, signal?: AbortSignal): Promise<StructuredToolInterface[]> {
113115
if (!callback) return [];
114116
const { onMessage: _, ...subCallback } = callback;
115117

@@ -164,6 +166,9 @@ export class ReActAgentService extends SingleAgentService {
164166
// 故意不透传 memory / agenda:抽取(extractFromConversation)无条件随 service 触发,
165167
// 而子 agent 的 Human 消息是编排者合成的 task 指令、非真实用户输入,抽取会污染记忆/日程。
166168
// 真实用户内容由编排者自身 turn 末尾统一抽取,子任务无需重复参与。
169+
// 插件按同一原则区分:抽取类插件默认 inheritToSubAgent=false 不下传,纯检索类显式置 true 才下传。
170+
const inheritedPlugins = this.plugins.filter(p => p.inheritToSubAgent);
171+
if (inheritedPlugins.length > 0) subContainer.registerInstance(IAgentPlugin, inheritedPlugins);
167172

168173
agentService = await this.agentFactory(agentId, subContainer);
169174

@@ -231,7 +236,7 @@ export class ReActAgentService extends SingleAgentService {
231236
};
232237

233238
const agentIds = this.agentSubNodes.map(a => a.id);
234-
const parentTools = await super.buildTools(callback, signal);
239+
const parentTools = await super.buildTools(ctx, callback, signal);
235240
return [
236241
createDispatchTaskTool(agentIds, runFn),
237242
createListTasksTool(getTasks),

‎packages/scorpio.ai/src/Agents/Single/SingleAgentService.ts‎

Lines changed: 96 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { IAgentToolService } from "../../AgentTool";
1414
import { ILoggerService } from "../../Logger";
1515
import { normalizeToMCPResult, truncateMCPToolResult, MCPContentType } from '../../Tools';
1616
import { 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";
1718
import { ContentPartType, MessageKind, type MessageContent, type ContentPart } from "../../Saver/IAgentSaverService";
1819
import { contentToString, truncateForLog } from "../../Utils/contentUtils";
1920
import { 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
}

‎packages/scorpio.ai/src/Agents/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export * from './AgentServiceBase';
2+
export * from './Plugins';
23
export * from './Single';
34
export * from './ReAct';
45
export * from './Generative';

‎packages/scorpio.ai/src/index.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,12 +398,18 @@ export {
398398
MessageRole,
399399
IAgentCallback,
400400
AgentCancelledError,
401+
402+
// 能力插件(system prompt + 工具 + turn 末尾副作用的可插拔单元)
403+
IAgentPlugin,
404+
AgentPluginPromptKind,
401405
} from "./Agents";
402406

403407
export type {
404408
AgentSubNode,
405409
CreateAgentFn,
406410
OnCreateThinkFn,
411+
AgentPluginContext,
412+
AgentTurn,
407413
} from "./Agents";
408414

409415
// ========================================

0 commit comments

Comments
 (0)