Skip to content
中文

AgentWorkflow ​

CORE · class · Runtime value

Executable catalog: validate references and bounded cycles before any handler runs.

Validation happens once, at construction, so traversal can assume every target exists and every cycle is budget-bounded.

Import ​

ts
import { AgentWorkflow } from '@jangts/agent-core/engine';
js
import { AgentWorkflow } from '@jangts/agent-core/engine';

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

Definition ​

ts
class AgentWorkflow<State, Result, Runtime>

Type parameters ​

Type parameterConstraintDefault type
State——
Result——
Runtime—undefined

Constructor ​

ts
new AgentWorkflow<State, Result, Runtime = undefined>(definition: AgentWorkflowDefinition<State, Result, Runtime>): AgentWorkflow<State, Result, Runtime>

Build and validate a workflow.

The entry node must start a round, because otherwise a workflow could loop forever without consuming the round budget. Renamed top-level fields are rejected as well.

ParameterTypePassingDescription
definitionAgentWorkflowDefinition<State, Result, Runtime>Required—
Fields of definition
FieldTypeRequiredDescription
idstringRequiredRead-only. Stable workflow id, also reported in every event.
chainSourceWorkflowChainSource | undefinedOptionalRead-only. App-owned authorized diagnostic reader; no global run storage is installed.
revisionstring | undefinedOptionalRead-only. Definition revision; lets hosts distinguish executions of different graph versions.
nodesreadonly WorkflowNode<State, Result, Runtime>[]RequiredRead-only. See the type definition and usage context.
isResult((result: Result) => boolean) | undefinedOptionalRead-only. Synchronous result adjudicator; returning anything other than true is a contract error.
entryNodeIdstring | undefinedOptionalRead-only. First node to enter; defaults to the first declared node, which must start a round.

Returns: AgentWorkflow<State, Result, Runtime>.

Instance properties ​

FieldTypeRequiredDescription
idstringRequiredRead-only. Workflow id, also used in diagnostics and error messages.
entryNodeIdstringRequiredRead-only. First node visited; always starts a round.
revisionstring | undefinedOptionalRead-only. Optional revision passed through to diagnostics.
isResult((result: Result) => boolean) | undefinedOptionalRead-only. Optional result guard; when present it must return exactly true.
definitionsreadonly Readonly<WorkflowNode<State, Result, Runtime>>[]RequiredRead-only. Frozen snapshot of all nodes, in registration order.

Member index ​

MemberPurpose
addDerive an extended workflow without mutating this catalog. Every node is copied with its callbacks rebound, so the new catalog keeps the same entry and result guard and can be composed repeatedly. Route overrides are keyed by node id and must name a node that exists after the merge.
toGraphExport topology from the registered snapshot without executing callbacks.
toChainRead an authorized run through the bound App source, or an explicit per-call source.
requireLook up a node that must exist.
idsSee the overload below for full inputs and outputs.
valuesSee the overload below for full inputs and outputs.
entriesSee the overload below for full inputs and outputs.
hasSee the overload below for full inputs and outputs.
getSee the overload below for full inputs and outputs.
describeProduce a serializable description of every node and route. Used by documentation and registration listings; it reports resolved ids and which routes are terminal or conditional, never the handler implementations.

Member details ​

add ​

Instance method.

Derive an extended workflow without mutating this catalog.

Every node is copied with its callbacks rebound, so the new catalog keeps the same entry and result guard and can be composed repeatedly. Route overrides are keyed by node id and must name a node that exists after the merge.

ts
add(extension: WorkflowExtension<State, Result, Runtime> | AgentWorkflow<State, Result, Runtime>, routes?: WorkflowExtension<State, Result, Runtime>["routes"]): AgentWorkflow<State, Result, Runtime>

Derive an extended workflow without mutating this catalog.

Every node is copied with its callbacks rebound, so the new catalog keeps the same entry and result guard and can be composed repeatedly. Route overrides are keyed by node id and must name a node that exists after the merge.

ParameterTypePassingDescription
extensionAgentWorkflow<State, Result, Runtime> | WorkflowExtension<State, Result, Runtime>Required—
routesReadonly<Record<string, readonly WorkflowRoute<State, Result, Runtime>[]>> | undefinedOptional—

Optional shapes of Parameter extension: choose one shape; required fields for each branch are listed separately.

Branch 1

AgentWorkflow<State, Result, Runtime>

Branch 2
FieldTypeRequiredDescription
nodesreadonly WorkflowNode<State, Result, Runtime>[]RequiredRead-only. Nodes appended to the definition; ids must not collide with existing nodes.
routesReadonly<Record<string, readonly WorkflowRoute<State, Result, Runtime>[]>> | undefinedOptionalRead-only. Replacement route lists keyed by node id; other nodes keep their declared routes.
revisionstring | undefinedOptionalRead-only. Extension revision, recorded so mixed definitions remain auditable.

Returns: AgentWorkflow<State, Result, Runtime>.

toGraph ​

Instance method.

Export topology from the registered snapshot without executing callbacks.

ts
toGraph(): WorkflowGraph

Export topology from the registered snapshot without executing callbacks.

No call parameters.

Returns: WorkflowGraph.

Return value structure
FieldTypeRequiredDescription
schemaVersion1RequiredRead-only. See the type definition and usage context.
workflowIdstringRequiredRead-only. See the type definition and usage context.
revisionstring | undefinedOptionalRead-only. See the type definition and usage context.
entryNodeIdstringRequiredRead-only. See the type definition and usage context.
nodesreadonly WorkflowGraphNode[]RequiredRead-only. See the type definition and usage context.
edgesreadonly WorkflowGraphEdge[]RequiredRead-only. See the type definition and usage context.

toChain ​

Instance method.

Read an authorized run through the bound App source, or an explicit per-call source.

ts
toChain(runId: string, source?: WorkflowChainSource | undefined): Promise<WorkflowChain>

Read an authorized run through the bound App source, or an explicit per-call source.

ParameterTypePassingDescription
runIdstringRequired—
sourceWorkflowChainSource | undefinedOptional—

Returns: Promise<WorkflowChain>.

Awaited value: WorkflowChain.

Return value structure
FieldTypeRequiredDescription
schemaVersion1RequiredRead-only. See the type definition and usage context.
workflowIdstringRequiredRead-only. See the type definition and usage context.
runIdstringRequiredRead-only. See the type definition and usage context.
nodesreadonly WorkflowChainNode[]RequiredRead-only. See the type definition and usage context.
transitionsreadonly WorkflowChainTransition[]RequiredRead-only. See the type definition and usage context.
coverageWorkflowChainCoverageRequiredRead-only. See the type definition and usage context.

require ​

Instance method.

Look up a node that must exist.

ts
require(id: string): WorkflowNode<State, Result, Runtime>

Look up a node that must exist.

ParameterTypePassingDescription
idstringRequired—

Returns: WorkflowNode<State, Result, Runtime>.

Return value structure
FieldTypeRequiredDescription
idstringRequiredRead-only. Stable node id referenced by routes and error handling.
descriptionstringRequiredRead-only. Required explanation of what the node does; also used in diagnostics.
namestring | undefinedOptionalRead-only. Display name; defaults to id when omitted.
report((update: void | Readonly<Partial<State>>, context: NodeReportingContext) => WorkflowNodeReport) | undefinedOptionalRead-only. Optional application-reported detail, collected only when content logging is enabled.
startsRoundboolean | undefinedOptionalRead-only. Reserves a fresh round on entry. Use it for steps that may legitimately repeat; entering such a node when the round budget is exhausted fails with the configured exhausted error.
onErrorNodeIdstring | undefinedOptionalRead-only. Node entered when run/provides/route fails; contract errors always propagate instead.
onErrorRouteIdstring | undefinedOptionalRead-only. Route id reported with the recovery transition.
requiresreadonly (keyof State & string)[] | undefinedOptionalRead-only. State keys that must be present before this node runs; enforced by the engine.
providesreadonly (keyof State & string)[] | undefinedOptionalRead-only. State keys this node is expected to produce; validated after run.
routesreadonly WorkflowRoute<State, Result, Runtime>[]RequiredRead-only. Candidate successors, evaluated in order. A getter must be pure; registration reads it once.
run((state: Readonly<State>, context: WorkflowContext<Runtime>) => void | Partial<State> | Promise<void | Partial<State>>) | undefinedOptionalRead-only. Return only changed fields. Core commits them after cancellation and output checks.

ids ​

Instance method.

ts
ids(): readonly string[]

No call parameters.

Returns: readonly string[].

values ​

Instance method.

ts
values(): MapIterator<WorkflowNode<State, Result, Runtime>>

No call parameters.

Returns: MapIterator<WorkflowNode<State, Result, Runtime>>.

entries ​

Instance method.

ts
entries(): MapIterator<[string, WorkflowNode<State, Result, Runtime>]>

No call parameters.

Returns: MapIterator<[string, WorkflowNode<State, Result, Runtime>]>.

has ​

Instance method.

ts
has(id: string): boolean
ParameterTypePassingDescription
idstringRequired—

Returns: boolean.

get ​

Instance method.

ts
get(id: string): WorkflowNode<State, Result, Runtime> | undefined
ParameterTypePassingDescription
idstringRequired—

Returns: WorkflowNode<State, Result, Runtime> \| undefined.

Optional shapes of Return value: choose one shape; required fields for each branch are listed separately.

Branch 1

undefined

Branch 2
FieldTypeRequiredDescription
idstringRequiredRead-only. Stable node id referenced by routes and error handling.
descriptionstringRequiredRead-only. Required explanation of what the node does; also used in diagnostics.
namestring | undefinedOptionalRead-only. Display name; defaults to id when omitted.
report((update: void | Readonly<Partial<State>>, context: NodeReportingContext) => WorkflowNodeReport) | undefinedOptionalRead-only. Optional application-reported detail, collected only when content logging is enabled.
startsRoundboolean | undefinedOptionalRead-only. Reserves a fresh round on entry. Use it for steps that may legitimately repeat; entering such a node when the round budget is exhausted fails with the configured exhausted error.
onErrorNodeIdstring | undefinedOptionalRead-only. Node entered when run/provides/route fails; contract errors always propagate instead.
onErrorRouteIdstring | undefinedOptionalRead-only. Route id reported with the recovery transition.
requiresreadonly (keyof State & string)[] | undefinedOptionalRead-only. State keys that must be present before this node runs; enforced by the engine.
providesreadonly (keyof State & string)[] | undefinedOptionalRead-only. State keys this node is expected to produce; validated after run.
routesreadonly WorkflowRoute<State, Result, Runtime>[]RequiredRead-only. Candidate successors, evaluated in order. A getter must be pure; registration reads it once.
run((state: Readonly<State>, context: WorkflowContext<Runtime>) => void | Partial<State> | Promise<void | Partial<State>>) | undefinedOptionalRead-only. Return only changed fields. Core commits them after cancellation and output checks.

describe ​

Instance method.

Produce a serializable description of every node and route.

Used by documentation and registration listings; it reports resolved ids and which routes are terminal or conditional, never the handler implementations.

ts
describe(): { startsRound: boolean; onErrorNodeId: string | undefined; requires: readonly (keyof State & string)[]; provides: readonly (keyof State & string)[]; routes: { targetNodeId: string | undefined; terminal: boolean; conditional: boolean; conditionId?: string | undefined; description?: string | undefined; id?: string | undefined; }[]; name?: string | undefined; id: string; description: string; }[]

Produce a serializable description of every node and route.

Used by documentation and registration listings; it reports resolved ids and which routes are terminal or conditional, never the handler implementations.

No call parameters.

Returns: { startsRound: boolean; onErrorNodeId: string \| undefined; requires: readonly (keyof State & string)[]; provides: readonly (keyof State & string)[]; routes: { targetNodeId: string \| undefined; terminal: boolean; conditional: boolean; conditionId?: string \| undefined; description?: string \| undefined; id?: string \| undefined; }[]; name?: string \| undefined; id: string; description: string; }[].

Examples ​

A single node completes the greeting ​

Beginner · Node.js

ts
import { AgentCoreEngine, defineWorkflow, route } from '@jangts/agent-core/engine';

type State = { name: string; answer?: string };
const workflow = defineWorkflow<State, string>({
  id: 'greeting',
  nodes: [{
    id: 'greet', description: '根据本次姓名生成问候', startsRound: true,
    run: state => ({ answer: '你好,' + state.name }),
    routes: [route.deliver('answer')],
  }],
});
console.log(workflow.entryNodeId);
console.log(workflow.describe());
js
import { AgentCoreEngine, defineWorkflow, route } from '@jangts/agent-core/engine';
const workflow = defineWorkflow({
    id: 'greeting',
    nodes: [{
            id: 'greet', description: '根据本次姓名生成问候', startsRound: true,
            run: state => ({ answer: '你好,' + state.name }),
            routes: [route.deliver('answer')],
        }],
});
console.log(workflow.entryNodeId);
console.log(workflow.describe());

Add a validation stage without changing state or the run call ​

Configuration · Node.js

ts
import { AgentCoreEngine, defineWorkflow, route } from '@jangts/agent-core/engine';
type State = { name: string; answer?: string; error?: string };
const workflow = defineWorkflow<State, string>({
  id: 'greeting',
  nodes: [
    { id: 'check', description: '检查姓名', startsRound: true,
      run: state => ({ error: state.name.trim() ? undefined : '姓名不能为空' }),
      routes: [route.toIfError('failure'), route.to('greet')] },
    { id: 'greet', description: '生成问候', provides: ['answer'],
      run: state => ({ answer: '你好,' + state.name }), routes: [route.deliver('answer')] },
    { id: 'failure', description: '返回校验提示', requires: ['error'], routes: [route.deliver('error')] },
  ],
});
console.log(await new AgentCoreEngine({ workflow }).run({ name: 'Ivan' }));
js
import { AgentCoreEngine, defineWorkflow, route } from '@jangts/agent-core/engine';
const workflow = defineWorkflow({
    id: 'greeting',
    nodes: [
        { id: 'check', description: '检查姓名', startsRound: true,
            run: state => ({ error: state.name.trim() ? undefined : '姓名不能为空' }),
            routes: [route.toIfError('failure'), route.to('greet')] },
        { id: 'greet', description: '生成问候', provides: ['answer'],
            run: state => ({ answer: '你好,' + state.name }), routes: [route.deliver('answer')] },
        { id: 'failure', description: '返回校验提示', requires: ['error'], routes: [route.deliver('error')] },
    ],
});
console.log(await new AgentCoreEngine({ workflow }).run({ name: 'Ivan' }));

The same node contract can be implemented by a class ​

Extension · Node.js

ts
import { AgentCoreEngine, defineWorkflow, route } from '@jangts/agent-core/engine';
type State = { name: string; answer?: string };
class GreetingNode {
  readonly id = 'greet';
  readonly description = '根据姓名生成问候';
  readonly startsRound = true;
  readonly routes = [route.deliver('answer')];
  #prefix = '你好,';
  run(state: Readonly<State>) { return { answer: this.#prefix + state.name }; }
}
const workflow = defineWorkflow<State, string>({ id: 'greeting', nodes: [new GreetingNode()] });
console.log(await new AgentCoreEngine({ workflow }).run({ name: 'Ivan' }));
js
import { AgentCoreEngine, defineWorkflow, route } from '@jangts/agent-core/engine';
class GreetingNode {
    id = 'greet';
    description = '根据姓名生成问候';
    startsRound = true;
    routes = [route.deliver('answer')];
    #prefix = '你好,';
    run(state) { return { answer: this.#prefix + state.name }; }
}
const workflow = defineWorkflow({ id: 'greeting', nodes: [new GreetingNode()] });
console.log(await new AgentCoreEngine({ workflow }).run({ name: 'Ivan' }));

API reference, usage examples and developer guides.