Skip to content
中文

CommandCatalog ​

KIT · class · Runtime value

Mode and cross-protocol field ownership checks are shared by all receiving hosts.

The catalog seals itself as soon as construction finishes, so a run cannot register a new command later; set remains available only for the superclass installation pass.

Import ​

ts
import { CommandCatalog } from '@jangts/agent-core/kits/interaction';
js
import { CommandCatalog } from '@jangts/agent-core/kits/interaction';

Other public entry points:@jangts/agent-core, @jangts/agent-core/types, @jangts/agent-core/kits/interaction, @jangts/agent-core/kits.

Definition ​

ts
class CommandCatalog<Value, Result, Args, Id>

Extends or implements: ProtocolRegistry<Command<Value, Result, Args> & { readonly id: Id }>.

Type parameters ​

Type parameterConstraintDefault type
ValueobjectRecord<string, unknown>
Result—Value
Argsunknown[][]
Idstringstring

Constructor ​

ts
new CommandCatalog<Value extends object = Record<string, unknown>, Result = Value, Args extends unknown[] = [], Id extends string = string>(definitions: Iterable<readonly [Id, Command<Value, Result, Args>]>, options?: CommandCatalogOptions): CommandCatalog<Value, Result, Args, Id>
ParameterTypePassingDescription
definitionsIterable<readonly [Id, Command<Value, Result, Args>]>Required—
optionsCommandCatalogOptionsOptional—
Fields of options
FieldTypeRequiredDescription
modeFieldstring | undefinedOptionalRead-only. Field carrying the mode selector, when modes are used.
unknownErrorstring | Error | undefinedOptionalRead-only. Rejection wording for an unknown command selector.
modeErrorstring | Error | undefinedOptionalRead-only. Rejection wording for a command used outside its declared modes.
ownershipErrorstring | Error | undefinedOptionalRead-only. Rejection wording for a model-supplied owned field.
tagsreadonly string[] | undefinedOptionalRead-only. Diagnostic tags attached to every rejection from this catalog.

Returns: CommandCatalog<Value, Result, Args, Id>.

Instance properties ​

FieldTypeRequiredDescription
definitionsreadonly Readonly<Command<Value, Result, Args> & { id: Id; }>[]RequiredRead-only. Compiled commands in registration order.

Member index ​

MemberPurpose
defineStatic. Compile and construct a catalog from definitions in one call.
compileStatic. Compile a set of definitions with shared envelope fields.
setInstall one compiled command during construction.
deleteRemoval is not supported.
clearClearing is not supported.
toRecordExplicit dictionary projection; definitions always remains an ordered array.
manifestThe same declarations drive purpose-specific menus, documentation and handler binding.
parseValidate and parse one payload as the named command. Checks run before the command's own parser: the id must exist, the mode (when configured) must be allowed, and no other command may claim a field that this payload sets. The last rule prevents one command from silently consuming another command's data.
idsSee the overload below for full inputs and outputs.
requireLook up a protocol that must exist.

Member details ​

define ​

Static member.

Compile and construct a catalog from definitions in one call.

ts
CommandCatalog.define<Value extends object, Result = Value, Args extends unknown[] = [], Id extends string = string>(definitions: Readonly<Record<Id, CommandDefinition<Value, Result, Args>>>, defaults?: Partial<CommandDefinition<Value, Result, Args>>, options?: CommandCatalogOptions): CommandCatalog<Value, Result, Args, Id>

Compile definitions and wrap them in a sealed catalog.

Type parameterConstraintDefault type
Valueobject—
Result—Value
Argsunknown[][]
Idstringstring
ParameterTypePassingDescription
definitionsReadonly<Record<Id, CommandDefinition<Value, Result, Args>>>Required—
defaultsPartial<CommandDefinition<Value, Result, Args>>Optional—
optionsCommandCatalogOptionsOptional—
Fields of defaults
FieldTypeRequiredDescription
categoryInteractionCategory | undefinedOptionalRead-only. Declared purpose; validated against the frozen category list.
versionnumber | undefinedOptionalRead-only. Protocol version, used to reject incompatible registrations.
descriptionstring | undefinedOptionalRead-only. See the type definition and usage context.
terminalboolean | undefinedOptionalRead-only. Marks a command that ends the interaction.
discriminator{ readonly field: string; readonly value: string; } | undefinedOptionalRead-only. Constant field identifying the command; its value is forced to the command id.
fieldsreadonly string[] | Readonly<Record<string, ProtocolField>> | undefinedOptionalRead-only. Field declarations by name, or an ordered list of field names.
ownedFieldsreadonly string[] | undefinedOptionalRead-only. Fields the program writes; may name fields not declared in fields.
additionalPropertiesboolean | undefinedOptionalRead-only. Whether fields outside the declaration are rejected; defaults to the compiler policy.
optionalPresence"own" | "defined" | undefinedOptionalRead-only. 'defined' rejects an explicitly undefined optional property; 'own' preserves its presence.
modesreadonly string[] | undefinedOptionalRead-only. App-declared modes in which the command is available.
errorProtocolReason<Value, Args> | undefinedOptionalRead-only. Rejection wording for the command as a whole.
tagsreadonly string[] | undefinedOptionalRead-only. Diagnostic tags attached to rejections from this command.
checksreadonly ProtocolCheck<Value, Args>[] | undefinedOptionalRead-only. Declarative rejection rules, evaluated in order after the structural checks.
refine((value: Value, ...args: Args) => void) | undefinedOptionalRead-only. Domain checks/bindings only; invoked after structural and declarative checks.
format((value: Value, ...args: Args) => Result) | undefinedOptionalRead-only. Formats the validated value into the command result.
Fields of options
FieldTypeRequiredDescription
modeFieldstring | undefinedOptionalRead-only. Field carrying the mode selector, when modes are used.
unknownErrorstring | Error | undefinedOptionalRead-only. Rejection wording for an unknown command selector.
modeErrorstring | Error | undefinedOptionalRead-only. Rejection wording for a command used outside its declared modes.
ownershipErrorstring | Error | undefinedOptionalRead-only. Rejection wording for a model-supplied owned field.
tagsreadonly string[] | undefinedOptionalRead-only. Diagnostic tags attached to every rejection from this catalog.

Returns: CommandCatalog<Value, Result, Args, Id>.

compile ​

Static member.

Compile a set of definitions with shared envelope fields.

ts
CommandCatalog.compile<Value extends object, Result = Value, Args extends unknown[] = [], Id extends string = string>(definitions: Readonly<Record<Id, CommandDefinition<Value, Result, Args>>>, defaults?: Partial<CommandDefinition<Value, Result, Args>>): Readonly<Record<Id, Command<Value, Result, Args>>>

Compile a whole catalog with shared envelope fields.

Applications declare only their own data and handlers. Defaults are merged in this order: unrelated default keys, then the command's own keys, with fields, checks and tags concatenated so shared envelope checks always run before per-command checks.

Type parameterConstraintDefault type
Valueobject—
Result—Value
Argsunknown[][]
Idstringstring
ParameterTypePassingDescription
definitionsReadonly<Record<Id, CommandDefinition<Value, Result, Args>>>Required—
defaultsPartial<CommandDefinition<Value, Result, Args>>Optional—
Fields of defaults
FieldTypeRequiredDescription
categoryInteractionCategory | undefinedOptionalRead-only. Declared purpose; validated against the frozen category list.
versionnumber | undefinedOptionalRead-only. Protocol version, used to reject incompatible registrations.
descriptionstring | undefinedOptionalRead-only. See the type definition and usage context.
terminalboolean | undefinedOptionalRead-only. Marks a command that ends the interaction.
discriminator{ readonly field: string; readonly value: string; } | undefinedOptionalRead-only. Constant field identifying the command; its value is forced to the command id.
fieldsreadonly string[] | Readonly<Record<string, ProtocolField>> | undefinedOptionalRead-only. Field declarations by name, or an ordered list of field names.
ownedFieldsreadonly string[] | undefinedOptionalRead-only. Fields the program writes; may name fields not declared in fields.
additionalPropertiesboolean | undefinedOptionalRead-only. Whether fields outside the declaration are rejected; defaults to the compiler policy.
optionalPresence"own" | "defined" | undefinedOptionalRead-only. 'defined' rejects an explicitly undefined optional property; 'own' preserves its presence.
modesreadonly string[] | undefinedOptionalRead-only. App-declared modes in which the command is available.
errorProtocolReason<Value, Args> | undefinedOptionalRead-only. Rejection wording for the command as a whole.
tagsreadonly string[] | undefinedOptionalRead-only. Diagnostic tags attached to rejections from this command.
checksreadonly ProtocolCheck<Value, Args>[] | undefinedOptionalRead-only. Declarative rejection rules, evaluated in order after the structural checks.
refine((value: Value, ...args: Args) => void) | undefinedOptionalRead-only. Domain checks/bindings only; invoked after structural and declarative checks.
format((value: Value, ...args: Args) => Result) | undefinedOptionalRead-only. Formats the validated value into the command result.

Returns: Readonly<Record<Id, Command<Value, Result, Args>>>.

set ​

Instance method.

Install one compiled command during construction.

ts
set(id: string, command: Command<Value, Result, Args>): CommandCatalog<Value, Result, Args, Id>

Install one compiled command during construction.

ParameterTypePassingDescription
idstringRequired—
commandCommand<Value, Result, Args>Required—
Fields of command
FieldTypeRequiredDescription
categoryInteractionCategory | undefinedOptionalRead-only. See the type definition and usage context.
versionnumber | undefinedOptionalRead-only. See the type definition and usage context.
descriptionstring | undefinedOptionalRead-only. See the type definition and usage context.
terminalboolean | undefinedOptionalRead-only. See the type definition and usage context.
fieldSchemasRecord<string, unknown>RequiredRead-only. Per-field schemas, including the forced discriminator field.
modelJsonSchemaRecord<string, unknown>RequiredRead-only. Schema for model output; only modelRequired fields are required here.
inputJsonSchemaRecord<string, unknown>RequiredRead-only. Schema for runtime input; every required field is required here.
modesreadonly string[] | undefinedOptionalRead-only. See the type definition and usage context.
ownedFieldsreadonly string[]RequiredRead-only. Field names the program owns; the model must not supply them.
keys(value: Record<string, unknown>) => string[]RequiredSelector values carried by value, used to resolve the command before parsing.
assert(value: Value, ...args: Args) => voidRequiredValidates without formatting; throws on the first failed check.
parse(value: Value, ...args: Args) => ResultRequiredValidates and returns the formatted result.

Returns: CommandCatalog<Value, Result, Args, Id>.

delete ​

Instance method.

Removal is not supported.

ts
delete(_id: string): boolean

Removal is not supported.

ParameterTypePassingDescription
_idstringRequired—

Returns: boolean.

clear ​

Instance method.

Clearing is not supported.

ts
clear(): void

Clearing is not supported.

No call parameters.

Returns: void.

toRecord ​

Instance method.

Explicit dictionary projection; definitions always remains an ordered array.

ts
toRecord(): Readonly<Record<Id, Command<Value, Result, Args>>>

Explicit dictionary projection; definitions always remains an ordered array.

No call parameters.

Returns: Readonly<Record<Id, Command<Value, Result, Args>>>.

manifest ​

Instance method.

The same declarations drive purpose-specific menus, documentation and handler binding.

ts
manifest(category?: InteractionCategory): readonly InteractionDescriptor[]

The same declarations drive purpose-specific menus, documentation and handler binding.

ParameterTypePassingDescription
categoryInteractionCategory | undefinedOptional—

Returns: readonly InteractionDescriptor[].

parse ​

Instance method.

Validate and parse one payload as the named command.

Checks run before the command's own parser: the id must exist, the mode (when configured) must be allowed, and no other command may claim a field that this payload sets. The last rule prevents one command from silently consuming another command's data.

ts
parse(id: string, value: Value, ...args: Args): Result

Validate and parse one payload as the named command.

Checks run before the command's own parser: the id must exist, the mode (when configured) must be allowed, and no other command may claim a field that this payload sets. The last rule prevents one command from silently consuming another command's data.

ParameterTypePassingDescription
idstringRequired—
valueValueRequired—
argsArgsRest parameter—

Returns: Result.

Awaited value: Awaited<Result>.

ids ​

Instance method.

ts
ids(): readonly string[]

No call parameters.

Returns: readonly string[].

require ​

Instance method.

Look up a protocol that must exist.

ts
require(id: string): Command<Value, Result, Args> & { readonly id: Id; }

Look up a protocol that must exist.

ParameterTypePassingDescription
idstringRequired—

Returns: Command<Value, Result, Args> & { readonly id: Id; }.

Return value structure
FieldTypeRequiredDescription
categoryInteractionCategory | undefinedOptionalRead-only. See the type definition and usage context.
versionnumber | undefinedOptionalRead-only. See the type definition and usage context.
descriptionstring | undefinedOptionalRead-only. See the type definition and usage context.
terminalboolean | undefinedOptionalRead-only. See the type definition and usage context.
fieldSchemasRecord<string, unknown>RequiredRead-only. Per-field schemas, including the forced discriminator field.
modelJsonSchemaRecord<string, unknown>RequiredRead-only. Schema for model output; only modelRequired fields are required here.
inputJsonSchemaRecord<string, unknown>RequiredRead-only. Schema for runtime input; every required field is required here.
modesreadonly string[] | undefinedOptionalRead-only. See the type definition and usage context.
ownedFieldsreadonly string[]RequiredRead-only. Field names the program owns; the model must not supply them.
keys(value: Record<string, unknown>) => string[]RequiredSelector values carried by value, used to resolve the command before parsing.
assert(value: Value, ...args: Args) => voidRequiredValidates without formatting; throws on the first failed check.
parse(value: Value, ...args: Args) => ResultRequiredValidates and returns the formatted result.
idIdRequiredRead-only. See the type definition and usage context.

Examples ​

First define one explanatory command and validate it ​

Beginner · Node.js

ts
import { Interaction } from '@jangts/agent-core/kits/interaction';
const protocol = Interaction.define({
  commandField: 'type', commands: {
    reply: { category: 'presentation', description: '展示已确认说明', fields: { text: { required: true, jsonSchema: { type: 'string' } } },
      checks: [{ occur: value => typeof value.text !== 'string', error: 'text 必须是字符串' }] },
  },
});
console.log(protocol.receive({ type: 'reply', text: '普通对象也能实现接口。' }));
console.log(protocol.modelJsonSchema);
js
import { Interaction } from '@jangts/agent-core/kits/interaction';
const protocol = Interaction.define({
    commandField: 'type', commands: {
        reply: { category: 'presentation', description: '展示已确认说明', fields: { text: { required: true, jsonSchema: { type: 'string' } } },
            checks: [{ occur: value => typeof value.text !== 'string', error: 'text 必须是字符串' }] },
    },
});
console.log(protocol.receive({ type: 'reply', text: '普通对象也能实现接口。' }));
console.log(protocol.modelJsonSchema);

Keep the same protocol and add complete handler binding ​

Configuration · Node.js

ts
import { Interaction } from '@jangts/agent-core/kits/interaction';
const protocol = Interaction.define({
  commandField: 'type', commands: {
    reply: { category: 'presentation', description: '展示已确认说明', fields: { text: { required: true, jsonSchema: { type: 'string' } } }, checks: [{ occur: value => typeof value.text !== 'string', error: 'text 必须是字符串' }] },
    unavailable: { category: 'receipt', description: '说明资料不可用', fields: {} },
  },
});
const dispatcher = Interaction.bind(protocol, {
  reply: value => '说明:' + String(value.text),
  unavailable: () => '资料暂不可用',
});
console.log(dispatcher.dispatch({ type: 'reply', text: '普通对象也能实现接口。' }, undefined));
console.log(dispatcher.catalog);
js
import { Interaction } from '@jangts/agent-core/kits/interaction';
const protocol = Interaction.define({
    commandField: 'type', commands: {
        reply: { category: 'presentation', description: '展示已确认说明', fields: { text: { required: true, jsonSchema: { type: 'string' } } }, checks: [{ occur: value => typeof value.text !== 'string', error: 'text 必须是字符串' }] },
        unavailable: { category: 'receipt', description: '说明资料不可用', fields: {} },
    },
});
const dispatcher = Interaction.bind(protocol, {
    reply: value => '说明:' + String(value.text),
    unavailable: () => '资料暂不可用',
});
console.log(dispatcher.dispatch({ type: 'reply', text: '普通对象也能实现接口。' }, undefined));
console.log(dispatcher.catalog);

Reuse the single-command and batch compilation entries directly ​

Extension · Node.js

When you use Interaction the selector is generated for you; when you use defineCommand yourself you may also supply discriminator explicitly. This example does not execute any tool.

ts
import { defineCommand, compileCommands, commandSchema, CommandCatalog } from '@jangts/agent-core/kits/interaction';
const reply = defineCommand({ fields: { text: { required: true } }, checks: [{ occur: value => typeof value.text !== 'string', error: '需要文本' }] });
console.log(reply.parse({ text: '接口说明' }));
const compiled = compileCommands({ reply: { fields: { text: { required: true } } } });
const commands = new CommandCatalog(Object.entries(compiled));
console.log(commandSchema('reply', commands.require('reply')), commands.manifest());
js
import { defineCommand, compileCommands, commandSchema, CommandCatalog } from '@jangts/agent-core/kits/interaction';
const reply = defineCommand({ fields: { text: { required: true } }, checks: [{ occur: value => typeof value.text !== 'string', error: '需要文本' }] });
console.log(reply.parse({ text: '接口说明' }));
const compiled = compileCommands({ reply: { fields: { text: { required: true } } } });
const commands = new CommandCatalog(Object.entries(compiled));
console.log(commandSchema('reply', commands.require('reply')), commands.manifest());

API reference, usage examples and developer guides.