Skip to content
中文

InteractionProtocol ​

KIT · class · Runtime value

Web/AI payload family. HTTP/SSE framing and actual command execution remain separate ports.

Every command registered here gets the envelope's discriminator forced to its own id, so a payload cannot claim one command while carrying another command's data.

Import ​

ts
import { Interaction } from '@jangts/agent-core/kits/interaction';
js
import { Interaction } 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 InteractionProtocol<Value, Result, Args, Id>

Type parameters ​

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

Constructor ​

ts
new InteractionProtocol<Value extends object = Record<string, unknown>, Result = Value, Args extends unknown[] = [], Id extends string = string>(definition: InteractionProtocolDefinition<Value, Result, Args, Id>): InteractionProtocol<Value, Result, Args, Id>
ParameterTypePassingDescription
definitionInteractionProtocolDefinition<Value, Result, Args, Id>Required—
Fields of definition
FieldTypeRequiredDescription
descriptionstring | undefinedOptionalRead-only. See the type definition and usage context.
tagsreadonly string[] | undefinedOptionalRead-only. Diagnostic tags attached to rejections from this command. Diagnostic tags attached to every rejection from this catalog.
errorProtocolReason<Value, Args> | undefinedOptionalRead-only. Rejection wording for the command as a whole.
fieldsreadonly string[] | Readonly<Record<string, ProtocolField>> | undefinedOptionalRead-only. Field declarations by name, or an ordered list of field names.
versionnumber | undefinedOptionalRead-only. Protocol version, used to reject incompatible registrations.
format((value: Value, ...args: Args) => Result) | undefinedOptionalRead-only. Formats the validated value into the command result.
categoryInteractionCategory | undefinedOptionalRead-only. Declared purpose; validated against the frozen category list.
terminalboolean | undefinedOptionalRead-only. Marks a command that ends the interaction.
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.
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.
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.
commandFieldstringRequiredRead-only. Field carrying the command id; also the canonical key in normalized output.
commandAliasesreadonly string[] | undefinedOptionalRead-only. Accepted only on input. Schema and normalized output always use commandField.
selectionErrorProtocolReason<Value, Args> | undefinedOptionalRead-only. Rejection wording when a payload selects no command.
commandsReadonly<Record<Id, CommandDefinition<Value, Result, Args>>>RequiredRead-only. See the type definition and usage context.

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

Static properties ​

FieldTypeRequiredDescription
categoriesreadonly InteractionCategory[]RequiredRead-only. See the type definition and usage context.

Instance properties ​

FieldTypeRequiredDescription
commandFieldstringRequiredRead-only. Field carrying the command id in a payload.
commandSelectorsreadonly string[]RequiredRead-only. Accepted selector names: the command field first, then any declared aliases.
commandsCommandCatalog<Value, Result, Args, Id>RequiredRead-only. Sealed catalog of the compiled commands.
modelJsonSchemaRecord<string, unknown>RequiredRead-only. JSON schema for the model, expressed as a union of the per-command schemas.
inputJsonSchemaRecord<string, unknown>RequiredRead-only. Strict JSON schema for transport input, expressed as a union of per-command schemas.

Member index ​

MemberPurpose
defineStatic. See the overload below for full inputs and outputs.
CommandsStatic. See the overload below for full inputs and outputs.
defineCommandStatic. See the overload below for full inputs and outputs.
commandSchemaStatic. See the overload below for full inputs and outputs.
bindStatic. See the overload below for full inputs and outputs.
parseParse a payload and return only the result.
receiveRetain the selected command id separately from a formatter's output.

Member details ​

define ​

Static member.

ts
InteractionProtocol.define<Value extends object = Record<string, unknown>, Result = Value, Args extends unknown[] = [], Id extends string = string>(definition: InteractionProtocolDefinition<Value, Result, Args, Id>): InteractionProtocol<Value, Result, Args, Id>

Construct a protocol from one definition.

Type parameterConstraintDefault type
ValueobjectRecord<string, unknown>
Result—Value
Argsunknown[][]
Idstringstring
ParameterTypePassingDescription
definitionInteractionProtocolDefinition<Value, Result, Args, Id>Required—
Fields of definition
FieldTypeRequiredDescription
descriptionstring | undefinedOptionalRead-only. See the type definition and usage context.
tagsreadonly string[] | undefinedOptionalRead-only. Diagnostic tags attached to rejections from this command. Diagnostic tags attached to every rejection from this catalog.
errorProtocolReason<Value, Args> | undefinedOptionalRead-only. Rejection wording for the command as a whole.
fieldsreadonly string[] | Readonly<Record<string, ProtocolField>> | undefinedOptionalRead-only. Field declarations by name, or an ordered list of field names.
versionnumber | undefinedOptionalRead-only. Protocol version, used to reject incompatible registrations.
format((value: Value, ...args: Args) => Result) | undefinedOptionalRead-only. Formats the validated value into the command result.
categoryInteractionCategory | undefinedOptionalRead-only. Declared purpose; validated against the frozen category list.
terminalboolean | undefinedOptionalRead-only. Marks a command that ends the interaction.
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.
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.
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.
commandFieldstringRequiredRead-only. Field carrying the command id; also the canonical key in normalized output.
commandAliasesreadonly string[] | undefinedOptionalRead-only. Accepted only on input. Schema and normalized output always use commandField.
selectionErrorProtocolReason<Value, Args> | undefinedOptionalRead-only. Rejection wording when a payload selects no command.
commandsReadonly<Record<Id, CommandDefinition<Value, Result, Args>>>RequiredRead-only. See the type definition and usage context.

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

Commands ​

Static member.

ts
new InteractionProtocol.Commands<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>.

defineCommand ​

Static member.

ts
InteractionProtocol.defineCommand<Value extends object = Record<string, unknown>, Result = Value, Args extends unknown[] = []>(definition: CommandDefinition<Value, Result, Args>): Command<Value, Result, Args>

Compile declarations once. Parsing is synchronous and never executes a registered tool.

Two schemas are produced from one declaration: modelJsonSchema marks only fields the model must fill, while inputJsonSchema marks every required field. A discriminator, when present, is prepended as a required constant field.

Type parameterConstraintDefault type
ValueobjectRecord<string, unknown>
Result—Value
Argsunknown[][]
ParameterTypePassingDescription
definitionCommandDefinition<Value, Result, Args>Required—
Fields of definition
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>>RequiredRead-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: Command<Value, Result, Args>.

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.

commandSchema ​

Static member.

ts
InteractionProtocol.commandSchema(id: string, protocol: ProtocolShape, discriminator?: string): Record<string, unknown>

Build a JSON schema for one command id.

Prefer compiled schemas; retain the existing open-schema contract for dynamic host protocols. A protocol without fieldSchemas falls back to an open object that only pins the discriminator, which keeps legacy hosts working without weakening compiled ones.

ParameterTypePassingDescription
idstringRequired—
protocolProtocolShapeRequired—
discriminatorstringOptional—
Fields of protocol
FieldTypeRequiredDescription
modelJsonSchemaRecord<string, unknown> | undefinedOptionalRead-only. Optional schema for model output.
inputJsonSchemaRecord<string, unknown> | undefinedOptionalRead-only. Optional schema for runtime input.
fieldSchemasRecord<string, unknown> | undefinedOptionalRead-only. Optional per-field schemas.
keys(value: Record<string, unknown>) => string[]RequiredSelector values carried by value.

Returns: Record<string, unknown>.

bind ​

Static member.

ts
InteractionProtocol.bind<Value extends object, Parsed, Args extends unknown[], Id extends string, Context, Output>(protocol: { readonly commands: Pick<InteractionProtocol<Value, Parsed, Args, Id>["commands"], "manifest">; receive(value: Value, ...args: Args): { id: Id; result: Parsed; }; }, handlers: InteractionHandlers<Id, Parsed, Context, Output>): Readonly<{ catalog: readonly Readonly<{ id: string; category: InteractionCategory | undefined; description: string | undefined; terminal: boolean | undefined; modes: readonly string[] | undefined; }>[]; dispatch(value: Value, context: Context, ...args: Args): Output; }>

Bind every registered transfer command to a local handler. Models cannot add handlers.

Type parameterConstraintDefault type
Valueobject—
Parsed——
Argsunknown[]—
Idstring—
Context——
Output——
ParameterTypePassingDescription
protocol{ readonly commands: Pick<InteractionProtocol<Value, Parsed, Args, Id>["commands"], "manifest">; receive(value: Value, ...args: Args): { id: Id; result: Parsed; }; }Required—
handlersReadonly<Record<Id, (value: Parsed, context: Context) => Output>>Required—
Fields of protocol
FieldTypeRequiredDescription
commandsPick<CommandCatalog<Value, Parsed, Args, Id>, "manifest">RequiredRead-only. See the type definition and usage context.
receive(value: Value, ...args: Args) => { id: Id; result: Parsed; }RequiredSee the type definition and usage context.

Returns: Readonly<{ catalog: readonly Readonly<{ id: string; category: InteractionCategory \| undefined; description: string \| undefined; terminal: boolean \| undefined; modes: readonly string[] \| undefined; }>[]; dispatch(value: Value, context: Context, ...args: Args): Output; }>.

Return value structure
FieldTypeRequiredDescription
catalogreadonly Readonly<{ id: string; category: InteractionCategory | undefined; description: string | undefined; terminal: boolean | undefined; modes: readonly string[] | undefined; }>[]RequiredSee the type definition and usage context.
dispatch(value: Value, context: Context, ...args: Args) => OutputRequiredSee the type definition and usage context.

parse ​

Instance method.

Parse a payload and return only the result.

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

Parse a payload and return only the result.

ParameterTypePassingDescription
valueValueRequired—
argsArgsRest parameter—

Returns: Result.

Awaited value: Awaited<Result>.

receive ​

Instance method.

Retain the selected command id separately from a formatter's output.

ts
receive(value: Value, ...args: Args): { id: Id; result: Result; }

Retain the selected command id separately from a formatter's output.

ParameterTypePassingDescription
valueValueRequired—
argsArgsRest parameter—

Returns: { id: Id; result: Result; }.

Return value structure
FieldTypeRequiredDescription
idIdRequiredSee the type definition and usage context.
resultResultRequiredSee 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.