api-tools — 工具系统契约
包名: @aalis/api-tools
源码: packages/api-tools/src/index.ts
实现: @aalis/plugin-tools(tools 服务本体);@aalis/plugin-tool-system 等 plugin-tool-* 是往里注册工具组的生产方
概述
定义 AI 工具系统的全部"非实现"契约:
- 工具数据结构(
RegisteredTool/ToolGroupInfo/ToolSummary) - 工具调用上下文(
ToolCallContext)—— 平台/会话语义 - 工具执行通知(
ToolExecuteMessage) - 服务接口
ToolService与领域 helperuseToolService/toolsWithGroups - 向
AalisEvents注入'tool:execute'
注:runtime 工具函数已迁出本契约包(见 index.ts 迁出注释):SSRF/私网判定 → @aalis/util-network-guard;工具输入路径解析 → @aalis/api-storage。本包只保留契约/类型。
服务接口
ts
interface ToolService {
register(tool: Omit<RegisteredTool, 'pluginName'>, contextId: string): () => void;
getDefinitions(filter?: { groups?: string[] }): ToolDefinition[];
getSummaries(filter?: { groups?: string[] }): ToolSummary[];
getAll(): Array<{ name; description; pluginName; visibility; groups? }>;
execute(toolName: string, args: Record<string, unknown>, callCtx: ToolCallContext): Promise<ToolExecutionResult>;
setExecutionGuard(guard: ExecutionGuard): void;
unregisterByPlugin(contextId: string): void;
registerGroup(group: Omit<ToolGroupInfo, 'pluginName'>, contextId: string): () => void;
getGroups(): ToolGroupInfo[];
}RegisteredTool 结构
ts
interface RegisteredTool {
definition: ToolDefinition; // OpenAI 风格函数声明
handler: (args, callCtx: ToolCallContext) => Promise<string | ToolExecutionResult>; // { content, images? }:images 交主模型亲眼看
pluginName: string;
visibility?: CapabilityVisibility; // 'public' | 'restricted'(默认 public)
// 注:CapabilityVisibility 从 @aalis/api-authority 导入
groups?: string[]; // 工具分组,未设置时始终可用
}领域 Helper
ts
const tools = useToolService(ctx);
tools.register({ definition, handler, ... }): () => void;
tools.registerGroup({ name, label, description? }): () => void;
// 自动给后续 register 注入 groups 字段
const groupTools = toolsWithGroups(tools, ['my-group']);
groupTools.register({ definition, handler }); // 自动 groups: ['my-group']helper 内部为每个 Context 维护一份绑定,经一条 whenService 订阅跟随 tools 提供者: 服务尚未 provide 时 register 调用会被自动延迟到服务就绪,提供者换人时整体重挂,调用方无需关心顺序。 同一 Context 内同名(工具名 / 分组名)是替换语义——新登记顶掉旧登记,旧登记的退订闭包随即失效,不会误删新登记。 Context 已 dispose 后的登记与 ctx.on 同口径:记 warn、不进枢纽,返回的退订闭包无动作。
事件(AalisEvents)
ts
'tool:execute': [{
sessionId: string;
platform?: string;
toolName: string;
args: Record<string, unknown>;
phase: 'start' | 'end';
result?: string; // 仅 phase='end'
}]供 WebUI / 日志归档订阅展示。
典型用法
ts
import { useToolService } from '@aalis/api-tools';
const tools = useToolService(ctx);
tools.register({
definition: { type: 'function', function: { name: 'my_tool', ... } },
handler: async (args, callCtx) => '...',
visibility: 'public',
groups: ['custom'],
});实现者
- @aalis/plugin-tools ——
tools服务本体(注册表、分组、可见性) - @aalis/plugin-tool-system —— 往里注册
system一个工具组(含 shell / 文件 / 系统信息 / HTTP 四类工具)
相关
- 权限校验见 api-authority
- storage URI 体系见 api-storage