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
import { Interaction } from '@jangts/agent-core/kits/interaction';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
class InteractionProtocol<Value, Result, Args, Id>Type parameters
| Type parameter | Constraint | Default type |
|---|---|---|
Value | object | Record<string, unknown> |
Result | — | Value |
Args | unknown[] | [] |
Id | string | string |
Constructor
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>| Parameter | Type | Passing | Description |
|---|---|---|---|
definition | InteractionProtocolDefinition<Value, Result, Args, Id> | Required | — |
Fields of definition
| Field | Type | Required | Description |
|---|---|---|---|
description | string | undefined | Optional | Read-only. See the type definition and usage context. |
tags | readonly string[] | undefined | Optional | Read-only. Diagnostic tags attached to rejections from this command. Diagnostic tags attached to every rejection from this catalog. |
error | ProtocolReason<Value, Args> | undefined | Optional | Read-only. Rejection wording for the command as a whole. |
fields | readonly string[] | Readonly<Record<string, ProtocolField>> | undefined | Optional | Read-only. Field declarations by name, or an ordered list of field names. |
version | number | undefined | Optional | Read-only. Protocol version, used to reject incompatible registrations. |
format | ((value: Value, ...args: Args) => Result) | undefined | Optional | Read-only. Formats the validated value into the command result. |
category | InteractionCategory | undefined | Optional | Read-only. Declared purpose; validated against the frozen category list. |
terminal | boolean | undefined | Optional | Read-only. Marks a command that ends the interaction. |
additionalProperties | boolean | undefined | Optional | Read-only. Whether fields outside the declaration are rejected; defaults to the compiler policy. |
optionalPresence | "own" | "defined" | undefined | Optional | Read-only. 'defined' rejects an explicitly undefined optional property; 'own' preserves its presence. |
checks | readonly ProtocolCheck<Value, Args>[] | undefined | Optional | Read-only. Declarative rejection rules, evaluated in order after the structural checks. |
refine | ((value: Value, ...args: Args) => void) | undefined | Optional | Read-only. Domain checks/bindings only; invoked after structural and declarative checks. |
modeField | string | undefined | Optional | Read-only. Field carrying the mode selector, when modes are used. |
unknownError | string | Error | undefined | Optional | Read-only. Rejection wording for an unknown command selector. |
modeError | string | Error | undefined | Optional | Read-only. Rejection wording for a command used outside its declared modes. |
ownershipError | string | Error | undefined | Optional | Read-only. Rejection wording for a model-supplied owned field. |
commandField | string | Required | Read-only. Field carrying the command id; also the canonical key in normalized output. |
commandAliases | readonly string[] | undefined | Optional | Read-only. Accepted only on input. Schema and normalized output always use commandField. |
selectionError | ProtocolReason<Value, Args> | undefined | Optional | Read-only. Rejection wording when a payload selects no command. |
commands | Readonly<Record<Id, CommandDefinition<Value, Result, Args>>> | Required | Read-only. See the type definition and usage context. |
Returns: InteractionProtocol<Value, Result, Args, Id>.
Static properties
| Field | Type | Required | Description |
|---|---|---|---|
categories | readonly InteractionCategory[] | Required | Read-only. See the type definition and usage context. |
Instance properties
| Field | Type | Required | Description |
|---|---|---|---|
commandField | string | Required | Read-only. Field carrying the command id in a payload. |
commandSelectors | readonly string[] | Required | Read-only. Accepted selector names: the command field first, then any declared aliases. |
commands | CommandCatalog<Value, Result, Args, Id> | Required | Read-only. Sealed catalog of the compiled commands. |
modelJsonSchema | Record<string, unknown> | Required | Read-only. JSON schema for the model, expressed as a union of the per-command schemas. |
inputJsonSchema | Record<string, unknown> | Required | Read-only. Strict JSON schema for transport input, expressed as a union of per-command schemas. |
Member index
| Member | Purpose |
|---|---|
define | Static. See the overload below for full inputs and outputs. |
Commands | Static. See the overload below for full inputs and outputs. |
defineCommand | Static. See the overload below for full inputs and outputs. |
commandSchema | Static. See the overload below for full inputs and outputs. |
bind | Static. See the overload below for full inputs and outputs. |
parse | Parse a payload and return only the result. |
receive | Retain the selected command id separately from a formatter's output. |
Member details
define
Static member.
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 parameter | Constraint | Default type |
|---|---|---|
Value | object | Record<string, unknown> |
Result | — | Value |
Args | unknown[] | [] |
Id | string | string |
| Parameter | Type | Passing | Description |
|---|---|---|---|
definition | InteractionProtocolDefinition<Value, Result, Args, Id> | Required | — |
Fields of definition
| Field | Type | Required | Description |
|---|---|---|---|
description | string | undefined | Optional | Read-only. See the type definition and usage context. |
tags | readonly string[] | undefined | Optional | Read-only. Diagnostic tags attached to rejections from this command. Diagnostic tags attached to every rejection from this catalog. |
error | ProtocolReason<Value, Args> | undefined | Optional | Read-only. Rejection wording for the command as a whole. |
fields | readonly string[] | Readonly<Record<string, ProtocolField>> | undefined | Optional | Read-only. Field declarations by name, or an ordered list of field names. |
version | number | undefined | Optional | Read-only. Protocol version, used to reject incompatible registrations. |
format | ((value: Value, ...args: Args) => Result) | undefined | Optional | Read-only. Formats the validated value into the command result. |
category | InteractionCategory | undefined | Optional | Read-only. Declared purpose; validated against the frozen category list. |
terminal | boolean | undefined | Optional | Read-only. Marks a command that ends the interaction. |
additionalProperties | boolean | undefined | Optional | Read-only. Whether fields outside the declaration are rejected; defaults to the compiler policy. |
optionalPresence | "own" | "defined" | undefined | Optional | Read-only. 'defined' rejects an explicitly undefined optional property; 'own' preserves its presence. |
checks | readonly ProtocolCheck<Value, Args>[] | undefined | Optional | Read-only. Declarative rejection rules, evaluated in order after the structural checks. |
refine | ((value: Value, ...args: Args) => void) | undefined | Optional | Read-only. Domain checks/bindings only; invoked after structural and declarative checks. |
modeField | string | undefined | Optional | Read-only. Field carrying the mode selector, when modes are used. |
unknownError | string | Error | undefined | Optional | Read-only. Rejection wording for an unknown command selector. |
modeError | string | Error | undefined | Optional | Read-only. Rejection wording for a command used outside its declared modes. |
ownershipError | string | Error | undefined | Optional | Read-only. Rejection wording for a model-supplied owned field. |
commandField | string | Required | Read-only. Field carrying the command id; also the canonical key in normalized output. |
commandAliases | readonly string[] | undefined | Optional | Read-only. Accepted only on input. Schema and normalized output always use commandField. |
selectionError | ProtocolReason<Value, Args> | undefined | Optional | Read-only. Rejection wording when a payload selects no command. |
commands | Readonly<Record<Id, CommandDefinition<Value, Result, Args>>> | Required | Read-only. See the type definition and usage context. |
Returns: InteractionProtocol<Value, Result, Args, Id>.
Commands
Static member.
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>| Parameter | Type | Passing | Description |
|---|---|---|---|
definitions | Iterable<readonly [Id, Command<Value, Result, Args>]> | Required | — |
options | CommandCatalogOptions | Optional | — |
Fields of options
| Field | Type | Required | Description |
|---|---|---|---|
modeField | string | undefined | Optional | Read-only. Field carrying the mode selector, when modes are used. |
unknownError | string | Error | undefined | Optional | Read-only. Rejection wording for an unknown command selector. |
modeError | string | Error | undefined | Optional | Read-only. Rejection wording for a command used outside its declared modes. |
ownershipError | string | Error | undefined | Optional | Read-only. Rejection wording for a model-supplied owned field. |
tags | readonly string[] | undefined | Optional | Read-only. Diagnostic tags attached to every rejection from this catalog. |
Returns: CommandCatalog<Value, Result, Args, Id>.
defineCommand
Static member.
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 parameter | Constraint | Default type |
|---|---|---|
Value | object | Record<string, unknown> |
Result | — | Value |
Args | unknown[] | [] |
| Parameter | Type | Passing | Description |
|---|---|---|---|
definition | CommandDefinition<Value, Result, Args> | Required | — |
Fields of definition
| Field | Type | Required | Description |
|---|---|---|---|
category | InteractionCategory | undefined | Optional | Read-only. Declared purpose; validated against the frozen category list. |
version | number | undefined | Optional | Read-only. Protocol version, used to reject incompatible registrations. |
description | string | undefined | Optional | Read-only. See the type definition and usage context. |
terminal | boolean | undefined | Optional | Read-only. Marks a command that ends the interaction. |
discriminator | { readonly field: string; readonly value: string; } | undefined | Optional | Read-only. Constant field identifying the command; its value is forced to the command id. |
fields | readonly string[] | Readonly<Record<string, ProtocolField>> | Required | Read-only. Field declarations by name, or an ordered list of field names. |
ownedFields | readonly string[] | undefined | Optional | Read-only. Fields the program writes; may name fields not declared in fields. |
additionalProperties | boolean | undefined | Optional | Read-only. Whether fields outside the declaration are rejected; defaults to the compiler policy. |
optionalPresence | "own" | "defined" | undefined | Optional | Read-only. 'defined' rejects an explicitly undefined optional property; 'own' preserves its presence. |
modes | readonly string[] | undefined | Optional | Read-only. App-declared modes in which the command is available. |
error | ProtocolReason<Value, Args> | undefined | Optional | Read-only. Rejection wording for the command as a whole. |
tags | readonly string[] | undefined | Optional | Read-only. Diagnostic tags attached to rejections from this command. |
checks | readonly ProtocolCheck<Value, Args>[] | undefined | Optional | Read-only. Declarative rejection rules, evaluated in order after the structural checks. |
refine | ((value: Value, ...args: Args) => void) | undefined | Optional | Read-only. Domain checks/bindings only; invoked after structural and declarative checks. |
format | ((value: Value, ...args: Args) => Result) | undefined | Optional | Read-only. Formats the validated value into the command result. |
Returns: Command<Value, Result, Args>.
Return value structure
| Field | Type | Required | Description |
|---|---|---|---|
category | InteractionCategory | undefined | Optional | Read-only. See the type definition and usage context. |
version | number | undefined | Optional | Read-only. See the type definition and usage context. |
description | string | undefined | Optional | Read-only. See the type definition and usage context. |
terminal | boolean | undefined | Optional | Read-only. See the type definition and usage context. |
fieldSchemas | Record<string, unknown> | Required | Read-only. Per-field schemas, including the forced discriminator field. |
modelJsonSchema | Record<string, unknown> | Required | Read-only. Schema for model output; only modelRequired fields are required here. |
inputJsonSchema | Record<string, unknown> | Required | Read-only. Schema for runtime input; every required field is required here. |
modes | readonly string[] | undefined | Optional | Read-only. See the type definition and usage context. |
ownedFields | readonly string[] | Required | Read-only. Field names the program owns; the model must not supply them. |
keys | (value: Record<string, unknown>) => string[] | Required | Selector values carried by value, used to resolve the command before parsing. |
assert | (value: Value, ...args: Args) => void | Required | Validates without formatting; throws on the first failed check. |
parse | (value: Value, ...args: Args) => Result | Required | Validates and returns the formatted result. |
commandSchema
Static member.
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.
| Parameter | Type | Passing | Description |
|---|---|---|---|
id | string | Required | — |
protocol | ProtocolShape | Required | — |
discriminator | string | Optional | — |
Fields of protocol
| Field | Type | Required | Description |
|---|---|---|---|
modelJsonSchema | Record<string, unknown> | undefined | Optional | Read-only. Optional schema for model output. |
inputJsonSchema | Record<string, unknown> | undefined | Optional | Read-only. Optional schema for runtime input. |
fieldSchemas | Record<string, unknown> | undefined | Optional | Read-only. Optional per-field schemas. |
keys | (value: Record<string, unknown>) => string[] | Required | Selector values carried by value. |
Returns: Record<string, unknown>.
bind
Static member.
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 parameter | Constraint | Default type |
|---|---|---|
Value | object | — |
Parsed | — | — |
Args | unknown[] | — |
Id | string | — |
Context | — | — |
Output | — | — |
| Parameter | Type | Passing | Description |
|---|---|---|---|
protocol | { readonly commands: Pick<InteractionProtocol<Value, Parsed, Args, Id>["commands"], "manifest">; receive(value: Value, ...args: Args): { id: Id; result: Parsed; }; } | Required | — |
handlers | Readonly<Record<Id, (value: Parsed, context: Context) => Output>> | Required | — |
Fields of protocol
| Field | Type | Required | Description |
|---|---|---|---|
commands | Pick<CommandCatalog<Value, Parsed, Args, Id>, "manifest"> | Required | Read-only. See the type definition and usage context. |
receive | (value: Value, ...args: Args) => { id: Id; result: Parsed; } | Required | See 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
| Field | Type | Required | Description |
|---|---|---|---|
catalog | readonly Readonly<{ id: string; category: InteractionCategory | undefined; description: string | undefined; terminal: boolean | undefined; modes: readonly string[] | undefined; }>[] | Required | See the type definition and usage context. |
dispatch | (value: Value, context: Context, ...args: Args) => Output | Required | See the type definition and usage context. |
parse
Instance method.
Parse a payload and return only the result.
parse(value: Value, ...args: Args): ResultParse a payload and return only the result.
| Parameter | Type | Passing | Description |
|---|---|---|---|
value | Value | Required | — |
args | Args | Rest parameter | — |
Returns: Result.
Awaited value: Awaited<Result>.
receive
Instance method.
Retain the selected command id separately from a formatter's output.
receive(value: Value, ...args: Args): { id: Id; result: Result; }Retain the selected command id separately from a formatter's output.
| Parameter | Type | Passing | Description |
|---|---|---|---|
value | Value | Required | — |
args | Args | Rest parameter | — |
Returns: { id: Id; result: Result; }.
Return value structure
| Field | Type | Required | Description |
|---|---|---|---|
id | Id | Required | See the type definition and usage context. |
result | Result | Required | See the type definition and usage context. |
Examples
- Interaction: declare commands and bind local handlers: The fields, purpose, selector, checks, and handler of a command come from one declaration; the model cannot add executable handlers.
First define one explanatory command and validate it
Beginner · Node.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);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
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);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.
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());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());Related policy source
- Fields, checks, and the model Schema
- Selectors and command receiving
- Bind local handlers by validated command