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
import { AgentWorkflow } from '@jangts/agent-core/engine';import { AgentWorkflow } from '@jangts/agent-core/engine';Other public entry points:@jangts/agent-core, @jangts/agent-core/engine, @jangts/agent-core/types.
Definition
class AgentWorkflow<State, Result, Runtime>Type parameters
| Type parameter | Constraint | Default type |
|---|---|---|
State | — | — |
Result | — | — |
Runtime | — | undefined |
Constructor
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.
| Parameter | Type | Passing | Description |
|---|---|---|---|
definition | AgentWorkflowDefinition<State, Result, Runtime> | Required | — |
Fields of definition
| Field | Type | Required | Description |
|---|---|---|---|
id | string | Required | Read-only. Stable workflow id, also reported in every event. |
chainSource | WorkflowChainSource | undefined | Optional | Read-only. App-owned authorized diagnostic reader; no global run storage is installed. |
revision | string | undefined | Optional | Read-only. Definition revision; lets hosts distinguish executions of different graph versions. |
nodes | readonly WorkflowNode<State, Result, Runtime>[] | Required | Read-only. See the type definition and usage context. |
isResult | ((result: Result) => boolean) | undefined | Optional | Read-only. Synchronous result adjudicator; returning anything other than true is a contract error. |
entryNodeId | string | undefined | Optional | Read-only. First node to enter; defaults to the first declared node, which must start a round. |
Returns: AgentWorkflow<State, Result, Runtime>.
Instance properties
| Field | Type | Required | Description |
|---|---|---|---|
id | string | Required | Read-only. Workflow id, also used in diagnostics and error messages. |
entryNodeId | string | Required | Read-only. First node visited; always starts a round. |
revision | string | undefined | Optional | Read-only. Optional revision passed through to diagnostics. |
isResult | ((result: Result) => boolean) | undefined | Optional | Read-only. Optional result guard; when present it must return exactly true. |
definitions | readonly Readonly<WorkflowNode<State, Result, Runtime>>[] | Required | Read-only. Frozen snapshot of all nodes, in registration order. |
Member index
| Member | Purpose |
|---|---|
add | 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. |
toGraph | Export topology from the registered snapshot without executing callbacks. |
toChain | Read an authorized run through the bound App source, or an explicit per-call source. |
require | Look up a node that must exist. |
ids | See the overload below for full inputs and outputs. |
values | See the overload below for full inputs and outputs. |
entries | See the overload below for full inputs and outputs. |
has | See the overload below for full inputs and outputs. |
get | See the overload below for full inputs and outputs. |
describe | 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. |
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.
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.
| Parameter | Type | Passing | Description |
|---|---|---|---|
extension | AgentWorkflow<State, Result, Runtime> | WorkflowExtension<State, Result, Runtime> | Required | — |
routes | Readonly<Record<string, readonly WorkflowRoute<State, Result, Runtime>[]>> | undefined | Optional | — |
Optional shapes of Parameter extension: choose one shape; required fields for each branch are listed separately.
Branch 1
AgentWorkflow<State, Result, Runtime>
Branch 2
| Field | Type | Required | Description |
|---|---|---|---|
nodes | readonly WorkflowNode<State, Result, Runtime>[] | Required | Read-only. Nodes appended to the definition; ids must not collide with existing nodes. |
routes | Readonly<Record<string, readonly WorkflowRoute<State, Result, Runtime>[]>> | undefined | Optional | Read-only. Replacement route lists keyed by node id; other nodes keep their declared routes. |
revision | string | undefined | Optional | Read-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.
toGraph(): WorkflowGraphExport topology from the registered snapshot without executing callbacks.
No call parameters.
Returns: WorkflowGraph.
Return value structure
| Field | Type | Required | Description |
|---|---|---|---|
schemaVersion | 1 | Required | Read-only. See the type definition and usage context. |
workflowId | string | Required | Read-only. See the type definition and usage context. |
revision | string | undefined | Optional | Read-only. See the type definition and usage context. |
entryNodeId | string | Required | Read-only. See the type definition and usage context. |
nodes | readonly WorkflowGraphNode[] | Required | Read-only. See the type definition and usage context. |
edges | readonly WorkflowGraphEdge[] | Required | Read-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.
toChain(runId: string, source?: WorkflowChainSource | undefined): Promise<WorkflowChain>Read an authorized run through the bound App source, or an explicit per-call source.
| Parameter | Type | Passing | Description |
|---|---|---|---|
runId | string | Required | — |
source | WorkflowChainSource | undefined | Optional | — |
Returns: Promise<WorkflowChain>.
Awaited value: WorkflowChain.
Return value structure
| Field | Type | Required | Description |
|---|---|---|---|
schemaVersion | 1 | Required | Read-only. See the type definition and usage context. |
workflowId | string | Required | Read-only. See the type definition and usage context. |
runId | string | Required | Read-only. See the type definition and usage context. |
nodes | readonly WorkflowChainNode[] | Required | Read-only. See the type definition and usage context. |
transitions | readonly WorkflowChainTransition[] | Required | Read-only. See the type definition and usage context. |
coverage | WorkflowChainCoverage | Required | Read-only. See the type definition and usage context. |
require
Instance method.
Look up a node that must exist.
require(id: string): WorkflowNode<State, Result, Runtime>Look up a node that must exist.
| Parameter | Type | Passing | Description |
|---|---|---|---|
id | string | Required | — |
Returns: WorkflowNode<State, Result, Runtime>.
Return value structure
| Field | Type | Required | Description |
|---|---|---|---|
id | string | Required | Read-only. Stable node id referenced by routes and error handling. |
description | string | Required | Read-only. Required explanation of what the node does; also used in diagnostics. |
name | string | undefined | Optional | Read-only. Display name; defaults to id when omitted. |
report | ((update: void | Readonly<Partial<State>>, context: NodeReportingContext) => WorkflowNodeReport) | undefined | Optional | Read-only. Optional application-reported detail, collected only when content logging is enabled. |
startsRound | boolean | undefined | Optional | Read-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. |
onErrorNodeId | string | undefined | Optional | Read-only. Node entered when run/provides/route fails; contract errors always propagate instead. |
onErrorRouteId | string | undefined | Optional | Read-only. Route id reported with the recovery transition. |
requires | readonly (keyof State & string)[] | undefined | Optional | Read-only. State keys that must be present before this node runs; enforced by the engine. |
provides | readonly (keyof State & string)[] | undefined | Optional | Read-only. State keys this node is expected to produce; validated after run. |
routes | readonly WorkflowRoute<State, Result, Runtime>[] | Required | Read-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>>) | undefined | Optional | Read-only. Return only changed fields. Core commits them after cancellation and output checks. |
ids
Instance method.
ids(): readonly string[]No call parameters.
Returns: readonly string[].
values
Instance method.
values(): MapIterator<WorkflowNode<State, Result, Runtime>>No call parameters.
Returns: MapIterator<WorkflowNode<State, Result, Runtime>>.
entries
Instance method.
entries(): MapIterator<[string, WorkflowNode<State, Result, Runtime>]>No call parameters.
Returns: MapIterator<[string, WorkflowNode<State, Result, Runtime>]>.
has
Instance method.
has(id: string): boolean| Parameter | Type | Passing | Description |
|---|---|---|---|
id | string | Required | — |
Returns: boolean.
get
Instance method.
get(id: string): WorkflowNode<State, Result, Runtime> | undefined| Parameter | Type | Passing | Description |
|---|---|---|---|
id | string | Required | — |
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
| Field | Type | Required | Description |
|---|---|---|---|
id | string | Required | Read-only. Stable node id referenced by routes and error handling. |
description | string | Required | Read-only. Required explanation of what the node does; also used in diagnostics. |
name | string | undefined | Optional | Read-only. Display name; defaults to id when omitted. |
report | ((update: void | Readonly<Partial<State>>, context: NodeReportingContext) => WorkflowNodeReport) | undefined | Optional | Read-only. Optional application-reported detail, collected only when content logging is enabled. |
startsRound | boolean | undefined | Optional | Read-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. |
onErrorNodeId | string | undefined | Optional | Read-only. Node entered when run/provides/route fails; contract errors always propagate instead. |
onErrorRouteId | string | undefined | Optional | Read-only. Route id reported with the recovery transition. |
requires | readonly (keyof State & string)[] | undefined | Optional | Read-only. State keys that must be present before this node runs; enforced by the engine. |
provides | readonly (keyof State & string)[] | undefined | Optional | Read-only. State keys this node is expected to produce; validated after run. |
routes | readonly WorkflowRoute<State, Result, Runtime>[] | Required | Read-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>>) | undefined | Optional | Read-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.
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
- Workflow: nodes, routes, and partial state updates: Use a single node definition that actually participates in execution to show order, branches, error destinations, and end conditions together.
- Reusing a base Workflow and Agent branches: add preserves the old Workflow and produces a new combined Workflow; fork inherits existing bindings and the branch origin.
A single node completes the greeting
Beginner · Node.js
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());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
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' }));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
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' }));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' }));Related policy source
- Execution implementation of the bounded loop, commit, and cancellation
- Reference, reachability, and bounded-loop validation