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
import { AgentCoreEngine } from '@jangts/agent-core/engine';import { AgentCoreEngine } from '@jangts/agent-core/engine';Other public entry points:@jangts/agent-core, @jangts/agent-core/engine, @jangts/agent-core/types.
Definition
class AgentCoreEngine<Result, State, App>Type parameters
| Type parameter | Constraint | Default type |
|---|---|---|
Result | — | — |
State | — | unknown |
App | — | undefined |
Constructor
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.
| Parameter | Type | Passing | Description |
|---|---|---|---|
settings | AgentCoreEngineSetup<State, Result, App> | Optional | — |
Optional shapes of Parameter settings: choose one shape; required fields for each branch are listed separately.
Branch 1
| Field | Type | Required | Description |
|---|---|---|---|
cache | EngineCacheOptions | undefined | Optional | Engine-local LRU bounds; not copied as cache data when forking. |
agentCache | AgentCachePort | undefined | Optional | Borrowed App service cache; forks must explicitly provide their own port. |
maxRounds | number | undefined | Optional | Round budget; must be a positive safe integer. Defaults to 8 rounds. |
execution | ExecutionOptions | undefined | Optional | Cancellation and diagnostics shared by every round. |
errors | { exhausted?: () => Error; } | undefined | Optional | Builds the error thrown when the round budget is exhausted (defaults to a BudgetError). |
branch | AgentBranch | undefined | Optional | Read-only. See the type definition and usage context. |
tools | ToolBinding | undefined | Optional | Read-only. See the type definition and usage context. |
model | AgentModelBinding | undefined | Optional | See the type definition and usage context. |
models | undefined | Optional | See the type definition and usage context. |
workflow | undefined | Optional | See the type definition and usage context. |
app | undefined | Optional | See the type definition and usage context. |
Branch 2
| Field | Type | Required | Description |
|---|---|---|---|
cache | EngineCacheOptions | undefined | Optional | Engine-local LRU bounds; not copied as cache data when forking. |
agentCache | AgentCachePort | undefined | Optional | Borrowed App service cache; forks must explicitly provide their own port. |
maxRounds | number | undefined | Optional | Round budget; must be a positive safe integer. Defaults to 8 rounds. |
execution | ExecutionOptions | undefined | Optional | Cancellation and diagnostics shared by every round. |
errors | { exhausted?: () => Error; } | undefined | Optional | Builds the error thrown when the round budget is exhausted (defaults to a BudgetError). |
branch | AgentBranch | undefined | Optional | Read-only. See the type definition and usage context. |
tools | ToolBinding | undefined | Optional | Read-only. See the type definition and usage context. |
model | string | undefined | Optional | See the type definition and usage context. |
models | Readonly<Record<string, AgentModelBinding>> | Required | See the type definition and usage context. |
maxModelCalls | number | undefined | Optional | See the type definition and usage context. |
workflow | undefined | Optional | See the type definition and usage context. |
app | undefined | Optional | See the type definition and usage context. |
Branch 3
| Field | Type | Required | Description |
|---|---|---|---|
cache | EngineCacheOptions | undefined | Optional | Engine-local LRU bounds; not copied as cache data when forking. |
agentCache | AgentCachePort | undefined | Optional | Borrowed App service cache; forks must explicitly provide their own port. |
maxRounds | number | undefined | Optional | Round budget; must be a positive safe integer. Defaults to 8 rounds. |
execution | ExecutionOptions | undefined | Optional | Cancellation and diagnostics shared by every round. |
errors | { exhausted?: () => Error; } | undefined | Optional | Builds the error thrown when the round budget is exhausted (defaults to a BudgetError). |
branch | AgentBranch | undefined | Optional | Read-only. See the type definition and usage context. |
tools | ToolBinding | undefined | Optional | Read-only. See the type definition and usage context. |
model | AgentModelBinding | undefined | Optional | See the type definition and usage context. |
models | undefined | Optional | See the type definition and usage context. |
workflow | AgentWorkflow<State, Result, App> | Required | Read-only. See the type definition and usage context. |
app | App | undefined | Optional | Read-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
| Field | Type | Required | Description |
|---|---|---|---|
cache | EngineCacheOptions | undefined | Optional | Engine-local LRU bounds; not copied as cache data when forking. |
agentCache | AgentCachePort | undefined | Optional | Borrowed App service cache; forks must explicitly provide their own port. |
maxRounds | number | undefined | Optional | Round budget; must be a positive safe integer. Defaults to 8 rounds. |
execution | ExecutionOptions | undefined | Optional | Cancellation and diagnostics shared by every round. |
errors | { exhausted?: () => Error; } | undefined | Optional | Builds the error thrown when the round budget is exhausted (defaults to a BudgetError). |
branch | AgentBranch | undefined | Optional | Read-only. See the type definition and usage context. |
tools | ToolBinding | undefined | Optional | Read-only. See the type definition and usage context. |
model | string | undefined | Optional | See the type definition and usage context. |
models | Readonly<Record<string, AgentModelBinding>> | Required | See the type definition and usage context. |
maxModelCalls | number | undefined | Optional | See the type definition and usage context. |
workflow | AgentWorkflow<State, Result, App> | Required | Read-only. See the type definition and usage context. |
app | App | undefined | Optional | Read-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
| Field | Type | Required | Description |
|---|---|---|---|
workflow | AgentWorkflow<State, Result, App> | Required | Read-only. The bound workflow. |
branch | AgentBranch | Required | Read-only. Identity of this engine's branch. |
Member index
| Member | Purpose |
|---|---|
Workflow | Static. Workflow catalog constructor, exposed so hosts do not import two modules. |
AttemptBudget | Static. Attempt budget, exposed for hosts that gate their own sub-steps. |
createWorkflow | Static. Factory for a validated workflow definition. |
bindModel | Bind the single model this engine will use. |
bindModelRuntime | 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. |
switchModel | Select a configured model, or replace the single bound model's configuration. |
bindToolRuntime | Bind the tool runtime used by workflow context. |
bindWorkflow | 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. |
checkpoint | 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. |
exportCheckpoint | Export a checkpoint for host-owned persistence. |
restoreCheckpoint | 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. |
fork | 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. |
run | Run 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.
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.
| 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>.
AttemptBudget
Static member.
Attempt budget, exposed for hosts that gate their own sub-steps.
new AgentCoreEngine.AttemptBudget(limit: number): AttemptBudget| Parameter | Type | Passing | Description |
|---|---|---|---|
limit | number | Required | — |
Returns: AttemptBudget.
createWorkflow
Static member.
Factory for a validated workflow definition.
AgentCoreEngine.createWorkflow<State, Result, Runtime = undefined>(definition: AgentWorkflowDefinition<State, Result, Runtime>): AgentWorkflow<State, Result, Runtime>Build a validated workflow from a definition.
| Type parameter | Constraint | Default type |
|---|---|---|
State | — | — |
Result | — | — |
Runtime | — | undefined |
| 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>.
bindModel
Instance method.
Bind the single model this engine will use.
bindModel(options: AgentModelBinding): AgentCoreEngine<Result, State, App>Bind the single model this engine will use.
| Parameter | Type | Passing | Description |
|---|---|---|---|
options | AgentModelBinding | Required | — |
Fields of options
| Field | Type | Required | Description |
|---|---|---|---|
provider | ChatProvider | Required | See the type definition and usage context. |
execution | undefined | Optional | See the type definition and usage context. |
transports | readonly ModelTransportDefinition<unknown>[] | undefined | Optional | See the type definition and usage context. |
sink | { output?: ModelRunnerPorts["onOutput"]; } | undefined | Optional | See the type definition and usage context. |
errors | { inputBudget?: ModelRunnerPorts["inputBudgetError"]; outputBudget?: ModelRunnerPorts["outputBudgetError"]; } | undefined | Optional | See the type definition and usage context. |
children | ModelChildPolicy | undefined | Optional | Read-only. See the type definition and usage context. |
maxInputChars | number | undefined | Optional | Character budget for the assembled input. |
maxSchemaChars | number | undefined | Optional | Character allowance for registered capability schemas. |
tokenBudget | ModelTokenBudget | undefined | Optional | See the type definition and usage context. |
maxOutputTokens | number | undefined | Optional | Default output reservation; invoke can override it for one call. |
maxCalls | number | undefined | Optional | Calls allowed for the whole request, including descendant runners' reservations. |
callTimeoutMs | number | undefined | Optional | Deadline for one provider call, in milliseconds. |
maxOutputChars | number | undefined | Optional | Cap on streamed output characters; exceeding it fails the call. |
usage | boolean | undefined | Optional | Request and record provider usage for each call. |
signal | undefined | Optional | See 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.
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.
| Parameter | Type | Passing | Description |
|---|---|---|---|
source | AgentModelRuntime | Required | — |
Fields of source
| Field | Type | Required | Description |
|---|---|---|---|
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>>; } | Required | Invoke 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; } | Required | Prepare 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. |
execution | ExecutionContext | Required | Read-only. See the type definition and usage context. |
remainingCalls | number | Required | Read-only. Calls still available to this runner after the parent's reserve is applied. |
callCount | number | Required | Read-only. Completed calls observed by this runner only. |
totalCallCount | number | Required | Read-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.
switchModel(options: AgentModelBinding | string): AgentCoreEngine<Result, State, App>Select a configured model, or replace the single bound model's configuration.
| Parameter | Type | Passing | Description |
|---|---|---|---|
options | string | AgentModelBinding | Required | — |
Optional shapes of Parameter options: choose one shape; required fields for each branch are listed separately.
Branch 1
string
Branch 2
| Field | Type | Required | Description |
|---|---|---|---|
provider | ChatProvider | Required | See the type definition and usage context. |
execution | undefined | Optional | See the type definition and usage context. |
transports | readonly ModelTransportDefinition<unknown>[] | undefined | Optional | See the type definition and usage context. |
sink | { output?: ModelRunnerPorts["onOutput"]; } | undefined | Optional | See the type definition and usage context. |
errors | { inputBudget?: ModelRunnerPorts["inputBudgetError"]; outputBudget?: ModelRunnerPorts["outputBudgetError"]; } | undefined | Optional | See the type definition and usage context. |
children | ModelChildPolicy | undefined | Optional | Read-only. See the type definition and usage context. |
maxInputChars | number | undefined | Optional | Character budget for the assembled input. |
maxSchemaChars | number | undefined | Optional | Character allowance for registered capability schemas. |
tokenBudget | ModelTokenBudget | undefined | Optional | See the type definition and usage context. |
maxOutputTokens | number | undefined | Optional | Default output reservation; invoke can override it for one call. |
maxCalls | number | undefined | Optional | Calls allowed for the whole request, including descendant runners' reservations. |
callTimeoutMs | number | undefined | Optional | Deadline for one provider call, in milliseconds. |
maxOutputChars | number | undefined | Optional | Cap on streamed output characters; exceeding it fails the call. |
usage | boolean | undefined | Optional | Request and record provider usage for each call. |
signal | undefined | Optional | See the type definition and usage context. |
Returns: AgentCoreEngine<Result, State, App>.
bindToolRuntime
Instance method.
Bind the tool runtime used by workflow context.
bindToolRuntime(tools: ToolBinding): AgentCoreEngine<Result, State, App>Bind the tool runtime used by workflow context.
| Parameter | Type | Passing | Description |
|---|---|---|---|
tools | ToolBinding | Required | — |
Optional shapes of Parameter tools: choose one shape; required fields for each branch are listed separately.
Branch 1
| Field | Type | Required | Description |
|---|---|---|---|
invoke | InvokeTool | Required | See the type definition and usage context. |
Branch 2
| Field | Type | Required | Description |
|---|---|---|---|
invokeAsync | (request: ToolInvocationRequest) => Promise<ToolResult<unknown>> | Required | Invoke 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.
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 parameter | Constraint | Default type |
|---|---|---|
NextState | — | — |
| Parameter | Type | Passing | Description |
|---|---|---|---|
workflow | AgentWorkflow<NextState, Result, undefined> | Required | — |
Returns: AgentCoreEngine<Result, NextState, undefined>.
bindWorkflow<NextState, NextApp>(workflow: AgentWorkflow<NextState, Result, NextApp>, app: NextApp): AgentCoreEngine<Result, NextState, NextApp>Bind a workflow together with its App dependencies.
| Type parameter | Constraint | Default type |
|---|---|---|
NextState | — | — |
NextApp | — | — |
| Parameter | Type | Passing | Description |
|---|---|---|---|
workflow | AgentWorkflow<NextState, Result, NextApp> | Required | — |
app | NextApp | Required | — |
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.
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 parameter | Constraint | Default type |
|---|---|---|
Data | — | — |
| Parameter | Type | Passing | Description |
|---|---|---|---|
data | Data | Required | — |
Returns: AgentCheckpoint<Data>.
Return value structure
| Field | Type | Required | Description |
|---|---|---|---|
id | string | Required | Read-only. Checkpoint identifier, unique within the engine. |
source | AgentBranch | Required | Read-only. Branch the checkpoint was taken on. |
read | () => Data | Required | See the type definition and usage context. |
exportCheckpoint
Instance method.
Export a checkpoint for host-owned persistence.
exportCheckpoint<Data>(checkpoint: AgentCheckpoint<Data>): AgentCheckpointRecord<Data>Export a checkpoint for host-owned persistence.
| Type parameter | Constraint | Default type |
|---|---|---|
Data | — | — |
| Parameter | Type | Passing | Description |
|---|---|---|---|
checkpoint | AgentCheckpoint<Data> | Required | — |
Fields of checkpoint
| Field | Type | Required | Description |
|---|---|---|---|
id | string | Required | Read-only. Checkpoint identifier, unique within the engine. |
source | AgentBranch | Required | Read-only. Branch the checkpoint was taken on. |
read | () => Data | Required | See the type definition and usage context. |
Returns: AgentCheckpointRecord<Data>.
Return value structure
| Field | Type | Required | Description |
|---|---|---|---|
id | string | Required | Read-only. Checkpoint identifier, preserved across export and restore. |
source | AgentBranch | Required | Read-only. Validated branch identity captured at checkpoint time. |
data | Data | Required | Read-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.
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 parameter | Constraint | Default type |
|---|---|---|
Data | — | — |
| Parameter | Type | Passing | Description |
|---|---|---|---|
record | AgentCheckpointRecord<Data> | Required | — |
Fields of record
| Field | Type | Required | Description |
|---|---|---|---|
id | string | Required | Read-only. Checkpoint identifier, preserved across export and restore. |
source | AgentBranch | Required | Read-only. Validated branch identity captured at checkpoint time. |
data | Data | Required | Read-only. Detached data payload; serializable by the host. |
Returns: AgentCheckpoint<Data>.
Return value structure
| Field | Type | Required | Description |
|---|---|---|---|
id | string | Required | Read-only. Checkpoint identifier, unique within the engine. |
source | AgentBranch | Required | Read-only. Branch the checkpoint was taken on. |
read | () => Data | Required | See 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.
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 parameter | Constraint | Default type |
|---|---|---|
Data | — | — |
| Parameter | Type | Passing | Description |
|---|---|---|---|
__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
| Field | Type | Required | Description |
|---|---|---|---|
at | AgentCheckpoint<Data> | Required | See the type definition and usage context. |
workflow | AgentWorkflow<State, Result, App> | WorkflowExtension<State, Result, App> | undefined | Optional | See the type definition and usage context. |
routes | Readonly<Record<string, readonly WorkflowRoute<State, Result, App>[]>> | undefined | Optional | See the type definition and usage context. |
resume | ((checkpoint: Data) => { app?: App; tools?: ToolBinding; model?: AgentModelRuntime; agentCache?: AgentCachePort; }) | undefined | Optional | See 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.
run(step: CoreStep<Result>, options?: { signal?: AbortSignal; modelId?: never; }): Promise<Result>Run the loop with a step function when no workflow is bound.
| Parameter | Type | Passing | Description |
|---|---|---|---|
step | CoreStep<Result> | Required | — |
options | { signal?: AbortSignal; modelId?: never; } | undefined | Optional | — |
Optional shapes of Parameter options: choose one shape; required fields for each branch are listed separately.
Branch 1
undefined
Branch 2
| Field | Type | Required | Description |
|---|---|---|---|
signal | AbortSignal | undefined | Optional | See the type definition and usage context. |
modelId | undefined | Optional | See the type definition and usage context. |
Returns: Promise<Result>.
Awaited value: Awaited<Result>.
run(state: State, options?: { signal?: AbortSignal; modelId?: string; }): Promise<Result>Run a bound workflow from an initial state.
| Parameter | Type | Passing | Description |
|---|---|---|---|
state | State | Required | — |
options | { signal?: AbortSignal; modelId?: string; } | undefined | Optional | — |
Optional shapes of Parameter options: choose one shape; required fields for each branch are listed separately.
Branch 1
undefined
Branch 2
| Field | Type | Required | Description |
|---|---|---|---|
signal | AbortSignal | undefined | Optional | See the type definition and usage context. |
modelId | string | undefined | Optional | See the type definition and usage context. |
Returns: Promise<Result>.
Awaited value: Awaited<Result>.
Examples
- Agent: run first, then bind tools and dependencies step by step: The Engine executes a bounded loop; after a Workflow is bound, each run only receives the data that changed in state.
- 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.
- Bind once, multiple models per run, and switching across runs: Provide stable model configuration at construction; requests select by configuration ID instead of injecting a Provider repeatedly.
- Real tool invocation and in-request runtime: Core registers and executes real tools and returns receipts carrying an invocation; business authorization is owned by the implementation registered by the App.
A single ordinary step is enough to run
Beginner · Node.js
import { AgentCoreEngine } from '@jangts/agent-core/engine';
const agent = new AgentCoreEngine<string>();
const answer = await agent.run(() => ({ type: 'complete', value: '你好,Core' }));
console.log(answer);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
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: '访客' }));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.
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 }));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 }));Related policy source
- Execution implementation of the bounded loop, commit, and cancellation
- Check order for tool input, execution, output, and late results