Skip to content
English

ToolRegistry ​

CORE · class · 运行时值

Registry mechanism only: visibility, authorization policy, schemas and semantic metadata are host registrations. A registry is mutable until sealed and keeps its own call log.

导入 ​

ts
import { ToolRegistry } from '@jangts/agent-core/tools';
js
import { ToolRegistry } from '@jangts/agent-core/tools';

其他公开入口:@jangts/agent-core、@jangts/agent-core/types、@jangts/agent-core/tools。

定义 ​

ts
class ToolRegistry<Tool>

泛型参数 ​

类型参数约束默认类型
ToolErasedToolErasedTool

构造函数 ​

ts
new ToolRegistry<Tool extends ErasedTool = ErasedTool>({ execution, errors }?: ToolRegistryOptions): ToolRegistry<Tool>
参数类型传递说明
__0ToolRegistryOptions可省略—
__0 的字段
字段类型必需说明
executionExecutionOptions | undefined可省略只读。Execution defaults applied to invocations that do not pass their own.
errorsPick<ToolRegistryPorts, "unavailable" | "errorCode"> | undefined可省略只读。Error factories shared by every tool in the registry.

返回: ToolRegistry<Tool>。

实例属性 ​

字段类型必需说明
eventsreadonly Readonly<ToolExecutionEvent<Tool["kind"]>>[]必需只读。Frozen snapshot of the recorded execution facts.
definitionsreadonly Readonly<Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>>>[]必需只读。Frozen snapshot of the registered tools, in declaration order.

成员目录 ​

成员用途
setDiagnosticsReplace the diagnostics scope used by subsequent calls. Calls already in flight keep the scope they started with.
registerRegister one executable tool. The stored entry is frozen and its parsers are bound to the tool, so later changes on the caller's object cannot alter validation or execution.
invokeInvoke a registered tool synchronously.
invokeAsyncInvoke a registered tool and await its result.
registerAllRegister several tools.
get完整输入输出见下方重载。
idsRegistered tool ids in declaration order.
entriesLive iterator over [id, tool] pairs; it reflects only entries added before sealing.
require完整输入输出见下方重载。
has完整输入输出见下方重载。
valuesLive iterator over the registered tools.
sealClose the registry to further registration. Sealing is idempotent and does not affect existing tools.

成员详情 ​

setDiagnostics ​

实例方法。

Replace the diagnostics scope used by subsequent calls.

Calls already in flight keep the scope they started with.

ts
setDiagnostics(diagnostics: ToolRegistryPorts["diagnostics"]): void

Replace the diagnostics scope used by subsequent calls.

Calls already in flight keep the scope they started with.

参数类型传递说明
diagnosticsDiagnosticContext | undefined必需—

参数 diagnostics的可选结构: 选择其中一种结构,各分支的字段要求分别列出。

分支 1

undefined

分支 2
字段类型必需说明
identityReadonly<DiagnosticIdentity> | undefined可省略只读。Identity of the current scope, when the scope is bound to an execution.
enabled(event: CoreEventName, content?: "metadata" | "content") => boolean必需Cheap pre-check so callers can skip building expensive payloads.
emit<K extends CoreEventName>(event: K, payload: () => CoreEventPayloads[K], debug?: DebugStepsOutput) => void必需Records one fact.
deliver<K extends CoreEventName>(event: K, payload: () => CoreEventPayloads[K], sink: (event: Extract<CoreEvent, { type: K; }>) => void | Promise<void>) => Promise<void>必需Ordered content delivery uses the same fact, while consumer failures propagate.
child(spanId: string, fields?: Readonly<DiagnosticSpanFields>) => DiagnosticContext必需Derives a child span; fields fills values the child knows but the parent does not.
withObserver(observer: import("./execution/events.js").ExecutionObserver) => DiagnosticContext必需Bind live observation without changing the log destination or request identity.

返回: void。

register ​

实例方法。

Register one executable tool.

The stored entry is frozen and its parsers are bound to the tool, so later changes on the caller's object cannot alter validation or execution.

ts
register(tool: Tool): ToolRegistry<Tool>

Register one executable tool.

The stored entry is frozen and its parsers are bound to the tool, so later changes on the caller's object cannot alter validation or execution.

参数类型传递说明
toolTool必需—

返回: ToolRegistry<Tool>。

invoke ​

实例方法。

Invoke a registered tool synchronously.

ts
invoke(request: ToolInvocationRequest): ToolResult<unknown>

Invoke a registered tool synchronously.

参数类型传递说明
requestToolInvocationRequest<string>必需—
request 的字段
字段类型必需说明
loggerSubFlowLogger | undefined可省略只读。Explicit recorder for this call, also available to its handler for deliberate use.
toolIdstring必需只读。见类型定义及调用场景。
inputunknown必需只读。Raw model arguments; parsed by the tool's input schema before authorization.
signalAbortSignal | undefined可省略只读。Per-call cancellation; can only shorten the surrounding execution lifetime.
diagnosticsDiagnosticContext | undefined可省略只读。见类型定义及调用场景。

返回: ToolResult<unknown>。

返回值结构
字段类型必需说明
valueunknown必需只读。见类型定义及调用场景。
invocationReadonly<ToolCallRecord>必需只读。见类型定义及调用场景。

invokeAsync ​

实例方法。

Invoke a registered tool and await its result.

ts
invokeAsync(request: ToolInvocationRequest): Promise<ToolResult<unknown>>

Invoke a registered tool and await its result.

参数类型传递说明
requestToolInvocationRequest<string>必需—
request 的字段
字段类型必需说明
loggerSubFlowLogger | undefined可省略只读。Explicit recorder for this call, also available to its handler for deliberate use.
toolIdstring必需只读。见类型定义及调用场景。
inputunknown必需只读。Raw model arguments; parsed by the tool's input schema before authorization.
signalAbortSignal | undefined可省略只读。Per-call cancellation; can only shorten the surrounding execution lifetime.
diagnosticsDiagnosticContext | undefined可省略只读。见类型定义及调用场景。

返回: Promise<ToolResult<unknown>>。

等待后的值: ToolResult<unknown>。

返回值结构
字段类型必需说明
valueunknown必需只读。见类型定义及调用场景。
invocationReadonly<ToolCallRecord>必需只读。见类型定义及调用场景。

registerAll ​

实例方法。

Register several tools.

ts
registerAll(tools: Iterable<Tool>): ToolRegistry<Tool>

Register several tools.

参数类型传递说明
toolsIterable<Tool>必需—

返回: ToolRegistry<Tool>。

get ​

实例方法。

ts
get(name: string): RegisteredTool<Tool> | undefined
参数类型传递说明
namestring必需—

返回: Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>> \| undefined。

返回值的可选结构: 选择其中一种结构,各分支的字段要求分别列出。

分支 1

undefined

分支 2
字段类型必需说明
id(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["id"]必需只读。见类型定义及调用场景。
kind(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["kind"]必需只读。见类型定义及调用场景。
description(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["description"] | undefined可省略只读。Optional here because the erased view does not require model-facing prose.
debugSteps(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["debugSteps"] | undefined可省略只读。见类型定义及调用场景。
parseInput(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["parseInput"]必需见类型定义及调用场景。
parseOutput(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["parseOutput"]必需见类型定义及调用场景。
execute(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["execute"]必需见类型定义及调用场景。

ids ​

实例方法。

Registered tool ids in declaration order.

ts
ids(): readonly string[]

Registered tool ids in declaration order.

无调用参数。

返回: readonly string[]。

entries ​

实例方法。

Live iterator over [id, tool] pairs; it reflects only entries added before sealing.

ts
entries(): IterableIterator<[string, RegisteredTool<Tool>]>

Live iterator over [id, tool] pairs; it reflects only entries added before sealing.

无调用参数。

返回: IterableIterator<[string, Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>>]>。

require ​

实例方法。

ts
require(id: string): RegisteredTool<Tool>
参数类型传递说明
idstring必需—

返回: Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>>。

返回值结构
字段类型必需说明
id(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["id"]必需只读。见类型定义及调用场景。
kind(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["kind"]必需只读。见类型定义及调用场景。
description(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["description"] | undefined可省略只读。Optional here because the erased view does not require model-facing prose.
debugSteps(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["debugSteps"] | undefined可省略只读。见类型定义及调用场景。
parseInput(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["parseInput"]必需见类型定义及调用场景。
parseOutput(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["parseOutput"]必需见类型定义及调用场景。
execute(ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>)["execute"]必需见类型定义及调用场景。

has ​

实例方法。

ts
has(name: string): boolean
参数类型传递说明
namestring必需—

返回: boolean。

values ​

实例方法。

Live iterator over the registered tools.

ts
values(): IterableIterator<RegisteredTool<Tool>>

Live iterator over the registered tools.

无调用参数。

返回: IterableIterator<Readonly<ErasedTool & RegistrationData<Tool> & Pick<Tool, Extract<keyof Tool, keyof ErasedTool>>>>。

seal ​

实例方法。

Close the registry to further registration.

Sealing is idempotent and does not affect existing tools.

ts
seal(): ToolRegistry<Tool>

Close the registry to further registration.

Sealing is idempotent and does not affect existing tools.

无调用参数。

返回: ToolRegistry<Tool>。

使用示例 ​

最小本地只读工具 ​

入门 · Node.js

ts
import { ToolRegistry } from '@jangts/agent-core/tools';
const tools = new ToolRegistry().register({
  id: 'get_status', kind: 'read', description: '读取演示服务状态',
  parseInput(value: unknown) { if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('需要对象'); return {}; },
  execute: () => '服务运行正常',
  parseOutput(value: unknown) { if (typeof value !== 'string') throw new TypeError('需要文本'); return value; },
}).seal();
const result = tools.invoke({ toolId: 'get_status', input: {} });
console.log(result.value, result.invocation.invocationId);
js
import { ToolRegistry } from '@jangts/agent-core/tools';
const tools = new ToolRegistry().register({
    id: 'get_status', kind: 'read', description: '读取演示服务状态',
    parseInput(value) { if (!value || typeof value !== 'object' || Array.isArray(value))
        throw new TypeError('需要对象'); return {}; },
    execute: () => '服务运行正常',
    parseOutput(value) { if (typeof value !== 'string')
        throw new TypeError('需要文本'); return value; },
}).seal();
const result = tools.invoke({ toolId: 'get_status', input: {} });
console.log(result.value, result.invocation.invocationId);

提前绑定,节点不再重复注入工具 ​

配置 · Node.js

第一个示例严格校验外部输入;第二个仅展示绑定关系,真实业务应使用相应 Schema 与授权。

ts
import { AgentCoreEngine, defineWorkflow, route } from '@jangts/agent-core/engine';
import { ToolRegistry } from '@jangts/agent-core/tools';
type State = { answer?: unknown };
const tools = new ToolRegistry().register({ id: 'get_status', kind: 'read',
  parseInput: () => ({}), execute: async () => '服务运行正常', parseOutput: value => value,
}).seal();
const workflow = defineWorkflow<State, unknown>({ id: 'status', nodes: [{
  id: 'read', description: '读取状态', startsRound: true,
  async run(_state, { tools }) { const { value } = await tools.invoke({ toolId: 'get_status', input: {} }); return { answer: value }; },
  routes: [route.deliver('answer')],
}] });
const agent = new AgentCoreEngine({ workflow }).bindToolRuntime(tools);
console.log(await agent.run({}));
js
import { AgentCoreEngine, defineWorkflow, route } from '@jangts/agent-core/engine';
import { ToolRegistry } from '@jangts/agent-core/tools';
const tools = new ToolRegistry().register({ id: 'get_status', kind: 'read',
    parseInput: () => ({}), execute: async () => '服务运行正常', parseOutput: value => value,
}).seal();
const workflow = defineWorkflow({ id: 'status', nodes: [{
            id: 'read', description: '读取状态', startsRound: true,
            async run(_state, { tools }) { const { value } = await tools.invoke({ toolId: 'get_status', input: {} }); return { answer: value }; },
            routes: [route.deliver('answer')],
        }] });
const agent = new AgentCoreEngine({ workflow }).bindToolRuntime(tools);
console.log(await agent.run({}));

相关策略源码 ​

相关定义 ​

接口参考、使用示例与开发指南。