Skip to content
中文

AgentCoreEngine ​

CORE · class · Runtime value

Bounded execution shared by applications; business rules are registered by each host.

Configuration is bound before a run and may be bound only once per model, tool runtime and workflow. A run resolves its signal from the engine, the request runtime and the caller, then executes either the bound workflow or a supplied step function until the round budget, cancellation or a completion stops it.

Import ​

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

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

Definition ​

ts
class AgentCoreEngine<Result, State, App>

Type parameters ​

Type parameterConstraintDefault type
Result——
State—unknown
App—undefined

Constructor ​

ts
new AgentCoreEngine<Result, State = unknown, App = undefined>(settings?: AgentCoreEngineSetup<State, Result, App>): AgentCoreEngine<Result, State, App>

Build an engine and validate its wiring.

Legacy top-level names (maxSteps, exhausted, signal, diagnostics, onWorkflowEvent, observe) are rejected rather than ignored, because silently dropping them would change budgets or observation.

ParameterTypePassingDescription
settingsAgentCoreEngineSetup<State, Result, App>Optional—

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

Branch 1
FieldTypeRequiredDescription
cacheEngineCacheOptions | undefinedOptionalEngine-local LRU bounds; not copied as cache data when forking.
agentCacheAgentCachePort | undefinedOptionalBorrowed App service cache; forks must explicitly provide their own port.
maxRoundsnumber | undefinedOptionalRound budget; must be a positive safe integer. Defaults to 8 rounds.
executionExecutionOptions | undefinedOptionalCancellation and diagnostics shared by every round.
errors{ exhausted?: () => Error; } | undefinedOptionalBuilds the error thrown when the round budget is exhausted (defaults to a BudgetError).
branchAgentBranch | undefinedOptionalRead-only. See the type definition and usage context.
toolsToolBinding | undefinedOptionalRead-only. See the type definition and usage context.
modelAgentModelBinding | undefinedOptionalSee the type definition and usage context.
modelsundefinedOptionalSee the type definition and usage context.
workflowundefinedOptionalSee the type definition and usage context.
appundefinedOptionalSee the type definition and usage context.
Branch 2
FieldTypeRequiredDescription
cacheEngineCacheOptions | undefinedOptionalEngine-local LRU bounds; not copied as cache data when forking.
agentCacheAgentCachePort | undefinedOptionalBorrowed App service cache; forks must explicitly provide their own port.
maxRoundsnumber | undefinedOptionalRound budget; must be a positive safe integer. Defaults to 8 rounds.
executionExecutionOptions | undefinedOptionalCancellation and diagnostics shared by every round.
errors{ exhausted?: () => Error; } | undefinedOptionalBuilds the error thrown when the round budget is exhausted (defaults to a BudgetError).
branchAgentBranch | undefinedOptionalRead-only. See the type definition and usage context.
toolsToolBinding | undefinedOptionalRead-only. See the type definition and usage context.
modelstring | undefinedOptionalSee the type definition and usage context.
modelsReadonly<Record<string, AgentModelBinding>>RequiredSee the type definition and usage context.
maxModelCallsnumber | undefinedOptionalSee the type definition and usage context.
workflowundefinedOptionalSee the type definition and usage context.
appundefinedOptionalSee the type definition and usage context.
Branch 3
FieldTypeRequiredDescription
cacheEngineCacheOptions | undefinedOptionalEngine-local LRU bounds; not copied as cache data when forking.
agentCacheAgentCachePort | undefinedOptionalBorrowed App service cache; forks must explicitly provide their own port.
maxRoundsnumber | undefinedOptionalRound budget; must be a positive safe integer. Defaults to 8 rounds.
executionExecutionOptions | undefinedOptionalCancellation and diagnostics shared by every round.
errors{ exhausted?: () => Error; } | undefinedOptionalBuilds the error thrown when the round budget is exhausted (defaults to a BudgetError).
branchAgentBranch | undefinedOptionalRead-only. See the type definition and usage context.
toolsToolBinding | undefinedOptionalRead-only. See the type definition and usage context.
modelAgentModelBinding | undefinedOptionalSee the type definition and usage context.
modelsundefinedOptionalSee the type definition and usage context.
workflowAgentWorkflow<State, Result, App>RequiredRead-only. See the type definition and usage context.
appApp | undefinedOptionalRead-only. See the type definition and usage context.

Type condition: AgentCoreEngineOptions & { readonly branch?: AgentBranch; readonly tools?: ToolBinding; } & { model?: AgentModelBinding; models?: never; } & { readonly workflow: AgentWorkflow<State, Result, App>; } & ([App] extends [undefined] ? { readonly app?: undefined; } : { readonly app: App; })

Branch 4
FieldTypeRequiredDescription
cacheEngineCacheOptions | undefinedOptionalEngine-local LRU bounds; not copied as cache data when forking.
agentCacheAgentCachePort | undefinedOptionalBorrowed App service cache; forks must explicitly provide their own port.
maxRoundsnumber | undefinedOptionalRound budget; must be a positive safe integer. Defaults to 8 rounds.
executionExecutionOptions | undefinedOptionalCancellation and diagnostics shared by every round.
errors{ exhausted?: () => Error; } | undefinedOptionalBuilds the error thrown when the round budget is exhausted (defaults to a BudgetError).
branchAgentBranch | undefinedOptionalRead-only. See the type definition and usage context.
toolsToolBinding | undefinedOptionalRead-only. See the type definition and usage context.
modelstring | undefinedOptionalSee the type definition and usage context.
modelsReadonly<Record<string, AgentModelBinding>>RequiredSee the type definition and usage context.
maxModelCallsnumber | undefinedOptionalSee the type definition and usage context.
workflowAgentWorkflow<State, Result, App>RequiredRead-only. See the type definition and usage context.
appApp | undefinedOptionalRead-only. See the type definition and usage context.

Type condition: AgentCoreEngineOptions & { readonly branch?: AgentBranch; readonly tools?: ToolBinding; } & { model?: string; models: Readonly<Record<string, AgentModelBinding>>; maxModelCalls?: number; } & { readonly workflow: AgentWorkflow<State, Result, App>; } & ([App] extends [undefined] ? { readonly app?: undefined; } : { readonly app: App; })

Returns: AgentCoreEngine<Result, State, App>.

Instance properties ​

FieldTypeRequiredDescription
workflowAgentWorkflow<State, Result, App>RequiredRead-only. The bound workflow.
branchAgentBranchRequiredRead-only. Identity of this engine's branch.

Member index ​

MemberPurpose
WorkflowStatic. Workflow catalog constructor, exposed so hosts do not import two modules.
AttemptBudgetStatic. Attempt budget, exposed for hosts that gate their own sub-steps.
createWorkflowStatic. Factory for a validated workflow definition.
bindModelBind the single model this engine will use.
bindModelRuntimeBind an existing request lifetime once, for App services sharing this Runner's budget. Callbacks are bound to the source runtime and the counters stay live getters, so the engine and the App observe exactly the same budget and signal.
switchModelSelect a configured model, or replace the single bound model's configuration.
bindToolRuntimeBind the tool runtime used by workflow context.
bindWorkflowBind a workflow, narrowing the engine's state and App types. Binding changes the engine's type parameters without changing its identity, so the same instance keeps its model, tools and branch. Bind a workflow together with its App dependencies.
checkpointTake an in-memory checkpoint of host-owned data. The data is cloned on write and on every read, so neither side can mutate the other.
exportCheckpointExport a checkpoint for host-owned persistence.
restoreCheckpointRecreate a checkpoint from a persisted record. The record's branch must match this engine's branch exactly; otherwise persisted data from another branch would be adopted silently.
forkCreate an engine on a new branch forked at a checkpoint. The forked engine keeps the round budget, observation and configuration, receives an optional workflow extension, and gets a new branch identity whose parent ids point at this engine. Live handles are not copied: an App dependency, request runtime or tool runtime must be restored by the resume callback, because they cannot be serialized.
runRun the loop with a step function when no workflow is bound. Run a bound workflow from an initial state.

Member details ​

Workflow ​

Static member.

Workflow catalog constructor, exposed so hosts do not import two modules.

ts
new AgentCoreEngine.Workflow<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>.

AttemptBudget ​

Static member.

Attempt budget, exposed for hosts that gate their own sub-steps.

ts
new AgentCoreEngine.AttemptBudget(limit: number): AttemptBudget
ParameterTypePassingDescription
limitnumberRequired—

Returns: AttemptBudget.

createWorkflow ​

Static member.

Factory for a validated workflow definition.

ts
AgentCoreEngine.createWorkflow<State, Result, Runtime = undefined>(definition: AgentWorkflowDefinition<State, Result, Runtime>): AgentWorkflow<State, Result, Runtime>

Build a validated workflow from a definition.

Type parameterConstraintDefault type
State——
Result——
Runtime—undefined
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>.

bindModel ​

Instance method.

Bind the single model this engine will use.

ts
bindModel(options: AgentModelBinding): AgentCoreEngine<Result, State, App>

Bind the single model this engine will use.

ParameterTypePassingDescription
optionsAgentModelBindingRequired—
Fields of options
FieldTypeRequiredDescription
providerChatProviderRequiredSee the type definition and usage context.
executionundefinedOptionalSee the type definition and usage context.
transportsreadonly ModelTransportDefinition<unknown>[] | undefinedOptionalSee the type definition and usage context.
sink{ output?: ModelRunnerPorts["onOutput"]; } | undefinedOptionalSee the type definition and usage context.
errors{ inputBudget?: ModelRunnerPorts["inputBudgetError"]; outputBudget?: ModelRunnerPorts["outputBudgetError"]; } | undefinedOptionalSee the type definition and usage context.
childrenModelChildPolicy | undefinedOptionalRead-only. See the type definition and usage context.
maxInputCharsnumber | undefinedOptionalCharacter budget for the assembled input.
maxSchemaCharsnumber | undefinedOptionalCharacter allowance for registered capability schemas.
tokenBudgetModelTokenBudget | undefinedOptionalSee the type definition and usage context.
maxOutputTokensnumber | undefinedOptionalDefault output reservation; invoke can override it for one call.
maxCallsnumber | undefinedOptionalCalls allowed for the whole request, including descendant runners' reservations.
callTimeoutMsnumber | undefinedOptionalDeadline for one provider call, in milliseconds.
maxOutputCharsnumber | undefinedOptionalCap on streamed output characters; exceeding it fails the call.
usageboolean | undefinedOptionalRequest and record provider usage for each call.
signalundefinedOptionalSee the type definition and usage context.

Returns: AgentCoreEngine<Result, State, App>.

bindModelRuntime ​

Instance method.

Bind an existing request lifetime once, for App services sharing this Runner's budget.

Callbacks are bound to the source runtime and the counters stay live getters, so the engine and the App observe exactly the same budget and signal.

ts
bindModelRuntime(source: AgentModelRuntime): AgentCoreEngine<Result, State, App>

Bind an existing request lifetime once, for App services sharing this Runner's budget.

Callbacks are bound to the source runtime and the counters stay live getters, so the engine and the App observe exactly the same budget and signal.

ParameterTypePassingDescription
sourceAgentModelRuntimeRequired—
Fields of source
FieldTypeRequiredDescription
invoke{ (request: string): Promise<ModelResult<string>>; <Result>(request: ModelCallRequest<never> & { readonly prepared: PreparedModelCall<Result>; }): Promise<ModelResult<Result>>; (request: ModelCallRequest<never>): Promise<ModelResult<string>>; <Result>(request: ModelCallRequest<ModelTransportDefinition<Result>> & { transport: ModelTransportDefinition<Result>; }): Promise<ModelResult<Result>>; <const Id extends string>(request: ModelCallRequest<Id> & { readonly transport: Id; }): Promise<ModelResult<RegisteredTransportOutput<readonly ModelTransportDefinition<unknown>[], Id>>>; (request: ModelCallRequest<string | ModelTransportDefinition<unknown>>): Promise<ModelResult<unknown>>; }RequiredInvoke one model call. Named and shorthand input share the same lifecycle: validation, measurement, budget charge, streaming, commit. A caller-supplied signal only shortens the call lifetime. Invoke a prepared call whose settings cannot be replaced. Invoke with the default transport and a plain-text result. Invoke with a transport instance supplied at the call site. Invoke with a transport id registered on this runner. Invoke without narrowing the transport type.
prepare{ (request?: import("../structs/model/runtime.js").ModelPrepareRequest<never>): import("../structs/model/runtime.js").PreparedModelCall<string>; <Result>(request: ModelPrepareRequest<ModelTransportDefinition<Result>> & { readonly transport: ModelTransportDefinition<Result>; }): PreparedModelCall<Result>; <const Id extends string>(request: ModelPrepareRequest<Id> & { readonly transport: Id; }): PreparedModelCall<RegisteredTransportOutput<readonly ModelTransportDefinition<unknown>[], Id>>; (request: import("../structs/model/runtime.js").ModelPrepareRequest<string | ModelTransportDefinition>): import("../structs/model/runtime.js").PreparedModelCall; }RequiredPrepare a call and measure it before invocation. A prepared call is single-use and bound to the stage, output tokens and transport it was measured with; invoke rejects any attempt to replace those settings. Prepare a call for a transport instance supplied at the call site. Prepare a call for a transport id, typed by the runner's registered transports. Prepare a call without narrowing the transport type.
executionExecutionContextRequiredRead-only. See the type definition and usage context.
remainingCallsnumberRequiredRead-only. Calls still available to this runner after the parent's reserve is applied.
callCountnumberRequiredRead-only. Completed calls observed by this runner only.
totalCallCountnumberRequiredRead-only. Includes descendant attempts; local callCount and journal remain isolated.

Returns: AgentCoreEngine<Result, State, App>.

switchModel ​

Instance method.

Select a configured model, or replace the single bound model's configuration.

ts
switchModel(options: AgentModelBinding | string): AgentCoreEngine<Result, State, App>

Select a configured model, or replace the single bound model's configuration.

ParameterTypePassingDescription
optionsstring | AgentModelBindingRequired—

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

Branch 1

string

Branch 2
FieldTypeRequiredDescription
providerChatProviderRequiredSee the type definition and usage context.
executionundefinedOptionalSee the type definition and usage context.
transportsreadonly ModelTransportDefinition<unknown>[] | undefinedOptionalSee the type definition and usage context.
sink{ output?: ModelRunnerPorts["onOutput"]; } | undefinedOptionalSee the type definition and usage context.
errors{ inputBudget?: ModelRunnerPorts["inputBudgetError"]; outputBudget?: ModelRunnerPorts["outputBudgetError"]; } | undefinedOptionalSee the type definition and usage context.
childrenModelChildPolicy | undefinedOptionalRead-only. See the type definition and usage context.
maxInputCharsnumber | undefinedOptionalCharacter budget for the assembled input.
maxSchemaCharsnumber | undefinedOptionalCharacter allowance for registered capability schemas.
tokenBudgetModelTokenBudget | undefinedOptionalSee the type definition and usage context.
maxOutputTokensnumber | undefinedOptionalDefault output reservation; invoke can override it for one call.
maxCallsnumber | undefinedOptionalCalls allowed for the whole request, including descendant runners' reservations.
callTimeoutMsnumber | undefinedOptionalDeadline for one provider call, in milliseconds.
maxOutputCharsnumber | undefinedOptionalCap on streamed output characters; exceeding it fails the call.
usageboolean | undefinedOptionalRequest and record provider usage for each call.
signalundefinedOptionalSee the type definition and usage context.

Returns: AgentCoreEngine<Result, State, App>.

bindToolRuntime ​

Instance method.

Bind the tool runtime used by workflow context.

ts
bindToolRuntime(tools: ToolBinding): AgentCoreEngine<Result, State, App>

Bind the tool runtime used by workflow context.

ParameterTypePassingDescription
toolsToolBindingRequired—

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

Branch 1
FieldTypeRequiredDescription
invokeInvokeToolRequiredSee the type definition and usage context.
Branch 2
FieldTypeRequiredDescription
invokeAsync(request: ToolInvocationRequest) => Promise<ToolResult<unknown>>RequiredInvoke a registered tool and await its result.

Returns: AgentCoreEngine<Result, State, App>.

bindWorkflow ​

Instance method.

Bind a workflow, narrowing the engine's state and App types.

Binding changes the engine's type parameters without changing its identity, so the same instance keeps its model, tools and branch. Bind a workflow together with its App dependencies.

ts
bindWorkflow<NextState>(workflow: AgentWorkflow<NextState, Result, undefined>): AgentCoreEngine<Result, NextState, undefined>

Bind a workflow, narrowing the engine's state and App types.

Binding changes the engine's type parameters without changing its identity, so the same instance keeps its model, tools and branch.

Type parameterConstraintDefault type
NextState——
ParameterTypePassingDescription
workflowAgentWorkflow<NextState, Result, undefined>Required—

Returns: AgentCoreEngine<Result, NextState, undefined>.

ts
bindWorkflow<NextState, NextApp>(workflow: AgentWorkflow<NextState, Result, NextApp>, app: NextApp): AgentCoreEngine<Result, NextState, NextApp>

Bind a workflow together with its App dependencies.

Type parameterConstraintDefault type
NextState——
NextApp——
ParameterTypePassingDescription
workflowAgentWorkflow<NextState, Result, NextApp>Required—
appNextAppRequired—

Returns: AgentCoreEngine<Result, NextState, NextApp>.

checkpoint ​

Instance method.

Take an in-memory checkpoint of host-owned data.

The data is cloned on write and on every read, so neither side can mutate the other.

ts
checkpoint<Data>(data: Data): AgentCheckpoint<Data>

Take an in-memory checkpoint of host-owned data.

The data is cloned on write and on every read, so neither side can mutate the other.

Type parameterConstraintDefault type
Data——
ParameterTypePassingDescription
dataDataRequired—

Returns: AgentCheckpoint<Data>.

Return value structure
FieldTypeRequiredDescription
idstringRequiredRead-only. Checkpoint identifier, unique within the engine.
sourceAgentBranchRequiredRead-only. Branch the checkpoint was taken on.
read() => DataRequiredSee the type definition and usage context.

exportCheckpoint ​

Instance method.

Export a checkpoint for host-owned persistence.

ts
exportCheckpoint<Data>(checkpoint: AgentCheckpoint<Data>): AgentCheckpointRecord<Data>

Export a checkpoint for host-owned persistence.

Type parameterConstraintDefault type
Data——
ParameterTypePassingDescription
checkpointAgentCheckpoint<Data>Required—
Fields of checkpoint
FieldTypeRequiredDescription
idstringRequiredRead-only. Checkpoint identifier, unique within the engine.
sourceAgentBranchRequiredRead-only. Branch the checkpoint was taken on.
read() => DataRequiredSee the type definition and usage context.

Returns: AgentCheckpointRecord<Data>.

Return value structure
FieldTypeRequiredDescription
idstringRequiredRead-only. Checkpoint identifier, preserved across export and restore.
sourceAgentBranchRequiredRead-only. Validated branch identity captured at checkpoint time.
dataDataRequiredRead-only. Detached data payload; serializable by the host.

restoreCheckpoint ​

Instance method.

Recreate a checkpoint from a persisted record.

The record's branch must match this engine's branch exactly; otherwise persisted data from another branch would be adopted silently.

ts
restoreCheckpoint<Data>(record: AgentCheckpointRecord<Data>): AgentCheckpoint<Data>

Recreate a checkpoint from a persisted record.

The record's branch must match this engine's branch exactly; otherwise persisted data from another branch would be adopted silently.

Type parameterConstraintDefault type
Data——
ParameterTypePassingDescription
recordAgentCheckpointRecord<Data>Required—
Fields of record
FieldTypeRequiredDescription
idstringRequiredRead-only. Checkpoint identifier, preserved across export and restore.
sourceAgentBranchRequiredRead-only. Validated branch identity captured at checkpoint time.
dataDataRequiredRead-only. Detached data payload; serializable by the host.

Returns: AgentCheckpoint<Data>.

Return value structure
FieldTypeRequiredDescription
idstringRequiredRead-only. Checkpoint identifier, unique within the engine.
sourceAgentBranchRequiredRead-only. Branch the checkpoint was taken on.
read() => DataRequiredSee the type definition and usage context.

fork ​

Instance method.

Create an engine on a new branch forked at a checkpoint.

The forked engine keeps the round budget, observation and configuration, receives an optional workflow extension, and gets a new branch identity whose parent ids point at this engine. Live handles are not copied: an App dependency, request runtime or tool runtime must be restored by the resume callback, because they cannot be serialized.

ts
fork<Data>({ at, workflow, routes, resume, }: { at: AgentCheckpoint<Data>; workflow?: AgentWorkflow<State, Result, App> | WorkflowExtension<State, Result, App>; routes?: WorkflowExtension<State, Result, App>["routes"]; resume?: (checkpoint: Data) => { app?: App; tools?: ToolBinding; model?: AgentModelRuntime; agentCache?: AgentCachePort; }; }): AgentCoreEngine<Result, State, App>

Create an engine on a new branch forked at a checkpoint.

The forked engine keeps the round budget, observation and configuration, receives an optional workflow extension, and gets a new branch identity whose parent ids point at this engine. Live handles are not copied: an App dependency, request runtime or tool runtime must be restored by the resume callback, because they cannot be serialized.

Type parameterConstraintDefault type
Data——
ParameterTypePassingDescription
__0{ at: AgentCheckpoint<Data>; workflow?: AgentWorkflow<State, Result, App> | WorkflowExtension<State, Result, App>; routes?: WorkflowExtension<State, Result, App>["routes"]; resume?: (checkpoint: Data) => { app?: App; tools?: ToolBinding; model?: AgentModelRuntime; agentCache?: AgentCachePort; }; }Required—
Fields of __0
FieldTypeRequiredDescription
atAgentCheckpoint<Data>RequiredSee the type definition and usage context.
workflowAgentWorkflow<State, Result, App> | WorkflowExtension<State, Result, App> | undefinedOptionalSee the type definition and usage context.
routesReadonly<Record<string, readonly WorkflowRoute<State, Result, App>[]>> | undefinedOptionalSee the type definition and usage context.
resume((checkpoint: Data) => { app?: App; tools?: ToolBinding; model?: AgentModelRuntime; agentCache?: AgentCachePort; }) | undefinedOptionalSee the type definition and usage context.

Returns: AgentCoreEngine<Result, State, App>.

run ​

Instance method.

Run the loop with a step function when no workflow is bound. Run a bound workflow from an initial state.

ts
run(step: CoreStep<Result>, options?: { signal?: AbortSignal; modelId?: never; }): Promise<Result>

Run the loop with a step function when no workflow is bound.

ParameterTypePassingDescription
stepCoreStep<Result>Required—
options{ signal?: AbortSignal; modelId?: never; } | undefinedOptional—

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

Branch 1

undefined

Branch 2
FieldTypeRequiredDescription
signalAbortSignal | undefinedOptionalSee the type definition and usage context.
modelIdundefinedOptionalSee the type definition and usage context.

Returns: Promise<Result>.

Awaited value: Awaited<Result>.

ts
run(state: State, options?: { signal?: AbortSignal; modelId?: string; }): Promise<Result>

Run a bound workflow from an initial state.

ParameterTypePassingDescription
stateStateRequired—
options{ signal?: AbortSignal; modelId?: string; } | undefinedOptional—

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

Branch 1

undefined

Branch 2
FieldTypeRequiredDescription
signalAbortSignal | undefinedOptionalSee the type definition and usage context.
modelIdstring | undefinedOptionalSee the type definition and usage context.

Returns: Promise<Result>.

Awaited value: Awaited<Result>.

Examples ​

A single ordinary step is enough to run ​

Beginner · Node.js

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

const agent = new AgentCoreEngine<string>();
const answer = await agent.run(() => ({ type: 'complete', value: '你好,Core' }));
console.log(answer);
js
import { AgentCoreEngine } from '@jangts/agent-core/engine';
const agent = new AgentCoreEngine();
const answer = await agent.run(() => ({ type: 'complete', value: '你好,Core' }));
console.log(answer);

Add an explicit Workflow and still call run ​

Configuration · 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')],
  }],
});

const agent = new AgentCoreEngine({ workflow });
console.log(await agent.run({ name: 'Ivan' }));
console.log(await agent.run({ name: '访客' }));
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')],
        }],
});
const agent = new AgentCoreEngine({ workflow });
console.log(await agent.run({ name: 'Ivan' }));
console.log(await agent.run({ name: '访客' }));

Bind once when dependencies become ready later ​

Extension · Node.js

No Workflow was passed again. The supplied signal is merged with the instance signal; cancellation does not let a late result become a successful commit.

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')],
  }],
});

const agent = new AgentCoreEngine<string>({ maxRounds: 2 }).bindWorkflow(workflow);
const controller = new AbortController();
console.log(await agent.run({ name: 'Ivan' }, { signal: controller.signal }));
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')],
        }],
});
const agent = new AgentCoreEngine({ maxRounds: 2 }).bindWorkflow(workflow);
const controller = new AbortController();
console.log(await agent.run({ name: 'Ivan' }, { signal: controller.signal }));

API reference, usage examples and developer guides.