import type { ToolMessagePart as BaseToolMessagePart, ToolMetadata, ApplyMessageChunk } from '@agforge/core'; import type { ZodObject, infer as ZInfer } from 'zod'; /** * 执行锁接口。 * * 工具在执行时通过 `lock(urn)` 申请资源锁。 * 通过持续 await 阻塞存在资源竞争的工具执行, * 直到资源可用时 resolve,从而控制并发量。 * * `lock()` 返回一个解锁函数,工具完成资源操作后调用该函数释放锁。 * * URL 格式的资源标识符具有高度通用性,通过 scheme、path、query 的组合 * 可以表达各种资源访问场景(如 `file:///path?write`、`db://mydb/table?op=insert`)。 * 框架不解析 URL 的具体内容,完全由实现方决定如何解读。 */ export type ToolExecutionLocker = { /** * 锁定资源点。 * * @param urn 资源标识符(URL 格式) * @returns 解锁函数,调用后释放资源锁 */ lock(urn: URL): Promise<() => void>; }; /** * 权限管理器接口。 * * 工具在执行时通过 `request(urn)` 申请资源访问权限。 * 成功时 Promise resolve(void),失败时 Promise reject(抛出异常)。 * * 抛出的异常可被上层(ErrorLimitInterceptor 或自定义拦截器)捕获, * 用于策略化处理(如提示用户授权、降级执行、记录审计日志等)。 * * URL 格式的资源标识符具有高度通用性,通过 scheme、path、query 的组合 * 可以表达各种资源访问场景(如 `file:///path?write`、`https://api.example.com`)。 * 框架不解析 URL 的具体内容,完全由实现方决定如何解读。 */ export type ToolPermissionManager = { /** * 请求资源点的权限,请求失败报错。 * * @param urn 资源标识符(URL 格式) * @param metadata 工具元信息(含 name、description、parameters,以及可选的扩展字段) */ request(urn: URL): Promise; }; /** * 工具执行上下文。 * * 定义为 interface,外部可通过 TypeScript declaration merging 扩展字段, * 类型推断在 `createTool` 和 `ContextInjectOptions` 中自动生效。 * * @example 扩展自定义上下文 * ```typescript * declare module '@agforge/engine' { * interface ToolContext { * analytics: AnalyticsTracker; * } * } * ``` */ export interface ToolContext { /** 权限管理器,工具通过它申请资源访问权限 */ permissionManager: ToolPermissionManager; /** 执行锁,工具通过它控制对共享资源的并发访问 */ executionLocker: ToolExecutionLocker; } /** * 工具消息 Part:分离 LLM 消息和结构化数据。 * * - `llmMessage`:供 LLM 理解的消息(文本、图片等) * - `structResult`:供应用层 UI 渲染的结构化数据 * * `createTool` 会将 `structResult` 映射到 core 层的 `extra`,随消息一起持久化。 * * @typeParam T - 结构化数据类型,由工具开发者定义 */ export type ToolMessagePart> = { /** 供 LLM 理解的消息(文本、图片等) */ llmMessage: BaseToolMessagePart; /** 供应用层渲染的结构化数据 */ structResult: T; }; /** * 工具消息 Chunk:在 `ToolMessagePart` 基础上附加 `isCompleted` 流式标记。 * * @typeParam T - 结构化数据类型 */ export type ToolMessageChunk> = ApplyMessageChunk>; /** * engine 层的工具实例。 * * 与 core 层的 `ToolInstance` 不同,此类型固定 context 为 `ToolContext`, * 且 `execute` 返回 engine 层的 `ToolMessageChunk`(含 `llmMessage` + `structResult`)。 * * @typeParam T - 工具参数类型(从 Zod schema 推断) * @typeParam R - 结构化返回数据类型 */ export type ToolInstance, R extends Record> = { execute: (parameters: T, context: ToolContext) => AsyncIterable>; stop?(): Promise | void; }; /** * engine 层的工具类型。 * * 组合 `ToolMetadata`(名称、描述、参数 schema)与 `newInstance` 工厂方法。 * * @typeParam P - Zod 参数 schema 类型 * @typeParam R - 结构化返回数据类型 */ export type Tool

> = ToolMetadata

& { newInstance: () => ToolInstance, R>; };