@noetaris/harness
v0.16.1
Published
Agent execution framework — harness implementation
Readme
@noetaris/harness
Agent execution framework — the harness implementation.
agent = llm + harnessThe harness is the reusable artifact: execution loop, state management, routing, and provider abstraction. The LLM is a swappable commodity component.
Installation
pnpm add @noetaris/harnessRequires Node.js ≥ 22.
Quick Start
import { createHarness, createAgent, field, required, runtime } from '@noetaris/harness'
// 1. Define the dependency interface your steps will need
interface Ctx {
model: { invoke(messages: string[], opts: any): Promise<{ text: string; toolCalls: any[] }> }
tools: Record<string, any>
prompts: { system: string }
}
// 2. Create the harness — fixes Ctx and infers State from the field schema
const base = createHarness<Ctx>()({
messages: field<string[]>({ default: () => [], reduce: (a, b) => [...a, ...b] }),
toolCalls: field<any[]> ({ default: () => [] }),
toolResults: field<any[]>({ default: () => [] }),
})
// 3. Define the loop — validated immediately at call time.
// Each builder call returns a new harness: keep the result.
const withLoop = base.loop(l =>
l.start()
.step('think', {
run: async (state, ctx) => {
const result = await ctx.model.invoke(state.messages, {
tools: Object.values(ctx.tools),
})
return { messages: [result.text], toolCalls: result.toolCalls }
},
route: (state) => state.toolCalls.length > 0 ? 'call_tools' : 'complete',
})
.on('call_tools').to('action')
.on('complete').end()
.step('action', {
run: async (state, ctx) => ({
toolResults: await runTools(state.toolCalls, ctx.tools),
}),
})
.next('think')
)
// 4. Declare providers
const h = withLoop
.provide('tools', { search: new MySearchTool() }) // hard-coded
.provide('prompts', required()) // must be supplied at createAgent()
.provide('model', runtime()) // must be supplied at agent.run() and agent.resume()
// 5. Create an agent — assigns an ID and fills required() slots
const agent = createAgent('my-agent', h, {
prompts: { system: 'You are a helpful assistant.' },
})
// 6. Run
const run = agent.run(
{ messages: ['What is the weather in Paris?'] },
{ model: new MyLLMAdapter() },
)
const outcome = await run
console.log(outcome.signal, outcome.state.messages.at(-1)) // messages is a string[]: no castConcepts
The Loop
A harness loop is a directed graph. Steps are nodes; transitions are edges.
run— transforms state. The only place state changes.route— reads post-run state, emits a named signal. Pure — noctx, no mutation.
Three step patterns:
| Pattern | run | route | Transition |
|---|---|---|---|
| Transform + route | ✅ | ✅ | .on(signal).to(step) |
| Transform + next | ✅ | ❌ | .next(name) or implicit |
| Decision node | ❌ | ✅ | .on(signal).to(step) |
The loop structure is validated at h.loop() call time. Violations are thrown together as a LoopValidationError with a violations: readonly string[] property.
State
State is defined as a schema of field<T>() declarations. The framework infers the State type — no separate interface needed.
const h = createHarness<Ctx>()({
messages: field<string[]>({
default: () => [],
reduce: (accumulated, update) => [...accumulated, ...update],
}),
count: field<number>({ default: () => 0 }),
})
// State = { messages: string[], count: number }Steps return a Partial<State> update. For a field with reduce, the new value is
reduce(current, update); a field without it takes the update as its value. reduce runs for:
- every update a step returns for the field;
- the input of
agent.run()on a session that has stored state (see Turns andrequestId): the input is reduced into the stored value; - the input of a session's first run, or of any run without a session store, for a field that has
a
defaulttoo: the value isreduce(default(), input); - a fork join, for a key several branches wrote.
So with messages: field({ default: () => [systemMessage], reduce: append }), the first
agent.run({ messages: [userMessage] }) starts with [systemMessage, userMessage]. On a first run, a
field without reduce, or without default, takes the input as its value. default alone is used
for a field the input leaves out. reduce does not run for the answer of an interrupt or for debug
setState.
Upgrading. Before, the input of a first run replaced the default of a field with
reduce: the example above started with[userMessage]only. If you passed the full value on the first run to make up for it, drop the part the default already gives.
The agent keeps the State type of its harness. The input of agent.run() and agent.debug() is
any subset of the declared fields, and outcome.state has the declared fields plus the framework
fields $error, $interrupt and $interruptResponses, the same state a step reads:
const agent = createAgent('counter', h.loop(/* … */), {}) // Agent<{ messages: string[]; count: number }>
const { state } = await agent.run({ count: 3 }, {})
state.count + 1 // number, no cast
state.$error?.name // ErrorInfo | null
state.$interruptResponses // Readonly<Record<string, unknown>> | undefined
await agent.run({ cuont: 3 }, {}) // compile error: 'cuont' is not a field of the state
state.total // compile error: not a field of the state| Type | Meaning |
|---|---|
| Agent<State, RuntimeSlots> | An agent of a harness whose state is State and whose runtime() slots are RuntimeSlots. createAgent returns it. |
| RunInput<State> | The input of run() and debug(): { [K in keyof State]?: State[K] | undefined }. |
| RunState<State> | The type of outcome.state: State plus $error, $interrupt and the optional $interruptResponses. |
| RunHandle<S>, RunOutcome<S> | S is the type of outcome.state. run() and both resume()s return RunHandle<RunState<State>>. |
| DebugSession<S>, DebugStop<S> | S is the type of outcome.state at the end of the session (done, and outcome of the end stop). |
Every type parameter defaults to Record<string, unknown>. Agent, RunHandle and RunOutcome
without type arguments are the loose types: any input, any resources, outcome.state is a plain record. Every
agent is assignable to Agent, so use it for a variable, a parameter or an array that holds agents
of different harnesses; an Agent is not assignable back to an Agent<State>. An agent of a
harness without a schema (createHarness<Ctx>()()) has a loose state too; its resources are
still typed by its runtime() slots.
What the types do not cover:
- They state what the schema declares, not what a run guarantees. A field without a
defaultthat no input and no step has set isundefinedat run time, as it is inside a step. - An input written as an object literal does not compile when it has a key outside the schema.
A variable still does when its type fits, for example one typed
Record<string, unknown>or an object with extra keys next to a declared one; so does any input of a looseAgent. The run carries such keys as it always did. - A schema whose type has a string index signature (for example a
Record<string, FieldDefinition<number>>built at run time) declares no field names: its agent is loose.Agent<any>is loose as well, with a state of typeany, and is assignable to and from every agent. - A declared field named like a framework key (
$error,$interrupt,$interruptResponses) is not supported: inoutcome.statethe key has the framework's type. resourcesis typed by theruntime()slots of the harness (see Run resources), not by the state.- The state in
RunEventscallbacks, in a debugSnapshot, insetState()and in a breakpoint condition is a plain record.
Upgrading.
Agent,RunHandle,RunOutcome,DebugSessionandDebugStophave a type parameter with a default, so code that names them without one compiles as before. What changes is the typecreateAgentreturns for a harness with a state schema:
- an input with a key the schema does not declare, or a value of the wrong type, no longer compiles;
outcome.state.xfor anxthe schema does not declare no longer compiles (it wasunknown). Read such a key through a cast toRecord<string, unknown>;- a declared field is no longer
unknown: a cast such asoutcome.state.count as numberis not needed any more, and a cast to an unrelated type no longer compiles;outcome.state.$errorisErrorInfo | nullandoutcome.state.$interruptis{ interruptId, prompt, response? } | null: code that used them without a null check needs one.To keep the old types for one agent, annotate it:
const agent: Agent = createAgent(…).An outcome that is built without running the loop (the store failed at load or claim, the session is busy, the call was refused because an interrupt is pending) now has
state.$interrupt: null, as every other outcome has. The key used to be absent there.
Forks and joins
.fork(name) splits the run into branches that run at the same time. Each branch starts from its
own copy of the state at the fork, so a branch sees its own writes and never a sibling's. When
every branch has ended, the join puts the branches' writes back into the main state, and the step
after the fork runs.
const h = createHarness<Ctx>()({
notes: field<string[]>({ default: () => [], reduce: (a, b) => [...a, ...b] }),
summary: field<string>(),
})
h.loop(l =>
l.start()
.step('plan', { run: async () => ({ notes: ['plan'] }) })
.fork('gather')
.branch('web', b => b.start().step('search', { run: async () => ({ notes: ['web'] }), route: () => 'done' }).on('done').end())
.branch('docs', b => b.start().step('read', { run: async () => ({ notes: ['docs'], summary: 'from docs' }), route: () => 'done' }).on('done').end())
.join('write', { run: writeReport, route: () => 'done' }) // sees notes: ['plan', 'web', 'docs']
.on('done').end()
)The join goes through the branches in the order they are declared, whatever order they finished in:
| The key was written by | The join gives |
|---|---|
| no branch | the value from before the fork |
| one branch | that branch's value of the key (for a key with reduce: the value from before the fork with the branch's updates folded in) |
| several branches, key has reduce | the value from before the fork, then every update the branches' steps returned for the key, folded in one by one with reduce: all of the first branch's, then the second's, and so on |
| several branches, no reduce | the run rejects with MissingReducerError |
- A branch has written a key when one of its steps returned it, also when the value is the same as before the fork.
- The value from before the fork is counted once: the join folds what the branches returned, not each branch's whole value.
- A fork inside a branch joins into that branch's state first; what its branches wrote then counts as written by the branch that holds it.
- A fork that pauses (an interrupt or a stop in a branch) saves each branch's state and writes with the run, so the join gives the same value when the fork is finished later or by another process.
- Updates must be plain JSON data to be folded one by one. The harness keeps a copy of every
update a branch returns for a key with
reduce, and only of plain JSON data, because that is what a store gives back unchanged. Plain JSON data is:null, booleans, strings, finite numbers except-0, arrays without holes or extra properties, and plain objects ({}literals with enumerable string keys only), holding only such values, at most 64 levels deep. When a branch returns anything else for a key (undefined, a function, aDate, a class instance, aBigInt,NaN, a value that throws when read, …), the join stops folding that branch's updates of that key one by one: if a sibling wrote the key too, it folds the branch's whole value of the key as a single update. The whole value already holds the value from before the fork, so an append reducer then shows that value twice. Other keys and other branches are not affected. In a nested fork this goes up one level: when an inner branch is folded by its whole value for a key, the branch that holds the inner fork is folded by its whole value for that key too. - The kept updates use memory until the join. Each branch holds all updates it returned for
keys with
reduce, next to its state: a branch that loops many times grows with every round, also when the reducer itself keeps only the last few values, and a paused fork's row holds them too. Keep long loops outside the branch, or write the key once at the end of the branch. - Framework keys (
$error,$interrupt,$interruptResponses) are not joined this way.
When a branch fails. A branch fails when one of its steps throws an error that the branch does
not handle (its own l.onError() step or an error-aware route). The fork then fails fast: it
aborts the ctx.signal of the other branches, waits until they have ended, and fails as a step
would: state.$error holds the error, and the run goes to the l.onError() step of the loop the
fork is in, or pauses on the fork with signal: '$error'. There is no join, and what the branches
wrote is dropped.
- The fork fails with the error of the branch that ended failed first. What counts is the
moment the branch ends, not the moment a step throws: a branch that holds an inner fork ends
only when every branch of that inner fork has ended, so a sibling whose step throws later can
still end failed first, and the fork then reports the sibling's error. A branch that ends
failed later, for example with an error of its own after the abort, does not replace the first
one. Branches that end failed in the same tick are ordered by the engine's promise scheduling;
only when their steps throw after the same number of
awaits (two first steps that throw at once, for example) is it the one declared first. - A branch that the abort cut is stopped, not failed. When a step of a sibling throws the
abort after the fork started to fail (see "What a stop gives" for what counts as the abort),
that branch ends there: its
l.onError()step does not run, an error-awarerouteis not called, andevents.onErroris not called for it. Observers getonStepSettledwithoutcome: 'stopped'and noonStepErrorfor the cut step, and the branch'sonRunEndhas$stopped. A fork inside a cut branch settles as'stopped'too (as'interrupt'when one of its branches was waiting on an interrupt). - An
AbortErrorthat a branch throws before any branch has failed (a timeout of its own, for example) is an error like any other, and fails the fork. - A sibling that ignores
ctx.signal(or catches the abort and returns) finishes the step it is in. It starts no further step: it stops at its next step boundary, and itsonRunEndhas$stopped. The fork waits for it and drops what it wrote. - A sibling that was waiting on an interrupt is dropped with the fork: nothing is left to answer,
and
state.$interruptisnullin the outcome.events.onInterruptand the observer'sonInterruptwere already called when the step raised the interrupt; nothing takes that back. The same holds for an interrupt raised in a fork inside a cut branch. - A failed fork is not saved branch by branch. When the run pauses on it with
$error, the next run starts the whole fork again, every branch from its first step. - In nested forks the error goes up level by level: the inner fork fails with the error of its branch, the branch that holds it fails with the same error (unless it handles it), and the outer fork reports that error while its other branches are cut.
Errors and $error
When a step's run or route throws, the framework writes the error into state.$error and:
- calls the step's own
route, when the step is declared withoptin: '$error'; - else goes to the
l.onError(step)step, when the loop has one; - else pauses the run: it settles with
signal: '$error'.
$error is null when there is no error, and it is set back to null when a later step's run
finishes well.
state.$error is a plain object (ErrorInfo), not the Error that was thrown:
{
name: 'QuotaError', // the error's name
message: 'quota used up',
stack: 'QuotaError: quota used up\n at …', // when the error has one
cause: { name: 'RangeError', message: 'socket closed', stack: '…' }, // when the error has one
code: 'E_QUOTA', // every other own enumerable field of the error
status: 429,
}l.onError('recover').start()
.step('call', { run: async () => { throw new QuotaError('quota used up') } })
// …
l.step('recover', {
run: async (state) => ({ note: `${state.$error?.name}: ${state.$error?.message}` }),
route: (state) => 'failed',
})- It is the same in every place: in the step after
l.onError(), in an error-awareroute, inoutcome.state.$error, in the row a session store saves, and in a step or a caller of another process that loads the session. It passes throughJSON.stringifyandstructuredCloneunchanged, so a run on the in-memory store and a run on a database see the same thing. instanceofis alwaysfalseon it. Test the name:state.$error?.name === 'QuotaError'.causehas the same shape, at most 8 levels deep. A cause that is not an error ({ cause: 'text' }) becomes{ name: 'Error', message: 'text' }. A cause ofnullorundefinedis no cause.- The other fields, and the
errorsof anAggregateError, are written as JSON would write them: aDateas an ISO string (anytoJSONis used), objects and arrays copied, functions, symbols andundefinedleft out (nullinside an array, also for a hole), a number that is not finite asnull,-0as0, aMapor aSetas{}. Apart from JSON: abigintbecomes its decimal string; anErrorinside a field or an array gets this same shape (other entries of anerrorslist stay as they are); a key named__proto__is left out; a field that cannot be read, that points back into the error, or that sits more than 8 levels deep is left out. - A thrown value that is not an object (
throw 'text') gives{ name: 'Error', message: 'text' }without astack. A thrown object that is not anErroris copied like one: itsnameandmessagewhen they are strings, and its fields. A thrown value that cannot be inspected (a revokedProxy) gives{ name: 'Error', message }; the run still settles. - The stack trace, with its file paths, is in the state, so a session store saves it and
outcome.statecarries it. Remove it before you send a state to a client. - The own fields of the error are copied and saved too, whatever they hold. An HTTP client error that carries the request (headers, a token) puts them into the store and into every checkpoint: keep secrets off error objects, or catch the error in the step and throw a smaller one. The copy has a depth limit (8 levels) and no size limit.
toErrorInfo(error)gives this same plain copy. It is the function the framework uses, so a test can build a realistic$errorfor a step that reads it, or compare an outcome with it:expect(outcome.state.$error).toEqual(toErrorInfo(thrown)).- The errors the framework itself reports in
$error(SessionBusyError,LeaseExpiredError,StoreLoadError,SessionPendingInterruptError) have this shape too:name,message, and their fields (sessionId,retryAfter,cause). - The thrown object itself goes to
events.onError(error, stepName), toevents.onStoreError, and to the observer (onStepError,onStepSettled,onRunEnd). A thrown value that is not anErrorreaches them asnew Error(String(value)).
Errors a call throws
Not every error ends up in state.$error. A mistake in the code that builds or calls the agent is
thrown at the call, and a mistake in the loop definition rejects the run:
| Where | How it reaches you | Error classes |
|---|---|---|
| h.loop(), h.definition() | thrown | LoopValidationError, LoopNotDefinedError; a plain Error from h.loop() for a builder call in the wrong place (.branch() that does not follow .fork() or another .branch(), .on() on a fork) |
| createAgent() | thrown | MissingLoopError, MissingSlotError, RuntimeSlotInAgentError, ReservedRuntimeSlotError, UnknownSlotError, MissingStoreSlotError, UnexpectedStoreSlotError, InvalidAgentOptionError, InvalidClaimOptionsError |
| agent.run(), agent.resume(), agent.debug() | thrown, before a run starts | MissingRuntimeSlotError, RequiredSlotInRunError, UnknownRunSlotError (the message names the call), InvalidRunResourceError, SessionInFlightError, SessionInDebugError, SessionPendingInterruptError (run() without a session store) |
| handle.resume() while the session is running | thrown | SessionInFlightError |
| agent.resume(), handle.resume(), DebugSession.answer() with no matching interrupt | thrown, or the returned promise rejects: handle both with one try around the await | NoInterruptError |
| a run | the handle's promise rejects | UnknownSignalError, NoNextStepError, MissingReducerError |
| a DebugSession command | next(), continue(), stepInto(), continueAll(), answer(): the command's promise rejects; focus(), setState() (synchronous): thrown | DebugCommandError |
Every one of these classes is exported from @noetaris/harness, and here the error is the object
itself, so instanceof works:
import { MissingRuntimeSlotError, UnknownSignalError } from '@noetaris/harness'
try {
const outcome = await agent.run(input, resources)
if (outcome.state.$error?.name === 'SessionBusyError') { /* a plain object: compare the name */ }
} catch (error) {
if (error instanceof MissingRuntimeSlotError) { /* thrown by run(): error.key is the slot */ }
else if (error instanceof UnknownSignalError) { /* the run rejected: error.step, error.signal */ }
else throw error
}- A thrown or rejected error: use
instanceofwith the exported class. state.$error: a plain object, comparename(see above).- The object given to
events.onError,events.onStoreErrorand the observer is the thrown one, soinstanceofworks there too, also forSessionBusyError,LeaseExpiredErrorandStoreLoadError, which a caller otherwise only sees by name instate.$error.
Upgrading.
state.$errorused to be the thrownErrorobject, and a store that writes JSON lost itsname,messageandstack. It is now always the plain object above.
outcome.state.$error instanceof SomeErroris now alwaysfalse: comparename.FrameworkState['$error']isErrorInfo | null(it wasError | null).name,message,stackread as before; any other field isunknown.causeis a plain object too, also when the original cause was a string or a number.- A thrown string no longer gets a
stackin$error.- Code that needs the object (its class, its methods) takes it from
events.onErroror the observer.- Rows written by an older version are not rewritten: a session saved with an error by a JSON store still has
$error: {}, and a step that continues it reads that.
Providers
h.provide() is the single extension point — everything on ctx comes through it.
h.provide('tools', { search: myTool }) // hard-coded — shared by all agents
h.provide('prompts', required()) // build-time — supplied at createAgent()
h.provide('model', runtime()) // per-run — supplied at agent.run() and agent.resume()Run resources
The second argument of agent.run() and agent.debug(), and the fourth of agent.resume(), is
resources. It holds a value for every runtime() slot, plus any of the reserved keys below. The
agent takes its type from the harness, so a mistake fails to compile:
const h = createHarness<{ model: Model; prompts: Prompts }>()(schema)
.provide('prompts', required())
.provide('model', runtime())
.loop(/* … */)
const agent = createAgent('chat', h, { prompts }) // Agent<State, { model: Model }>
agent.run(input, { model, sessionId: 'chat-1' }) // ok
agent.run(input, { sessionId: 'chat-1' }) // compile error: 'model' is missing
agent.run(input, { model, modle: model }) // compile error: unknown key
agent.run(input, { model, checkpoint: 'always' }) // compile error: not a CheckpointMode
agent.resume(answer, 'chat-1', 'q1') // compile error: resume() needs { model }| Reserved key | Type | Read by |
|---|---|---|
| sessionId, requestId | string | run(), debug() |
| signal | AbortSignal | all three |
| listeners | Record<string, RunListener> | all three |
| events | RunEvents | all three |
| observer, onObserverError | Observer, ObserverErrorSink | all three |
| claimOptions | ClaimOptions | all three |
| parentRunId | string | all three |
| checkpoint | CheckpointMode | all three |
resume()needsresourcesonly when the harness hasruntime()slots. Without them, the argument can be left out, andresourcestakes the reserved keys only.- A listener can declare the payload it expects:
{ 'tool.call': (p: ToolCallEvent) => … }compiles without a cast. Nothing checks that the step emits that type. claimOptionstakes extra fields for the store next tottlMs: they are passed on tostore.claim.- A
runtime()slot cannot have the name of a reserved key.createAgent()does not compile for such a harness, and throwsReservedRuntimeSlotErrorat run time. - A
runtime()marker inside a provided value (provide('cfg', { key: runtime() })) is not a slot. It is not in the type ofresources, andrun()does not ask for it: only a marker given directly toprovide()makes a runtime slot. - The calls still check
resourcesat run time, for callers without types. A looseAgent(no type arguments) takes anyresources, as before.
Upgrading. This is a breaking change for types only; the run-time checks are the same.
Agenthas a second type parameter,RuntimeSlots(defaultRecord<string, unknown>). Code that passes a wrongresourceson purpose (for example a test ofMissingRuntimeSlotError) no longer compiles: mark the line with// @ts-expect-error, or annotate the agent as the looseAgent. Aruntime()slot named like a reserved key, which used to be accepted, is now rejected.ClaimOptionshas an index signature for the extra fields of the store.
Session Store
h.store() adds persistence. The reserved session key is used by the framework to save and restore state across runs.
import { InMemorySessionStore } from '@noetaris/harness-store'
h.store({
session: new InMemorySessionStore(), // framework-managed lifecycle
})Note: Only the
sessionkey is processed today. Surfacing additional store keys to steps asctx.store.<name>is planned but not yet wired up — non-session keys passed toh.store()are currently ignored.
The framework injects ctx.sessionId automatically on every run — no declaration in Ctx needed.
Session phase: agent.status()
await agent.status(sessionId) tells where a session stands. There are five phases:
| Phase | Meaning | Who can see it |
|---|---|---|
| in-flight | this agent instance is running the session right now | only the agent instance that runs it |
| fresh | no run is stored | everyone who reads the store |
| paused | the last run paused: on an interrupt (pendingInterrupts lists them), a stop or an unhandled error | everyone who reads the store |
| completed | the last run reached an .end(); signal is its exit signal | everyone who reads the store |
| running | the last stored run is a checkpoint (see Checkpoints): the run is still going in another instance, its instance died, or its final save failed | everyone who reads the store |
const run = agent.run(input, { sessionId: 's1' })
await agent.status('s1') // { phase: 'in-flight', step: null }
await run
await agent.status('s1') // the stored phase, for example { phase: 'completed', signal: 'done' }in-flightcomes from the agent's memory, not from the store. It is the answer from the momentrun(),resume()orhandle.resume()returns its handle until that handle settles, also while a stop is pending. The store is not read.stepis alwaysnull; usehandle.currentStepfor the step that is running.- It is per agent instance. Another process, and a second agent created in the same process,
read the store: for a session this agent runs they get the last settled phase (
freshduring the first turn,completedduring a later one,pausedduring a resume), orrunningonce the run has saved a checkpoint. - Once the handle settles, the answer is the stored phase again at once. With checkpoints on, a
run whose final save failed leaves its last checkpoint in the store. So this instance then
reports
runningtoo. - A call that throws before a run starts (a bad resource,
SessionInFlightError) changes nothing. - A session held by
agent.debug()isin-flightwhile its run is held at a stop or executing. At an interrupt stop the run has settled, so the answer is the storedpausedphase with the pending interrupt. - Without a session store the answer is
in-flightorfresh, nothing else.
Turns and requestId
With a session store, a session is a conversation thread. Each agent.run() on it is one
turn (a request). A turn may span several runs — run(), then a resume() for each
interrupt — and every run of a turn is saved with the turn's requestId.
// one turn per user message, on one thread
await agent.run({ messages: [msg1] }, { sessionId: 'chat-1', requestId: 'msg-1' })
await agent.run({ messages: [msg2] }, { sessionId: 'chat-1', requestId: 'msg-2' })A new turn continues from the state the last turn left: each input field is merged with its
reduce (or replaced when it has none), and the run starts again from the entry step.
$error, $interrupt and $interruptResponses start fresh for each new turn.
requestId is optional. It is the turn's idempotency key: a call with a requestId the
session already ran does not run it again. What agent.run(input, { sessionId, requestId })
does depends on the session's latest run:
| Latest run | No requestId, or a new one | The latest run's requestId (a retry) |
|---|---|---|
| none | runs from the entry step | – |
| completed | a new turn | returns its outcome, runs nothing |
| paused on an interrupt | resolves $error with SessionPendingInterruptError | returns its outcome (signal: '$interrupt'), runs nothing |
| paused by a stop or an unhandled error | merges the input and continues from where it paused | continues from where it paused, without merging the input again |
| a checkpoint ('running': its instance died mid-run or its final save failed, see Checkpoints) | merges the input and continues from the last finished step | continues after the last finished step, without merging the input again |
A retry of an earlier request (not the latest) is found with the store's optional
findRequest and its outcome is returned; it never runs again, since later turns have
moved on from it. A store without findRequest only recognises the latest run's
requestId, so a late retry of an earlier request runs as a new turn.
Notes:
- A retry returns the request's current outcome, not its first response: if the turn
paused and was then resumed to completion, the retry returns the completed outcome. A
retry that returns
signal: '$interrupt'can be resumed from its handle. - A returned (not re-run) outcome fires no observer events and saves nothing; its
handle.runIdhas no stored run and no trace. - Without a
requestId, every call is a new turn. For a session that serves one request, passrequestId: sessionIdto get "run once, then return the result". - Duplicate calls at the same time are safe only with a store that supports claims: the
second call resolves
$errorwithSessionBusyErrorand its retry then returns the outcome. Without claims, both calls may run. - Without a session store,
requestIdis ignored. sessionIdandrequestIdmust be non-empty strings when given; otherwiseagent.run()throwsInvalidRunResourceError.
Checkpoints
By default a session is saved only when a run settles. If the instance dies in the middle of a
long turn, the next run starts the whole turn again, and the side effects of the steps that
already finished happen again. With checkpoint: 'step', the session is also saved after every
finished top-level step:
const agent = createAgent('agent', h, {}, { checkpoint: 'step' }) // every run of this agent
agent.run(input, { sessionId, requestId, checkpoint: 'off' }) // or per call: 'off' | 'step' turn ── a ── save ── b ── save ── c ──✕ crash
↑
next run ─────────┘ continues from c; a and b do not run again- Each checkpoint is a new stored run with
phase: 'running',step= the next step to run, and the state after the finished step.agent.status()reports it as{ phase: 'running', step, instanceId?, checkpointedAt }, except in the agent instance that runs the session, which reportsin-flight(see Session phase). - Running the session again continues from that step, like a stopped run (see the table above):
a retry with the same
requestIddoes not merge its input again. With a store that supports claims, another instance getsSessionBusyErrorwhile the owner's claim is alive, and can take over once it expires. - Steps run at least once: only the step that was running when the instance died runs again, so only that step needs to be idempotent.
- A fork is saved as a whole: there is a checkpoint before it and after it, none inside. A crash inside a fork runs the whole fork again.
- Checkpoints do not change how the claim is kept: it is extended once per step boundary, with
or without them (see Keeping the claim). A single step that runs longer
than the claim TTL still needs
ctx.keepAlive(). onCheckpoint(ctx, { step, version, durationMs })on an observer reports each saved checkpoint. A checkpoint that is skipped (its state can't be copied withstructuredClone, or the store failed) is reported toevents.onStoreErrorwith phase'checkpoint', and the run goes on.- When the store reports that another writer saved the session first, or that this instance's
claim was taken over, the run stops at once with
LeaseExpiredError(reported with phase'claim') and saves nothing more. Detecting a taken-over claim needs a store that checksSaveOptions.leaseonsave()(see Fencing). - Without a session store the option does nothing. Each checkpoint is one store write per step.
Limits:
- Nothing in core looks for runs whose instance died. The session continues only when something
runs it again: a retry with the same
requestId, a queue that redelivers the request, or your own sweep over sessions whoseagent.status()is'running'. - Every checkpoint is a stored run, and none are removed:
loadHistory()grows by one run per finished step. Filter byphasewhen you read it. branch()starts from the last stored run of arunId. It can't start from an earlier checkpoint of that run.- It is all top-level steps or none; you can't pick which steps save.
- A step has no fencing token to pass to other systems. A stale instance is stopped at its next save to the session store, but what its step already wrote elsewhere stays written.
- If a save reached the store but the call still failed (a timeout, a dropped connection), the
next checkpoint conflicts with it and the run stops with
LeaseExpiredError. The next run continues from that save; steps still run at least once.
Upgrading.
StoredRun.phaseandSessionPhasehave a new value,'running'. Aswitchthat handles every phase needs a case for it.checkpointis now a reserved run resource. Aruntime()slot namedcheckpointno longer reachesctx, and the value passed under that key must be'off'or'step'. Rename the slot.SessionStore.savetakes an optional fourth argument,SaveOptions. Existing stores keep working, without fencing.- With a store that fences, a run whose final save is rejected because it lost its claim now settles
$errorwithLeaseExpiredError. Before, it returned its result although the store did not keep it.
Keeping the claim
With a store that supports claims (claim), a run claims its session for the claim TTL
(claimOptions.ttlMs, default 30 000 ms). While the claim is alive, another instance that runs
the session gets SessionBusyError. If the owner dies, the claim frees itself when the TTL runs
out.
SessionBusyError.retryAfter says how long to wait: the milliseconds until the holder's claim
ends. Core asks the store for it with store.claimExpiresIn(agentId, sessionId), once, right
after the refused claim.
const outcome = await agent.run(input, { sessionId })
const error = outcome.state.$error // ErrorInfo | null (the agent's harness declares a state schema)
if (error?.name === 'SessionBusyError') {
const ms = error['retryAfter'] as number | undefined // milliseconds, or undefined
if (ms !== undefined) res.setHeader('Retry-After', Math.ceil(ms / 1000)) // the header is in seconds
return res.status(429).end()
}- It is a hint. The holder extends its claim at every step, so the session can stay busy longer; it releases the claim when its run settles, so the session can be free sooner.
- It is
undefinedwhen the store has noclaimExpiresIn, when that call fails or does not give a finite number of 0 or more, and when the claim was already gone at the lookup (a retry at once may then succeed). A failed lookup is not reported: the outcome is stillSessionBusyError, andonStoreErrorfires once, with that error. PostgresSessionStoreandRedisSessionStorehaveclaimExpiresIn. A custom store addsclaimExpiresIn(agentId, sessionId): Promise<number | null>: the milliseconds until the current claim ends,nullwhen no claim holds the session. The cost is one store call per refused claim.
The TTL of a call is its claimOptions resource, then AgentOptions.claimOptions, then
HARNESS_CLAIM_TTL_MS, then 30 000 ms. ttlMs must be a finite number greater than 0. A
claimOptions resource that is not an object with such a ttlMs makes run(), debug() and
resume() throw InvalidRunResourceError at the call, before the session is touched; it does not
fall back to the default.
An HARNESS_CLAIM_TTL_MS that is set but not such a number is not used: the TTL is 30 000 ms.
The first time this happens, core gives a Node process warning (process.emitWarning). It
warns once per process.
Every claim also says who asks for it. When the agent was created with instanceId, core passes
it to the store as options.instanceId of store.claim(agentId, sessionId, options), from
agent.run(), agent.resume(), handle.resume() and agent.debug() alike. A store that
records it (in its claim record, and as instanceId on the Lease it returns) lets an operator
see which instance holds a session. Without an instanceId on the agent the key is absent.
- The id is always the agent's own. An
instanceIdinside aclaimOptionsresource or insideAgentOptions.claimOptionsis dropped; the other fields of both are passed on tostore.claim. store.extendClaim(lease, { ttlMs })gets noinstanceId: extending a claim does not change its holder, and the lease the store returned already carries it.- A custom store that ignores
instanceId, or returns aLeasewithout it, works as before. Core does not readLease.instanceId.
A run that makes progress keeps its claim. Before every step but its first, core calls
store.extendClaim(lease, { ttlMs }), and the claim lives for one more TTL from that moment:
claim ── a ── extend ── b ── extend ── c ── save ── release
└─ TTL ─┘ └─ TTL ─┘ └─ TTL ─┘So the TTL does not have to cover the whole run. It has to cover each stretch between two extensions: from the claim to the end of the first step (loading the session and, on a resume, writing the answer are inside it), and after that each single step, from one step boundary to the next.
- Steps inside fork branches extend the claim too. Branches that finish a step at the same time share one call.
- It is the same for
agent.run(),agent.resume(),handle.resume()andagent.debug(), and the same withcheckpoint: 'step': one extension per step boundary, never two. - The cost is one store call per step. A single-step run makes none. The call is awaited: the next step starts when the store has answered, so a store call that hangs holds the run at that boundary, as a checkpoint save does.
- A step that runs longer than the TTL loses the claim: the run stops at the next step boundary
with
LeaseExpiredErrorand saves nothing. The last step has no boundary after it, so the lease is checked once more before the final save. Checkpoints do not help inside a step. For such a step, callctx.keepAlive()between pieces of work, start a background renewal withconst stop = ctx.keepAlive({ every: ms })(callstop()in afinally), or use a TTL longer than the step. - When the store answers an extension with "the claim is gone" (it rejects with an error named
LeaseNotFoundError, asPostgresSessionStoreandRedisSessionStoredo), the run stops at that boundary withLeaseExpiredError, the store's error as itscause, and saves nothing. - Any other failed extension (the store is down, a timeout) is ignored. The run goes on with the
lease it holds, and the next step boundary tries again. If the lease runs out first, the run
stops with
LeaseExpiredError. A custom store that rejects with another error gets this. - A store with
claimbut withoutextendClaimis never asked to extend: there the TTL has to cover the whole run, asctx.keepAlive()can do nothing either. A lease whoseexpiresAtisInfinityis not extended. Without a claiming store nothing here applies.
Upgrading. A run on a claiming store now makes one
extendClaimcall per step boundary also when checkpoints are off. A run of several steps that together take longer than the claim TTL no longer ends withLeaseExpiredError.A
claimOptionsresource with a badttlMs(0, negative,NaN,Infinity, not a number) or that is not an object used to be passed to the store as it was, or silently replaced by the default. The call now throwsInvalidRunResourceError. OmitclaimOptionsto get the default.
store.claimnow getsoptions.instanceIdwhen the agent has aninstanceId. A store that spreadsoptionsinto its claim record starts to store it.AgentOptions.claimOptionsis passed to the store with all its fields, as aclaimOptionsresource is; before, onlyttlMswas kept. AninstanceIdwritten insideclaimOptionsno longer reaches the store.
SessionBusyError.retryAfteris now set, with a store that hasclaimExpiresIn. It is the milliseconds until the claim ends, not a time since the epoch as its comment said before (the field was never set). A store withoutclaimExpiresInworks as before.
Fencing
With a store that supports claims, a run holds a lease on its session. A lease can be lost while
the run still works: the claim expires (a single step ran longer than the claim TTL without
ctx.keepAlive(), or the claim could not be extended in time), and another instance claims the
session and runs it. The first instance is now stale. Without fencing, its next save would
overwrite the new owner's progress.
Core already stops a run at the next step boundary once its lease has expired by the local clock.
It checks once more before the final save, so this holds even with a store that ignores
SaveOptions.lease. Fencing covers what that check can't see: a save made before that boundary, and clocks that differ
between instances.
So every save a run makes while it holds a claim (each checkpoint, the final save, and writing an
interrupt answer on resume()) passes the lease as SaveOptions.lease. A store that fences
checks, in the same atomic step as the version check, that the session's claim is still that
lease. If not, it writes nothing and throws an error named LeaseLostError.
A (stale): save {lease A} ──► store: claim is now B's → LeaseLostError → A stops, $error
B (owner): save {lease B} ──► store: claim ok, version ok → savedWhat the caller of the stale run sees:
- The run settles
signal: '$error'withLeaseExpiredErrorinstate.$error(name: 'LeaseExpiredError'). Itscauseis the store'sLeaseLostError(cause.name).events.onStoreErrorgets theLeaseExpiredErrorobject with phase'claim'. - Nothing more is saved for that run.
- Any other error from the final save is still only reported (phase
'persist'), and the run keeps its signal.
PostgresSessionStore and RedisSessionStore fence. InMemorySessionStore and
LocalFileSessionStore have no claims, so there is nothing to fence. A custom store that ignores
SaveOptions keeps only the version check.
Interrupts
A run can be stopped or resumed:
const run = agent.run(initialState, slots)
run.stop() // no further step starts, and ctx.signal aborts; settles with signal null
// When a step calls ctx.interrupt(), the run settles with signal "$interrupt".
// Resume in the same process:
const resumed = run.resume(response, interruptId)
// Or cross-process (requires a session store). Pass the runtime() slots again:
const resumed = agent.resume(response, sessionId, interruptId, { model })agent.resume() takes resources as its fourth argument. Like run(), it needs a value for
every runtime() slot of the harness, and checks them the same way: a missing slot throws
MissingRuntimeSlotError, a required() slot throws RequiredSlotInRunError, and a key that is
neither a runtime() slot nor a reserved resource throws UnknownRunSlotError. Slot values are not
stored with the session, so the process that resumes passes its own. run.resume() and a
resume() on the handle that agent.resume() returns reuse the slots of the call that made the
handle. An agent without runtime() slots can leave resources out. With them, the argument is
required in the type too (see Run resources).
ctx.interrupt() inside a try/catch. The first time a step reaches ctx.interrupt(), the
call does not return: it pauses the run by throwing an internal error named InterruptPause
through the step. A catch around the call gets that error too. Throw it again, or the run does
not pause as it should. The class is not exported; test it with isInterruptPause():
import { isInterruptPause } from '@noetaris/harness'
run: async (state, ctx) => {
try {
const answer = await ctx.interrupt('Approve?', 'approval')
return { approved: await save(answer) }
} catch (error) {
if (isInterruptPause(error)) throw error // the pause: always pass it on
return { approved: false } // a real failure of save()
}
}isInterruptPause(error) is true only for the value ctx.interrupt() threw. A test of the name,
(error as Error).name === 'InterruptPause', still works too.
A catch that throws again everything it does not handle needs no special case. After
resume(), the step runs again from its start and ctx.interrupt() returns the answer.
Steps see ctx.signal, an AbortSignal of the run. stop() aborts it, so a step that passes
ctx.signal on (a model call, a fetch) is cut; a step that ignores it runs to its end, and the run
stops before the next step.
What a stop gives. A stop is not an error. The run settles with signal: null wherever the stop
lands, whether stop() or the caller's signal caused it:
| Where the stop lands | State in the outcome | The session pauses on |
|---|---|---|
| Between two steps, or in a step that ignores ctx.signal and finishes | has the update of the finished step | the next step |
| In a step that is cut: it throws the abort it got through ctx.signal (a model call, a fetch) | as it was before that step; $error is not changed | the cut step: the next run executes it again from its start |
| In a step that catches the abort and returns | has what the step returned | the next step |
A cut step does not go to l.onError(), its error-aware route is not called, and events.onError
is not called. Observers get onStepSettled with outcome: 'stopped' and no onStepError; the run
ends with $stopped.
A step counts as cut when both are true: the run is stopped (ctx.signal is aborted), and what the
step throws is the abort.
The abort is the reason of ctx.signal, an error named AbortError, or an error that has one of
the two in its cause chain. So keep the abort as cause when a step wraps errors:
throw new Error('model call failed', { cause }). Everything else stays an error:
- An error that is not the abort, thrown while a stop is in flight, sets
$errorand goes tol.onError()when the loop has one; the stop then lands before the next step. - An
AbortErrorthrown while the run is not stopped (a timeout of the step's own, for example) is an error like any other. An expired lease is not a stop either. - While the run is stopped, an
AbortErrorof the step's own counts as the abort too, also in a step that does not usectx.signal: the step is cut and runs again next time.
A cut step runs again from its start, so what it did before the cut happens twice. Keep such steps safe to repeat.
After a stop. With a session store, the session is saved as paused on the step in the table above, with no signal, and its claim is released:
agent.status(sessionId)gives{ phase: 'paused', step, pendingInterrupts: [] }.agent.run(input, { sessionId }), on any instance, continues from that step (see the table in Turns andrequestIdfor how the input is merged).- There is no interrupt to answer:
agent.resume()rejects withNoInterruptErrorandrun.resume()throws it. - A resumed run that is stopped keeps the answer it was given in the saved state, also when the
stop came before its first step. The step that asked gets the answer when the next
run()executes it; do not answer again.
Without a session store a stopped run cannot be continued. This is a known limit (see
LIMITATIONS.md). The paused state is in the outcome only: run.resume() throws
NoInterruptError, and a new run() starts from the entry step. Use a session store (the in-memory
@noetaris/harness-store is enough) when a run must be stopped and continued later.
One case is kept: a run.resume() without a store that is stopped before its first step (its
signal was already aborted, for example) has used nothing. It settles with signal: '$interrupt'
and the state it resumed, and the answer is not kept. Call resume() again, on that handle or on
the one before it.
The signal resource is an AbortSignal of the caller. run() and agent.resume() both take it:
when it aborts, the run stops as with stop(). ctx.signal aborts on either cause, stop() or the
caller's signal. In a run started by run() or resume() it carries the caller's reason when
the caller aborted; in a debug session the caller's abort ends the session as stop() does, so
ctx.signal has the reason of a stop(). It is not the caller's signal itself, and stop() never
aborts the caller's signal. A resumed run
follows the signal of the call that made its handle: run.resume() follows the signal given to
run(), and a resume() on the handle that agent.resume() returns follows the signal given to
agent.resume(). A signal that is already aborted stops the resumed run before its first step. The
signal is not stored with the session, so agent.resume() in another process follows only the
signal passed to it.
The listeners and events resources work on agent.resume() as on run(): listeners are
called for what the resumed steps pass to ctx.emit(), and events takes onBeforeStep,
onAfterStep, onError, onComplete, onInterrupt and onStoreError. A value that is not a plain
object is ignored, as in run(). A resumed run calls the listeners and events of the call that made
its handle: run.resume() calls those given to run(), and a resume() on the handle that
agent.resume() returns calls those given to agent.resume(). They are not stored with the
session, so agent.resume() in another process calls only the ones passed to it:
const resumed = agent.resume(response, sessionId, interruptId, {
model,
listeners: { progress: (payload) => console.log(payload) },
events: { onAfterStep: (name) => console.log('done', name) },
})Only the own keys of the listeners object are listeners. An event name that the object merely
inherits (toString, constructor, __proto__, a method of its class) has no listener: ctx.emit()
calls nothing for it, reports nothing, and the observer's onEvent still gets the event. A key the
object sets itself is a listener whatever its name, and an object made with Object.create(null)
works too. Note that the literal { __proto__: fn } sets the prototype; it does not set a key. Write
{ ['__proto__']: fn } to get a listener for an event named __proto__.
A listener that throws does not fail the step. ctx.emit() never throws into the step: the error
goes to onObserverError (per call, else the agent's option, else console.error) with
{ hookName: 'listener', eventName }, where eventName is the name passed to ctx.emit(). The step
goes on, and the observer's onEvent still gets the event. ctx.emit() is synchronous and does not
await what a listener returns. When a listener returns a native Promise (an async listener) and
it rejects, the rejection is reported the same way, after the step has moved on. This holds for
run(), handle.resume(), agent.resume(), fork branches and debug():
await agent.run(input, {
listeners: { progress: (payload) => render(payload) },
onObserverError: (error, { hookName, eventName }) => {
if (hookName === 'listener') console.warn(`listener for ${eventName} failed`, error)
},
})An events callback only watches the run, so one that throws does not change it either. The run
does not await these callbacks. A throw, or the rejection of a native Promise the callback returns,
goes to the same sink with { hookName: 'events.<name>' } and no eventName, and the run goes on
as if the callback had returned: the outcome, state.$error and the stored session are what they
are without the callback, and the observer hooks and the other callbacks are still called. The
hookName values are 'events.onBeforeStep', 'events.onAfterStep', 'events.onComplete',
'events.onError', 'events.onInterrupt' and 'events.onStoreError'. This holds for run(),
handle.resume(), agent.resume(), fork branches and debug(). The callbacks are read from the
events object once, when run() or agent.resume() is called: one set on the object later is not
called, on a chained handle.resume() either. Reading the resources is part of the call itself: a
resource that throws when it is read (a getter, a Proxy) makes run() or agent.resume() throw
that error, and the session and a pending interrupt stay as they were:
await agent.run(input, {
events: { onAfterStep: (name) => metrics.count(name) },
onObserverError: (error, { hookName }) => {
if (hookName.startsWith('events.')) console.warn(`${hookName} failed`, error)
},
})Upgrading. An
eventscallback that threw used to reject the run with the callback's error (andonStoreErrorreplaced the store-error outcome with a rejection). Now the run settles normally and the error goes toonObserverError, or toconsole.errorwithout a sink.
- Code that threw in a callback to stop a run must call
handle.stop()or throw in the step.- An
onObserverErrorsink now also receives these errors: tell them apart by ahookNamethat starts with'events.'.- The callbacks are read from the
eventsobject once perrun()oragent.resume()call. Before,onBeforeStepwas read at each step and the others at each run and eachhandle.resume(), so a callback set on the object later was picked up. Set every callback before the call.
In all, agent.resume() reads these reserved resources: signal, listeners, events,
observer, onObserverError, parentRunId (the caller's run id, for a sub agent resumed from a
step), claimOptions and checkpoint. The two other reserved keys of run(), sessionId and
requestId, are accepted without an error and ignored: the session is the second argument, and a
resume continues the turn that paused.
parentRunId applies to that resumed run only: calling
resume() again on the handle it returns keeps the other resources but not parentRunId, which
is stale by then. With a store, both agent.resume() and run.resume() record the agent's
instanceId in the resumed run's metadata and, when the store supports claims, claim the
session for the resumed run; a resume() on the returned handle reuses the same claim TTL.
Resume replays the interrupted step from the top. On resume, the step that called
ctx.interrupt() runs again from its first line; each ctx.interrupt() call it reaches
returns the stored response instead of pausing. State updates from the paused attempt are
not kept — a step's update is applied only when run returns. So any side effect a step
performs before ctx.interrupt() (an HTTP call, a DB write, a sub agent run) happens
again on resume. Making that safe is up to the step: guard the side effect so a replay
skips or reuses it.
Inside a fork, only paused branches replay. When a fork pauses, each branch is saved
separately. On resume, a branch that already finished is not run again — its saved state
goes straight to the join. Every branch that is still paused runs again from its paused
step, even if the response you sent was for a different branch; a branch with no response
yet reaches its ctx.interrupt() again and re-pauses. The session stays paused until
every pending interrupt (see agent.status(sessionId).pendingInterrupts) is answered.
If any branch fails, the fork fails fast with the error of the branch that ended failed first: the
other branches are aborted and paused branches are dropped (see "When a branch fails" under
Forks and joins). The same happens when a branch throws a graph-definition error
(for example a signal with no matching .on()): the other branches are aborted, and the
run rejects with that error only after they have stopped, also when another branch had failed
before. In both cases a sibling that the abort cut is stopped, not failed.
Stopping a fork. stop() while a fork runs stops each branch at its next step
boundary, or cuts the step the branch is in (see "What a stop gives" above): a cut branch
pauses on the cut step, a branch that already finished stays finished. A branch that the stop
cut never fails the fork: if another branch throws an error of its own during the stop, the
fork fails with that error. The same holds without a stop: when a branch fails, the fork aborts
the other branches, and a branch cut by that abort is stopped, not failed, so the fork fails with
the error of the branch that ended failed first. What happens next after a stop depends on whether any
branch is waiting on an interrupt:
| At the stop | Run settles with | To continue |
|---|---|---|
| No branch is waiting on an interrupt | signal: null — a plain stop; agent.status() shows paused with no pending interrupts | agent.run() on the same session continues the fork: finished branches are not run again, stopped branches continue from where they stopped. resume() throws NoInterruptError. |
| At least one branch (at any depth) is waiting on an interrupt | signal: '$interrupt' | resume() answers it and re-runs every paused branch, including the ones that were only stopped |
Input passed to the agent.run() that continues a stopped fork is merged into the main
state only. The branches that continue keep their own saved state and do not see it; it
is visible from the join onward.
Calling sub agents from a step
A sub agent is just another agent with its own session. When it pauses, its run()
resolves with signal: '$interrupt' — it does not throw — so the calling step must pass
the interrupt up with ctx.interrupt() and, after resume, call the sub agent's
resume(). Because the step replays, the call must be idempotent. Checking the sub
agent's session phase is enough:
async function callSubAgent(agent: Agent, sessionId: string, input: object, ctx: any) {
const status = await agent.status(sessionId)
if (status.phase === 'completed') return loadResult(sessionId) // your own lookup — don't run again
if (status.phase === 'in-flight') {
// an earlier call has not settled yet: run() and resume() would throw SessionInFlightError
throw new Error(`sub agent session ${sessionId} is still running`)
}
const pending = status.phase === 'paused' ? status.pendingInterrupts[0] : undefined
let outcome
if (pending !== undefined) {
const answer = await ctx.interrupt(pending.prompt, `${sessionId}:${pending.interruptId}`)
outcome = await agent.resume(answer, sessionId, pending.interruptId, { signal: ctx.signal })
} else {
// fresh, paused by a stop or an error, or a checkpoint: run() starts or continues it
outcome = await agent.run(input, { sessionId, signal: ctx.signal })
}
if (outcome.signal === '$interrupt') {
// `Agent` without a type argument is the loose type: its state is a plain record
const { interruptId, prompt } = outcome.state['$interrupt'] as { interruptId: string; prompt: unknown }
await ctx.interrupt(prompt, `${sessionId}:${interruptId}`) // pauses the main agent
}
return outcome.state
}The phase is in-flight when an earlier call in this process has not settled yet. This can
happen when the main run was stopped and then resumed at once. run() and resume() would
throw SessionInFlightError then, so the snippet fails the step with its own error. Passing
ctx.signal stops the sub agent when the main step is stopped.
Use a stable sub agent sessionId (for example derived from the main sessionId) so a
replay finds the same session. To run several sub agents in parallel, put each in its own
fork branch rather than Promise.all in one step: then, when one pauses, the finished ones
are not run again on resume.
h.loop(l =>
l.start()
.fork('research')
.branch('web', b => b.start()
.step('callWeb', {
run: async (s, ctx) => ({ web: await callSubAgent(webAgent, `${ctx.sessionId}:web`, {}, ctx) }),
route: () => 'done',
})
.on('done').end()) // inside a branch, .end() ends the branch
.branch('docs', b => b.start()
.step('callDocs', {
run: async (s, ctx) => ({ docs: await callSubAgent(docsAgent, `${ctx.sessionId}:docs`, {}, ctx) }),
route: () => 'done',
})
.on('done').end())
.join('merge', { run: mergeResults, route: () => 'done' })
.on('done').end()
)If a fork fails fast while a sub agent is paused, that sub agent's own session stays paused in its store — clean it up or reuse it the next time the step runs.
Debugging a run
agent.debug(initialState, resources) starts a run held before its first step and returns a
DebugSession. Each command runs part of the run and resolves with the next stop: where the
run is held, the step that just settled, and a copy of the state. It takes the same arguments as
agent.run() and drives the whole run chain — an interrupt is answered inside the session.
const dbg = agent.debug({}, { sessionId: '