@noetaris/harness 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/harness/state-field.ts","../src/harness/ctx-markers.ts","../src/loop/loop-dsl.ts","../src/loop/loop-validator.ts","../src/harness/harness-builder.ts","../src/agent/observer.ts","../src/agent/ctx-interrupt.ts","../src/agent/ctx-emit.ts","../src/agent/ctx-within.ts","../src/loop/loop-executor.ts","../src/agent/session-store.ts","../src/agent/concurrency-errors.ts","../src/agent/ctx-keep-alive.ts","../src/agent/session-lifecycle.ts","../src/agent/interrupt-resume.ts","../src/agent/run-handle.ts","../src/agent/create-agent.ts","../src/agent/event-callbacks.ts"],"sourcesContent":["// Phantom symbol — never accessible at runtime; required for reliable T inference\n// even when neither `default` nor `reduce` is provided\ndeclare const _fieldType: unique symbol\n\n/**\n * Descriptor for a single state field, produced by {@link field}.\n *\n * - `default` — factory called once on session start to populate the field when no\n * initial value is supplied.\n * - `reduce` — merge function invoked on resume: `reduce(storedValue, incomingValue)`.\n * When absent, incoming values overwrite stored ones on resume.\n */\nexport type FieldDefinition<T> = {\n readonly [_fieldType]: T\n readonly default?: () => T\n readonly reduce?: (current: T, update: T) => T\n}\n\n/**\n * Derives the concrete state record type from a schema object whose values are\n * {@link FieldDefinition} descriptors.\n *\n * @example\n * ```ts\n * const schema = { count: field<number>({ default: () => 0 }) }\n * type State = StateFromSchema<typeof schema> // { count: number }\n * ```\n */\n// use FieldDefinition<any> in bounds, not FieldDefinition<unknown> — reduce makes T invariant\nexport type StateFromSchema<S> = {\n [K in keyof S]: S[K] extends FieldDefinition<infer T> ? T : never\n}\n\ntype FieldOptions<T> = {\n default?: () => T\n reduce?: (current: T, update: T) => T\n}\n\n/**\n * Declare a typed state field with an optional default factory and optional\n * reduce function.\n *\n * @param options.default - Factory called once at session start.\n * @param options.reduce - Merge function for resume: `(stored, incoming) => merged`.\n *\n * @example\n * ```ts\n * const schema = {\n * messages: field<string[]>({ default: () => [], reduce: (a, b) => [...a, ...b] }),\n * }\n * ```\n */\nexport function field<T>(options?: FieldOptions<T>): FieldDefinition<T> {\n return { ...options } as FieldDefinition<T> // as: phantom [_fieldType] is type-level only; the runtime object can never carry the symbol property\n}\n","/** @internal Discriminant tag for {@link RequiredMarker}. */\nexport const REQUIRED_TAG = '__noetaris_required__' as const\n/** @internal Discriminant tag for {@link RuntimeMarker}. */\nexport const RUNTIME_TAG = '__noetaris_runtime__' as const\n\n// string literal _tag is the sole type-level discriminant; phantom symbols were tried but\n// TypeScript does not enforce non-exported unique symbol keys across module boundaries\n\n/**\n * Sentinel returned by {@link required} to mark a context slot that **must** be\n * supplied at `createAgent()` time (not at `agent.run()` time).\n */\nexport type RequiredMarker = { readonly _tag: typeof REQUIRED_TAG }\n\n/**\n * Sentinel returned by {@link runtime} to mark a context slot that **must** be\n * supplied at `agent.run()` time (not at `createAgent()` time).\n */\nexport type RuntimeMarker = { readonly _tag: typeof RUNTIME_TAG }\n\n// function guard prevents TypeScript from recursing into Function's own method properties\n// (call, bind, apply, etc.) when T is a function type, which would make the mapped type\n// unresolvable and break @ts-expect-error enforcement on concrete value checks\n/**\n * Recursive variant of `T` that allows any nested position to also be a\n * {@link RequiredMarker} or {@link RuntimeMarker}. Used as the `value`\n * parameter type on {@link Harness.provide}.\n */\nexport type DeepWithMarkers<T> =\n T extends (...args: any[]) => any\n ? T | RequiredMarker | RuntimeMarker\n : T extends object\n ? { [K in keyof T]: DeepWithMarkers<T[K]> | RequiredMarker | RuntimeMarker } | RequiredMarker | RuntimeMarker\n : T | RequiredMarker | RuntimeMarker\n\n/**\n * Return a {@link RequiredMarker} sentinel that instructs the harness to\n * require this slot at `createAgent()` time.\n *\n * @example\n * ```ts\n * h.provide('llm', required())\n * ```\n */\nexport function required(): RequiredMarker {\n return { _tag: REQUIRED_TAG }\n}\n\n/**\n * Return a {@link RuntimeMarker} sentinel that instructs the harness to\n * require this slot at `agent.run()` time instead of `createAgent()` time.\n *\n * @example\n * ```ts\n * h.provide('signal', runtime())\n * ```\n */\nexport function runtime(): RuntimeMarker {\n return { _tag: RUNTIME_TAG }\n}\n\n/**\n * Type guard — returns `true` when `value` is a {@link RequiredMarker}.\n */\nexport function isRequiredMarker(value: unknown): value is RequiredMarker {\n return value !== null && typeof value === 'object' && '_tag' in value && value._tag === REQUIRED_TAG\n}\n\n/**\n * Type guard — returns `true` when `value` is a {@link RuntimeMarker}.\n */\nexport function isRuntimeMarker(value: unknown): value is RuntimeMarker {\n return value !== null && typeof value === 'object' && '_tag' in value && value._tag === RUNTIME_TAG\n}\n","import type { KeepAliveFn } from '../agent/ctx-keep-alive.js'\n\n// -----------------------------------------------------------------------\n// Framework-reserved state fields — readable in run/route, not writable from run return\n// -----------------------------------------------------------------------\n\n/**\n * Framework-managed fields injected into every step function's `state` argument.\n *\n * - `$error` — the `Error` thrown by the previous step, or `null` if no error occurred.\n * Only populated on the error path; non-error-aware steps never see a non-null value here.\n * - `$interrupt` — set while a step is awaiting a resume response. The `response` field\n * is populated after {@link Agent.resume} is called.\n */\nexport interface FrameworkState {\n readonly $error: Error | null\n readonly $interrupt: {\n readonly interruptId: string\n readonly prompt: unknown\n readonly response?: unknown\n } | null\n}\n\n/**\n * The complete state type visible inside {@link RunFn} step functions:\n * the user-defined state `S` merged with {@link FrameworkState}.\n */\nexport type StepState<S> = S & FrameworkState\n\n// -----------------------------------------------------------------------\n// Step function signatures\n// -----------------------------------------------------------------------\n\n/**\n * State transformer. Receives the full step state and ctx; returns a partial update\n * of user-defined state fields only (framework-reserved fields are excluded from return).\n * May be async.\n */\nexport type RunFn<S, Ctx> = (\n state: StepState<S>,\n ctx: Ctx & {\n readonly agentId: string\n readonly sessionId: string\n readonly runId: string\n readonly signal: AbortSignal\n readonly interrupt: (prompt: unknown, id?: string) => Promise<unknown>\n readonly emit: (name: string, payload?: unknown) => void\n /**\n * Run `fn` inside the observer's scope for an event this step already emitted — `type` is\n * that event's name (e.g. `'tool.call'`), `payload` carries its id (e.g. `{ toolCallId }`).\n * Returns `fn`'s own result. A passthrough when no observer implements `wrap`.\n */\n readonly within: <T>(type: string, payload: unknown, fn: () => Promise<T>) => Promise<T>\n readonly keepAlive: KeepAliveFn\n },\n) => Promise<Partial<Omit<S, '$error' | '$interrupt'>>> | Partial<Omit<S, '$error' | '$interrupt'>>\n\n/**\n * Pure signal emitter. Receives step state without $error — the route is not called on the error\n * path unless the step opts in via `optin: '$error'` in the step config. Synchronous by design.\n * No ctx — pure read only.\n */\nexport type RouteFn<S> = (state: S & Omit<FrameworkState, '$error'>) => string\n\n/**\n * Pure signal emitter for error-aware steps (optin: '$error').\n * Receives the full step state including $error — the executor calls this on both the success\n * and error paths. Declare `optin: '$error'` in the step config to use this variant.\n */\nexport type ErrorAwareRouteFn<S> = (state: StepState<S>) => string\n\n/**\n * Options passed to `.step(name, options)`. At least one of `run` or `route` must be set.\n *\n * Two variants:\n * - Without `optin`: route receives state without `$error` (TypeScript-enforced). On error,\n * the framework falls through to `l.onError()` or pauses with `signal: \"$error\"` automatically.\n * - With `optin: '$error'`: route receives the full state including `$error`, and the executor\n * calls route on the error path. Use this when the step's route needs to inspect or handle errors.\n */\nexport type StepOptions<S, Ctx> =\n | {\n readonly optin: '$error'\n run?: RunFn<S, Ctx>\n route?: ErrorAwareRouteFn<S>\n }\n | {\n readonly optin?: undefined\n run?: RunFn<S, Ctx>\n route?: RouteFn<S>\n }\n\n// -----------------------------------------------------------------------\n// LoopDefinition — the captured topology produced by the builder\n// -----------------------------------------------------------------------\n\n/**\n * Where a signal transition routes to.\n * 'step' — routes to the named step.\n * 'end' — exits the loop; run resolves with the emitted signal.\n */\nexport type TransitionTarget =\n | { readonly kind: 'step'; readonly name: string }\n | { readonly kind: 'end' }\n\n/** A single `.on(signal).to(step)` or `.on(signal).end()` declaration. */\nexport interface SignalTransition {\n readonly signal: string\n readonly target: TransitionTarget\n}\n\n/**\n * Compiled step definition stored in LoopDefinition.\n * run and route are stored as-is (user functions — validated structurally, not semantically).\n * transitions: all .on() declarations attached to this step.\n * next: explicit .next(name) target, or undefined if none declared.\n * errorAware: true when the step was declared with optin: '$error' — the executor calls route\n * on the error path when this is true.\n */\nexport interface StepDef {\n readonly name: string\n readonly run: RunFn<unknown, unknown> | undefined\n readonly route: RouteFn<unknown> | undefined\n readonly transitions: readonly SignalTransition[]\n readonly next: string | undefined\n readonly errorAware: boolean\n}\n\n/**\n * A single `.branch(name, fn)` declaration inside a fork.\n * definition is the branch's own, independently-captured LoopDefinition — built by running\n * the branch's builder lambda against a fresh createLoopBuilder() instance. Inside a branch,\n * `.end()` means \"this branch is done,\" not \"the run is done\" (see LoopBuilder.branch).\n */\nexport interface BranchDef {\n readonly name: string\n readonly definition: LoopDefinition\n}\n\n/**\n * Compiled fork node stored in LoopDefinition.steps alongside StepDef nodes.\n * A fork has no run/route of its own — it never emits a signal, so .on() is not supported on it.\n * next: explicit .next(name) target for the step that runs once every branch has settled\n * (the \"join\"), or undefined to fall through to the next declared top-level node.\n * Discriminated from StepDef structurally (see isForkDef) rather than via a tag field, so\n * existing StepDef-only code and hand-built StepDef literals are unaffected.\n */\nexport interface ForkDef {\n readonly name: string\n readonly branches: readonly BranchDef[]\n readonly next: string | undefined\n}\n\n/** A top-level node in a LoopDefinition: either an ordinary step or a fork. */\nexport type LoopNode = StepDef | ForkDef\n\n/** Structural type guard distinguishing ForkDef from StepDef within a LoopNode. */\nexport function isForkDef(node: LoopNode): node is ForkDef {\n return 'branches' in node\n}\n\n/**\n * Complete loop topology captured from the builder lambda.\n * Immutable snapshot — produced once, consumed by LoopValidator and (later) F6.\n *\n * startCalled: true if l.start() was invoked at least once.\n * entryStep: name of the first .step()/.fork() declared after .start() was called; undefined if\n * .start() was never called or no node was declared after it.\n * steps: all declared top-level nodes (steps and forks) in declaration order.\n * onError: the fallback step name from l.onError(), or undefined if not set.\n */\nexport interface LoopDefinition {\n readonly startCalled: boolean\n readonly entryStep: string | undefined\n readonly steps: readonly LoopNode[]\n readonly onError: string | undefined\n}\n\n// -----------------------------------------------------------------------\n// LoopBuilder — the DSL object passed to the h.loop() builder lambda\n// -----------------------------------------------------------------------\n\n/**\n * Fluent chain returned by .on(signal). Caller must call either .to(step) or .end()\n * to complete the transition declaration.\n */\nexport interface OnChain<S, Ctx> {\n /** Route the signal to the named step. Returns the builder for further chaining. */\n to(step: string): LoopBuilder<S, Ctx>\n /** Exit the loop when this signal is emitted. Returns the builder for further chaining. */\n end(): LoopBuilder<S, Ctx>\n}\n\n/**\n * The DSL object passed as `l` to the h.loop(l => ...) builder lambda.\n * All methods mutate internal state and return `this` for chaining.\n */\nexport interface LoopBuilder<S, Ctx> {\n /** Mark the loop as having a declared entry. The first .step()/.fork() called after .start() is the entry. */\n start(): LoopBuilder<S, Ctx>\n /** Declare a step. At least one of run or route must be set (validated later by LoopValidator). */\n step(name: string, options: StepOptions<S, Ctx>): LoopBuilder<S, Ctx>\n /**\n * Declare a fork: a named node that splits execution into 2+ concurrent branches, declared\n * with .branch() immediately after. The step immediately following the fork automatically\n * waits for every branch to settle (the \"join\") — no separate join primitive exists.\n *\n * Per-step telemetry is attributed correctly across concurrent branches: the harness scopes\n * each branch's slots per step via {@link ObserverAware.withTelemetry}, so telemetry travels\n * with the call rather than through shared instance state. See `ObserverAware`'s doc comment\n * (`agent/observer.ts`).\n */\n fork(name: string): LoopBuilder<S, Ctx>\n /**\n * Declare one branch of the fork most recently opened with .fork(). Must be called immediately\n * after .fork() or another .branch() on the same fork — throws otherwise.\n * builderFn receives a fresh LoopBuilder scoped to this branch, using the same .step()/.on()/\n * .next() vocabulary as the top level; inside it, .end() means \"this branch is done,\" not\n * \"the run is done.\"\n */\n branch(name: string, builderFn: (b: LoopBuilder<S, Ctx>) => void): LoopBuilder<S, Ctx>\n /**\n * Declare the step that runs once every branch of the preceding fork has settled.\n * Pure alias of .step(name, options) — not enforced by the validator, just a naming\n * convenience so the DSL reads as fork/branch/join.\n */\n join(name: string, options: StepOptions<S, Ctx>): LoopBuilder<S, Ctx>\n /**\n * Begin a signal transition declaration. Must be called immediately after .step() or after\n * a previous .on().to() or .on().end() chain (attaches to the most recently declared step).\n * Throws if the most recently declared node is a fork — a fork has no run/route to emit\n * a signal from.\n */\n on(signal: string): OnChain<S, Ctx>\n /**\n * Declare an explicit unconditional next target for the most recently declared step.\n * Mutually exclusive with route (validated by LoopValidator).\n */\n next(name: string): LoopBuilder<S, Ctx>\n /**\n * Declare a loop-level fallback error step. Any step whose run throws and whose\n * route does not handle $error will route to this step instead of pausing the session.\n * Only one onError target per loop; multiple calls replace the previous target (last wins).\n */\n onError(step: string): LoopBuilder<S, Ctx>\n}\n\n// -----------------------------------------------------------------------\n// Error class\n// -----------------------------------------------------------------------\n\n/** Thrown by extractLoopDefinition when the argument is not a createLoopBuilder() instance. */\nexport class InvalidLoopBuilderError extends Error {\n constructor() {\n super('argument is not a LoopBuilder instance — was it created by createLoopBuilder?')\n this.name = 'InvalidLoopBuilderError'\n }\n}\n\n// -----------------------------------------------------------------------\n// Internal implementation\n// -----------------------------------------------------------------------\n\n// Module-private symbol for internal state\nconst _builderState = Symbol('builderState')\n\n// Internal mutable step definition during collection\ninterface StepDefMutable {\n name: string\n run: RunFn<unknown, unknown> | undefined\n route: RouteFn<unknown> | undefined\n transitions: SignalTransition[]\n next: string | undefined\n errorAware: boolean\n}\n\n// Internal mutable fork definition during collection. Branches are pushed already-immutable\n// (extractLoopDefinition runs on the branch's own builder as soon as .branch() is called).\ninterface ForkDefMutable {\n name: string\n branches: BranchDef[]\n next: string | undefined\n}\n\ntype NodeMutable = StepDefMutable | ForkDefMutable\n\n// Structural discriminant shared with isForkDef — a fork is the only node with `branches`.\nfunction isForkNodeMutable(node: NodeMutable): node is ForkDefMutable {\n return 'branches' in node\n}\n\n// Internal mutable builder state\ninterface BuilderState {\n startCalled: boolean\n entryStep: string | undefined\n steps: NodeMutable[]\n onError: string | undefined\n}\n\n// Deep freeze utility\nfunction deepFreeze<T extends object>(obj: T): T {\n Object.freeze(obj)\n\n for (const value of Object.values(obj)) {\n if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {\n deepFreeze(value)\n }\n }\n\n return obj\n}\n\n/**\n * Create a new LoopBuilder instance for use in a h.loop() lambda.\n * The returned object accumulates all DSL calls in mutable internal state.\n */\nexport function createLoopBuilder<S, Ctx>(): LoopBuilder<S, Ctx> {\n const state: BuilderState = {\n startCalled: false,\n entryStep: undefined,\n steps: [],\n onError: undefined,\n }\n\n const builder: any = {\n start(this: any): LoopBuilder<S, Ctx> {\n state.startCalled = true\n return this\n },\n\n step(this: any, name: string, options: StepOptions<S, Ctx>): LoopBuilder<S, Ctx> {\n const stepDef: StepDefMutable = {\n name,\n run: options.run as RunFn<unknown, unknown> | undefined, // as: contravariance in state parameter\n route: options.route as RouteFn<unknown> | undefined, // as: contravariance in state parameter\n transitions: [],\n next: undefined,\n errorAware: options.optin === '$error',\n }\n state.steps.push(stepDef)\n\n // Set entryStep to the first step after start() was called\n if (state.startCalled && state.entryStep === undefined) {\n state.entryStep = name\n }\n\n return this\n },\n\n fork(this: any, name: string): LoopBuilder<S, Ctx> {\n const forkNode: ForkDefMutable = { name, branches: [], next: undefined }\n state.steps.push(forkNode)\n\n // Forks are valid entry points, same as steps\n if (state.startCalled && state.entryStep === undefined) {\n state.entryStep = name\n }\n\n return this\n },\n\n branch(this: any, name: string, builderFn: (b: LoopBuilder<S, Ctx>) => void): LoopBuilder<S, Ctx> {\n const currentNode = state.steps.at(-1)\n if (currentNode === undefined || !isForkNodeMutable(currentNode)) {\n throw new Error(\n '.branch() must be called immediately after .fork() or another .branch() on the same fork',\n )\n }\n\n // Independent builder instance: branch declarations never touch the outer state\n const branchBuilder = createLoopBuilder<S, Ctx>()\n builderFn(branchBuilder)\n const branchDefinition = extractLoopDefinition(\n branchBuilder as LoopBuilder<unknown, unknown>,\n )\n currentNode.branches.push({ name, definition: branchDefinition })\n\n return this\n },\n\n join(this: any, name: string, options: StepOptions<S, Ctx>): LoopBuilder<S, Ctx> {\n return this.step(name, options)\n },\n\n on(this: any, signal: string): OnChain<S, Ctx> {\n // Guard: if no step has been declared yet, return no-op OnChain\n if (state.steps.length === 0) {\n return {\n to: () => this,\n end: () => this,\n }\n }\n\n const currentNode = state.steps.at(-1)!\n if (isForkNodeMutable(currentNode)) {\n throw new Error(\n '.on() cannot be called on a fork — a fork has no run/route to emit a signal from',\n )\n }\n const currentStep = currentNode\n\n return {\n to: (step: string): LoopBuilder<S, Ctx> => {\n currentStep.transitions.push({\n signal,\n target: { kind: 'step', name: step },\n })\n return this\n },\n end: (): LoopBuilder<S, Ctx> => {\n currentStep.transitions.push({\n signal,\n target: { kind: 'end' },\n })\n return this\n },\n }\n },\n\n next(this: any, name: string): LoopBuilder<S, Ctx> {\n // Guard: if no node has been declared yet, this is a no-op\n if (state.steps.length > 0) {\n const currentNode = state.steps.at(-1)\n if (currentNode !== undefined) {\n currentNode.next = name\n }\n }\n return this\n },\n\n onError(this: any, step: string): LoopBuilder<S, Ctx> {\n state.onError = step\n return this\n },\n }\n\n // Attach the internal state symbol\n ;(builder as any)[_builderState] = state\n\n return builder as LoopBuilder<S, Ctx>\n}\n\n/**\n * Extract the LoopDefinition accumulated by a builder created with createLoopBuilder().\n * Called by harness-builder.ts immediately after the user's builder lambda returns.\n * Throws InvalidLoopBuilderError if the argument was not produced by createLoopBuilder().\n */\nexport function extractLoopDefinition(builder: LoopBuilder<unknown, unknown>): LoopDefinition {\n // Identity check: ensure builder has the internal state symbol\n if (builder === null || builder === undefined || !(_builderState in builder)) {\n throw new InvalidLoopBuilderError()\n }\n\n const state = (builder as any)[_builderState] as BuilderState\n\n // Convert mutable nodes (steps and forks) to immutable ones\n const immutableSteps: LoopNode[] = state.steps.map((node) => {\n if (isForkNodeMutable(node)) {\n // Each branch's own definition is already frozen (captured by .branch() at declaration\n // time); only the BranchDef wrapper and the branches array need freezing here.\n const branches = Object.freeze(\n node.branches.map((b) => Object.freeze({ name: b.name, definition: b.definition })),\n ) as readonly BranchDef[]\n const forkDef: ForkDef = {\n name: node.name,\n branches,\n next: node.next,\n }\n return Object.freeze(forkDef)\n }\n\n const transitions = Object.freeze([...node.transitions]) as readonly SignalTransition[]\n // Freeze each transition\n for (const transition of transitions) {\n Object.freeze(transition)\n Object.freeze(transition.target)\n }\n const stepDef: StepDef = {\n name: node.name,\n run: node.run,\n route: node.route,\n transitions,\n next: node.next,\n errorAware: node.errorAware,\n }\n return Object.freeze(stepDef)\n })\n\n // Create the frozen LoopDefinition\n const definition: LoopDefinition = {\n startCalled: state.startCalled,\n entryStep: state.entryStep,\n steps: Object.freeze(immutableSteps),\n onError: state.onError,\n }\n\n // Deep freeze the entire structure\n return deepFreeze(definition)\n}\n","import type { LoopDefinition, StepDef } from './loop-dsl.js'\nimport { isForkDef } from './loop-dsl.js'\n\n// -----------------------------------------------------------------------\n// Error class\n// -----------------------------------------------------------------------\n\n/**\n * Thrown by validateLoop() when the LoopDefinition violates one or more structural rules.\n * violations: every rule violation found, as human-readable strings.\n * The full list is always reported — validateLoop() never fails fast on the first violation.\n */\nexport class LoopValidationError extends Error {\n readonly violations: readonly string[]\n\n constructor(violations: readonly string[]) {\n super(`loop validation failed:\\n${violations.map((v) => ` - ${v}`).join('\\n')}`)\n this.name = 'LoopValidationError'\n this.violations = violations\n }\n}\n\n// -----------------------------------------------------------------------\n// Public API\n// -----------------------------------------------------------------------\n\n/**\n * Validate a LoopDefinition against all structural rules.\n * Collects every violation before throwing, so developers see the full picture.\n *\n * Applies the 9 structural rules recursively to the top-level definition and to every branch's\n * own definition at every depth (a fork nested inside a branch is validated too, even though it\n * isn't specially supported yet — see HANDOVER-fork-join.md decision #13). Also checks two\n * fork-specific rules (≥2 branches, unique branch names within a fork) and one whole-tree rule\n * (every step/fork name unique across the entire nested structure, so a persisted cursor string\n * stays unambiguous regardless of which branch it names).\n *\n * @param def - a LoopDefinition produced by extractLoopDefinition()\n * @throws LoopValidationError if one or more validation rules are violated\n */\nexport function validateLoop(def: LoopDefinition): void {\n const violations = collectViolations(def, undefined)\n\n const nameLocations = new Map<string, string[]>()\n collectNameLocations(def, undefined, nameLocations)\n for (const [name, locations] of nameLocations) {\n if (locations.length > 1) {\n violations.push(\n `name \"${name}\" is declared more than once across the nested structure: ${locations.join(', ')}`,\n )\n }\n }\n\n if (violations.length > 0) {\n throw new LoopValidationError(violations)\n }\n}\n\n/**\n * Recursively collects structural and fork-specific violations for one definition and every\n * branch definition nested under it. pathLabel is undefined at the top level; inside a branch\n * it's a '/'-joined fork/branch breadcrumb (e.g. \"review/credit\") used to prefix messages so a\n * violation can be located. Does not throw — validateLoop aggregates across the whole tree first.\n */\nfunction collectViolations(def: LoopDefinition, pathLabel: string | undefined): string[] {\n const prefix = pathLabel !== undefined ? `in branch \"${pathLabel}\": ` : ''\n const violations = collectStructuralViolations(def).map((v) => prefix + v)\n\n for (const node of def.steps) {\n if (!isForkDef(node)) continue\n\n // Rule 10 — a fork needs at least 2 branches\n if (node.branches.length < 2) {\n violations.push(\n `${prefix}fork \"${node.name}\" must have at least 2 branches (found ${node.branches.length})`,\n )\n }\n\n // Rule 11 — branch names unique within this fork (their own namespace — see collectNameLocations)\n const seenBranchNames = new Set<string>()\n for (const branch of node.branches) {\n if (seenBranchNames.has(branch.name)) {\n violations.push(`${prefix}fork \"${node.name}\" has duplicate branch name \"${branch.name}\"`)\n }\n seenBranchNames.add(branch.name)\n }\n\n for (const branch of node.branches) {\n const branchPath =\n pathLabel !== undefined ? `${pathLabel}/${node.name}/${branch.name}` : `${node.name}/${branch.name}`\n violations.push(...collectViolations(branch.definition, branchPath))\n }\n }\n\n return violations\n}\n\n/**\n * Walks the entire nested tree recording every declaration location for every step/fork name.\n * Branch names are deliberately excluded — they're validated for uniqueness within their own\n * fork by Rule 11 above, not as part of this global step/fork namespace.\n */\nfunction collectNameLocations(\n def: LoopDefinition,\n path: string | undefined,\n acc: Map<string, string[]>,\n): void {\n for (const node of def.steps) {\n const location = path !== undefined ? `${path}/${node.name}` : node.name\n const locations = acc.get(node.name) ?? []\n locations.push(location)\n acc.set(node.name, locations)\n\n if (isForkDef(node)) {\n for (const branch of node.branches) {\n const branchPath = path !== undefined ? `${path}/${node.name}/${branch.name}` : `${node.name}/${branch.name}`\n collectNameLocations(branch.definition, branchPath, acc)\n }\n }\n }\n}\n\n/**\n * The original 9 structural rules, scoped to a single LoopDefinition — no recursion into\n * branches here; collectViolations calls this once per definition in the tree.\n */\nfunction collectStructuralViolations(def: LoopDefinition): string[] {\n const violations: string[] = []\n\n // Build a set of all declared top-level node names once (steps and forks) — reuse for rules 6 and 8\n const names = new Set(def.steps.map((s) => s.name))\n\n // Rules 1, 2, 4, 9 concern run/route/transitions, which only exist on StepDef — a fork is a\n // different kind of node by construction and is exempt from these. Its own rules (>=2 branches,\n // unique branch names) are checked separately in collectViolations, which calls this function.\n const stepNodes = def.steps.filter((s): s is StepDef => !isForkDef(s))\n\n // -----------------------------------------------------------------------\n // Rule 1 — Every step has at least `run` or `route`\n // -----------------------------------------------------------------------\n for (const step of stepNodes) {\n if (step.run === undefined && step.route === undefined) {\n violations.push(`step \"${step.name}\" must have at least one of run or route`)\n }\n }\n\n // -----------------------------------------------------------------------\n // Rule 2 — A step with `route` must have at least one `.on()` transition\n // -----------------------------------------------------------------------\n for (const step of stepNodes) {\n if (step.route !== undefined && step.transitions.length === 0) {\n violations.push(`step \"${step.name}\" has route but no .on() transitions — every signal must be handled`)\n }\n }\n\n // -----------------------------------------------------------------------\n // Rule 3 — A node without `route` must have a next target\n // (a fork never has a route, so it is held to the same \"needs an exit path\" rule as a step)\n // -----------------------------------------------------------------------\n for (const [i, node] of def.steps.entries()) {\n if (node === undefined) continue\n const hasRoute = !isForkDef(node) && node.route !== undefined\n if (!hasRoute) {\n // Non-last nodes have implicit next = the following node; they satisfy rule 3\n // Last node must have explicit next or be unreachable via rule 8\n const isLast = i === def.steps.length - 1\n if (isLast && node.next === undefined) {\n violations.push(\n `step \"${node.name}\" has no route, no explicit .next(), and no following step — no exit path`,\n )\n }\n }\n }\n\n // -----------------------------------------------------------------------\n // Rule 4 — A step cannot have both `route` and `.next()`\n // -----------------------------------------------------------------------\n for (const step of stepNodes) {\n if (step.route !== undefined && step.next !== undefined) {\n violations.push(`step \"${step.name}\" has both route and .next() — these are mutually exclusive`)\n }\n }\n\n // -----------------------------------------------------------------------\n // Rule 5 — No duplicate step names\n // -----------------------------------------------------------------------\n const seen = new Set<string>()\n for (const step of def.steps) {\n if (seen.has(step.name)) {\n violations.push(`duplicate step name \"${step.name}\"`)\n }\n seen.add(step.name)\n }\n\n // -----------------------------------------------------------------------\n // Rule 6 — All `.to(name)` targets, `.next()` targets, and `onError` target\n // must reference a declared step\n // -----------------------------------------------------------------------\n for (const step of stepNodes) {\n for (const transition of step.transitions) {\n if (transition.target.kind === 'step') {\n if (!names.has(transition.target.name)) {\n violations.push(\n `step \"${step.name}\" has .on(\"${transition.signal}\").to(\"${transition.target.name}\") but step \"${transition.target.name}\" is not declared`,\n )\n }\n }\n }\n }\n\n for (const node of def.steps) {\n if (node.next !== undefined) {\n if (!names.has(node.next)) {\n violations.push(\n `step \"${node.name}\" has .next(\"${node.next}\") but step \"${node.next}\" is not declared`,\n )\n }\n }\n }\n\n if (def.onError !== undefined) {\n if (!names.has(def.onError)) {\n violations.push(`onError target \"${def.onError}\" is not a declared step`)\n }\n }\n\n // -----------------------------------------------------------------------\n // Rule 7 — The loop must have an entry (`.start()`) and at least one exit (`.end()`)\n // -----------------------------------------------------------------------\n if (def.startCalled === false) {\n violations.push(`loop is missing .start() — call l.start() before declaring steps`)\n }\n\n if (def.startCalled && def.entryStep === undefined) {\n violations.push(`l.start() was called but no step was declared after it — declare at least one step`)\n }\n\n // Check for at least one exit (.end())\n let hasExit = false\n for (const step of stepNodes) {\n for (const transition of step.transitions) {\n if (transition.target.kind === 'end') {\n hasExit = true\n break\n }\n }\n if (hasExit) break\n }\n\n if (!hasExit) {\n violations.push(`loop has no exit — add at least one .on(\"<signal>\").end()`)\n }\n\n // -----------------------------------------------------------------------\n // Rule 8 — No unreachable steps\n // -----------------------------------------------------------------------\n // Only checked if def.entryStep !== undefined (rule 7 covers missing entry)\n if (def.entryStep !== undefined) {\n // BFS from entryStep to find all reachable steps\n const reachable = new Set<string>([def.entryStep])\n const queue: string[] = [def.entryStep]\n\n // Also mark onError target as reachable upfront\n if (def.onError !== undefined) {\n reachable.add(def.onError)\n if (!queue.includes(def.onError)) {\n queue.push(def.onError)\n }\n }\n\n while (queue.length > 0) {\n const currentName = queue.shift()!\n const currentNode = def.steps.find((s) => s.name === currentName)\n\n if (!currentNode) continue\n\n // Add all steps reachable via signal transitions (a fork has none — it never routes)\n if (!isForkDef(currentNode)) {\n for (const transition of currentNode.transitions) {\n if (transition.target.kind === 'step') {\n if (!reachable.has(transition.target.name)) {\n reachable.add(transition.target.name)\n queue.push(transition.target.name)\n }\n }\n }\n }\n\n // Add next target if explicit or implicit (a fork never has a route)\n const hasRoute = !isForkDef(currentNode) && currentNode.route !== undefined\n if (hasRoute) {\n // Step has route, so no implicit next\n if (currentNode.next !== undefined && !reachable.has(currentNode.next)) {\n reachable.add(currentNode.next)\n queue.push(currentNode.next)\n }\n } else {\n // Node has no route: follow explicit next or implicit next\n if (currentNode.next !== undefined) {\n if (!reachable.has(currentNode.next)) {\n reachable.add(currentNode.next)\n queue.push(currentNode.next)\n }\n } else {\n // Implicit next: the following node in def.steps, if any\n const currentIndex = def.steps.findIndex((s) => s.name === currentName)\n if (currentIndex !== -1 && currentIndex < def.steps.length - 1) {\n const nextNode = def.steps[currentIndex + 1]\n if (nextNode !== undefined) {\n const nextNodeName = nextNode.name\n if (!reachable.has(nextNodeName)) {\n reachable.add(nextNodeName)\n queue.push(nextNodeName)\n }\n }\n }\n }\n }\n }\n\n // Check for unreachable steps\n for (const step of def.steps) {\n if (!reachable.has(step.name)) {\n violations.push(`step \"${step.name}\" is unreachable from the entry step \"${def.entryStep}\"`)\n }\n }\n }\n\n // -----------------------------------------------------------------------\n // Rule 9 (derived) — A step without `route` must not declare `.on()` signal transitions\n // -----------------------------------------------------------------------\n for (const step of stepNodes) {\n if (step.route === undefined && step.transitions.length > 0) {\n violations.push(\n `step \"${step.name}\" has .on() transitions but no route — .on() is only valid when route is set`,\n )\n }\n }\n\n return violations\n}\n","import type { FieldDefinition, StateFromSchema } from './state-field.js'\nimport type { RequiredMarker, RuntimeMarker, DeepWithMarkers } from './ctx-markers.js'\nimport type { LoopBuilder, LoopDefinition } from '../loop/loop-dsl.js'\nimport { createLoopBuilder, extractLoopDefinition } from '../loop/loop-dsl.js'\nimport { validateLoop } from '../loop/loop-validator.js'\n\n// -----------------------------------------------------------------------\n// Harness type — accumulated at the type level across provide() calls\n// -----------------------------------------------------------------------\n\n/**\n * Immutable builder that accumulates context-slot declarations, store bindings,\n * and the loop definition for an agent. Produced by {@link createHarness} and\n * consumed by {@link createAgent}.\n *\n * The four type parameters track what has been declared so far:\n * - `Ctx` — the full context shape expected by step functions.\n * - `State` — the state record shape derived from the schema passed to `createHarness()`.\n * - `Req` — keys declared as {@link required} (must be supplied to `createAgent`).\n * - `Run` — keys declared as {@link runtime} (must be supplied to `agent.run()`).\n *\n * Each call returns a **new** `Harness` instance; the original is unchanged.\n *\n * @example\n * ```ts\n * const h = createHarness<Ctx>()(schema)\n * .provide('llm', required())\n * .provide('model', 'claude-3-5-haiku-20241022')\n * .store({ session: new InMemorySessionStore() })\n * .loop(l => {\n * l.start().step('run', { run, route }).on('done').end()\n * })\n * ```\n */\nexport type Harness<\n Ctx,\n State,\n Req extends keyof Ctx = never,\n Run extends keyof Ctx = never,\n> = {\n /**\n * Declare a context slot.\n *\n * - Pass {@link required} to require the value at `createAgent()` time.\n * - Pass {@link runtime} to require the value at `agent.run()` time.\n * - Pass any concrete value (or a deep object mixing in markers) to bind it now.\n */\n provide<K extends keyof Ctx>(key: K, value: RequiredMarker): Harness<Ctx, State, Req | K, Run>\n provide<K extends keyof Ctx>(key: K, value: RuntimeMarker): Harness<Ctx, State, Req, Run | K>\n provide<K extends keyof Ctx>(key: K, value: DeepWithMarkers<Ctx[K]>): Harness<Ctx, State, Req, Run>\n\n /**\n * Bind session store(s). Pass `{ session: myStore }` to enable persistence and\n * interrupt/resume across processes.\n */\n // store() Req/Run are not affected at the type level; nested markers are runtime-validated only (F2 spike constraint)\n store(stores: DeepWithMarkers<{ session?: unknown } & Record<string, unknown>>): Harness<Ctx, State, Req, Run>\n\n /**\n * Define the execution loop using the {@link LoopBuilder} DSL.\n *\n * @param builder - Callback that receives a `LoopBuilder` and uses it to\n * declare steps, transitions, and the entry point.\n */\n // loop() parameter is LoopBuilder<State, Ctx> after F4 implementation\n loop(builder: (l: LoopBuilder<State, Ctx>) => void): Harness<Ctx, State, Req, Run>\n\n /**\n * Return the frozen {@link LoopDefinition} captured when {@link loop} was called.\n *\n * @throws {LoopNotDefinedError} if `h.loop()` has not been called on this harness instance.\n */\n definition(): LoopDefinition\n}\n\n// -----------------------------------------------------------------------\n// ProviderEntry — one entry produced by each provide() or store() call\n// -----------------------------------------------------------------------\n\nexport interface ProviderEntry {\n readonly kind: 'provide' | 'store'\n readonly key: string\n readonly value: unknown\n}\n\n// -----------------------------------------------------------------------\n// HarnessInternals — the structural contract between HarnessBuilder and createAgent (F5)\n// -----------------------------------------------------------------------\n\n// _req, _run, _state are type witnesses: never assigned at runtime, carry type-level info to F5\nexport interface HarnessInternals<\n Ctx,\n State,\n Req extends keyof Ctx,\n Run extends keyof Ctx,\n> {\n readonly stateSchema: Record<string, FieldDefinition<unknown>> | undefined\n readonly providers: readonly ProviderEntry[]\n readonly loopDef: LoopDefinition | undefined\n readonly _req: Req | undefined\n readonly _run: Run | undefined\n readonly _state: State | undefined\n}\n\n// -----------------------------------------------------------------------\n// Internal accessor — used by createAgent (F5) to unwrap internals\n// -----------------------------------------------------------------------\n\n// symbol key is module-private; external code cannot read or forge the internals slot\nconst _internals = Symbol('_internals')\n\nexport type HarnessWithInternals<\n Ctx,\n State,\n Req extends keyof Ctx,\n Run extends keyof Ctx,\n> = Harness<Ctx, State, Req, Run> & {\n readonly [_internals]: HarnessInternals<Ctx, State, Req, Run>\n}\n\nexport function getInternals<\n Ctx,\n State,\n Req extends keyof Ctx,\n Run extends keyof Ctx,\n>(harness: Harness<Ctx, State, Req, Run>): HarnessInternals<Ctx, State, Req, Run> {\n if (harness === null || typeof harness !== 'object' || !(_internals in harness)) {\n throw new HarnessInternalsError()\n }\n return (harness as HarnessWithInternals<Ctx, State, Req, Run>)[_internals] // as: `_internals in harness` check above guarantees the symbol key is present\n}\n\n// -----------------------------------------------------------------------\n// Error class\n// -----------------------------------------------------------------------\n\n/** @internal Thrown when {@link getInternals} is called on a non-harness value. */\nexport class HarnessInternalsError extends Error {\n constructor() {\n super('value is not a HarnessBuilder instance — was it created by createHarness?')\n this.name = 'HarnessInternalsError'\n }\n}\n\n/**\n * Thrown by {@link Harness.definition} when `h.loop()` has not been called yet.\n */\nexport class LoopNotDefinedError extends Error {\n constructor() {\n super('loop is not defined — call h.loop() before accessing h.definition()')\n this.name = 'LoopNotDefinedError'\n }\n}\n\n// -----------------------------------------------------------------------\n// createHarness — the public factory\n// -----------------------------------------------------------------------\n\n/**\n * Create a harness builder for the given context type.\n *\n * Call the returned function (optionally with a state schema) to get the\n * {@link Harness} builder on which you chain `.provide()`, `.store()`, and `.loop()`.\n *\n * @example\n * ```ts\n * interface Ctx { llm: LLM; model: string }\n * const schema = { messages: field<string[]>({ default: () => [] }) }\n *\n * const h = createHarness<Ctx>()(schema)\n * ```\n */\nexport function createHarness<Ctx = any>(): <S extends object = {}>( // any: allows createHarness() without an explicit Ctx type parameter\n stateSchema?: S,\n) => Harness<Ctx, StateFromSchema<S>> {\n return <S extends object = {}>(stateSchema?: S): Harness<Ctx, StateFromSchema<S>> => {\n const internals: HarnessInternals<Ctx, StateFromSchema<S>, never, never> = {\n stateSchema: stateSchema as Record<string, FieldDefinition<unknown>> | undefined, // as: S extends object; cast to internal schema representation\n providers: Object.freeze([]),\n loopDef: undefined,\n _req: undefined,\n _run: undefined,\n _state: undefined,\n }\n\n return createBuilderInstance(internals)\n }\n}\n\nfunction createBuilderInstance<\n Ctx,\n State,\n Req extends keyof Ctx = never,\n Run extends keyof Ctx = never,\n>(internals: HarnessInternals<Ctx, State, Req, Run>): HarnessWithInternals<Ctx, State, Req, Run> {\n const builder: any = { // any: TypeScript cannot infer overloaded call signatures from object literal method definitions\n provide<K extends keyof Ctx>(\n key: K,\n value: RequiredMarker | RuntimeMarker | DeepWithMarkers<Ctx[K]>,\n ): Harness<Ctx, State, any, any> { // any: Req/Run accumulation is tracked at the type level via overloads; method body uses any to avoid inference conflicts\n const newProviders = Object.freeze([\n ...internals.providers,\n { kind: 'provide' as const, key: String(key), value },\n ])\n const newInternals: HarnessInternals<Ctx, State, any, any> = { // any: same reason as return type annotation above\n stateSchema: internals.stateSchema,\n providers: newProviders,\n loopDef: internals.loopDef,\n _req: undefined,\n _run: undefined,\n _state: undefined,\n }\n return createBuilderInstance(newInternals)\n },\n\n store(stores: DeepWithMarkers<{ session?: unknown } & Record<string, unknown>>): Harness<Ctx, State, Req, Run> {\n const newProviders = Object.freeze([\n ...internals.providers,\n { kind: 'store' as const, key: '__store__', value: stores },\n ])\n const newInternals: HarnessInternals<Ctx, State, Req, Run> = {\n stateSchema: internals.stateSchema,\n providers: newProviders,\n loopDef: internals.loopDef,\n _req: undefined,\n _run: undefined,\n _state: undefined,\n }\n return createBuilderInstance(newInternals)\n },\n\n loop(builderFn: (l: LoopBuilder<State, Ctx>) => void): Harness<Ctx, State, Req, Run> {\n const lb = createLoopBuilder<State, Ctx>()\n builderFn(lb)\n const def = extractLoopDefinition(lb as LoopBuilder<unknown, unknown>) // as: generic S/Ctx erased for internal storage\n validateLoop(def)\n const newInternals: HarnessInternals<Ctx, State, Req, Run> = {\n stateSchema: internals.stateSchema,\n providers: internals.providers,\n loopDef: def,\n _req: undefined,\n _run: undefined,\n _state: undefined,\n }\n return createBuilderInstance(newInternals)\n },\n\n definition(): LoopDefinition {\n if (internals.loopDef === undefined) {\n throw new LoopNotDefinedError()\n }\n return internals.loopDef\n },\n\n [_internals]: internals,\n }\n\n return builder\n}\n","import type { RunRef } from './session-store.js'\n\n/**\n * Identifies the agent and session for run-level observer callbacks.\n */\nexport interface RunContext {\n readonly agentId: string\n readonly sessionId: string\n /**\n * The UUID for this specific run invocation. Always present in RunContext\n * passed to observer methods.\n */\n readonly runId: string\n /**\n * Optional parent run UUID for cross-process trace correlation. Present\n * when parentRunId was passed to agent.run() resources. Absent for top-level\n * runs or when not provided by the caller.\n */\n readonly parentRunId?: string\n /**\n * The physical instance ID of the agent process, if configured via\n * `createAgent()` options. Absent when `instanceId` was not provided.\n */\n readonly instanceId?: string\n /**\n * Branch-name path (outermost to innermost), present only when this context describes a\n * fork branch's own nested run rather than the top-level run. A branch is implemented as\n * its own recursive runLoop call, so it fires onRunStart/onRunEnd on the same observer as\n * the top-level run, under the same runId — this field is what makes those distinguishable\n * from the real top-level pair. Absent for the top-level run.\n */\n readonly branchPath?: readonly string[]\n /**\n * The run this one continues: the run that paused the session (on an interrupt, a stop or\n * an unhandled error), with the carrier its observer produced. Present on a resumed\n * top-level run only — never on a fork branch's context, never together with `branchedFrom`.\n */\n readonly resumedFrom?: RunRef\n /**\n * The run this session was branched from (`SessionStore.branch`), in the source session.\n * Present on the branched session's first top-level run only.\n */\n readonly branchedFrom?: RunRef & { readonly sessionId: string }\n}\n\n/**\n * Identifies the agent, session, and current step for step-level observer callbacks.\n */\nexport interface StepContext {\n readonly agentId: string\n readonly sessionId: string\n /**\n * The runId of the run this step belongs to — the same value as `RunContext.runId`. Steps\n * inside fork branches carry the top-level run's id (tell branches apart with `branchPath`).\n * A resumed run has a new id. Empty string only when the loop is driven without a runId\n * (direct `runLoop` use), as for `RunContext.runId`.\n */\n readonly runId: string\n readonly stepName: string\n /**\n * Branch-name path (outermost to innermost), present only when this step runs inside a\n * fork branch. Absent for a step at the top level of the loop (including the fork node\n * itself, which is one atomic step from the outer run's point of view).\n */\n readonly branchPath?: readonly string[]\n}\n\n/**\n * Where execution goes after a step settles.\n *\n * - `step` — the next step to run (a route target, `.next()`, the implicit next step, the\n * `l.onError()` fallback, or the join after a fork).\n * - `end` — the loop ended via `.end()` (inside a fork branch: the branch ended).\n * - `pause` — the run paused (interrupt, stop, or an unhandled error) and can be continued later.\n * - `throw` — a graph-definition error (`UnknownSignalError`, `NoNextStepError`,\n * `MissingReducerError`) is about to reject the run.\n */\nexport type StepSettledNext =\n | { readonly kind: 'step'; readonly name: string }\n | { readonly kind: 'end' }\n | { readonly kind: 'pause' }\n | { readonly kind: 'throw' }\n\n/**\n * Payload of {@link Observer.onStepSettled}: everything known about one step once its\n * outcome and destination are final. Optional keys are omitted, never set to `undefined`.\n */\nexport interface StepSettledEvent {\n /** `'stopped'` only occurs on fork nodes whose branches were stopped without an interrupt. */\n readonly outcome: 'ok' | 'error' | 'interrupt' | 'stopped'\n /** From `onStepStart` until the destination is known — includes `route()`. */\n readonly durationMs: number\n /**\n * The value `run()` returned, present iff it was applied to state. The raw reference,\n * unfiltered — it may be aliased into state, so copy it before the next step if you keep it.\n */\n readonly update?: Record<string, unknown>\n /** Present iff `route()` was called and returned a signal. */\n readonly signal?: string\n readonly next: StepSettledNext\n /** Present iff `outcome` is `'error'`. */\n readonly error?: Error\n /** Present iff `outcome` is `'interrupt'` on a plain (non-fork) step. */\n readonly interrupt?: { readonly interruptId: string; readonly prompt: unknown }\n /**\n * Fork nodes only, when every branch ended done or paused (not when the fork failed):\n * each branch in declaration order.\n */\n readonly fork?: {\n readonly branches: readonly { readonly name: string; readonly status: 'done' | 'paused'; readonly touchedKeys: readonly string[] }[]\n }\n}\n\n/**\n * What {@link Observer.wrap} is asked to enclose.\n *\n * - `step` — one step's `run()`. Hooks (`onStepStart`, `onStepEnd`, …) and `route()` run outside it.\n * - `event` — a call inside a step that an event already opened, named by that event's `type`\n * (e.g. `'tool.call'`, `'llm.request'`), with a `payload` carrying the id the event used\n * (e.g. `{ toolCallId }`, `{ callId }`). Requested via `ctx.within()` or `TelemetryContext.within()`.\n */\nexport type WrapScope =\n | { readonly kind: 'step' }\n | { readonly kind: 'event'; readonly type: string; readonly payload: unknown }\n\n/**\n * Observability hook interface. All methods are optional — implement only\n * the hooks you need.\n *\n * Pass an `Observer` implementation in `agent.run()` resources under the key\n * `'observer'`, or bind it to an {@link ObserverAware} slot before running.\n *\n * LLM adapters emit `'llm.response'` events via `onEvent` carrying an\n * `LLMUsageEvent` payload for token tracking.\n *\n * @example\n * ```ts\n * const obs: Observer = {\n * onRunStart: (ctx) => console.log('run started', ctx.sessionId),\n * onEvent: (ctx, type, payload) => metrics.record(type, payload),\n * }\n * agent.run({}, { llm, observer: obs })\n * ```\n */\nexport interface Observer {\n /** Called once when a run begins, before the first step executes. */\n onRunStart?: (ctx: RunContext) => void\n /**\n * Called once when a run settles — completed, stopped, paused, or rejected by a thrown error\n * (a graph-definition error or a throwing callback).\n *\n * When the run ends because of an error, `signal` is `'$error'` and `error` holds it: the error\n * a step's `run` or `route` threw, or a failed fork's branch error, when no `onError` step\n * handled it (the run resolves paused); or the original thrown value when the run rejects (it\n * rejects right after). `error` is absent on every other ending. A route may also return\n * `'$error'` as an ordinary signal; that ending has no `error` key, so test for `error`, not\n * for the signal.\n */\n onRunEnd?: (ctx: RunContext, event: { signal: string; durationMs: number; error?: unknown }) => void\n /** Called immediately before each step's `run` function is invoked. */\n onStepStart?: (ctx: StepContext) => void\n /** Called after a step completes successfully. */\n onStepEnd?: (ctx: StepContext, event: { durationMs: number }) => void\n /** Called when a step's `run` function throws. */\n onStepError?: (ctx: StepContext, event: { error: unknown; durationMs: number }) => void\n /** Called when a step issues a `ctx.interrupt()`. */\n onInterrupt?: (ctx: StepContext, event: { prompt: unknown; interruptId: string }) => void\n /**\n * Called for arbitrary named events emitted by step code via `ctx.emit()` or\n * by LLM adapters (e.g. `'llm.response'`).\n */\n onEvent?: (ctx: StepContext, type: string, payload: unknown) => void\n /**\n * Called exactly once per step, on every path, once the step's outcome and destination\n * are final: after `onStepEnd` / `onStepError` / `onInterrupt` (when that hook fires on the\n * path) and before `onRunEnd`. Also fires for fork nodes and for steps inside fork branches\n * (with `ctx.branchPath`). Not fired when a run stops before starting a step.\n */\n onStepSettled?: (ctx: StepContext, event: StepSettledEvent) => void\n /**\n * Run `fn` inside this observer's scope — e.g. make a span the active context so code in\n * `fn` (auto-instrumented clients, sub agents) nests under it. The only hook that encloses\n * work rather than being notified about it.\n *\n * Call `fn` at most once and return its promise. The harness never trusts the wrapper:\n * `fn` always runs exactly once, and the caller always gets `fn`'s own result. A wrapper\n * that throws before calling `fn` is reported via `onObserverError` (hook name `'wrap'`) and\n * `fn` runs unwrapped; one that never calls `fn` just loses its scope; one that swallows or\n * replaces `fn`'s result is ignored. A wrapper error after `fn` was called is reported too,\n * unless it is `fn`'s own rejection passed through.\n *\n * Not guarded: a wrapper that never settles hangs the step it encloses.\n */\n wrap?: <T>(ctx: StepContext, scope: WrapScope, fn: () => Promise<T>) => Promise<T>\n /**\n * Called once per top-level run, right after `onRunStart` (never for a fork branch). Return\n * an opaque string map that lets a later run refer back to this one — e.g. the run's trace\n * context. Core saves it on the run's record and hands it back as `RunContext.resumedFrom.carrier`\n * (or `branchedFrom.carrier`) to the run that continues or branches from it. Return\n * `undefined` for nothing. Only string values are kept; a throw is reported via\n * `onObserverError` (hook name `'carry'`) and counts as `undefined`.\n */\n carry?: (ctx: RunContext) => Record<string, string> | undefined\n}\n\n/**\n * The telemetry a resource needs to attribute an `invoke()` call to the correct\n * run and step: the run's {@link Observer} and the current {@link StepContext}.\n *\n * The harness passes this per call rather than storing it on the resource instance,\n * so concurrently-running fork branches that share one instance never race on it —\n * each call carries its own context by value.\n */\nexport interface TelemetryContext {\n /**\n * The run's observer, fault-isolated: a hook that throws is reported via `onObserverError`\n * and never reaches the caller. Not the object passed to `agent.run()` itself.\n */\n readonly observer: Observer\n readonly stepContext: StepContext\n /**\n * Run `fn` inside the observer's scope for the event `type` (e.g. `'llm.request'`), whose\n * `payload` carries that event's id (e.g. `{ callId }`). Bound to this step. A passthrough\n * when the observer has no `wrap`; wrapper faults are isolated as for {@link Observer.wrap}.\n */\n within<T>(type: string, payload: unknown, fn: () => Promise<T>): Promise<T>\n}\n\n/**\n * Implemented by resources (e.g. LLM adapters) that emit per-step telemetry.\n *\n * The harness calls {@link ObserverAware.withTelemetry} at the start of each step for every\n * slot that exposes it, and installs the returned value as that slot on the step's `ctx`.\n * Step code then calls the returned view (e.g. `ctx.llm.invoke(...)`) with no telemetry\n * arguments, and the view forwards the {@link TelemetryContext} into the call it wraps — so\n * telemetry travels *with the call* rather than living in mutable instance state.\n *\n * The return is typed `unknown` because core exports no LLM-domain type; a concrete adapter\n * narrows it (e.g. to its `LLM` view). The harness treats the returned value as an opaque\n * slot, exactly as it treats every provided slot.\n */\nexport interface ObserverAware {\n /**\n * Return a view of this resource scoped to the given telemetry. The harness installs\n * the returned value as the resource's slot on the step's `ctx` before calling `step.run`.\n * Called once per step (and once per step per branch), so each concurrent branch gets its\n * own scoped view and there is no shared field to race on.\n */\n withTelemetry(ctx: TelemetryContext): unknown\n}\n\n/**\n * Combine multiple {@link Observer} instances into one. Each hook on the\n * composite forwards to all constituent observers in order.\n *\n * @example\n * ```ts\n * const observer = composeObservers([otelObserver, metricsObserver])\n * ```\n */\n/**\n * Identifies which observer hook threw. Passed to an {@link ObserverErrorSink}.\n */\nexport interface ObserverErrorContext {\n /** The observer hook that threw, e.g. `'onStepStart'`, `'onRunEnd'`, `'onEvent'`. */\n readonly hookName: string\n}\n\n/**\n * Opt-in sink for errors thrown by observer callbacks. Supplied under the\n * `'onObserverError'` key in `agent.run()` / `agent.resume()` resources.\n *\n * Telemetry is a side-channel: an observer that throws must never crash a run.\n * The harness routes every such throw here and continues. The sink is called at\n * most once per failed hook invocation and MUST NOT rethrow into the run — if it\n * does, the harness contains that too (see {@link safeInvoke}).\n */\nexport type ObserverErrorSink = (error: unknown, ctx: ObserverErrorContext) => void\n\n/**\n * Route an observer-hook error to the sink, or, when no sink is configured, to a\n * single `console.error` that names the hook. A sink that itself throws is\n * caught and reported the same way — it never escapes.\n */\nfunction reportObserverError(\n error: unknown,\n ctx: ObserverErrorContext,\n sink: ObserverErrorSink | undefined,\n): void {\n if (sink !== undefined) {\n try {\n sink(error, ctx)\n } catch (sinkError) {\n // A throwing sink must never crash the run, and must not vanish silently.\n console.error(`[harness] onObserverError sink threw while handling '${ctx.hookName}':`, sinkError)\n }\n return\n }\n // Default sink: visible, not silent, and names the failing hook.\n console.error(`[harness] observer hook '${ctx.hookName}' threw:`, error)\n}\n\n/**\n * Invoke one observer-hook call with fault isolation. Runs `call()`; if it\n * throws, the error is routed to `sink` (or the default) and `safeInvoke`\n * returns normally — it never rethrows into the run.\n *\n * `call` is a thunk that performs the exact hook call, e.g.\n * `() => obs?.onStepStart?.(stepCtx)`, so optional-chaining semantics are\n * preserved: when the observer or hook is absent the thunk is a no-op.\n */\nexport function safeInvoke(\n hookName: string,\n call: () => void,\n sink: ObserverErrorSink | undefined,\n): void {\n try {\n call()\n } catch (error) {\n reportObserverError(error, { hookName }, sink)\n }\n}\n\n/**\n * Like {@link safeInvoke}, for a hook that returns a value: returns what `call()` returned,\n * or `undefined` after reporting its throw.\n */\nexport function safeCall<T>(\n hookName: string,\n call: () => T,\n sink: ObserverErrorSink | undefined,\n): T | undefined {\n try {\n return call()\n } catch (error) {\n reportObserverError(error, { hookName }, sink)\n return undefined\n }\n}\n\n/**\n * Run `fn` inside `wrap` with the harness owning `fn`'s result — the isolation rule for\n * {@link Observer.wrap}. `fn` runs exactly once, whatever the wrapper does: if the wrapper\n * never calls it, it is started here. The returned promise is always `fn`'s own. Wrapper\n * errors are reported (hook name `'wrap'`) unless they are `fn`'s own rejection passed through.\n */\nexport async function runWrapped<T>(\n wrap: (inner: () => Promise<T>) => unknown,\n fn: () => Promise<T> | T,\n onObserverError: ObserverErrorSink | undefined,\n): Promise<T> {\n let p: Promise<T> | undefined\n const inner = (): Promise<T> => {\n if (p === undefined) {\n // A sync throw from fn becomes a rejection of p, so it is never taken for a wrapper error.\n p = new Promise<T>(resolve => resolve(fn()))\n // Mark p handled: fn may fail while a wrapper that didn't await it is still pending.\n p.catch(() => {})\n }\n return p\n }\n try {\n await wrap(inner)\n } catch (e) {\n // Re-read through an annotated const: control flow narrows `p` to undefined here, since it is only assigned inside `inner`.\n const started: Promise<T> | undefined = p\n const passedThrough = started !== undefined && await started.then(() => false, (err: unknown) => err === e)\n if (!passedThrough) reportObserverError(e, { hookName: 'wrap' }, onObserverError)\n }\n return inner()\n}\n\nexport function composeObservers(observers: Observer[], onObserverError?: ObserverErrorSink): Observer {\n const wrappers = observers.filter(o => o.wrap !== undefined)\n return {\n onRunStart: (ctx) => {\n for (const o of observers) safeInvoke('onRunStart', () => o.onRunStart?.(ctx), onObserverError)\n },\n onRunEnd: (ctx, event) => {\n for (const o of observers) safeInvoke('onRunEnd', () => o.onRunEnd?.(ctx, event), onObserverError)\n },\n onStepStart: (ctx) => {\n for (const o of observers) safeInvoke('onStepStart', () => o.onStepStart?.(ctx), onObserverError)\n },\n onStepEnd: (ctx, event) => {\n for (const o of observers) safeInvoke('onStepEnd', () => o.onStepEnd?.(ctx, event), onObserverError)\n },\n onStepError: (ctx, event) => {\n for (const o of observers) safeInvoke('onStepError', () => o.onStepError?.(ctx, event), onObserverError)\n },\n onInterrupt: (ctx, event) => {\n for (const o of observers) safeInvoke('onInterrupt', () => o.onInterrupt?.(ctx, event), onObserverError)\n },\n onEvent: (ctx, type, payload) => {\n for (const o of observers) safeInvoke('onEvent', () => o.onEvent?.(ctx, type, payload), onObserverError)\n },\n onStepSettled: (ctx, event) => {\n for (const o of observers) safeInvoke('onStepSettled', () => o.onStepSettled?.(ctx, event), onObserverError)\n },\n // Each observer isolated on its own; later keys win.\n carry: (ctx) => {\n let merged: Record<string, string> | undefined\n for (const o of observers) {\n const carried: unknown = safeCall('carry', () => o.carry?.(ctx), onObserverError)\n if (typeof carried !== 'object' || carried === null || Array.isArray(carried)) continue\n merged = Object.assign(merged ?? {}, carried)\n }\n return merged\n },\n // First observer outermost; each layer isolated on its own by runWrapped.\n wrap: <T>(ctx: StepContext, scope: WrapScope, fn: () => Promise<T>): Promise<T> => {\n const layer = (i: number): Promise<T> =>\n i === wrappers.length\n ? fn()\n : runWrapped(inner => wrappers[i]!.wrap!(ctx, scope, inner), () => layer(i + 1), onObserverError)\n return layer(0)\n },\n }\n}\n","// -----------------------------------------------------------------------\n// InterruptPause — internal control-flow signal between ctx-interrupt and loop-executor\n// -----------------------------------------------------------------------\n\nexport class InterruptPause extends Error {\n readonly interruptId: string\n readonly prompt: unknown\n\n constructor(interruptId: string, prompt: unknown) {\n super(`interrupt requested for id \"${interruptId}\"`)\n this.name = 'InterruptPause'\n this.interruptId = interruptId\n this.prompt = prompt\n }\n}\n\n// -----------------------------------------------------------------------\n// isInterruptPause — type guard used by runLoop\n// -----------------------------------------------------------------------\n\nexport function isInterruptPause(error: unknown): error is InterruptPause {\n return error instanceof InterruptPause\n}\n\n// -----------------------------------------------------------------------\n// createInterruptFn — factory for ctx.interrupt()\n// -----------------------------------------------------------------------\n\nexport function createInterruptFn(\n state: Record<string, unknown>,\n callCountRef: { current: number },\n branchPath?: readonly string[],\n): (prompt: unknown, id?: string) => Promise<unknown> {\n const prefix = branchPath !== undefined && branchPath.length > 0 ? `${branchPath.join(':')}:` : ''\n return async (prompt: unknown, id?: string): Promise<unknown> => {\n const isAutoId = id === undefined\n const effectiveId = isAutoId ? `$auto:${prefix}${callCountRef.current}` : id\n\n // only auto-id calls increment the counter\n if (isAutoId) {\n callCountRef.current++\n }\n\n const responses = state.$interruptResponses as Record<string, unknown>\n\n if (effectiveId in responses) {\n return responses[effectiveId]\n }\n\n state.$interrupt = { interruptId: effectiveId, prompt }\n throw new InterruptPause(effectiveId, prompt)\n }\n}\n","import { safeInvoke, type Observer, type ObserverErrorSink, type StepContext } from './observer.js'\n\n/**\n * Create the ctx.emit function for a single runLoop invocation.\n * Returns a synchronous, fire-and-forget dispatcher.\n * Fires the matching listener (if registered) AND observer.onEvent (if observer\n * is set and stepCtxRef.current is non-null) independently for each call.\n */\nexport function createEmitFn(\n listeners: Record<string, (payload: unknown) => void>,\n observer?: Observer,\n stepCtxRef?: { current: StepContext | null },\n onObserverError?: ObserverErrorSink,\n): (name: string, payload?: unknown) => void {\n return (name: string, payload?: unknown): void => {\n listeners[name]?.(payload)\n if (observer !== undefined && stepCtxRef !== undefined && stepCtxRef.current !== null) {\n const ctx = stepCtxRef.current\n safeInvoke('onEvent', () => observer.onEvent?.(ctx, name, payload), onObserverError)\n }\n }\n}\n\n/**\n * Extract the listeners map from agent.run() resources.\n * Returns an empty object if the 'listeners' key is absent or not a plain object.\n */\nexport function extractRunListeners(\n resources: Record<string, unknown>,\n): Record<string, (payload: unknown) => void> {\n const raw = resources['listeners']\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n return {}\n }\n // plain object: return as-is; listener values are not validated\n return raw as Record<string, (payload: unknown) => void> // as: duck-typed plain object confirmed above; values are caller's responsibility\n}\n","import { runWrapped, type Observer, type ObserverErrorSink, type StepContext } from './observer.js'\n\n/**\n * Create a `within(type, payload, fn)` function: runs `fn` inside `observer.wrap` with an\n * `event` scope for the step `currentStep()` returns at call time. A passthrough (`fn()`) when\n * there is no observer, no `wrap`, or no current step. Used for both `ctx.within` (current step\n * of a runLoop) and `TelemetryContext.within` (bound to one step).\n */\nexport function createWithinFn(\n observer: Observer | undefined,\n currentStep: () => StepContext | null,\n onObserverError: ObserverErrorSink | undefined,\n): <T>(type: string, payload: unknown, fn: () => Promise<T>) => Promise<T> {\n return <T>(type: string, payload: unknown, fn: () => Promise<T>): Promise<T> => {\n const wrap = observer?.wrap\n const stepCtx = currentStep()\n if (wrap === undefined || stepCtx === null) return fn()\n return runWrapped(inner => wrap(stepCtx, { kind: 'event', type, payload }, inner), fn, onObserverError)\n }\n}\n\n/**\n * Run one step's `run()` inside `observer.wrap` with the `step` scope, or call it directly when\n * the observer has no `wrap`.\n */\nexport function runStepScope<T>(\n observer: Observer | undefined,\n stepCtx: StepContext,\n fn: () => Promise<T> | T,\n onObserverError: ObserverErrorSink | undefined,\n): Promise<T> | T {\n const wrap = observer?.wrap\n if (wrap === undefined) return fn()\n return runWrapped(inner => wrap(stepCtx, { kind: 'step' }, inner), fn, onObserverError)\n}\n","import type { LoopDefinition, ForkDef, BranchDef } from '../loop/loop-dsl.js'\nimport { isForkDef } from '../loop/loop-dsl.js'\nimport type { FieldDefinition } from '../harness/state-field.js'\nimport { composeObservers, safeCall, safeInvoke, type Observer, type ObserverErrorSink, type RunContext, type StepContext, type StepSettledEvent, type TelemetryContext } from '../agent/observer.js'\nimport { createInterruptFn, isInterruptPause } from '../agent/ctx-interrupt.js'\nimport { createEmitFn } from '../agent/ctx-emit.js'\nimport { createWithinFn, runStepScope } from '../agent/ctx-within.js'\nimport type { RunCarrier, RunRef } from '../agent/session-store.js'\n\n// A shared no-op observer, so a telemetry-scoped slot always receives a well-formed\n// observer even when the run configured none.\nconst NOOP_OBSERVER: Observer = {}\n\n// -----------------------------------------------------------------------\n// Cursor — a plain step name, or (once a fork is paused) a composite pointer\n// into that fork's branches. See HANDOVER-fork-join.md §4 / Phase 3.\n// -----------------------------------------------------------------------\n\nexport type Cursor = string | ForkCursor\n\n/**\n * Persisted/returned shape of a paused fork. Always lists every branch of the fork, in\n * declaration order (never completion order — see decision #8). A branch never appears\n * with an 'errored' status: an uncaught branch error always escalates to whole-fork\n * failure (decision #9) rather than sitting here as a persisted per-branch state.\n */\nexport interface ForkCursor {\n readonly kind: 'fork'\n readonly fork: string\n readonly branches: readonly BranchCursor[]\n}\n\nexport type BranchCursor =\n | {\n readonly name: string\n readonly status: 'done'\n readonly state: Record<string, unknown>\n readonly touchedKeys: readonly string[]\n }\n | {\n readonly name: string\n readonly status: 'paused'\n readonly state: Record<string, unknown>\n readonly cursor: Cursor\n readonly touchedKeys: readonly string[]\n }\n\n/** Structural type guard distinguishing a ForkCursor from a plain step-name cursor. */\nexport function isForkCursor(cursor: Cursor): cursor is ForkCursor {\n return typeof cursor !== 'string'\n}\n\n// -----------------------------------------------------------------------\n// LoopResult\n// -----------------------------------------------------------------------\n\nexport interface LoopResult {\n readonly state: Record<string, unknown>\n readonly signal: string | null\n readonly cursor: Cursor | null\n readonly paused: boolean\n /** What the run's observer returned from `carry`. Top-level runs only; absent when nothing was carried. */\n readonly carrier?: RunCarrier\n}\n\n// -----------------------------------------------------------------------\n// Error classes\n// -----------------------------------------------------------------------\n\nexport class UnknownSignalError extends Error {\n readonly step: string\n readonly signal: string\n constructor(step: string, signal: string) {\n super(`step \"${step}\" emitted signal \"${signal}\" with no matching .on() transition`)\n this.name = 'UnknownSignalError'\n this.step = step\n this.signal = signal\n }\n}\n\nexport class NoNextStepError extends Error {\n readonly step: string\n constructor(step: string) {\n super(\n `step \"${step}\" has no route, no explicit next, and is the last declared step — execution cannot continue`,\n )\n this.name = 'NoNextStepError'\n this.step = step\n }\n}\n\n/**\n * Thrown when a fork's branches, once all done, have more than one branch touching the\n * same state key with no `field({ reduce })` declared for it (decision #7). Like\n * UnknownSignalError/NoNextStepError, this is a graph-definition bug — it propagates\n * uncaught rather than routing through `$error`/`onError`.\n */\nexport class MissingReducerError extends Error {\n readonly fork: string\n readonly key: string\n readonly branches: readonly string[]\n constructor(fork: string, key: string, branches: readonly string[]) {\n super(\n `fork \"${fork}\": state key \"${key}\" was touched by multiple branches (${branches.join(', ')}) but has no reducer declared — add field({ reduce }) for \"${key}\"`,\n )\n this.name = 'MissingReducerError'\n this.fork = fork\n this.key = key\n this.branches = branches\n }\n}\n\n// -----------------------------------------------------------------------\n// Private helpers\n// -----------------------------------------------------------------------\n\nfunction buildImplicitNextMap(graph: LoopDefinition): Map<string, string | null> {\n const map = new Map<string, string | null>()\n for (let i = 0; i < graph.steps.length; i++) {\n const step = graph.steps[i]!\n const next = i + 1 < graph.steps.length ? graph.steps[i + 1]!.name : null\n map.set(step.name, next)\n }\n return map\n}\n\nfunction applyUpdate(\n state: Record<string, unknown>,\n update: Record<string, unknown>,\n schema: Record<string, FieldDefinition<any>> | undefined, // any: FieldDefinition uses invariant T; any is required for heterogeneous schema maps\n touchedKeys?: Set<string>,\n): void {\n for (const [key, value] of Object.entries(update)) {\n if (key === '$error' || key === '$interrupt' || key === '$interruptResponses') continue\n const reducer = schema?.[key]?.reduce\n if (reducer !== undefined) {\n state[key] = reducer(state[key], value)\n } else {\n state[key] = value\n }\n touchedKeys?.add(key)\n }\n}\n\n/**\n * Fires onStepSettled for one step, stamping durationMs from the step's start. Skips building\n * the event entirely when no observer listens.\n */\nfunction fireSettled(\n obs: Observer | undefined,\n stepCtx: StepContext,\n stepStart: number,\n fields: Omit<StepSettledEvent, 'durationMs'>,\n onObserverError: ObserverErrorSink | undefined,\n): void {\n const hook = obs?.onStepSettled\n if (hook === undefined) return\n const event: StepSettledEvent = { ...fields, durationMs: Date.now() - stepStart }\n safeInvoke('onStepSettled', () => hook(stepCtx, event), onObserverError)\n}\n\n/** The StepContext for a step of this runLoop: the run's identity plus the step name. */\nfunction stepContextOf(runCtx: RunContext, stepName: string): StepContext {\n return {\n agentId: runCtx.agentId,\n sessionId: runCtx.sessionId,\n runId: runCtx.runId,\n stepName,\n ...(runCtx.branchPath !== undefined ? { branchPath: runCtx.branchPath } : {}),\n }\n}\n\nfunction asError(e: unknown): Error {\n return e instanceof Error ? e : new Error(String(e))\n}\n\n// -----------------------------------------------------------------------\n// Public API\n// -----------------------------------------------------------------------\n\nexport interface LoopCallbacks {\n onBeforeStep?: (name: string, state: Record<string, unknown>) => void\n onAfterStep?: (name: string, state: Record<string, unknown>) => void\n onError?: (error: unknown, stepName: string) => void\n onComplete?: (state: Record<string, unknown>, signal: string) => void\n onInterrupt?: (prompt: unknown, interruptId: string) => void\n /**\n * Listeners for user-emitted events (ctx.emit). Keyed by event name.\n * A missing key means ctx.emit(name) is a no-op for that name.\n */\n listeners?: Record<string, (payload: unknown) => void>\n /** Observer for structured telemetry. All lifecycle methods are optional. F16b. */\n observer?: Observer\n /**\n * Opt-in sink for errors thrown by observer callbacks. When a hook throws, the\n * error is routed here (or, if absent, to a default `console.error`) and the\n * run continues — a telemetry fault never aborts a run.\n */\n onObserverError?: ObserverErrorSink\n /**\n * The UUID for this specific invocation. Included in RunContext for observer\n * methods. Absent when no observer is active (observer is still consistent).\n */\n runId?: string\n /**\n * Optional parent run UUID for cross-process trace correlation.\n * Included in RunContext when provided.\n */\n parentRunId?: string\n /**\n * Pre-filtered, keyed list of ObserverAware slots that expose `withTelemetry`.\n * At every step start, before invoking step.run, the loop installs\n * `ctx[key] = slot.withTelemetry({ observer, stepContext })` so telemetry travels with\n * the call. Wrapping always reads from the stored real `slot`, never a prior wrapped\n * value, so re-scoping each step (and each branch, on its own ctx) is safe under concurrency.\n */\n telemetrySlots?: ReadonlyArray<{ key: string; slot: { withTelemetry(ctx: TelemetryContext): unknown } }>\n /**\n * Internal: when set, applyUpdate records every key it writes into this Set.\n * Used by fork dispatch to track which keys a single branch touched, for the\n * declaration-order fold at the join (decisions #6/7/8). Not for external use —\n * a normal top-level runLoop call never sets this.\n */\n touchedKeys?: Set<string>\n /**\n * Internal: branch-name path (outermost to innermost) this runLoop call is running as, if\n * any. Absent for a top-level (non-branch) runLoop call. Two consumers:\n * - qualifies auto-generated interrupt ids ($auto:N -> $auto:branch:N) so sibling branches'\n * default ids can't collide once exposed outside their own runLoop call (Phase 4);\n * - carried onto StepContext/RunContext so an observer can tell a branch's own step/run\n * events apart from the top-level run's (Phase 7) — see HANDOVER-fork-join.md §4.\n */\n branchPath?: readonly string[]\n /** The run this one continues. Put on the top-level RunContext only, never on a branch's. */\n resumedFrom?: RunRef\n /** The run this session was branched from. Put on the top-level RunContext only, never on a branch's. */\n branchedFrom?: RunRef & { sessionId: string }\n}\n\n/**\n * What `carry` returned, reduced to what a record can hold: a frozen copy of its string\n * entries, or `undefined` when it is not a plain map or has none.\n */\nfunction normalizeCarrier(carried: unknown): RunCarrier | undefined {\n if (typeof carried !== 'object' || carried === null || Array.isArray(carried)) return undefined\n const entries = Object.entries(carried).filter(([, v]) => typeof v === 'string')\n return entries.length > 0 ? Object.freeze(Object.fromEntries(entries) as Record<string, string>) : undefined\n}\n\ntype Ctx = Record<string, unknown> & {\n readonly agentId: string\n readonly sessionId: string\n readonly signal?: AbortSignal\n}\n\nexport async function runLoop(\n graph: LoopDefinition,\n state: Record<string, unknown>,\n ctx: Ctx,\n schema: Record<string, FieldDefinition<any>> | undefined, // any: see applyUpdate comment\n shouldStop?: () => boolean,\n startCursor?: Cursor,\n callbacks?: LoopCallbacks,\n): Promise<LoopResult> {\n const { onBeforeStep, onAfterStep, onError, onComplete, onInterrupt } = callbacks ?? {}\n const obs = callbacks?.observer\n const onObserverError = callbacks?.onObserverError\n const implicitNextMap = buildImplicitNextMap(graph)\n\n // Initialize framework-reserved fields if absent\n if (!('$error' in state)) state.$error = null\n if (!('$interrupt' in state)) state.$interrupt = null\n if (!('$interruptResponses' in state)) state.$interruptResponses = {}\n\n const runStart = Date.now()\n const branchPath = callbacks?.branchPath\n const isBranch = branchPath !== undefined && branchPath.length > 0\n const runCtx: RunContext = {\n agentId: ctx.agentId,\n sessionId: ctx.sessionId,\n runId: typeof callbacks?.runId === 'string' ? callbacks.runId : '',\n ...(typeof callbacks?.parentRunId === 'string' ? { parentRunId: callbacks.parentRunId } : {}),\n ...(typeof ctx.instanceId === 'string' ? { instanceId: ctx.instanceId } : {}),\n ...(isBranch ? { branchPath } : {}),\n // Branch runLoops receive the outer callbacks by spread, so the refs are dropped here.\n ...(!isBranch && callbacks?.resumedFrom !== undefined ? { resumedFrom: callbacks.resumedFrom } : {}),\n ...(!isBranch && callbacks?.branchedFrom !== undefined ? { branchedFrom: callbacks.branchedFrom } : {}),\n }\n safeInvoke('onRunStart', () => obs?.onRunStart?.(runCtx), onObserverError)\n // The run's own context is fixed from onRunStart on, so the observer is asked once, right here.\n const carrier = isBranch ? undefined : normalizeCarrier(safeCall('carry', () => obs?.carry?.(runCtx), onObserverError))\n const withCarrier = (result: LoopResult): LoopResult => carrier !== undefined ? { ...result, carrier } : result\n // The one place a run ends, so onRunEnd fires exactly once on every path — including a throw.\n let runEnded = false\n // `failure` is passed only on the endings caused by an error, so the event has an `error`\n // key exactly then — even when the thrown value is undefined.\n const endRun = (signal: string, failure?: { error: unknown }): void => {\n runEnded = true\n const event = { signal, durationMs: Date.now() - runStart, ...(failure !== undefined ? { error: failure.error } : {}) }\n safeInvoke('onRunEnd', () => obs?.onRunEnd?.(runCtx, event), onObserverError)\n }\n\n // callCountRef is shared between createInterruptFn and the per-step reset below\n const callCountRef = { current: 0 }\n const stepCtxRef: { current: StepContext | null } = { current: null }\n // mutate ctx in-place so step.run receives the same object reference (invariant for callers)\n ;(ctx as Record<string, unknown>)['interrupt'] = createInterruptFn(state, callCountRef, callbacks?.branchPath) // as: Record<string, unknown> allows adding framework-injected fields to ctx\n ;(ctx as Record<string, unknown>)['emit'] = createEmitFn(callbacks?.listeners ?? {}, obs, stepCtxRef, onObserverError) // as: see interrupt line comment\n ;(ctx as Record<string, unknown>)['within'] = createWithinFn(obs, () => stepCtxRef.current, onObserverError) // as: see interrupt line comment\n // What telemetry-scoped slots (LLM adapters) call hooks on: the run's observer, fault-isolated\n // like every core call site, so an observer that throws on an adapter event never fails the step.\n const telemetryObserver = obs !== undefined ? composeObservers([obs], onObserverError) : NOOP_OBSERVER\n\n let cursor: Cursor = startCursor ?? graph.entryStep!\n\n try {\n while (true) {\n if (shouldStop?.()) {\n endRun('$stopped')\n return withCarrier({ state, signal: null, cursor, paused: true })\n }\n\n // Resuming a previously-paused fork: cursor is a composite ForkCursor, not a step name.\n if (isForkCursor(cursor)) {\n const forkCursor: ForkCursor = cursor\n const forkNode = graph.steps.find(s => s.name === forkCursor.fork)!\n if (!isForkDef(forkNode)) {\n // Graph changed shape between pause and resume — treat like any other unresolvable cursor.\n throw new NoNextStepError(forkCursor.fork)\n }\n onBeforeStep?.(forkNode.name, { ...state })\n const outcome = await handleFork(\n forkNode, forkCursor.branches, state, ctx, schema, shouldStop, callbacks, obs, runCtx, endRun, implicitNextMap, graph,\n )\n if (outcome.done) {\n return withCarrier(outcome.result)\n }\n cursor = outcome.nextCursor\n continue\n }\n\n // pass a shallow snapshot so onBeforeStep observers see pre-run values even after state is mutated\n onBeforeStep?.(cursor, { ...state })\n\n const node = graph.steps.find(s => s.name === cursor)!\n if (isForkDef(node)) {\n const outcome = await handleFork(\n node, undefined, state, ctx, schema, shouldStop, callbacks, obs, runCtx, endRun, implicitNextMap, graph,\n )\n if (outcome.done) {\n return withCarrier(outcome.result)\n }\n cursor = outcome.nextCursor\n continue\n }\n const step = node\n\n // reset per-step counter before run (even for decision nodes, per design)\n callCountRef.current = 0\n\n const stepCtx = stepContextOf(runCtx, cursor)\n stepCtxRef.current = stepCtx\n const stepStart = Date.now()\n safeInvoke('onStepStart', () => obs?.onStepStart?.(stepCtx), onObserverError)\n if (callbacks?.telemetrySlots !== undefined) {\n const telemetry: TelemetryContext = {\n observer: telemetryObserver,\n stepContext: stepCtx,\n within: createWithinFn(obs, () => stepCtx, onObserverError),\n }\n for (const { key, slot } of callbacks.telemetrySlots) {\n ;(ctx as Record<string, unknown>)[key] = slot.withTelemetry(telemetry)\n }\n }\n\n let runSucceeded = false\n // The run's return value once applied to state — reported as onStepSettled's `update`.\n let applied: Record<string, unknown> | undefined\n const settle = (fields: Omit<StepSettledEvent, 'durationMs'>): void =>\n fireSettled(obs, stepCtx, stepStart, { ...fields, ...(applied !== undefined ? { update: applied } : {}) }, onObserverError)\n\n if (step.run !== undefined) {\n // capture whether responses exist before the run; only clear interrupt state if they did\n const hadResponses = Object.keys(state.$interruptResponses as Record<string, unknown>).length > 0\n try {\n const run = step.run\n const update = await runStepScope(obs, stepCtx, () => run(\n state as unknown as Parameters<typeof run>[0],\n ctx as Parameters<typeof run>[1],\n ), onObserverError)\n applyUpdate(state, update as Record<string, unknown>, schema, callbacks?.touchedKeys)\n applied = update as Record<string, unknown>\n // clear interrupt state only after a step that had stored responses to replay\n if (hadResponses) {\n state.$interrupt = null\n state.$interruptResponses = {}\n }\n runSucceeded = true\n } catch (e) {\n if (isInterruptPause(e)) {\n // InterruptPause was caught: $interrupt already written by createInterruptFn\n onInterrupt?.(e.prompt, e.interruptId)\n safeInvoke('onInterrupt', () => obs?.onInterrupt?.(stepCtx, { prompt: e.prompt, interruptId: e.interruptId }), onObserverError)\n settle({ outcome: 'interrupt', interrupt: { interruptId: e.interruptId, prompt: e.prompt }, next: { kind: 'pause' } })\n endRun('$interrupt')\n return withCarrier({ state, signal: '$interrupt', cursor, paused: true })\n }\n // domain error: normalize to Error and set $error; do not rethrow\n state.$error = e instanceof Error ? e : new Error(String(e))\n onError?.(state.$error, cursor)\n safeInvoke('onStepError', () => obs?.onStepError?.(stepCtx, { error: state.$error, durationMs: Date.now() - stepStart }), onObserverError)\n }\n }\n\n if (runSucceeded) {\n // clear $error after a successful run, before calling route\n state.$error = null\n onAfterStep?.(cursor, state)\n safeInvoke('onStepEnd', () => obs?.onStepEnd?.(stepCtx, { durationMs: Date.now() - stepStart }), onObserverError)\n }\n\n // route is called when: route exists AND (run succeeded, step has no run, OR step opted in\n // to error routing via optin: '$error' in the step config)\n const callRoute =\n step.route !== undefined &&\n (runSucceeded || step.run === undefined || step.errorAware)\n\n if (callRoute) {\n // callRoute implies step.route !== undefined; non-null assertion is sound here\n const routeFn = step.route!\n let signal: string\n try {\n signal = routeFn(state as unknown as Parameters<typeof routeFn>[0])\n } catch (e) {\n // route itself threw — treat as terminal error; state update from run already stands\n state.$error = e instanceof Error ? e : new Error(String(e))\n settle({ outcome: 'error', error: state.$error as Error, next: { kind: 'pause' } })\n endRun('$error', { error: state.$error })\n return withCarrier({ state, signal: '$error', cursor, paused: true })\n }\n // An error-aware route runs after a failed run: the step still settles as an error.\n const routed = runSucceeded || step.run === undefined\n ? { outcome: 'ok' as const, signal }\n : { outcome: 'error' as const, signal, error: state.$error as Error }\n const transition = step.transitions.find(t => t.signal === signal)\n if (transition === undefined) {\n const unknownSignal = new UnknownSignalError(cursor, signal)\n settle({ outcome: 'error', signal, error: unknownSignal, next: { kind: 'throw' } })\n throw unknownSignal\n }\n if (transition.target.kind === 'end') {\n settle({ ...routed, next: { kind: 'end' } })\n onComplete?.(state, signal)\n endRun(signal)\n return withCarrier({ state, signal, cursor: null, paused: false })\n }\n settle({ ...routed, next: { kind: 'step', name: transition.target.name } })\n cursor = transition.target.name\n } else if (step.run !== undefined && !runSucceeded) {\n // run threw, route bypassed (not error-aware) or no route: apply l.onError() fallback or pause\n if (graph.onError !== undefined) {\n settle({ outcome: 'error', error: state.$error as Error, next: { kind: 'step', name: graph.onError } })\n cursor = graph.onError\n } else {\n settle({ outcome: 'error', error: state.$error as Error, next: { kind: 'pause' } })\n endRun('$error', { error: state.$error })\n return withCarrier({ state, signal: '$error', cursor, paused: true })\n }\n } else {\n const next = step.next ?? implicitNextMap.get(cursor) ?? null\n if (next === null) {\n const noNext = new NoNextStepError(cursor)\n settle({ outcome: 'error', error: noNext, next: { kind: 'throw' } })\n throw noNext\n }\n settle({ outcome: 'ok', next: { kind: 'step', name: next } })\n cursor = next\n }\n }\n } catch (e) {\n // A run that rejects still ends: observers pairing onRunStart/onRunEnd must not be left open.\n if (!runEnded) endRun('$error', { error: e })\n throw e\n }\n}\n\n// -----------------------------------------------------------------------\n// Fork dispatch (Phase 3 — see HANDOVER-fork-join.md)\n// -----------------------------------------------------------------------\n\ninterface BranchOutcome {\n readonly name: string\n readonly result: LoopResult\n readonly touchedKeys: ReadonlySet<string>\n}\n\n/**\n * Runs (or fast-forwards) one branch. When `prior` is a 'done' BranchCursor, the branch\n * already completed in an earlier runLoop call — nothing to execute, its stored state and\n * touched keys just carry forward to the fold. Otherwise the branch is dispatched fresh\n * (prior undefined) or resumed (prior is 'paused') via a private, independent runLoop call.\n */\nasync function runBranch(\n branch: BranchDef,\n prior: BranchCursor | undefined,\n outerState: Record<string, unknown>,\n outerCtx: Ctx,\n schema: Record<string, FieldDefinition<any>> | undefined,\n shouldStop: (() => boolean) | undefined,\n branchSignal: AbortSignal,\n branchCallbacks: LoopCallbacks | undefined,\n): Promise<BranchOutcome> {\n if (prior !== undefined && prior.status === 'done') {\n return {\n name: branch.name,\n result: { state: prior.state, signal: null, cursor: null, paused: false },\n touchedKeys: new Set(prior.touchedKeys),\n }\n }\n\n const touchedKeys = new Set<string>(prior?.status === 'paused' ? prior.touchedKeys : [])\n // Private copy: branches never share the live state object (decision #8).\n const privateState = prior !== undefined ? { ...prior.state } : { ...outerState }\n const privateCtx: Ctx = { ...outerCtx, signal: branchSignal }\n const branchStartCursor = prior?.status === 'paused' ? prior.cursor : undefined\n const branchPath = [...(branchCallbacks?.branchPath ?? []), branch.name]\n\n const result = await runLoop(\n branch.definition,\n privateState,\n privateCtx,\n schema,\n shouldStop,\n branchStartCursor,\n { ...branchCallbacks, touchedKeys, branchPath },\n )\n\n return { name: branch.name, result, touchedKeys }\n}\n\ntype ForkBranchSummary = NonNullable<StepSettledEvent['fork']>['branches'][number]\n\ninterface ForkDispatchResult {\n readonly kind: 'success' | 'paused' | 'failed'\n readonly forkCursor?: ForkCursor\n /** Set when kind is 'success': every branch, done, in declaration order. */\n readonly branches?: readonly ForkBranchSummary[]\n /**\n * Set when kind is 'paused': true if at least one paused branch is waiting on an interrupt\n * (at any depth — a nested fork reports '$interrupt' only under the same rule), false if\n * every paused branch was only stopped.\n */\n readonly interrupted?: boolean\n readonly error?: Error\n}\n\n/**\n * Dispatches every branch of a fork concurrently (fresh, or resuming from `priorBranches`),\n * then classifies the outcome: 'failed' if any branch failed uncaught (fail-fast — siblings'\n * AbortSignals are triggered, best-effort, decision #9), 'paused' if any branch is still\n * paused with none failed (decision #11), or 'success' once every branch is 'done', in which\n * case this also performs the declaration-order fold into outerState (decisions #6/7/8).\n * A 'paused' result is flagged `interrupted` when a paused branch is waiting on an interrupt\n * rather than just stopped.\n */\nasync function dispatchFork(\n forkNode: ForkDef,\n priorBranches: readonly BranchCursor[] | undefined,\n outerState: Record<string, unknown>,\n outerCtx: Ctx,\n schema: Record<string, FieldDefinition<any>> | undefined,\n shouldStop: (() => boolean) | undefined,\n callbacks: LoopCallbacks | undefined,\n): Promise<ForkDispatchResult> {\n const priorByName = new Map((priorBranches ?? []).map(b => [b.name, b] as const))\n\n const localAborts = forkNode.branches.map(() => new AbortController())\n const outerSignal = outerCtx.signal\n const branchSignals = forkNode.branches.map((_, i) =>\n outerSignal !== undefined ? AbortSignal.any([outerSignal, localAborts[i]!.signal]) : localAborts[i]!.signal,\n )\n\n // Branch-internal steps must not drive the outer \"current step\" (a fork is one atomic\n // step for that purpose) or fire the outer onComplete (a branch's .end() ends the\n // branch, not the run — decision #3). Destructure (rather than override with undefined)\n // to satisfy exactOptionalPropertyTypes: an omitted key, not a key set to undefined.\n const { onBeforeStep: _outerOnBeforeStep, onAfterStep: _outerOnAfterStep, onComplete: _outerOnComplete, ...branchCallbacksRest } = callbacks ?? {}\n const branchCallbacksBase: LoopCallbacks | undefined = callbacks !== undefined ? branchCallbacksRest : undefined\n\n // allSettled, not all: a branch that throws must not leave its siblings running (and\n // reporting steps) after the fork has settled — they are cancelled and awaited first.\n const settled = await Promise.allSettled(\n forkNode.branches.map(async (branch, i) => {\n const prior = priorByName.get(branch.name)\n let outcome: BranchOutcome\n try {\n outcome = await runBranch(branch, prior, outerState, outerCtx, schema, shouldStop, branchSignals[i]!, branchCallbacksBase)\n } catch (e) {\n for (const controller of localAborts) controller.abort()\n throw e\n }\n if (outcome.result.paused && outcome.result.signal === '$error') {\n // Fail-fast: cancel siblings (best-effort — cooperative, via AbortSignal).\n for (const controller of localAborts) controller.abort()\n }\n return outcome\n }),\n )\n // Declaration-order-first rejection, so the thrown error never depends on completion order.\n const rejected = settled.find((r): r is PromiseRejectedResult => r.status === 'rejected')\n if (rejected !== undefined) throw rejected.reason\n const outcomes = settled.map(r => (r as PromiseFulfilledResult<BranchOutcome>).value)\n\n const failed = outcomes.find(o => o.result.paused && o.result.signal === '$error')\n if (failed !== undefined) {\n return { kind: 'failed', error: failed.result.state.$error as Error }\n }\n\n const anyPaused = outcomes.some(o => o.result.paused)\n if (anyPaused) {\n const branches: BranchCursor[] = outcomes.map((o) => {\n if (o.result.paused) {\n return {\n name: o.name,\n status: 'paused',\n state: o.result.state,\n cursor: o.result.cursor!,\n touchedKeys: [...o.touchedKeys],\n }\n }\n return {\n name: o.name,\n status: 'done',\n state: o.result.state,\n touchedKeys: [...o.touchedKeys],\n }\n })\n const interrupted = outcomes.some(o => o.result.paused && o.result.signal === '$interrupt')\n return { kind: 'paused', forkCursor: { kind: 'fork', fork: forkNode.name, branches }, interrupted }\n }\n\n // All branches done — fold into outerState, declaration order (decision #8).\n const keyOwners = new Map<string, string[]>()\n for (const outcome of outcomes) {\n for (const key of outcome.touchedKeys) {\n const owners = keyOwners.get(key) ?? []\n owners.push(outcome.name)\n keyOwners.set(key, owners)\n }\n }\n\n for (const outcome of outcomes) {\n for (const key of outcome.touchedKeys) {\n const owners = keyOwners.get(key)!\n if (owners.length > 1) {\n const reducer = schema?.[key]?.reduce\n if (reducer === undefined) {\n throw new MissingReducerError(forkNode.name, key, owners)\n }\n outerState[key] = reducer(outerState[key], outcome.result.state[key])\n } else {\n outerState[key] = outcome.result.state[key]\n }\n }\n }\n\n return {\n kind: 'success',\n branches: outcomes.map(o => ({ name: o.name, status: 'done' as const, touchedKeys: [...o.touchedKeys] })),\n }\n}\n\ntype ForkStepOutcome =\n | { readonly done: true; readonly result: LoopResult }\n | { readonly done: false; readonly nextCursor: string }\n\n/**\n * Wraps dispatchFork with the same telemetry/onError/onComplete-adjacent handling a plain\n * step gets, and translates its result into either a terminal LoopResult (paused or failed-\n * and-unhandled) or the next cursor to continue the outer while-loop with.\n */\nasync function handleFork(\n forkNode: ForkDef,\n priorBranches: readonly BranchCursor[] | undefined,\n state: Record<string, unknown>,\n ctx: Ctx,\n schema: Record<string, FieldDefinition<any>> | undefined,\n shouldStop: (() => boolean) | undefined,\n callbacks: LoopCallbacks | undefined,\n obs: Observer | undefined,\n runCtx: RunContext,\n endRun: (signal: string, failure?: { error: unknown }) => void,\n implicitNextMap: Map<string, string | null>,\n graph: LoopDefinition,\n): Promise<ForkStepOutcome> {\n const stepCtx = stepContextOf(runCtx, forkNode.name)\n const stepStart = Date.now()\n const onObserverError = callbacks?.onObserverError\n safeInvoke('onStepStart', () => obs?.onStepStart?.(stepCtx), onObserverError)\n\n let dispatch: ForkDispatchResult\n try {\n dispatch = await dispatchFork(forkNode, priorBranches, state, ctx, schema, shouldStop, callbacks)\n } catch (e) {\n fireSettled(obs, stepCtx, stepStart, { outcome: 'error', error: asError(e), next: { kind: 'throw' } }, onObserverError)\n throw e\n }\n\n if (dispatch.kind === 'paused') {\n const fork = {\n branches: dispatch.forkCursor!.branches.map(b => ({ name: b.name, status: b.status, touchedKeys: b.touchedKeys })),\n }\n // Only an interrupt pending somewhere below makes the fork resumable via resume(); a fork\n // whose branches were merely stopped settles exactly like a plain stop.\n if (dispatch.interrupted === true) {\n fireSettled(obs, stepCtx, stepStart, { outcome: 'interrupt', next: { kind: 'pause' }, fork }, onObserverError)\n endRun('$interrupt')\n return { done: true, result: { state, signal: '$interrupt', cursor: dispatch.forkCursor!, paused: true } }\n }\n fireSettled(obs, stepCtx, stepStart, { outcome: 'stopped', next: { kind: 'pause' }, fork }, onObserverError)\n endRun('$stopped')\n return { done: true, result: { state, signal: null, cursor: dispatch.forkCursor!, paused: true } }\n }\n\n if (dispatch.kind === 'failed') {\n state.$error = dispatch.error!\n callbacks?.onError?.(state.$error, forkNode.name)\n safeInvoke('onStepError', () => obs?.onStepError?.(stepCtx, { error: state.$error, durationMs: Date.now() - stepStart }), onObserverError)\n if (graph.onError !== undefined) {\n fireSettled(obs, stepCtx, stepStart, { outcome: 'error', error: state.$error as Error, next: { kind: 'step', name: graph.onError } }, onObserverError)\n return { done: false, nextCursor: graph.onError }\n }\n fireSettled(obs, stepCtx, stepStart, { outcome: 'error', error: state.$error as Error, next: { kind: 'pause' } }, onObserverError)\n endRun('$error', { error: state.$error })\n return { done: true, result: { state, signal: '$error', cursor: forkNode.name, paused: true } }\n }\n\n // success\n state.$error = null\n safeInvoke('onStepEnd', () => obs?.onStepEnd?.(stepCtx, { durationMs: Date.now() - stepStart }), onObserverError)\n callbacks?.onAfterStep?.(forkNode.name, state)\n const next = forkNode.next ?? implicitNextMap.get(forkNode.name) ?? null\n if (next === null) {\n const noNext = new NoNextStepError(forkNode.name)\n fireSettled(obs, stepCtx, stepStart, { outcome: 'error', error: noNext, next: { kind: 'throw' } }, onObserverError)\n throw noNext\n }\n fireSettled(obs, stepCtx, stepStart, { outcome: 'ok', next: { kind: 'step', name: next }, fork: { branches: dispatch.branches! } }, onObserverError)\n return { done: false, nextCursor: next }\n}\n","import type { Cursor, BranchCursor } from '../loop/loop-executor.js'\nimport { isForkCursor } from '../loop/loop-executor.js'\n\ntype SchemaLike = Record<string, {\n readonly default?: (() => unknown) | undefined\n // any on reduce params: function parameter contravariance means typed reducers (e.g. (current: string[]) => string[])\n // are not assignable to (current: unknown) => unknown; any erases the bound safely for runtime use\n readonly reduce?: ((current: any, next: any) => unknown) | undefined // any: see above\n}>\n\n// -----------------------------------------------------------------------\n// ClaimOptions — lease duration passed to claim() and extendClaim()\n// -----------------------------------------------------------------------\n\n/**\n * Options passed to {@link SessionStore.claim}.\n *\n * `ttlMs` is the initial lease duration in milliseconds. The claim expires\n * if not renewed within this window — enabling crash recovery by other instances.\n */\nexport interface ClaimOptions {\n /** Lease duration in milliseconds. Must be a positive integer. */\n readonly ttlMs: number\n}\n\n// -----------------------------------------------------------------------\n// Lease — distributed lease handle returned by claim() and extendClaim()\n// -----------------------------------------------------------------------\n\n/**\n * A successfully acquired distributed lease on a session.\n *\n * Returned by {@link SessionStore.claim} when no other instance holds the\n * session. The framework holds this object for the duration of the run and\n * passes it to {@link SessionStore.release} and {@link SessionStore.extendClaim}.\n */\nexport interface Lease {\n /**\n * Wall-clock expiry timestamp (milliseconds since epoch).\n * The framework checks `Date.now() >= lease.expiresAt` at each step boundary\n * to detect TTL expiry without contacting the store.\n */\n readonly expiresAt: number\n /**\n * The `agentId` this lease was issued for.\n * Stored in the claim record for stuck-lease diagnosis.\n */\n readonly agentId: string\n /**\n * The `sessionId` this lease covers.\n */\n readonly sessionId: string\n /**\n * The `instanceId` of the holder, if provided to `createAgent()`.\n * Written into the store's claim record for operational diagnostics.\n * Absent when `instanceId` was not configured.\n */\n readonly instanceId?: string\n /**\n * Store-implementation-specific token — e.g. a Redis key name, a lock token,\n * or a database row ID. Opaque to the framework; passed back unmodified on\n * `release` and `extendClaim` calls so the store can locate the record.\n */\n readonly token: unknown\n}\n\n// -----------------------------------------------------------------------\n// StoredRunMetadata — operational metadata written into StoredRun\n// -----------------------------------------------------------------------\n\n/**\n * Operational metadata written by the framework into every {@link StoredRun}.\n *\n * The framework writes only `instanceId`. All other fields are reserved for\n * domain-specific operational annotations (tenantId, region, requestId, etc.).\n */\nexport interface StoredRunMetadata {\n /** The `instanceId` of the instance that produced this run. Absent when not configured. */\n instanceId?: string\n /** Open extension point — domain-specific fields. */\n [key: string]: unknown\n}\n\n// -----------------------------------------------------------------------\n// RunRef — a pointer back to an earlier run\n// -----------------------------------------------------------------------\n\n/**\n * Opaque string map an observer's `carry` hook returns for a run (e.g. a trace\n * context). Core stores it on the run's record and hands it back to later runs; it never\n * reads it.\n */\nexport type RunCarrier = Readonly<Record<string, string>>\n\n/** Points at one earlier run, with the carrier that run's observer produced (if any). */\nexport interface RunRef {\n readonly runId: string\n /** Absent when that run had no observer that carries, or its `carry` returned nothing. */\n readonly carrier?: RunCarrier\n}\n\n// -----------------------------------------------------------------------\n// SessionStore — the persistence contract\n// -----------------------------------------------------------------------\n\n/**\n * Persistence contract for agent sessions.\n *\n * Implementations must be safe to call concurrently for **different** sessions;\n * concurrent calls for the **same** session are prevented by the harness concurrency guards.\n *\n * `loadHistory` and `branch` are optional extensions:\n * - `loadHistory` — full run history for a session (used by branching and debugging tools).\n * - `branch` — fork a session at a specific past run, returning a new session ID.\n */\nexport interface SessionStore {\n /**\n * Load the most recent {@link StoredRun} for the given session, or `null` if\n * the session has never been saved.\n */\n load(agentId: string, sessionId: string): Promise<StoredRun | null>\n\n /**\n * Persist a run record as a conditional write.\n *\n * Implementations must compare `run.version` against the version of the\n * currently stored record before writing:\n * - If the stored version equals `run.version - 1` (or there is no stored\n * record and `run.version === 0`), the write succeeds.\n * - Otherwise, another writer committed a newer version concurrently — the\n * implementation must throw `ConcurrentModificationError`.\n */\n save(agentId: string, sessionId: string, run: StoredRun): Promise<void>\n\n /**\n * Return the full ordered run history for a session, oldest first.\n * Optional — omit if your store does not support history.\n */\n loadHistory?(agentId: string, sessionId: string): Promise<StoredRun[]>\n\n /**\n * Fork the session at the state captured by `runId`, returning a new session ID\n * whose initial state equals the forked run's `finalState`.\n * Optional — omit if your store does not support branching.\n *\n * Save the new session's version-0 record as a seed the next run continues: `phase: 'paused'`,\n * no `step`, both states equal to the source run's `finalState`, and `branchedFrom` set to the\n * source session, `runId` and the source run's `carrier` (when it has one). When the source is\n * itself such a seed, copy its `branchedFrom` instead (or leave it out if it has none): a seed's\n * own `runId` never ran. The seed has no `carrier` of its own.\n *\n * @throws {@link BranchNotFoundError} when `runId` is not found in history.\n */\n branch?(agentId: string, sessionId: string, runId: string): Promise<string>\n\n /**\n * Attempt to acquire a distributed claim on the session before starting a run.\n *\n * - Returns a {@link Lease} when the claim is acquired.\n * - Returns `null` when another instance already holds the claim — the framework\n * throws {@link SessionBusyError} immediately without starting any LLM work.\n *\n * Optional — stores that do not support distributed locking omit this method.\n * The framework checks for its presence before calling it.\n */\n claim?(agentId: string, sessionId: string, options: ClaimOptions): Promise<Lease | null>\n\n /**\n * Release a held claim after the run settles.\n *\n * Called by the framework after `save()` completes (or after an error that\n * prevents saving). Stores may use this to remove the lock record immediately\n * rather than waiting for TTL expiry.\n *\n * Optional — omit if your store does not support claim/release.\n */\n release?(lease: Lease): Promise<void>\n\n /**\n * Extend the TTL of an active claim.\n *\n * Called by `ctx.keepAlive()` (both one-shot and background interval modes).\n * The store must update `expiresAt` on the claim record; the new expiry is\n * `Date.now() + options.ttlMs`. The returned `Lease` object carries the updated\n * `expiresAt`; the framework replaces its held reference with the returned value.\n *\n * Optional — omit if your store does not support claim/release.\n */\n extendClaim?(lease: Lease, options: ClaimOptions): Promise<Lease>\n}\n\n// -----------------------------------------------------------------------\n// StoredRun — the per-run serialized record (replaces StoredSession)\n// -----------------------------------------------------------------------\n\n/**\n * Serializable snapshot of a single agent run, written to the store after\n * every run settles (either `'paused'` on an interrupt or `'completed'`).\n *\n * - `phase: 'paused'` — the run paused on an interrupt; `step` is the step that\n * issued the interrupt and `signal` is `'$interrupt'`. `step` is a plain step name,\n * or (when the run paused inside a fork) a composite `ForkCursor` carrying every\n * branch's own state/cursor — see `Cursor` in `loop-executor.ts` and\n * HANDOVER-fork-join.md §4/Phase 5. A plain-string `step` from before fork/join\n * existed is still a valid `Cursor`, so old rows load and resume unchanged.\n * - `phase: 'completed'` — the loop exited normally; `signal` holds the exit\n * signal (or is absent when the loop ended without emitting a signal).\n */\nexport interface StoredRun {\n readonly agentId: string\n readonly runId: string\n readonly sessionId: string\n readonly version: number\n readonly startedAt: string\n readonly settledAt: string\n readonly phase: 'paused' | 'completed'\n readonly initialState: Record<string, unknown>\n readonly finalState: Record<string, unknown>\n readonly signal?: string\n readonly step?: Cursor\n /**\n * Operational metadata written by the framework.\n *\n * The framework writes `instanceId` when configured; all other fields are\n * domain-defined. Absent for runs produced before this field was added.\n */\n readonly metadata?: StoredRunMetadata\n /**\n * What the run's observer returned from `carry` (e.g. its trace context). Describes this\n * run only. Absent when no observer carried anything.\n */\n readonly carrier?: RunCarrier\n /**\n * Set by `SessionStore.branch` on the seed record of a branched session: the run it was\n * branched from, in the source session. The branched session's first run reports it as\n * `RunContext.branchedFrom`.\n */\n readonly branchedFrom?: RunRef & { readonly sessionId: string }\n}\n\n// -----------------------------------------------------------------------\n// SessionPhase — the agent.status() query result\n// -----------------------------------------------------------------------\n\n/**\n * Discriminated union returned by {@link Agent.status} describing the lifecycle\n * phase of a session.\n *\n * - `'fresh'` — no run has been stored yet.\n * - `'in-flight'` — a run is currently executing (in-process guard only; not\n * detectable cross-process from the store alone).\n * - `'paused'` — the last run settled on an interrupt; `step` identifies the\n * step that issued the interrupt. When the run paused inside a fork, `step` is\n * the fork's own name (not the richer per-branch detail — see `pendingInterrupts`).\n * - `'completed'` — the last run exited the loop; `signal` is the exit signal.\n */\nexport type SessionPhase =\n | { readonly phase: 'fresh' }\n | { readonly phase: 'in-flight'; readonly step: null }\n | {\n readonly phase: 'paused'\n readonly signal?: string\n readonly step: string\n /**\n * Every interrupt currently awaiting a response, one per paused branch when the run\n * paused inside a fork (a single-element array for a plain, non-forked pause). Lets a\n * caller discover and resolve each one — via `Agent.resume(response, sessionId, id)` —\n * independently; the session stays `'paused'` until every entry is resolved.\n */\n readonly pendingInterrupts: readonly PendingInterrupt[]\n }\n | { readonly phase: 'completed'; readonly signal?: string }\n\n/** One outstanding `ctx.interrupt()` call awaiting a response. See {@link SessionPhase}. */\nexport interface PendingInterrupt {\n readonly interruptId: string\n readonly prompt: unknown\n /**\n * The step that raised this interrupt. For a forked pause this is a `/`-joined\n * breadcrumb (`\"<fork>/<branch>/<step>\"`, recursing further for nested forks) —\n * same style as the validator's own fork/branch violation paths.\n */\n readonly step: string\n}\n\n// -----------------------------------------------------------------------\n// collectPendingInterrupts — recursively finds every paused branch's own $interrupt\n// -----------------------------------------------------------------------\n\nfunction collectPendingInterrupts(cursor: Cursor | undefined, state: Record<string, unknown>): PendingInterrupt[] {\n if (cursor !== undefined && isForkCursor(cursor)) {\n const result: PendingInterrupt[] = []\n for (const branch of cursor.branches) {\n if (branch.status !== 'paused') continue\n const paused = branch as Extract<BranchCursor, { status: 'paused' }>\n for (const pi of collectPendingInterrupts(paused.cursor, paused.state)) {\n result.push({ ...pi, step: `${cursor.fork}/${paused.name}/${pi.step}` })\n }\n }\n return result\n }\n\n const interrupt = state['$interrupt'] as { interruptId: string; prompt: unknown } | null | undefined\n if (interrupt === null || interrupt === undefined) return []\n const step = typeof cursor === 'string' ? cursor : ''\n return [{ interruptId: interrupt.interruptId, prompt: interrupt.prompt, step }]\n}\n\n// -----------------------------------------------------------------------\n// storedSessionToPhase — converts a raw load result to SessionPhase\n// -----------------------------------------------------------------------\n\nexport function storedSessionToPhase(loaded: StoredRun | null): SessionPhase {\n if (loaded === null) {\n return { phase: 'fresh' }\n }\n\n if (loaded.phase === 'paused') {\n // A paused fork's step is a composite ForkCursor — project it to the fork's own name;\n // pendingInterrupts carries the full per-branch detail.\n const step = loaded.step === undefined ? '' : isForkCursor(loaded.step) ? loaded.step.fork : loaded.step\n const pendingInterrupts = collectPendingInterrupts(loaded.step, loaded.finalState)\n if (loaded.signal !== undefined) {\n return { phase: 'paused', step, signal: loaded.signal, pendingInterrupts }\n }\n return { phase: 'paused', step, pendingInterrupts }\n }\n\n // completed\n if (loaded.signal !== undefined) {\n return { phase: 'completed', signal: loaded.signal }\n }\n return { phase: 'completed' }\n}\n\n// -----------------------------------------------------------------------\n// initializeState — state merge for fresh sessions and resumptions\n// -----------------------------------------------------------------------\n\nexport function initializeState(\n stored: StoredRun | null,\n initialStateArg: Record<string, unknown>,\n schema: SchemaLike | undefined,\n): Record<string, unknown> {\n const argKeys = new Set(Object.keys(initialStateArg))\n\n if (stored === null) {\n return buildFreshState(initialStateArg, argKeys, schema)\n }\n\n return buildResumedState(stored, initialStateArg, argKeys, schema)\n}\n\nfunction buildFreshState(\n initialStateArg: Record<string, unknown>,\n argKeys: Set<string>,\n schema: SchemaLike | undefined,\n): Record<string, unknown> {\n const result: Record<string, unknown> = { ...initialStateArg }\n\n if (schema === undefined || Object.keys(schema).length === 0) {\n return result\n }\n\n for (const key of Object.keys(schema)) {\n if (argKeys.has(key)) {\n // initialStateArg wins — already in result via spread\n continue\n }\n const field = schema[key]\n if (field !== undefined && field.default !== undefined) {\n result[key] = field.default()\n }\n }\n\n return result\n}\n\nfunction buildResumedState(\n stored: StoredRun,\n initialStateArg: Record<string, unknown>,\n argKeys: Set<string>,\n schema: SchemaLike | undefined,\n): Record<string, unknown> {\n const result: Record<string, unknown> = { ...stored.finalState }\n\n // Apply initialStateArg fields on top of stored state\n for (const key of argKeys) {\n const fieldDef = schema?.[key]\n if (fieldDef?.reduce !== undefined) {\n result[key] = fieldDef.reduce(stored.finalState[key], initialStateArg[key])\n } else {\n result[key] = initialStateArg[key]\n }\n }\n\n // Apply schema defaults for keys absent from both stored.finalState and initialStateArg\n if (schema !== undefined) {\n for (const key of Object.keys(schema)) {\n if (argKeys.has(key)) continue\n if (key in stored.finalState) continue\n const field = schema[key]\n if (field !== undefined && field.default !== undefined) {\n result[key] = field.default()\n }\n }\n }\n\n return result\n}\n","/**\n * Thrown by {@link Agent.run} or {@link Agent.resume} when the given session\n * is already executing a run in the same process.\n *\n * Wait for the in-flight {@link RunHandle} to settle before starting a new run.\n */\nexport class SessionInFlightError extends Error {\n /** The session that was already in-flight. */\n readonly sessionId: string\n\n constructor(sessionId: string) {\n super(`session \"${sessionId}\" is already in-flight`)\n this.name = 'SessionInFlightError'\n this.sessionId = sessionId\n }\n}\n\n/**\n * Thrown by {@link Agent.run} when the session is paused on an unanswered\n * interrupt. Call {@link Agent.resume} (or `handle.resume()`) instead.\n */\nexport class SessionPendingInterruptError extends Error {\n /** The session that is awaiting an interrupt response. */\n readonly sessionId: string\n\n constructor(sessionId: string) {\n super(`session \"${sessionId}\" is paused on an interrupt — use agent.resume() instead of agent.run()`)\n this.name = 'SessionPendingInterruptError'\n this.sessionId = sessionId\n }\n}\n\n/**\n * Thrown by the harness when the session store's `load()` call rejects.\n * The original error is available on the `cause` property.\n */\nexport class StoreLoadError extends Error {\n readonly cause: unknown\n\n constructor(cause: unknown) {\n super('session store failed to load session')\n this.name = 'StoreLoadError'\n this.cause = cause\n }\n}\n\n/**\n * Thrown by {@link Agent.run} when `store.claim()` returns `null` —\n * another instance already holds the session claim.\n *\n * The caller may inspect `retryAfter` to implement a `429 Retry-After`\n * response or a retry backoff. How to respond is not the framework's concern.\n */\nexport class SessionBusyError extends Error {\n /** The session that is currently claimed by another instance. */\n readonly sessionId: string\n /**\n * Hint: earliest time (milliseconds since epoch) when a retry may succeed.\n * Derived from the original claim's `expiresAt`. Present when the store\n * includes expiry information in a busy response; absent otherwise.\n */\n // declare: avoids useDefineForClassFields emitting an undefined own property initializer;\n // the field is only written when retryAfter is provided (exactOptionalPropertyTypes guard)\n declare readonly retryAfter?: number\n\n constructor(sessionId: string, retryAfter?: number) {\n super(`session \"${sessionId}\" is currently claimed by another instance`)\n this.name = 'SessionBusyError'\n this.sessionId = sessionId\n // conditional assignment: avoids producing retryAfter: undefined as an own property\n // which exactOptionalPropertyTypes forbids at call sites\n if (retryAfter !== undefined) this.retryAfter = retryAfter\n }\n}\n\n/**\n * Thrown by the framework at a step boundary when the active lease has expired\n * without renewal.\n *\n * The run stops without saving state — the session remains at its last\n * checkpoint, allowing another instance to claim and resume it.\n */\nexport class LeaseExpiredError extends Error {\n /** The session whose lease expired. */\n readonly sessionId: string\n\n constructor(sessionId: string) {\n super(`lease for session \"${sessionId}\" has expired — run stopped without saving`)\n this.name = 'LeaseExpiredError'\n this.sessionId = sessionId\n }\n}\n\n","import type { SessionStore, Lease } from './session-store.js'\n\n/**\n * A mutable reference to the currently held lease.\n * `null` when claim/lease is not in use (no-store or store without claim()).\n * Updated in-place by `extendClaim()` responses.\n */\nexport type LeaseRef = { current: Lease | null }\n\n/**\n * Options for background renewal mode.\n */\nexport interface KeepAliveOptions {\n /**\n * Renewal interval in milliseconds. A background timer calls\n * `store.extendClaim()` at this cadence.\n * Must be less than the original claim `ttlMs` to ensure renewal\n * reaches the store before expiry.\n */\n readonly every: number\n}\n\n/**\n * The stop function returned by `ctx.keepAlive({ every })`.\n * Always call this in a `finally` block to cancel the background timer.\n */\nexport type StopFn = () => void\n\n/**\n * The `ctx.keepAlive` function type injected into the step ctx.\n *\n * - Called with no arguments: one-shot TTL extension. Returns a Promise.\n * - Called with `{ every: ms }`: starts a background interval renewal timer.\n * Returns a `StopFn` synchronously.\n */\nexport type KeepAliveFn =\n ((() => Promise<void>) & ((options: KeepAliveOptions) => StopFn))\n\n/**\n * Create the `ctx.keepAlive` function for a single run.\n *\n * @param leaseRef - Mutable reference to the active lease.\n * @param store - The session store, or `undefined` when no store configured.\n * @param originalTtlMs - The `ttlMs` from the `ClaimOptions` used in the initial claim.\n * @returns The `keepAlive` function to inject into step `ctx`.\n */\nexport function createKeepAliveFn(\n leaseRef: LeaseRef,\n store: SessionStore | undefined,\n originalTtlMs: number,\n): KeepAliveFn {\n function keepAlive(options?: KeepAliveOptions): Promise<void> | StopFn {\n const isBackground = typeof options === 'object' && options !== null && 'every' in options\n const extendClaim = store?.extendClaim\n\n if (isBackground) {\n // background renewal mode\n if (leaseRef.current === null || typeof extendClaim !== 'function') {\n // no-op: no active lease or store doesn't support extendClaim\n return noopStop\n }\n\n let handle: ReturnType<typeof setInterval> | null = setInterval(() => {\n if (leaseRef.current === null) {\n // lease was released after timer started — skip but keep timer running\n return\n }\n // swallow errors — timer must continue regardless of extendClaim failures\n void (async () => {\n try {\n const renewed = await extendClaim.call(store, leaseRef.current!, { ttlMs: originalTtlMs })\n leaseRef.current = renewed\n } catch {\n /* swallow: expiry check at step boundary is the safety net */\n }\n })()\n }, options.every)\n\n return function stop() {\n if (handle !== null) {\n clearInterval(handle)\n handle = null\n }\n }\n }\n\n // one-shot mode\n if (leaseRef.current === null || typeof extendClaim !== 'function') {\n return Promise.resolve()\n }\n\n const snapshot = leaseRef.current\n return (async () => {\n const renewed = await extendClaim.call(store, snapshot, { ttlMs: originalTtlMs })\n leaseRef.current = renewed\n })()\n }\n\n // as: overloaded function — runtime discriminates on options presence\n return keepAlive as KeepAliveFn\n}\n\nfunction noopStop(): void {\n // no-op stop: no timer was started\n}\n","import type { FieldDefinition } from '../harness/state-field.js'\nimport type { ProviderEntry } from '../harness/harness-builder.js'\nimport type { LoopDefinition } from '../loop/loop-dsl.js'\nimport type { LoopCallbacks, LoopResult } from '../loop/loop-executor.js'\nimport { runLoop } from '../loop/loop-executor.js'\nimport type { Observer, ObserverErrorSink, TelemetryContext } from './observer.js'\nimport {\n type SessionStore,\n type StoredRun,\n type StoredRunMetadata,\n type SessionPhase,\n initializeState,\n storedSessionToPhase,\n} from './session-store.js'\nimport { StoreLoadError, LeaseExpiredError } from './concurrency-errors.js'\nimport { createKeepAliveFn, type LeaseRef } from './ctx-keep-alive.js'\n\n// -----------------------------------------------------------------------\n// SessionRunOptions — optional parameters for runWithSession\n// -----------------------------------------------------------------------\n\nexport interface SessionRunOptions {\n /** Checked at the top of each loop iteration; returning true halts the run. */\n readonly shouldStop?: () => boolean\n /**\n * Called if the session store fails. `phase` is `'load'` (store failed at run start),\n * `'persist'` (store failed at run end/pause), or `'claim'` (claim returned null or threw).\n * Run result is still returned when phase is 'persist'.\n */\n readonly onStoreError?: (error: unknown, phase: 'load' | 'persist' | 'claim') => void\n /** Called just before each step executes. Used by RunHandle to track currentStep and fire onBeforeStep. */\n readonly onBeforeStep?: (name: string, state: Record<string, unknown>) => void\n /** Called after a step's run completes successfully and applyUpdate has been applied. */\n readonly onAfterStep?: (name: string, state: Record<string, unknown>) => void\n /** Called immediately when a step's run throws a non-interrupt error, before error routing. */\n readonly onError?: (error: unknown, stepName: string) => void\n /** Called when the loop exits via .on(signal).end() (paused: false). */\n readonly onComplete?: (state: Record<string, unknown>, signal: string) => void\n /** Called when ctx.interrupt() pauses the run (isInterruptPause is true). */\n readonly onInterrupt?: (prompt: unknown, interruptId: string) => void\n /** Listeners for user-emitted events (ctx.emit). Keyed by event name. */\n readonly listeners?: Record<string, (payload: unknown) => void>\n /** Structured telemetry observer for this run. All methods optional. F16b. */\n readonly observer?: Observer\n /** Opt-in sink for errors thrown by observer callbacks; passed through to runLoop callbacks. */\n readonly onObserverError?: ObserverErrorSink\n /**\n * Active lease reference. The factory closes over this ref; it is updated\n * in-place by `extendClaim()` calls. Absent when no claim is in use.\n */\n readonly leaseRef?: LeaseRef\n /**\n * The `instanceId` from `AgentOptions`, if provided. Written into\n * `StoredRun.metadata` on every terminal save and into `RunContext` for observers.\n */\n readonly instanceId?: string\n /**\n * The original claim `ttlMs` — passed to `createKeepAliveFn` as `originalTtlMs`\n * so `ctx.keepAlive()` uses the same TTL for renewals. Defaults to 30_000 when absent.\n */\n readonly claimTtlMs?: number\n /**\n * Optional parent run UUID — set when parentRunId was passed as a resource\n * to agent.run(). Threaded through to RunContext for cross-process trace\n * correlation. Absent for top-level runs.\n */\n readonly parentRunId?: string\n /**\n * Pre-filtered, keyed list of ObserverAware slots that expose `withTelemetry`.\n * Passed through to runLoop callbacks, which per step install\n * `ctx[key] = slot.withTelemetry({ observer, stepContext })`. Absent when no slots\n * expose `withTelemetry`.\n */\n readonly telemetrySlots?: ReadonlyArray<{ key: string; slot: { withTelemetry(ctx: TelemetryContext): unknown } }>\n}\n\n// -----------------------------------------------------------------------\n// resolveSessionStore — extract SessionStore from storeEntries\n// -----------------------------------------------------------------------\n\nexport function resolveSessionStore(\n storeEntries: readonly ProviderEntry[],\n overrides?: Record<string, unknown>,\n): SessionStore | undefined {\n let result: SessionStore | undefined = undefined\n\n for (const entry of storeEntries) {\n if (entry.kind !== 'store') continue\n\n const value = entry.value\n if (value === null || typeof value !== 'object') continue\n\n const rec = value as Record<string, unknown> // as: TypeScript cannot narrow `object` to `Record<string, unknown>` for index access\n if (!('session' in rec)) continue\n\n // Prefer override when provided (fulfils a required() marker declared at harness-build time)\n const rawSession = rec['session']\n const session = (overrides !== undefined && 'session' in overrides) ? overrides['session'] : rawSession\n if (session === null || typeof session !== 'object') continue\n\n const s = session as Record<string, unknown> // as: same narrowing needed to index into the duck-typed session object\n if (typeof s['load'] === 'function' && typeof s['save'] === 'function') {\n // last valid store wins\n result = session as unknown as SessionStore // as: duck-typing confirmed above; no instanceof available for a structural interface\n }\n }\n\n return result\n}\n\n// -----------------------------------------------------------------------\n// querySessionPhase — implements agent.status() query\n// -----------------------------------------------------------------------\n\nexport async function querySessionPhase(\n store: SessionStore | undefined,\n agentId: string,\n sessionId: string,\n): Promise<SessionPhase> {\n if (store === undefined) {\n return { phase: 'fresh' }\n }\n\n const loaded = await store.load(agentId, sessionId)\n return storedSessionToPhase(loaded)\n}\n\n// -----------------------------------------------------------------------\n// runRefsOf — which earlier run the next run continues or branches from\n// -----------------------------------------------------------------------\n\n/**\n * A paused record with a cursor is a run that paused: the next run resumes it. A paused\n * record without one is a branch seed (`SessionStore.branch` writes no `step`): the next run\n * is the branched session's first. Only the loaded record's own carrier is passed on.\n */\nfunction runRefsOf(loaded: StoredRun | null): Pick<LoopCallbacks, 'resumedFrom' | 'branchedFrom'> {\n if (loaded === null || loaded.phase !== 'paused') return {}\n if (loaded.step !== undefined) {\n return { resumedFrom: { runId: loaded.runId, ...(loaded.carrier !== undefined ? { carrier: loaded.carrier } : {}) } }\n }\n return loaded.branchedFrom !== undefined ? { branchedFrom: loaded.branchedFrom } : {}\n}\n\n// -----------------------------------------------------------------------\n// runWithSession — full session lifecycle wrapper around runLoop\n// -----------------------------------------------------------------------\n\nexport async function runWithSession(\n store: SessionStore | undefined,\n agentId: string,\n sessionId: string,\n runId: string,\n graph: LoopDefinition,\n initialStateArg: Record<string, unknown>,\n schema: Record<string, FieldDefinition<any>> | undefined, // any: FieldDefinition uses invariant T; heterogeneous schema maps require any\n ctx: Record<string, unknown> & { readonly agentId: string; readonly sessionId: string },\n options?: SessionRunOptions,\n): Promise<LoopResult> {\n // Inject keepAlive into ctx — no-op when no lease is active (leaseRef.current === null)\n const leaseRef = options?.leaseRef ?? { current: null }\n const keepAlive = createKeepAliveFn(leaseRef, store, options?.claimTtlMs ?? 30_000)\n ;(ctx as Record<string, unknown>)['keepAlive'] = keepAlive // mutate in-place like runLoop does for interrupt/emit\n\n // Build composedShouldStop — checks caller predicate AND lease expiry\n let leaseExpired = false\n const composedShouldStop = (): boolean => {\n if (options?.shouldStop?.() === true) return true\n if (leaseRef.current !== null && leaseRef.current.expiresAt <= Date.now()) {\n leaseExpired = true\n return true\n }\n return false\n }\n\n if (store === undefined) {\n const state = initializeState(null, initialStateArg, schema)\n const result = await runLoop(graph, state, ctx, schema, composedShouldStop, undefined, {\n ...options,\n runId,\n ...(options?.parentRunId !== undefined ? { parentRunId: options.parentRunId } : {}),\n })\n if (leaseExpired) {\n const expiredError = new LeaseExpiredError(sessionId)\n options?.onStoreError?.(expiredError, 'claim')\n throw expiredError\n }\n return result\n }\n\n // Load phase — on failure: fire onStoreError('load') and return synthetic error result\n // Run never begins; 'await run' always resolves (never rejects) per docs/agent.md guarantee\n let loaded: StoredRun | null\n try {\n loaded = await store.load(agentId, sessionId)\n } catch (error: unknown) {\n const storeError = new StoreLoadError(error)\n options?.onStoreError?.(storeError, 'load')\n const failState = initializeState(null, initialStateArg, schema)\n ;(failState as Record<string, unknown>)['$error'] = storeError\n return { state: failState, signal: '$error', paused: false, cursor: null }\n }\n\n // Short-circuit for completed sessions — return stored result immediately without executing\n if (loaded !== null && loaded.phase === 'completed') {\n return {\n state: loaded.finalState,\n signal: loaded.signal ?? null,\n cursor: null,\n paused: false,\n }\n }\n\n // Merge stored snapshot (or null for fresh) with caller-supplied initial state\n const state = initializeState(loaded, initialStateArg, schema)\n // Snapshot before runLoop — runLoop mutates state in place so we must copy before execution\n const initialStateSnapshot = { ...state }\n const startedAt = new Date().toISOString()\n\n // Execute — errors from runLoop propagate uncaught (except LeaseExpiredError handled below)\n const result = await runLoop(graph, state, ctx, schema, composedShouldStop, loaded?.step, {\n ...options,\n runId,\n ...(options?.parentRunId !== undefined ? { parentRunId: options.parentRunId } : {}),\n ...runRefsOf(loaded),\n })\n\n // Lease-expired path — do NOT persist; signal error to caller\n if (leaseExpired) {\n const expiredError = new LeaseExpiredError(sessionId)\n options?.onStoreError?.(expiredError, 'claim')\n throw expiredError\n }\n\n const settledAt = new Date().toISOString()\n\n // Build optional metadata\n const metadata: StoredRunMetadata | undefined =\n options?.instanceId !== undefined ? { instanceId: options.instanceId } : undefined\n\n // Terminal save — errors are swallowed; LoopResult is always returned\n try {\n const version = (loaded?.version ?? -1) + 1\n if (result.paused) {\n const saved: StoredRun = {\n agentId,\n runId,\n sessionId,\n version,\n startedAt,\n settledAt,\n phase: 'paused',\n initialState: initialStateSnapshot,\n finalState: result.state,\n step: result.cursor!,\n ...(result.signal !== null ? { signal: result.signal } : {}),\n ...(metadata !== undefined ? { metadata } : {}),\n ...(result.carrier !== undefined ? { carrier: result.carrier } : {}),\n }\n await store.save(agentId, sessionId, saved)\n } else {\n const saved: StoredRun = {\n agentId,\n runId,\n sessionId,\n version,\n startedAt,\n settledAt,\n phase: 'completed',\n initialState: initialStateSnapshot,\n finalState: result.state,\n ...(result.signal !== null ? { signal: result.signal } : {}),\n ...(metadata !== undefined ? { metadata } : {}),\n ...(result.carrier !== undefined ? { carrier: result.carrier } : {}),\n }\n await store.save(agentId, sessionId, saved)\n }\n } catch (error) {\n options?.onStoreError?.(error, 'persist')\n // terminal save error is swallowed; LoopResult is returned to caller regardless\n }\n\n return result\n}\n","import type { SessionStore, StoredRun } from './session-store.js'\nimport type { Cursor, ForkCursor, BranchCursor } from '../loop/loop-executor.js'\nimport { isForkCursor } from '../loop/loop-executor.js'\n\n// -----------------------------------------------------------------------\n// NoInterruptError\n// -----------------------------------------------------------------------\n\n/**\n * Thrown by {@link RunHandle.resume} or {@link Agent.resume} when the session\n * is not currently paused on a matching interrupt.\n *\n * Common causes: the run has not yet settled, the session does not exist,\n * or the supplied `interruptId` does not match the pending interrupt.\n */\nexport class NoInterruptError extends Error {\n constructor() {\n super(\n 'resume() called but the session is not paused on a matching interrupt — ' +\n 'verify the session exists, its phase is \"paused\", and interruptId matches',\n )\n this.name = 'NoInterruptError'\n }\n}\n\n// -----------------------------------------------------------------------\n// injectInterruptResponseIntoState — locates and answers one pending interrupt\n// -----------------------------------------------------------------------\n\n/** Result of {@link injectInterruptResponseIntoState}. */\nexport interface InjectResult {\n readonly cursor: Cursor | undefined\n readonly state: Record<string, unknown>\n /** `false` when no pending interrupt (at any depth) matched `interruptId`. */\n readonly found: boolean\n}\n\nfunction injectIntoForkCursor(cursor: ForkCursor, interruptId: string, response: unknown): ForkCursor | null {\n let matched = false\n const branches: BranchCursor[] = cursor.branches.map((branch) => {\n if (matched || branch.status !== 'paused') return branch\n const paused = branch as Extract<BranchCursor, { status: 'paused' }>\n const branchInterrupt = paused.state['$interrupt'] as { interruptId: string } | null | undefined\n if (branchInterrupt !== null && branchInterrupt !== undefined && branchInterrupt.interruptId === interruptId) {\n matched = true\n const existing = (paused.state['$interruptResponses'] as Record<string, unknown>) ?? {}\n return {\n ...paused,\n state: { ...paused.state, $interrupt: null, $interruptResponses: { ...existing, [interruptId]: response } },\n }\n }\n if (isForkCursor(paused.cursor)) {\n const nested = injectIntoForkCursor(paused.cursor, interruptId, response)\n if (nested !== null) {\n matched = true\n return { ...paused, cursor: nested }\n }\n }\n return branch\n })\n return matched ? { ...cursor, branches } : null\n}\n\n/**\n * Locates the pending interrupt matching `interruptId` — either at the top level (plain,\n * non-forked pause) or inside a paused branch of a `ForkCursor`, recursing into nested forks\n * (decision #13) — and returns an updated `cursor`/`state` with the response injected.\n * `found: false` and both inputs unchanged when nothing matches.\n */\nexport function injectInterruptResponseIntoState(\n cursor: Cursor | undefined,\n state: Record<string, unknown>,\n interruptId: string,\n response: unknown,\n): InjectResult {\n if (cursor !== undefined && isForkCursor(cursor)) {\n const updated = injectIntoForkCursor(cursor, interruptId, response)\n return updated === null\n ? { cursor, state, found: false }\n : { cursor: updated, state, found: true }\n }\n\n const interrupt = state['$interrupt'] as { interruptId: string } | null | undefined\n if (interrupt === null || interrupt === undefined || interrupt.interruptId !== interruptId) {\n return { cursor, state, found: false }\n }\n\n const existing = (state['$interruptResponses'] as Record<string, unknown>) ?? {}\n return {\n cursor,\n state: { ...state, $interrupt: null, $interruptResponses: { ...existing, [interruptId]: response } },\n found: true,\n }\n}\n\n// -----------------------------------------------------------------------\n// injectInterruptResponse\n// -----------------------------------------------------------------------\n\nexport async function injectInterruptResponse(\n store: SessionStore,\n agentId: string,\n sessionId: string,\n interruptId: string,\n response: unknown,\n): Promise<void> {\n const loaded = await store.load(agentId, sessionId)\n\n if (loaded === null) throw new NoInterruptError()\n if (loaded.phase !== 'paused') throw new NoInterruptError()\n\n const result = injectInterruptResponseIntoState(loaded.step, loaded.finalState, interruptId, response)\n if (!result.found) throw new NoInterruptError()\n\n const updated: StoredRun = {\n agentId: loaded.agentId,\n runId: loaded.runId,\n sessionId: loaded.sessionId,\n version: loaded.version + 1,\n startedAt: loaded.startedAt,\n settledAt: loaded.settledAt,\n phase: 'paused',\n initialState: loaded.initialState,\n finalState: result.state,\n ...(result.cursor !== undefined ? { step: result.cursor } : {}),\n ...(loaded.signal !== undefined ? { signal: loaded.signal } : {}),\n ...(loaded.metadata !== undefined ? { metadata: loaded.metadata } : {}),\n ...(loaded.carrier !== undefined ? { carrier: loaded.carrier } : {}),\n ...(loaded.branchedFrom !== undefined ? { branchedFrom: loaded.branchedFrom } : {}),\n }\n\n await store.save(agentId, sessionId, updated)\n}\n","/**\n * The resolved value of a {@link RunHandle} promise: the final state and the\n * signal that caused the loop to exit.\n *\n * `signal` is `null` when the loop exited via `.end()` without an explicit signal,\n * `'$interrupt'` when paused on an interrupt, or any custom signal string returned\n * by a route function.\n */\nexport interface RunOutcome {\n readonly state: Record<string, unknown>\n readonly signal: string | null\n}\n\n/**\n * Handle returned synchronously by {@link Agent.run} and {@link Agent.resume}.\n *\n * Implements `PromiseLike<RunOutcome>` so it can be `await`-ed directly.\n *\n * @example\n * ```ts\n * const handle = agent.run({}, { llm })\n * console.log(handle.sessionId) // available immediately\n * const { state, signal } = await handle\n * ```\n */\nexport interface RunHandle extends PromiseLike<RunOutcome> {\n /** Cancel the in-flight run at the next safe point between steps. Idempotent. */\n stop(): void\n\n /**\n * Provide a response to a pending `ctx.interrupt()` call and start a new run.\n * Returns a new {@link RunHandle} for the resumed execution.\n *\n * Throws {@link NoInterruptError} when the run has not settled on `signal: '$interrupt'`.\n *\n * @param response - The value to deliver as the interrupt response.\n * @param interruptId - The `interruptId` from `state.$interrupt`.\n */\n resume(response: unknown, interruptId: string): RunHandle\n\n /** The session identity for this run. */\n readonly sessionId: string\n\n /**\n * Unique identifier for this specific invocation.\n * One UUID per `agent.run()` or `agent.resume()` call.\n */\n readonly runId: string\n\n /**\n * The name of the step currently executing in this process.\n * `null` before the first step runs, after execution settles, and always\n * when inspected cross-process.\n */\n readonly currentStep: string | null\n}\n\nimport { NoInterruptError } from './interrupt-resume.js'\n\nexport function createRunHandle(\n sessionId: string,\n runId: string,\n execution: Promise<RunOutcome>,\n stopFlag: { stopped: boolean },\n stepRef: { current: string | null },\n resumeFn?: (response: unknown, interruptId: string) => RunHandle,\n): RunHandle {\n let settledOutcome: RunOutcome | null = null\n\n // NOTE: raw .then(onFulfilled, onRejected) is intentional here — NOT a coding-standards\n // violation. async/await requires wrapping in a new async function, which changes control\n // flow and does not populate `settledOutcome` as a side-effect at resolution time.\n // .then() attaches handlers to an already-running Promise, allowing us to capture the\n // fulfilled RunOutcome into the closure variable synchronously within the callback at the\n // moment of resolution. run.resume() reads settledOutcome synchronously, so this is the\n // only correct pattern; replacing it with async/await would break synchronous access.\n const settled = execution.then(\n (outcome: RunOutcome): RunOutcome => {\n settledOutcome = outcome\n stepRef.current = null\n return outcome\n },\n (err: unknown): RunOutcome => {\n stepRef.current = null\n throw err\n },\n )\n\n const handle: RunHandle = {\n then<TResult1 = RunOutcome, TResult2 = never>(\n onfulfilled?: ((value: RunOutcome) => TResult1 | PromiseLike<TResult1>) | null | undefined,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null | undefined,\n ): Promise<TResult1 | TResult2> {\n return settled.then(onfulfilled, onrejected)\n },\n\n stop(): void {\n stopFlag.stopped = true\n },\n\n resume(response: unknown, interruptId: string): RunHandle {\n // backward-compatibility: 4-arg handle (no resumeFn) + unsettled → old stub error\n if (settledOutcome === null && resumeFn === undefined) {\n throw new Error('not implemented — requires F9')\n }\n if (settledOutcome === null) {\n throw new NoInterruptError()\n }\n if (settledOutcome.signal !== '$interrupt') {\n throw new NoInterruptError()\n }\n if (resumeFn === undefined) {\n throw new NoInterruptError()\n }\n return resumeFn(response, interruptId)\n },\n\n get sessionId(): string {\n return sessionId\n },\n\n get runId(): string {\n return runId\n },\n\n get currentStep(): string | null {\n return stepRef.current\n },\n }\n\n return handle\n}\n","import {\n getInternals,\n type Harness,\n type HarnessInternals,\n type ProviderEntry,\n} from '../harness/harness-builder.js'\nimport { isRequiredMarker, isRuntimeMarker } from '../harness/ctx-markers.js'\nimport type { LoopDefinition } from '../loop/loop-dsl.js'\nimport type { FieldDefinition } from '../harness/state-field.js'\nimport type { SessionPhase, ClaimOptions, Lease, RunCarrier } from './session-store.js'\nimport { resolveSessionStore, runWithSession, querySessionPhase, type SessionRunOptions } from './session-lifecycle.js'\nimport { runLoop } from '../loop/loop-executor.js'\nimport type { Cursor } from '../loop/loop-executor.js'\nimport { createRunHandle, type RunHandle, type RunOutcome } from './run-handle.js'\nimport { NoInterruptError, injectInterruptResponse, injectInterruptResponseIntoState } from './interrupt-resume.js'\nimport {\n SessionInFlightError,\n SessionPendingInterruptError,\n SessionBusyError,\n LeaseExpiredError,\n StoreLoadError,\n} from './concurrency-errors.js'\nimport type { LeaseRef } from './ctx-keep-alive.js'\nimport { randomUUID } from 'node:crypto'\nimport { extractRunEvents } from './event-callbacks.js'\nimport { extractRunListeners } from './ctx-emit.js'\nimport type { Observer, ObserverErrorSink, TelemetryContext } from './observer.js'\nimport { initializeState } from './session-store.js'\n\n// -----------------------------------------------------------------------\n// Module-level constants\n// -----------------------------------------------------------------------\n\n/**\n * Pre-filter the provided slots down to the telemetry-aware ones, keyed by their ctx key.\n * The loop installs `ctx[key] = slot.withTelemetry({ observer, stepContext })` per step.\n */\nfunction buildTelemetrySlots(\n entries: Iterable<readonly [string, unknown]>,\n): Array<{ key: string; slot: { withTelemetry(ctx: TelemetryContext): unknown } }> {\n const out: Array<{ key: string; slot: { withTelemetry(ctx: TelemetryContext): unknown } }> = []\n for (const [key, slot] of entries) {\n if (slot !== null && typeof slot === 'object' && typeof (slot as Record<string, unknown>)['withTelemetry'] === 'function') { // as: duck-typed structural check\n out.push({ key, slot: slot as { withTelemetry(ctx: TelemetryContext): unknown } }) // as: narrowed by duck-type check on line above\n }\n }\n return out\n}\n\n// -----------------------------------------------------------------------\n// Module-private helpers\n// -----------------------------------------------------------------------\n\nfunction extractRunObserver(resources: Record<string, unknown>): Observer | undefined {\n const raw = resources['observer']\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined\n return raw as Observer // as: duck-typed plain object confirmed; methods not validated\n}\n\nfunction extractRunErrorSink(resources: Record<string, unknown>): ObserverErrorSink | undefined {\n const raw = resources['onObserverError']\n return typeof raw === 'function' ? (raw as ObserverErrorSink) : undefined // as: duck-typed function confirmed\n}\n\n/** Options passed to createAgent(). */\nexport interface AgentOptions {\n /**\n * Stable identifier for the process or replica running this agent instance.\n * Written to `StoredRun.metadata` on every save and propagated to observers\n * via `RunContext.instanceId`.\n */\n readonly instanceId?: string\n /**\n * Concrete store instances for slots declared with `required()` inside `h.store()`.\n * Keyed by the store key used in the harness (e.g. `{ session: myStore }`).\n */\n readonly stores?: Record<string, unknown>\n}\n\n// -----------------------------------------------------------------------\n// Agent — the minimal public object returned by createAgent\n// -----------------------------------------------------------------------\n\nexport interface Agent {\n /** The agent's unique identifier, as provided to createAgent(). */\n readonly id: string\n\n /**\n * Start a new run. Returns a RunHandle synchronously before execution begins.\n */\n run(initialState: Record<string, unknown>, resources: Record<string, unknown>): RunHandle\n\n /**\n * Cross-process entry point for responding to a pending interrupt.\n * Returns a RunHandle synchronously; the execution promise performs the resume.\n *\n * The optional fourth argument `resources` accepts:\n * - `observer?: Observer` — structured telemetry for the resumed run (see Observability)\n * - `parentRunId?: string` — the caller's run id, as for `run()`; set on this resumed run's\n * `RunContext` only (a later `handle.resume()` on the returned handle does not inherit it)\n * - `events?.onStoreError?` — raw store-error callback (unchanged from prior shape)\n */\n resume(\n response: unknown,\n sessionId: string,\n interruptId: string,\n resources?: Record<string, unknown>,\n ): RunHandle\n\n /**\n * Query the session store for the current phase of a session.\n */\n status(sessionId: string): Promise<SessionPhase>\n}\n\n// -----------------------------------------------------------------------\n// AgentInternals — the resolved internal state\n// -----------------------------------------------------------------------\n\nexport interface AgentInternals {\n readonly agentId: string\n readonly resolvedProviders: ReadonlyMap<string, unknown>\n readonly storeEntries: readonly ProviderEntry[]\n readonly loopDef: LoopDefinition\n readonly stateSchema: Record<string, FieldDefinition<unknown>> | undefined\n /** Keys declared as runtime() in the harness — must be filled in agent.run() resources. */\n readonly runtimeKeys: ReadonlySet<string>\n /** Keys declared as required() in the harness — must NOT appear in agent.run() resources. */\n readonly requiredKeys: ReadonlySet<string>\n}\n\n// -----------------------------------------------------------------------\n// Error classes\n// -----------------------------------------------------------------------\n\n/** Thrown by {@link createAgent} when the harness has no `.loop()` declaration. */\nexport class MissingLoopError extends Error {\n constructor() {\n super('harness has no loop — call h.loop() before createAgent(id, h, slots)')\n this.name = 'MissingLoopError'\n }\n}\n\n/** Thrown by {@link createAgent} when a `required()` slot is absent from `slots`. */\nexport class MissingSlotError extends Error {\n /** The missing slot key. */\n readonly key: string\n\n constructor(key: string) {\n super(`required slot \"${key}\" was not provided in createAgent slots`)\n this.name = 'MissingSlotError'\n this.key = key\n }\n}\n\n/** Thrown by {@link createAgent} when a `runtime()` slot is passed in `slots` instead of `agent.run()`. */\nexport class RuntimeSlotInAgentError extends Error {\n /** The offending slot key. */\n readonly key: string\n\n constructor(key: string) {\n super(`slot \"${key}\" is a runtime() slot — provide it in agent.run(), not createAgent()`)\n this.name = 'RuntimeSlotInAgentError'\n this.key = key\n }\n}\n\n/** Thrown by {@link createAgent} when `slots` contains a key not declared in the harness. */\nexport class UnknownSlotError extends Error {\n /** The unknown slot key. */\n readonly key: string\n\n constructor(key: string) {\n super(`slot \"${key}\" is not declared in the harness — remove it or add h.provide(\"${key}\", required())`)\n this.name = 'UnknownSlotError'\n this.key = key\n }\n}\n\n/** @internal Thrown when `getAgentInternals` is called on a non-agent value. */\nexport class AgentInternalsError extends Error {\n constructor() {\n super('value was not produced by createAgent — cannot read AgentInternals')\n this.name = 'AgentInternalsError'\n }\n}\n\n/** Thrown by {@link Agent.run} when a `runtime()` slot is absent from `resources`. */\nexport class MissingRuntimeSlotError extends Error {\n /** The missing runtime slot key. */\n readonly key: string\n constructor(key: string) {\n super(`runtime slot \"${key}\" was not provided in agent.run() resources`)\n this.name = 'MissingRuntimeSlotError'\n this.key = key\n }\n}\n\n/** Thrown by {@link Agent.run} when a `required()` slot is passed in `resources` instead of `createAgent()`. */\nexport class RequiredSlotInRunError extends Error {\n /** The offending slot key. */\n readonly key: string\n constructor(key: string) {\n super(`slot \"${key}\" is a required() slot — provide it in createAgent(), not agent.run()`)\n this.name = 'RequiredSlotInRunError'\n this.key = key\n }\n}\n\n/** Thrown by {@link Agent.run} when `resources` contains a key that was not declared as `runtime()`. */\nexport class UnknownRunSlotError extends Error {\n /** The unknown resource key. */\n readonly key: string\n constructor(key: string) {\n super(`slot \"${key}\" is not a runtime() slot — do not pass it in agent.run() resources`)\n this.name = 'UnknownRunSlotError'\n this.key = key\n }\n}\n\n/** Thrown by {@link createAgent} when a `required()` store marker has no matching entry in `agentOptions.stores`. */\nexport class MissingStoreSlotError extends Error {\n /** The store key (e.g. `\"session\"`) that was not provided. */\n readonly key: string\n constructor(key: string) {\n super(`required store slot \"${key}\" was not provided in createAgent options.stores`)\n this.name = 'MissingStoreSlotError'\n this.key = key\n }\n}\n\n/** Thrown by {@link createAgent} when `agentOptions.stores` contains a key that is not declared as `required()` in the harness. */\nexport class UnexpectedStoreSlotError extends Error {\n /** The unexpected store key. */\n readonly key: string\n constructor(key: string) {\n super(`store slot \"${key}\" was not declared as required() in the harness — do not pass it in options.stores`)\n this.name = 'UnexpectedStoreSlotError'\n this.key = key\n }\n}\n\n// -----------------------------------------------------------------------\n// Module-private symbol for AttachInternals\n// -----------------------------------------------------------------------\n\nconst _agentInternals = Symbol('_agentInternals')\n\ntype AgentWithInternals = Agent & {\n readonly [_agentInternals]: AgentInternals\n}\n\n// -----------------------------------------------------------------------\n// createAgent — the public factory\n// -----------------------------------------------------------------------\n\n/** What a resume run gets besides the response; each key omitted when not given. */\ninterface ResumeResources {\n readonly onStoreError?: (error: unknown, phase: 'load' | 'persist' | 'claim') => void\n readonly observer?: Observer\n readonly onObserverError?: ObserverErrorSink\n readonly telemetrySlots?: ReadonlyArray<{ key: string; slot: { withTelemetry(ctx: TelemetryContext): unknown } }>\n readonly parentRunId?: string\n}\n\n/**\n * Instantiate an agent from a fully-configured {@link Harness}.\n *\n * Validates that all `required()` slots are present in `slots`, that no\n * `runtime()` slots are passed here, and that the harness has a loop defined.\n *\n * @param id - A stable, human-readable identifier for this agent (used as the\n * first argument to every store operation).\n * @param h - The harness produced by `createHarness()...loop()`.\n * @param slots - Values for every slot declared with `required()` in the harness.\n * @param options - Optional agent-level options (e.g., instanceId).\n *\n * @throws {@link MissingLoopError} when `h.loop()` was never called.\n * @throws {@link MissingSlotError} when a `required()` slot is absent from `slots`.\n * @throws {@link RuntimeSlotInAgentError} when a `runtime()` slot is passed in `slots`.\n * @throws {@link UnknownSlotError} when `slots` contains a key not declared in the harness.\n *\n * @example\n * ```ts\n * const agent = createAgent('my-agent', h, { llm: new Claude('claude-3-5-haiku-20241022') })\n * const handle = agent.run({}, {})\n * const { state, signal } = await handle\n * ```\n */\nexport function createAgent<Ctx, State, Req extends keyof Ctx, Run extends keyof Ctx>(\n id: string,\n h: Harness<Ctx, State, Req, Run>,\n slots: Pick<Ctx, Req>,\n agentOptions?: AgentOptions,\n): Agent {\n // Get harness internals; propagate HarnessInternalsError if h is not a real Harness\n const internals: HarnessInternals<Ctx, State, Req, Run> = getInternals(h)\n\n // Validation 1: loop exists\n if (internals.loopDef === undefined) {\n throw new MissingLoopError()\n }\n\n // Build a map of provider entries with kind 'provide' for slot validation\n const providerMap = new Map<string, ProviderEntry>()\n for (const entry of internals.providers) {\n if (entry.kind === 'provide') {\n providerMap.set(entry.key, entry)\n }\n }\n\n // Validation 2: no unknown keys in slots\n for (const key of Object.keys(slots)) {\n if (!providerMap.has(key)) {\n throw new UnknownSlotError(key)\n }\n }\n\n // Validation 3: no runtime() markers in slots\n for (const key of Object.keys(slots)) {\n const entry = providerMap.get(key)\n if (entry && isRuntimeMarker(entry.value)) {\n throw new RuntimeSlotInAgentError(key)\n }\n }\n\n // Validation 4: all required() slots are provided\n for (const entry of internals.providers) {\n if (entry.kind === 'provide' && isRequiredMarker(entry.value)) {\n if (!(entry.key in slots)) {\n throw new MissingSlotError(entry.key)\n }\n }\n }\n\n // Build resolvedProviders map: iterate all providers in order, last-registered-wins\n const resolvedProviders = new Map<string, unknown>()\n const storeEntries: ProviderEntry[] = []\n const runtimeKeys = new Set<string>()\n const requiredKeys = new Set<string>()\n\n for (const entry of internals.providers) {\n if (entry.kind === 'store') {\n storeEntries.push(entry)\n } else if (entry.kind === 'provide') {\n if (isRequiredMarker(entry.value)) {\n // Replace required() marker with the slot value\n resolvedProviders.set(entry.key, (slots as Record<string, unknown>)[entry.key]) // as: Req extends keyof Ctx erases to plain index at runtime\n requiredKeys.add(entry.key)\n } else if (isRuntimeMarker(entry.value)) {\n runtimeKeys.add(entry.key)\n // runtime() markers are not included in resolvedProviders\n } else {\n // Concrete value: include as-is\n resolvedProviders.set(entry.key, entry.value)\n }\n }\n }\n\n // Validate the 'session' store slot — the only store key with framework-managed lifecycle.\n // Other store keys (user-defined, future ctx.store.<name>) are not processed here.\n let sessionIsRequired = false\n for (const entry of storeEntries) {\n const storeValue = entry.value\n if (storeValue === null || typeof storeValue !== 'object') continue\n const storeRec = storeValue as Record<string, unknown> // as: same narrowing as resolveSessionStore\n if ('session' in storeRec && isRequiredMarker(storeRec['session'])) {\n sessionIsRequired = true // last-registered store entry wins, consistent with resolveSessionStore\n }\n }\n const sessionStoreOverride = agentOptions?.stores?.['session']\n const storeOverrides: Record<string, unknown> = {}\n if (sessionIsRequired) {\n if (sessionStoreOverride === undefined) throw new MissingStoreSlotError('session')\n storeOverrides['session'] = sessionStoreOverride\n } else if (sessionStoreOverride !== undefined) {\n throw new UnexpectedStoreSlotError('session')\n }\n\n // Resolve session store from store entries at construction time\n const capturedStore = resolveSessionStore(\n storeEntries,\n Object.keys(storeOverrides).length > 0 ? storeOverrides : undefined,\n )\n\n // Construct AgentInternals\n const agentInternals: AgentInternals = {\n agentId: id,\n resolvedProviders,\n storeEntries,\n loopDef: internals.loopDef, // Guaranteed to be non-undefined by validation 1\n stateSchema: internals.stateSchema,\n runtimeKeys,\n requiredKeys,\n }\n\n // Reserved keys are skipped during agent.run() resource validation\n const reservedRunKeys = new Set(['sessionId', 'signal', 'events', 'listeners', 'observer', 'onObserverError', 'claimOptions', 'parentRunId'])\n\n // one per agent instance; tracks all session IDs currently executing\n const inFlightSessions = new Set<string>()\n\n // one per agent instance; tracks session IDs paused on an unanswered interrupt\n // cleared when agent.resume() or run.resume() is called; populated when a run settles with signal: \"$interrupt\"\n const interruptPendingSessions = new Set<string>()\n\n // -----------------------------------------------------------------------\n // makeAgentResumeHandle — factory for cross-process resume RunHandles\n // -----------------------------------------------------------------------\n\n const makeAgentResumeHandle = (\n resp: unknown,\n sId: string,\n iId: string,\n resumeResources: ResumeResources = {},\n ): RunHandle => {\n const { onStoreError, observer, onObserverError, telemetrySlots, parentRunId } = resumeResources\n let _stopped = false\n const abortController = new AbortController()\n const flag = {\n get stopped(): boolean { return _stopped },\n set stopped(v: boolean) { _stopped = v; if (v) abortController.abort() },\n }\n const ref: { current: string | null } = { current: null }\n const rId = randomUUID()\n\n const exec = (async (): Promise<RunOutcome> => {\n await Promise.resolve()\n const claimOptions: ClaimOptions = { ttlMs: 30_000 }\n let leaseRef: LeaseRef | undefined = undefined\n try {\n if (typeof capturedStore?.claim === 'function') {\n let lease: Lease | null\n try {\n lease = await capturedStore.claim(id, sId, claimOptions)\n } catch (claimError: unknown) {\n const loadError = new StoreLoadError(claimError)\n onStoreError?.(loadError, 'claim')\n const failState = initializeState(null, {}, agentInternals.stateSchema)\n ;(failState as Record<string, unknown>)['$error'] = loadError\n return { state: failState, signal: '$error' }\n }\n if (lease === null) {\n const busyError = new SessionBusyError(sId)\n onStoreError?.(busyError, 'claim')\n const failState = initializeState(null, {}, agentInternals.stateSchema)\n ;(failState as Record<string, unknown>)['$error'] = busyError\n return { state: failState, signal: '$error' }\n }\n leaseRef = { current: lease }\n }\n try {\n if (capturedStore === undefined) throw new NoInterruptError()\n try {\n await injectInterruptResponse(capturedStore, id, sId, iId, resp)\n } catch (injectError: unknown) {\n if (injectError instanceof NoInterruptError) throw injectError\n // store I/O failure during interrupt injection — report as 'claim' phase error\n const storeError = new StoreLoadError(injectError)\n onStoreError?.(storeError, 'claim')\n const failState = initializeState(null, {}, agentInternals.stateSchema)\n ;(failState as Record<string, unknown>)['$error'] = storeError\n return { state: failState, signal: '$error' }\n }\n const agentCtx: Record<string, unknown> & { readonly agentId: string; readonly sessionId: string; readonly runId: string; readonly signal: AbortSignal } = {\n ...Object.fromEntries(agentInternals.resolvedProviders),\n agentId: id,\n sessionId: sId,\n runId: rId,\n signal: abortController.signal,\n ...(agentOptions?.instanceId !== undefined ? { instanceId: agentOptions.instanceId } : {}),\n }\n const r = await runWithSession(\n capturedStore,\n id,\n sId,\n rId,\n agentInternals.loopDef,\n {},\n agentInternals.stateSchema,\n agentCtx,\n {\n shouldStop: () => flag.stopped,\n onBeforeStep: (n: string) => { ref.current = n },\n ...(onStoreError !== undefined ? { onStoreError } : {}),\n ...(leaseRef !== undefined ? { leaseRef, claimTtlMs: claimOptions.ttlMs } : {}),\n ...(observer !== undefined ? { observer } : {}),\n ...(onObserverError !== undefined ? { onObserverError } : {}),\n ...(telemetrySlots !== undefined && telemetrySlots.length > 0 ? { telemetrySlots } : {}),\n ...(agentOptions?.instanceId !== undefined ? { instanceId: agentOptions.instanceId } : {}),\n ...(parentRunId !== undefined ? { parentRunId } : {}),\n },\n )\n if (r.signal === '$interrupt') interruptPendingSessions.add(sId)\n return { state: r.state, signal: r.signal }\n } catch (error: unknown) {\n if (error instanceof LeaseExpiredError) {\n const failState = initializeState(null, {}, agentInternals.stateSchema)\n ;(failState as Record<string, unknown>)['$error'] = error\n return { state: failState, signal: '$error' }\n }\n throw error\n } finally {\n if (leaseRef !== undefined && typeof capturedStore?.release === 'function') {\n try { await capturedStore.release(leaseRef.current!) } catch { /* swallow */ }\n }\n }\n } finally {\n inFlightSessions.delete(sId)\n }\n })()\n\n const resumeFn = (r: unknown, i: string): RunHandle => {\n // Synchronous fence — same invariant as agent.resume()\n if (inFlightSessions.has(sId)) throw new SessionInFlightError(sId)\n interruptPendingSessions.delete(sId)\n inFlightSessions.add(sId)\n // Same resources as this resume, except parentRunId: the caller's run id is stale by now.\n const { parentRunId: _staleParentRunId, ...inherited } = resumeResources\n return makeAgentResumeHandle(r, sId, i, inherited)\n }\n return createRunHandle(sId, rId, exec, flag, ref, resumeFn)\n }\n\n // Create and return Agent with attached internals\n const agent: AgentWithInternals = {\n id,\n run: (initialState: Record<string, unknown>, resources: Record<string, unknown>): RunHandle => {\n // Validation pass 1: unknown keys (not reserved, not runtime, not required)\n for (const key of Object.keys(resources)) {\n if (reservedRunKeys.has(key)) continue\n if (!agentInternals.runtimeKeys.has(key) && !agentInternals.requiredKeys.has(key)) {\n throw new UnknownRunSlotError(key)\n }\n }\n\n // Validation pass 2: required() keys passed in resources\n for (const key of Object.keys(resources)) {\n if (reservedRunKeys.has(key)) continue\n if (agentInternals.requiredKeys.has(key)) {\n throw new RequiredSlotInRunError(key)\n }\n }\n\n // Validation pass 3: missing runtime() keys\n for (const key of agentInternals.runtimeKeys) {\n if (!(key in resources)) {\n throw new MissingRuntimeSlotError(key)\n }\n }\n\n // Session ID resolution\n const sessionId =\n typeof resources['sessionId'] === 'string' ? resources['sessionId'] : randomUUID()\n\n // Run ID — unique per agent.run() invocation, available synchronously on RunHandle\n const runId = randomUUID()\n\n // Synchronous concurrency fences — must precede any await (per docs/agent.md Concurrency section)\n if (inFlightSessions.has(sessionId)) throw new SessionInFlightError(sessionId)\n if (interruptPendingSessions.has(sessionId)) throw new SessionPendingInterruptError(sessionId)\n inFlightSessions.add(sessionId)\n\n // AbortSignal and stop-flag wiring\n let _stopped = false\n const abortController = new AbortController()\n const stopFlag = {\n get stopped(): boolean { return _stopped },\n set stopped(v: boolean) { _stopped = v; if (v) abortController.abort() },\n }\n const rawSignal = resources['signal']\n let ctxSignal: AbortSignal = abortController.signal\n if (rawSignal instanceof AbortSignal) {\n ctxSignal = rawSignal\n rawSignal.addEventListener('abort', () => { stopFlag.stopped = true; abortController.abort() }, { once: true })\n if (rawSignal.aborted) stopFlag.stopped = true\n }\n\n // Fresh stepRef per call for currentStep tracking\n const stepRef: { current: string | null } = { current: null }\n\n // Assemble ctx: resolvedProviders merged with runtime slots and sessionId, runId, and signal\n const runtimeSlots: Record<string, unknown> = {}\n for (const key of agentInternals.runtimeKeys) {\n if (reservedRunKeys.has(key)) continue // reserved keys are consumed by framework, not injected into ctx\n runtimeSlots[key] = resources[key]\n }\n const ctx: Record<string, unknown> & { readonly agentId: string; readonly sessionId: string; readonly runId: string; readonly signal: AbortSignal } = {\n ...Object.fromEntries(agentInternals.resolvedProviders),\n ...runtimeSlots,\n agentId: id,\n sessionId,\n runId,\n signal: ctxSignal,\n ...(agentOptions?.instanceId !== undefined ? { instanceId: agentOptions.instanceId } : {}),\n }\n\n // Extract event callbacks and listeners from resources (reserved keys)\n const events = extractRunEvents(resources)\n const listeners = extractRunListeners(resources)\n\n const observer = extractRunObserver(resources)\n const onObserverError = extractRunErrorSink(resources)\n // Pre-filter telemetry-aware slots (keyed). The loop installs a per-step scoped view\n // of each at ctx[key] before step.run. resolvedProviders first, runtimeSlots second,\n // so a runtime slot wins the same key — matching ctx assembly order.\n const telemetrySlots = buildTelemetrySlots([\n ...agentInternals.resolvedProviders.entries(),\n ...Object.entries(runtimeSlots),\n ])\n\n // Extract parentRunId from resources (reserved key)\n const parentRunId =\n typeof resources['parentRunId'] === 'string' ? resources['parentRunId'] : undefined\n\n const options: SessionRunOptions = {\n shouldStop: () => stopFlag.stopped,\n onBeforeStep: (name: string, state: Record<string, unknown>) => {\n stepRef.current = name\n events.onBeforeStep?.(name, state)\n },\n // spread optional event callbacks only when defined (exactOptionalPropertyTypes requires omission, not undefined)\n ...(events.onStoreError !== undefined ? { onStoreError: events.onStoreError } : {}),\n ...(events.onAfterStep !== undefined ? { onAfterStep: events.onAfterStep } : {}),\n ...(events.onError !== undefined ? { onError: events.onError } : {}),\n ...(events.onComplete !== undefined ? { onComplete: events.onComplete } : {}),\n ...(events.onInterrupt !== undefined ? { onInterrupt: events.onInterrupt } : {}),\n ...(Object.keys(listeners).length > 0 ? { listeners } : {}),\n ...(observer !== undefined ? { observer } : {}),\n ...(onObserverError !== undefined ? { onObserverError } : {}),\n ...(agentOptions?.instanceId !== undefined ? { instanceId: agentOptions.instanceId } : {}),\n ...(parentRunId !== undefined ? { parentRunId } : {}),\n ...(telemetrySlots.length > 0 ? { telemetrySlots } : {}),\n }\n\n // lastResult captures the LoopResult for same-process in-memory resume chaining\n let lastResult: { state: Record<string, unknown>; cursor: Cursor | null; runId: string; carrier?: RunCarrier } | null = null\n\n // Launch execution asynchronously — agent.run() returns before any async work begins\n const execution = (async (): Promise<RunOutcome> => {\n // Yield so agent.run() can return the RunHandle before any loop iteration starts\n await Promise.resolve()\n\n // Parse claimOptions from resources (reserved key); default ttlMs=30_000\n const rawClaimOpts = resources['claimOptions']\n const claimOptions: ClaimOptions =\n typeof rawClaimOpts === 'object' && rawClaimOpts !== null &&\n typeof (rawClaimOpts as Record<string, unknown>)['ttlMs'] === 'number'\n ? (rawClaimOpts as ClaimOptions)\n : { ttlMs: 30_000 }\n\n let leaseRef: LeaseRef | undefined = undefined\n\n try {\n if (typeof capturedStore?.claim === 'function') {\n let lease: Lease | null\n try {\n lease = await capturedStore.claim(id, sessionId, claimOptions)\n } catch (claimError: unknown) {\n const loadError = new StoreLoadError(claimError)\n events.onStoreError?.(loadError, 'claim')\n const failState = initializeState(null, initialState, agentInternals.stateSchema)\n ;(failState as Record<string, unknown>)['$error'] = loadError\n return { state: failState, signal: '$error' }\n }\n if (lease === null) {\n const busyError = new SessionBusyError(sessionId)\n events.onStoreError?.(busyError, 'claim')\n const failState = initializeState(null, initialState, agentInternals.stateSchema)\n ;(failState as Record<string, unknown>)['$error'] = busyError\n return { state: failState, signal: '$error' }\n }\n leaseRef = { current: lease }\n }\n try {\n const r = await runWithSession(\n capturedStore,\n id,\n sessionId,\n runId,\n agentInternals.loopDef,\n initialState,\n agentInternals.stateSchema,\n ctx,\n {\n ...options,\n ...(leaseRef !== undefined ? { leaseRef, claimTtlMs: claimOptions.ttlMs } : {}),\n },\n )\n if (r.signal === '$interrupt') interruptPendingSessions.add(sessionId)\n lastResult = { state: r.state, cursor: r.cursor, runId, ...(r.carrier !== undefined ? { carrier: r.carrier } : {}) }\n return { state: r.state, signal: r.signal }\n } catch (error: unknown) {\n if (error instanceof LeaseExpiredError) {\n // onStoreError already called by runWithSession before throwing\n const failState = initializeState(null, initialState, agentInternals.stateSchema)\n ;(failState as Record<string, unknown>)['$error'] = error\n return { state: failState, signal: '$error' }\n }\n throw error\n } finally {\n if (leaseRef !== undefined && typeof capturedStore?.release === 'function') {\n try { await capturedStore.release(leaseRef.current!) } catch { /* swallow */ }\n }\n }\n } finally {\n inFlightSessions.delete(sessionId)\n }\n })()\n\n // buildResumeFn — creates a recursive resumeFn for same-process chaining via run.resume()\n const buildResumeFn = (): ((response: unknown, interruptId: string) => RunHandle) => {\n return (response: unknown, interruptId: string): RunHandle => {\n // Synchronous fence — same invariant as agent.run()\n if (inFlightSessions.has(sessionId)) throw new SessionInFlightError(sessionId)\n interruptPendingSessions.delete(sessionId)\n inFlightSessions.add(sessionId)\n\n let _resumeStopped = false\n const resumeAbortController = new AbortController()\n const resumeStopFlag = {\n get stopped(): boolean { return _resumeStopped },\n set stopped(v: boolean) { _resumeStopped = v; if (v) resumeAbortController.abort() },\n }\n const resumeStepRef: { current: string | null } = { current: null }\n const resumeRunId = randomUUID()\n\n const resumeExecution = (async (): Promise<RunOutcome> => {\n await Promise.resolve()\n try {\n // Create a new ctx for this resume invocation with updated runId and signal\n const resumeCtx: Record<string, unknown> & { readonly agentId: string; readonly sessionId: string; readonly runId: string; readonly signal: AbortSignal } = {\n ...ctx,\n runId: resumeRunId,\n signal: resumeAbortController.signal,\n }\n\n if (capturedStore !== undefined) {\n // Cross-process path: inject response into store, reload, and re-run\n await injectInterruptResponse(capturedStore, id, sessionId, interruptId, response)\n const r = await runWithSession(\n capturedStore,\n id,\n sessionId,\n resumeRunId,\n agentInternals.loopDef,\n {},\n agentInternals.stateSchema,\n resumeCtx,\n {\n shouldStop: () => resumeStopFlag.stopped,\n onBeforeStep: (n: string, s: Record<string, unknown>) => {\n resumeStepRef.current = n\n events.onBeforeStep?.(n, s)\n },\n // spread optional event callbacks only when defined (exactOptionalPropertyTypes requires omission, not undefined)\n ...(events.onStoreError !== undefined ? { onStoreError: events.onStoreError } : {}),\n ...(events.onAfterStep !== undefined ? { onAfterStep: events.onAfterStep } : {}),\n ...(events.onError !== undefined ? { onError: events.onError } : {}),\n ...(events.onComplete !== undefined ? { onComplete: events.onComplete } : {}),\n ...(events.onInterrupt !== undefined ? { onInterrupt: events.onInterrupt } : {}),\n ...(Object.keys(listeners).length > 0 ? { listeners } : {}),\n ...(observer !== undefined ? { observer } : {}),\n ...(onObserverError !== undefined ? { onObserverError } : {}),\n ...(telemetrySlots.length > 0 ? { telemetrySlots } : {}),\n ...(agentOptions?.instanceId !== undefined ? { instanceId: agentOptions.instanceId } : {}),\n },\n )\n if (r.signal === '$interrupt') interruptPendingSessions.add(sessionId)\n lastResult = { state: r.state, cursor: r.cursor, runId: resumeRunId, ...(r.carrier !== undefined ? { carrier: r.carrier } : {}) }\n return { state: r.state, signal: r.signal }\n }\n\n // Same-process in-memory path: locate the pending interrupt (top-level, or\n // inside a paused fork branch) and re-run from cursor.\n const prev = lastResult\n if (prev === null) throw new NoInterruptError()\n const injected = injectInterruptResponseIntoState(prev.cursor ?? undefined, prev.state, interruptId, response)\n if (!injected.found) throw new NoInterruptError()\n const state = injected.state\n const cursor = injected.cursor\n const r = await runLoop(\n agentInternals.loopDef,\n state,\n resumeCtx,\n agentInternals.stateSchema,\n () => resumeStopFlag.stopped,\n cursor,\n {\n runId: resumeRunId,\n resumedFrom: { runId: prev.runId, ...(prev.carrier !== undefined ? { carrier: prev.carrier } : {}) },\n onBeforeStep: (n: string, s: Record<string, unknown>) => {\n resumeStepRef.current = n\n events.onBeforeStep?.(n, s)\n },\n ...(events.onAfterStep !== undefined ? { onAfterStep: events.onAfterStep } : {}),\n ...(events.onError !== undefined ? { onError: events.onError } : {}),\n ...(events.onComplete !== undefined ? { onComplete: events.onComplete } : {}),\n ...(events.onInterrupt !== undefined ? { onInterrupt: events.onInterrupt } : {}),\n ...(Object.keys(listeners).length > 0 ? { listeners } : {}),\n ...(observer !== undefined ? { observer } : {}),\n ...(onObserverError !== undefined ? { onObserverError } : {}),\n ...(telemetrySlots.length > 0 ? { telemetrySlots } : {}),\n },\n )\n if (r.signal === '$interrupt') interruptPendingSessions.add(sessionId)\n lastResult = { state: r.state, cursor: r.cursor, runId: resumeRunId, ...(r.carrier !== undefined ? { carrier: r.carrier } : {}) }\n return { state: r.state, signal: r.signal }\n } catch (error: unknown) {\n if (error instanceof LeaseExpiredError) {\n // onStoreError already called by runWithSession before throwing\n const failState = initializeState(null, initialState, agentInternals.stateSchema)\n ;(failState as Record<string, unknown>)['$error'] = error\n return { state: failState, signal: '$error' }\n }\n throw error\n } finally {\n inFlightSessions.delete(sessionId)\n }\n })()\n\n return createRunHandle(sessionId, resumeRunId, resumeExecution, resumeStopFlag, resumeStepRef, buildResumeFn())\n }\n }\n\n return createRunHandle(sessionId, runId, execution, stopFlag, stepRef, buildResumeFn())\n },\n\n resume: (\n response: unknown,\n sessionId: string,\n interruptId: string,\n resources?: Record<string, unknown>,\n ): RunHandle => {\n // SessionInFlightError fence is first — before any extraction or binding (Invariant 3)\n if (inFlightSessions.has(sessionId)) throw new SessionInFlightError(sessionId)\n interruptPendingSessions.delete(sessionId)\n inFlightSessions.add(sessionId)\n const events = extractRunEvents(resources ?? {})\n const observer = extractRunObserver(resources ?? {})\n const onObserverError = extractRunErrorSink(resources ?? {})\n // Build telemetrySlots from resolvedProviders only (no runtime slots in resume path)\n const telemetrySlots = buildTelemetrySlots(agentInternals.resolvedProviders.entries())\n const parentRunId = resources?.['parentRunId']\n return makeAgentResumeHandle(response, sessionId, interruptId, {\n ...(events.onStoreError !== undefined ? { onStoreError: events.onStoreError } : {}),\n ...(observer !== undefined ? { observer } : {}),\n ...(onObserverError !== undefined ? { onObserverError } : {}),\n ...(telemetrySlots.length > 0 ? { telemetrySlots } : {}),\n ...(typeof parentRunId === 'string' ? { parentRunId } : {}),\n })\n },\n\n status: (sessionId: string) => querySessionPhase(capturedStore, id, sessionId),\n [_agentInternals]: agentInternals,\n }\n\n return agent\n}\n\n// -----------------------------------------------------------------------\n// getAgentInternals — accessor for AgentInternals\n// -----------------------------------------------------------------------\n\nexport function getAgentInternals(agent: Agent): AgentInternals {\n if (agent === null || typeof agent !== 'object' || !(_agentInternals in agent)) {\n throw new AgentInternalsError()\n }\n return (agent as AgentWithInternals)[_agentInternals] // as: _agentInternals in agent guard above guarantees the symbol key is present\n}\n","/**\n * Framework-fired event callbacks for a single agent.run() invocation.\n * All fields are optional — omit any you do not need.\n * Callbacks are fire-and-forget; their return value is ignored.\n * Scoped to the run — released when the run settles.\n *\n * Note: user-emitted events (formerly onLlmCall etc.) are replaced by\n * ctx.emit(name, payload) + the 'listeners' resource key. See agent.md.\n */\nexport interface RunEvents {\n /** Called just before a step's run function is invoked. */\n onBeforeStep?: (name: string, state: Record<string, unknown>) => void\n /** Called just after a step's run function completes successfully (state update applied). */\n onAfterStep?: (name: string, state: Record<string, unknown>) => void\n /**\n * Called when the loop exits normally via .on(signal).end().\n * Not called for paused outcomes (stop, abort, error, interrupt).\n */\n onComplete?: (state: Record<string, unknown>, signal: string) => void\n /**\n * Called immediately when a step's run throws a non-interrupt error, before error routing.\n * Fires regardless of how the error is ultimately handled. Does not affect routing or state.\n */\n onError?: (error: unknown, stepName: string) => void\n /**\n * Called when ctx.interrupt() pauses the run (i.e. when isInterruptPause is true).\n * Fires with the prompt and interruptId from the InterruptPause exception, before the\n * run resolves with signal: \"$interrupt\".\n */\n onInterrupt?: (prompt: unknown, interruptId: string) => void\n /**\n * Called if the session store fails at load, persist, or claim phase.\n * phase: 'load' — store failed at run start (run never executed).\n * phase: 'persist' — store failed at run end (run completed but state not saved).\n * phase: 'claim' — store.claim() returned null (busy) or threw (network error).\n */\n onStoreError?: (error: unknown, phase: 'load' | 'persist' | 'claim') => void\n}\n\n/**\n * Extract and validate the events object from agent.run() resources.\n * Returns an empty RunEvents if no events key is present.\n */\nexport function extractRunEvents(resources: Record<string, unknown>): RunEvents {\n const raw = resources['events']\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n return {}\n }\n // plain object: return as-is; callbacks are optional and missing keys are undefined\n return raw as RunEvents // as: duck-typed plain object confirmed above; RunEvents fields are all optional\n}\n"],"mappings":";AAoDO,SAAS,MAAS,SAA+C;AACtE,SAAO,EAAE,GAAG,QAAQ;AACtB;;;ACrDO,IAAM,eAAe;AAErB,IAAM,cAAc;AAyCpB,SAAS,WAA2B;AACzC,SAAO,EAAE,MAAM,aAAa;AAC9B;AAWO,SAAS,UAAyB;AACvC,SAAO,EAAE,MAAM,YAAY;AAC7B;AAKO,SAAS,iBAAiB,OAAyC;AACxE,SA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AAC,eAAe,GAAG;AAAA,EACrB;AAEA,SAAO;AACT;","names":["field","state","result","r"]}
1
+ {"version":3,"sources":["../src/harness/state-field.ts","../src/harness/ctx-markers.ts","../src/loop/loop-dsl.ts","../src/loop/loop-validator.ts","../src/harness/harness-builder.ts","../src/agent/observer.ts","../src/agent/ctx-interrupt.ts","../src/agent/ctx-emit.ts","../src/agent/ctx-within.ts","../src/loop/loop-executor.ts","../src/agent/session-store.ts","../src/agent/concurrency-errors.ts","../src/agent/ctx-keep-alive.ts","../src/agent/session-lifecycle.ts","../src/agent/claim-scope.ts","../src/agent/interrupt-resume.ts","../src/agent/run-handle.ts","../src/agent/create-agent.ts","../src/agent/event-callbacks.ts"],"sourcesContent":["// Phantom symbol — never accessible at runtime; required for reliable T inference\n// even when neither `default` nor `reduce` is provided\ndeclare const _fieldType: unique symbol\n\n/**\n * Descriptor for a single state field, produced by {@link field}.\n *\n * - `default` — factory called once on session start to populate the field when no\n * initial value is supplied.\n * - `reduce` — merge function invoked on resume: `reduce(storedValue, incomingValue)`.\n * When absent, incoming values overwrite stored ones on resume.\n */\nexport type FieldDefinition<T> = {\n readonly [_fieldType]: T\n readonly default?: () => T\n readonly reduce?: (current: T, update: T) => T\n}\n\n/**\n * Derives the concrete state record type from a schema object whose values are\n * {@link FieldDefinition} descriptors.\n *\n * @example\n * ```ts\n * const schema = { count: field<number>({ default: () => 0 }) }\n * type State = StateFromSchema<typeof schema> // { count: number }\n * ```\n */\n// use FieldDefinition<any> in bounds, not FieldDefinition<unknown> — reduce makes T invariant\nexport type StateFromSchema<S> = {\n [K in keyof S]: S[K] extends FieldDefinition<infer T> ? T : never\n}\n\ntype FieldOptions<T> = {\n default?: () => T\n reduce?: (current: T, update: T) => T\n}\n\n/**\n * Declare a typed state field with an optional default factory and optional\n * reduce function.\n *\n * @param options.default - Factory called once at session start.\n * @param options.reduce - Merge function for resume: `(stored, incoming) => merged`.\n *\n * @example\n * ```ts\n * const schema = {\n * messages: field<string[]>({ default: () => [], reduce: (a, b) => [...a, ...b] }),\n * }\n * ```\n */\nexport function field<T>(options?: FieldOptions<T>): FieldDefinition<T> {\n return { ...options } as FieldDefinition<T> // as: phantom [_fieldType] is type-level only; the runtime object can never carry the symbol property\n}\n","/** @internal Discriminant tag for {@link RequiredMarker}. */\nexport const REQUIRED_TAG = '__noetaris_required__' as const\n/** @internal Discriminant tag for {@link RuntimeMarker}. */\nexport const RUNTIME_TAG = '__noetaris_runtime__' as const\n\n// string literal _tag is the sole type-level discriminant; phantom symbols were tried but\n// TypeScript does not enforce non-exported unique symbol keys across module boundaries\n\n/**\n * Sentinel returned by {@link required} to mark a context slot that **must** be\n * supplied at `createAgent()` time (not at `agent.run()` time).\n */\nexport type RequiredMarker = { readonly _tag: typeof REQUIRED_TAG }\n\n/**\n * Sentinel returned by {@link runtime} to mark a context slot that **must** be\n * supplied at `agent.run()` time (not at `createAgent()` time).\n */\nexport type RuntimeMarker = { readonly _tag: typeof RUNTIME_TAG }\n\n// function guard prevents TypeScript from recursing into Function's own method properties\n// (call, bind, apply, etc.) when T is a function type, which would make the mapped type\n// unresolvable and break @ts-expect-error enforcement on concrete value checks\n/**\n * Recursive variant of `T` that allows any nested position to also be a\n * {@link RequiredMarker} or {@link RuntimeMarker}. Used as the `value`\n * parameter type on {@link Harness.provide}.\n */\nexport type DeepWithMarkers<T> =\n T extends (...args: any[]) => any\n ? T | RequiredMarker | RuntimeMarker\n : T extends object\n ? { [K in keyof T]: DeepWithMarkers<T[K]> | RequiredMarker | RuntimeMarker } | RequiredMarker | RuntimeMarker\n : T | RequiredMarker | RuntimeMarker\n\n/**\n * Return a {@link RequiredMarker} sentinel that instructs the harness to\n * require this slot at `createAgent()` time.\n *\n * @example\n * ```ts\n * h.provide('llm', required())\n * ```\n */\nexport function required(): RequiredMarker {\n return { _tag: REQUIRED_TAG }\n}\n\n/**\n * Return a {@link RuntimeMarker} sentinel that instructs the harness to\n * require this slot at `agent.run()` time instead of `createAgent()` time.\n *\n * @example\n * ```ts\n * h.provide('signal', runtime())\n * ```\n */\nexport function runtime(): RuntimeMarker {\n return { _tag: RUNTIME_TAG }\n}\n\n/**\n * Type guard — returns `true` when `value` is a {@link RequiredMarker}.\n */\nexport function isRequiredMarker(value: unknown): value is RequiredMarker {\n return value !== null && typeof value === 'object' && '_tag' in value && value._tag === REQUIRED_TAG\n}\n\n/**\n * Type guard — returns `true` when `value` is a {@link RuntimeMarker}.\n */\nexport function isRuntimeMarker(value: unknown): value is RuntimeMarker {\n return value !== null && typeof value === 'object' && '_tag' in value && value._tag === RUNTIME_TAG\n}\n","import type { KeepAliveFn } from '../agent/ctx-keep-alive.js'\n\n// -----------------------------------------------------------------------\n// Framework-reserved state fields — readable in run/route, not writable from run return\n// -----------------------------------------------------------------------\n\n/**\n * Framework-managed fields injected into every step function's `state` argument.\n *\n * - `$error` — the `Error` thrown by the previous step, or `null` if no error occurred.\n * Only populated on the error path; non-error-aware steps never see a non-null value here.\n * - `$interrupt` — set while a step is awaiting a resume response. The `response` field\n * is populated after {@link Agent.resume} is called.\n */\nexport interface FrameworkState {\n readonly $error: Error | null\n readonly $interrupt: {\n readonly interruptId: string\n readonly prompt: unknown\n readonly response?: unknown\n } | null\n}\n\n/**\n * The complete state type visible inside {@link RunFn} step functions:\n * the user-defined state `S` merged with {@link FrameworkState}.\n */\nexport type StepState<S> = S & FrameworkState\n\n// -----------------------------------------------------------------------\n// Step function signatures\n// -----------------------------------------------------------------------\n\n/**\n * State transformer. Receives the full step state and ctx; returns a partial update\n * of user-defined state fields only (framework-reserved fields are excluded from return).\n * May be async.\n */\nexport type RunFn<S, Ctx> = (\n state: StepState<S>,\n ctx: Ctx & {\n readonly agentId: string\n readonly sessionId: string\n readonly runId: string\n readonly signal: AbortSignal\n readonly interrupt: (prompt: unknown, id?: string) => Promise<unknown>\n readonly emit: (name: string, payload?: unknown) => void\n /**\n * Run `fn` inside the observer's scope for an event this step already emitted — `type` is\n * that event's name (e.g. `'tool.call'`), `payload` carries its id (e.g. `{ toolCallId }`).\n * Returns `fn`'s own result. A passthrough when no observer implements `wrap`.\n */\n readonly within: <T>(type: string, payload: unknown, fn: () => Promise<T>) => Promise<T>\n readonly keepAlive: KeepAliveFn\n },\n) => Promise<Partial<Omit<S, '$error' | '$interrupt'>>> | Partial<Omit<S, '$error' | '$interrupt'>>\n\n/**\n * Pure signal emitter. Receives step state without $error — the route is not called on the error\n * path unless the step opts in via `optin: '$error'` in the step config. Synchronous by design.\n * No ctx — pure read only.\n */\nexport type RouteFn<S> = (state: S & Omit<FrameworkState, '$error'>) => string\n\n/**\n * Pure signal emitter for error-aware steps (optin: '$error').\n * Receives the full step state including $error — the executor calls this on both the success\n * and error paths. Declare `optin: '$error'` in the step config to use this variant.\n */\nexport type ErrorAwareRouteFn<S> = (state: StepState<S>) => string\n\n/**\n * Options passed to `.step(name, options)`. At least one of `run` or `route` must be set.\n *\n * Two variants:\n * - Without `optin`: route receives state without `$error` (TypeScript-enforced). On error,\n * the framework falls through to `l.onError()` or pauses with `signal: \"$error\"` automatically.\n * - With `optin: '$error'`: route receives the full state including `$error`, and the executor\n * calls route on the error path. Use this when the step's route needs to inspect or handle errors.\n */\nexport type StepOptions<S, Ctx> =\n | {\n readonly optin: '$error'\n run?: RunFn<S, Ctx>\n route?: ErrorAwareRouteFn<S>\n }\n | {\n readonly optin?: undefined\n run?: RunFn<S, Ctx>\n route?: RouteFn<S>\n }\n\n// -----------------------------------------------------------------------\n// LoopDefinition — the captured topology produced by the builder\n// -----------------------------------------------------------------------\n\n/**\n * Where a signal transition routes to.\n * 'step' — routes to the named step.\n * 'end' — exits the loop; run resolves with the emitted signal.\n */\nexport type TransitionTarget =\n | { readonly kind: 'step'; readonly name: string }\n | { readonly kind: 'end' }\n\n/** A single `.on(signal).to(step)` or `.on(signal).end()` declaration. */\nexport interface SignalTransition {\n readonly signal: string\n readonly target: TransitionTarget\n}\n\n/**\n * Compiled step definition stored in LoopDefinition.\n * run and route are stored as-is (user functions — validated structurally, not semantically).\n * transitions: all .on() declarations attached to this step.\n * next: explicit .next(name) target, or undefined if none declared.\n * errorAware: true when the step was declared with optin: '$error' — the executor calls route\n * on the error path when this is true.\n */\nexport interface StepDef {\n readonly name: string\n readonly run: RunFn<unknown, unknown> | undefined\n readonly route: RouteFn<unknown> | undefined\n readonly transitions: readonly SignalTransition[]\n readonly next: string | undefined\n readonly errorAware: boolean\n}\n\n/**\n * A single `.branch(name, fn)` declaration inside a fork.\n * definition is the branch's own, independently-captured LoopDefinition — built by running\n * the branch's builder lambda against a fresh createLoopBuilder() instance. Inside a branch,\n * `.end()` means \"this branch is done,\" not \"the run is done\" (see LoopBuilder.branch).\n */\nexport interface BranchDef {\n readonly name: string\n readonly definition: LoopDefinition\n}\n\n/**\n * Compiled fork node stored in LoopDefinition.steps alongside StepDef nodes.\n * A fork has no run/route of its own — it never emits a signal, so .on() is not supported on it.\n * next: explicit .next(name) target for the step that runs once every branch has settled\n * (the \"join\"), or undefined to fall through to the next declared top-level node.\n * Discriminated from StepDef structurally (see isForkDef) rather than via a tag field, so\n * existing StepDef-only code and hand-built StepDef literals are unaffected.\n */\nexport interface ForkDef {\n readonly name: string\n readonly branches: readonly BranchDef[]\n readonly next: string | undefined\n}\n\n/** A top-level node in a LoopDefinition: either an ordinary step or a fork. */\nexport type LoopNode = StepDef | ForkDef\n\n/** Structural type guard distinguishing ForkDef from StepDef within a LoopNode. */\nexport function isForkDef(node: LoopNode): node is ForkDef {\n return 'branches' in node\n}\n\n/**\n * Complete loop topology captured from the builder lambda.\n * Immutable snapshot — produced once, consumed by LoopValidator and (later) F6.\n *\n * startCalled: true if l.start() was invoked at least once.\n * entryStep: name of the first .step()/.fork() declared after .start() was called; undefined if\n * .start() was never called or no node was declared after it.\n * steps: all declared top-level nodes (steps and forks) in declaration order.\n * onError: the fallback step name from l.onError(), or undefined if not set.\n */\nexport interface LoopDefinition {\n readonly startCalled: boolean\n readonly entryStep: string | undefined\n readonly steps: readonly LoopNode[]\n readonly onError: string | undefined\n}\n\n// -----------------------------------------------------------------------\n// LoopBuilder — the DSL object passed to the h.loop() builder lambda\n// -----------------------------------------------------------------------\n\n/**\n * Fluent chain returned by .on(signal). Caller must call either .to(step) or .end()\n * to complete the transition declaration.\n */\nexport interface OnChain<S, Ctx> {\n /** Route the signal to the named step. Returns the builder for further chaining. */\n to(step: string): LoopBuilder<S, Ctx>\n /** Exit the loop when this signal is emitted. Returns the builder for further chaining. */\n end(): LoopBuilder<S, Ctx>\n}\n\n/**\n * The DSL object passed as `l` to the h.loop(l => ...) builder lambda.\n * All methods mutate internal state and return `this` for chaining.\n */\nexport interface LoopBuilder<S, Ctx> {\n /** Mark the loop as having a declared entry. The first .step()/.fork() called after .start() is the entry. */\n start(): LoopBuilder<S, Ctx>\n /** Declare a step. At least one of run or route must be set (validated later by LoopValidator). */\n step(name: string, options: StepOptions<S, Ctx>): LoopBuilder<S, Ctx>\n /**\n * Declare a fork: a named node that splits execution into 2+ concurrent branches, declared\n * with .branch() immediately after. The step immediately following the fork automatically\n * waits for every branch to settle (the \"join\") — no separate join primitive exists.\n *\n * Per-step telemetry is attributed correctly across concurrent branches: the harness scopes\n * each branch's slots per step via {@link ObserverAware.withTelemetry}, so telemetry travels\n * with the call rather than through shared instance state. See `ObserverAware`'s doc comment\n * (`agent/observer.ts`).\n */\n fork(name: string): LoopBuilder<S, Ctx>\n /**\n * Declare one branch of the fork most recently opened with .fork(). Must be called immediately\n * after .fork() or another .branch() on the same fork — throws otherwise.\n * builderFn receives a fresh LoopBuilder scoped to this branch, using the same .step()/.on()/\n * .next() vocabulary as the top level; inside it, .end() means \"this branch is done,\" not\n * \"the run is done.\"\n */\n branch(name: string, builderFn: (b: LoopBuilder<S, Ctx>) => void): LoopBuilder<S, Ctx>\n /**\n * Declare the step that runs once every branch of the preceding fork has settled.\n * Pure alias of .step(name, options) — not enforced by the validator, just a naming\n * convenience so the DSL reads as fork/branch/join.\n */\n join(name: string, options: StepOptions<S, Ctx>): LoopBuilder<S, Ctx>\n /**\n * Begin a signal transition declaration. Must be called immediately after .step() or after\n * a previous .on().to() or .on().end() chain (attaches to the most recently declared step).\n * Throws if the most recently declared node is a fork — a fork has no run/route to emit\n * a signal from.\n */\n on(signal: string): OnChain<S, Ctx>\n /**\n * Declare an explicit unconditional next target for the most recently declared step.\n * Mutually exclusive with route (validated by LoopValidator).\n */\n next(name: string): LoopBuilder<S, Ctx>\n /**\n * Declare a loop-level fallback error step. Any step whose run throws and whose\n * route does not handle $error will route to this step instead of pausing the session.\n * Only one onError target per loop; multiple calls replace the previous target (last wins).\n */\n onError(step: string): LoopBuilder<S, Ctx>\n}\n\n// -----------------------------------------------------------------------\n// Error class\n// -----------------------------------------------------------------------\n\n/** Thrown by extractLoopDefinition when the argument is not a createLoopBuilder() instance. */\nexport class InvalidLoopBuilderError extends Error {\n constructor() {\n super('argument is not a LoopBuilder instance — was it created by createLoopBuilder?')\n this.name = 'InvalidLoopBuilderError'\n }\n}\n\n// -----------------------------------------------------------------------\n// Internal implementation\n// -----------------------------------------------------------------------\n\n// Module-private symbol for internal state\nconst _builderState = Symbol('builderState')\n\n// Internal mutable step definition during collection\ninterface StepDefMutable {\n name: string\n run: RunFn<unknown, unknown> | undefined\n route: RouteFn<unknown> | undefined\n transitions: SignalTransition[]\n next: string | undefined\n errorAware: boolean\n}\n\n// Internal mutable fork definition during collection. Branches are pushed already-immutable\n// (extractLoopDefinition runs on the branch's own builder as soon as .branch() is called).\ninterface ForkDefMutable {\n name: string\n branches: BranchDef[]\n next: string | undefined\n}\n\ntype NodeMutable = StepDefMutable | ForkDefMutable\n\n// Structural discriminant shared with isForkDef — a fork is the only node with `branches`.\nfunction isForkNodeMutable(node: NodeMutable): node is ForkDefMutable {\n return 'branches' in node\n}\n\n// Internal mutable builder state\ninterface BuilderState {\n startCalled: boolean\n entryStep: string | undefined\n steps: NodeMutable[]\n onError: string | undefined\n}\n\n// Deep freeze utility\nfunction deepFreeze<T extends object>(obj: T): T {\n Object.freeze(obj)\n\n for (const value of Object.values(obj)) {\n if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {\n deepFreeze(value)\n }\n }\n\n return obj\n}\n\n/**\n * Create a new LoopBuilder instance for use in a h.loop() lambda.\n * The returned object accumulates all DSL calls in mutable internal state.\n */\nexport function createLoopBuilder<S, Ctx>(): LoopBuilder<S, Ctx> {\n const state: BuilderState = {\n startCalled: false,\n entryStep: undefined,\n steps: [],\n onError: undefined,\n }\n\n const builder: any = {\n start(this: any): LoopBuilder<S, Ctx> {\n state.startCalled = true\n return this\n },\n\n step(this: any, name: string, options: StepOptions<S, Ctx>): LoopBuilder<S, Ctx> {\n const stepDef: StepDefMutable = {\n name,\n run: options.run as RunFn<unknown, unknown> | undefined, // as: contravariance in state parameter\n route: options.route as RouteFn<unknown> | undefined, // as: contravariance in state parameter\n transitions: [],\n next: undefined,\n errorAware: options.optin === '$error',\n }\n state.steps.push(stepDef)\n\n // Set entryStep to the first step after start() was called\n if (state.startCalled && state.entryStep === undefined) {\n state.entryStep = name\n }\n\n return this\n },\n\n fork(this: any, name: string): LoopBuilder<S, Ctx> {\n const forkNode: ForkDefMutable = { name, branches: [], next: undefined }\n state.steps.push(forkNode)\n\n // Forks are valid entry points, same as steps\n if (state.startCalled && state.entryStep === undefined) {\n state.entryStep = name\n }\n\n return this\n },\n\n branch(this: any, name: string, builderFn: (b: LoopBuilder<S, Ctx>) => void): LoopBuilder<S, Ctx> {\n const currentNode = state.steps.at(-1)\n if (currentNode === undefined || !isForkNodeMutable(currentNode)) {\n throw new Error(\n '.branch() must be called immediately after .fork() or another .branch() on the same fork',\n )\n }\n\n // Independent builder instance: branch declarations never touch the outer state\n const branchBuilder = createLoopBuilder<S, Ctx>()\n builderFn(branchBuilder)\n const branchDefinition = extractLoopDefinition(\n branchBuilder as LoopBuilder<unknown, unknown>,\n )\n currentNode.branches.push({ name, definition: branchDefinition })\n\n return this\n },\n\n join(this: any, name: string, options: StepOptions<S, Ctx>): LoopBuilder<S, Ctx> {\n return this.step(name, options)\n },\n\n on(this: any, signal: string): OnChain<S, Ctx> {\n // Guard: if no step has been declared yet, return no-op OnChain\n if (state.steps.length === 0) {\n return {\n to: () => this,\n end: () => this,\n }\n }\n\n const currentNode = state.steps.at(-1)!\n if (isForkNodeMutable(currentNode)) {\n throw new Error(\n '.on() cannot be called on a fork — a fork has no run/route to emit a signal from',\n )\n }\n const currentStep = currentNode\n\n return {\n to: (step: string): LoopBuilder<S, Ctx> => {\n currentStep.transitions.push({\n signal,\n target: { kind: 'step', name: step },\n })\n return this\n },\n end: (): LoopBuilder<S, Ctx> => {\n currentStep.transitions.push({\n signal,\n target: { kind: 'end' },\n })\n return this\n },\n }\n },\n\n next(this: any, name: string): LoopBuilder<S, Ctx> {\n // Guard: if no node has been declared yet, this is a no-op\n if (state.steps.length > 0) {\n const currentNode = state.steps.at(-1)\n if (currentNode !== undefined) {\n currentNode.next = name\n }\n }\n return this\n },\n\n onError(this: any, step: string): LoopBuilder<S, Ctx> {\n state.onError = step\n return this\n },\n }\n\n // Attach the internal state symbol\n ;(builder as any)[_builderState] = state\n\n return builder as LoopBuilder<S, Ctx>\n}\n\n/**\n * Extract the LoopDefinition accumulated by a builder created with createLoopBuilder().\n * Called by harness-builder.ts immediately after the user's builder lambda returns.\n * Throws InvalidLoopBuilderError if the argument was not produced by createLoopBuilder().\n */\nexport function extractLoopDefinition(builder: LoopBuilder<unknown, unknown>): LoopDefinition {\n // Identity check: ensure builder has the internal state symbol\n if (builder === null || builder === undefined || !(_builderState in builder)) {\n throw new InvalidLoopBuilderError()\n }\n\n const state = (builder as any)[_builderState] as BuilderState\n\n // Convert mutable nodes (steps and forks) to immutable ones\n const immutableSteps: LoopNode[] = state.steps.map((node) => {\n if (isForkNodeMutable(node)) {\n // Each branch's own definition is already frozen (captured by .branch() at declaration\n // time); only the BranchDef wrapper and the branches array need freezing here.\n const branches = Object.freeze(\n node.branches.map((b) => Object.freeze({ name: b.name, definition: b.definition })),\n ) as readonly BranchDef[]\n const forkDef: ForkDef = {\n name: node.name,\n branches,\n next: node.next,\n }\n return Object.freeze(forkDef)\n }\n\n const transitions = Object.freeze([...node.transitions]) as readonly SignalTransition[]\n // Freeze each transition\n for (const transition of transitions) {\n Object.freeze(transition)\n Object.freeze(transition.target)\n }\n const stepDef: StepDef = {\n name: node.name,\n run: node.run,\n route: node.route,\n transitions,\n next: node.next,\n errorAware: node.errorAware,\n }\n return Object.freeze(stepDef)\n })\n\n // Create the frozen LoopDefinition\n const definition: LoopDefinition = {\n startCalled: state.startCalled,\n entryStep: state.entryStep,\n steps: Object.freeze(immutableSteps),\n onError: state.onError,\n }\n\n // Deep freeze the entire structure\n return deepFreeze(definition)\n}\n","import type { LoopDefinition, StepDef } from './loop-dsl.js'\nimport { isForkDef } from './loop-dsl.js'\n\n// -----------------------------------------------------------------------\n// Error class\n// -----------------------------------------------------------------------\n\n/**\n * Thrown by validateLoop() when the LoopDefinition violates one or more structural rules.\n * violations: every rule violation found, as human-readable strings.\n * The full list is always reported — validateLoop() never fails fast on the first violation.\n */\nexport class LoopValidationError extends Error {\n readonly violations: readonly string[]\n\n constructor(violations: readonly string[]) {\n super(`loop validation failed:\\n${violations.map((v) => ` - ${v}`).join('\\n')}`)\n this.name = 'LoopValidationError'\n this.violations = violations\n }\n}\n\n// -----------------------------------------------------------------------\n// Public API\n// -----------------------------------------------------------------------\n\n/**\n * Validate a LoopDefinition against all structural rules.\n * Collects every violation before throwing, so developers see the full picture.\n *\n * Applies the 9 structural rules recursively to the top-level definition and to every branch's\n * own definition at every depth (a fork nested inside a branch is validated too, even though it\n * isn't specially supported yet — see HANDOVER-fork-join.md decision #13). Also checks two\n * fork-specific rules (≥2 branches, unique branch names within a fork) and one whole-tree rule\n * (every step/fork name unique across the entire nested structure, so a persisted cursor string\n * stays unambiguous regardless of which branch it names).\n *\n * @param def - a LoopDefinition produced by extractLoopDefinition()\n * @throws LoopValidationError if one or more validation rules are violated\n */\nexport function validateLoop(def: LoopDefinition): void {\n const violations = collectViolations(def, undefined)\n\n const nameLocations = new Map<string, string[]>()\n collectNameLocations(def, undefined, nameLocations)\n for (const [name, locations] of nameLocations) {\n if (locations.length > 1) {\n violations.push(\n `name \"${name}\" is declared more than once across the nested structure: ${locations.join(', ')}`,\n )\n }\n }\n\n if (violations.length > 0) {\n throw new LoopValidationError(violations)\n }\n}\n\n/**\n * Recursively collects structural and fork-specific violations for one definition and every\n * branch definition nested under it. pathLabel is undefined at the top level; inside a branch\n * it's a '/'-joined fork/branch breadcrumb (e.g. \"review/credit\") used to prefix messages so a\n * violation can be located. Does not throw — validateLoop aggregates across the whole tree first.\n */\nfunction collectViolations(def: LoopDefinition, pathLabel: string | undefined): string[] {\n const prefix = pathLabel !== undefined ? `in branch \"${pathLabel}\": ` : ''\n const violations = collectStructuralViolations(def).map((v) => prefix + v)\n\n for (const node of def.steps) {\n if (!isForkDef(node)) continue\n\n // Rule 10 — a fork needs at least 2 branches\n if (node.branches.length < 2) {\n violations.push(\n `${prefix}fork \"${node.name}\" must have at least 2 branches (found ${node.branches.length})`,\n )\n }\n\n // Rule 11 — branch names unique within this fork (their own namespace — see collectNameLocations)\n const seenBranchNames = new Set<string>()\n for (const branch of node.branches) {\n if (seenBranchNames.has(branch.name)) {\n violations.push(`${prefix}fork \"${node.name}\" has duplicate branch name \"${branch.name}\"`)\n }\n seenBranchNames.add(branch.name)\n }\n\n for (const branch of node.branches) {\n const branchPath =\n pathLabel !== undefined ? `${pathLabel}/${node.name}/${branch.name}` : `${node.name}/${branch.name}`\n violations.push(...collectViolations(branch.definition, branchPath))\n }\n }\n\n return violations\n}\n\n/**\n * Walks the entire nested tree recording every declaration location for every step/fork name.\n * Branch names are deliberately excluded — they're validated for uniqueness within their own\n * fork by Rule 11 above, not as part of this global step/fork namespace.\n */\nfunction collectNameLocations(\n def: LoopDefinition,\n path: string | undefined,\n acc: Map<string, string[]>,\n): void {\n for (const node of def.steps) {\n const location = path !== undefined ? `${path}/${node.name}` : node.name\n const locations = acc.get(node.name) ?? []\n locations.push(location)\n acc.set(node.name, locations)\n\n if (isForkDef(node)) {\n for (const branch of node.branches) {\n const branchPath = path !== undefined ? `${path}/${node.name}/${branch.name}` : `${node.name}/${branch.name}`\n collectNameLocations(branch.definition, branchPath, acc)\n }\n }\n }\n}\n\n/**\n * The original 9 structural rules, scoped to a single LoopDefinition — no recursion into\n * branches here; collectViolations calls this once per definition in the tree.\n */\nfunction collectStructuralViolations(def: LoopDefinition): string[] {\n const violations: string[] = []\n\n // Build a set of all declared top-level node names once (steps and forks) — reuse for rules 6 and 8\n const names = new Set(def.steps.map((s) => s.name))\n\n // Rules 1, 2, 4, 9 concern run/route/transitions, which only exist on StepDef — a fork is a\n // different kind of node by construction and is exempt from these. Its own rules (>=2 branches,\n // unique branch names) are checked separately in collectViolations, which calls this function.\n const stepNodes = def.steps.filter((s): s is StepDef => !isForkDef(s))\n\n // -----------------------------------------------------------------------\n // Rule 1 — Every step has at least `run` or `route`\n // -----------------------------------------------------------------------\n for (const step of stepNodes) {\n if (step.run === undefined && step.route === undefined) {\n violations.push(`step \"${step.name}\" must have at least one of run or route`)\n }\n }\n\n // -----------------------------------------------------------------------\n // Rule 2 — A step with `route` must have at least one `.on()` transition\n // -----------------------------------------------------------------------\n for (const step of stepNodes) {\n if (step.route !== undefined && step.transitions.length === 0) {\n violations.push(`step \"${step.name}\" has route but no .on() transitions — every signal must be handled`)\n }\n }\n\n // -----------------------------------------------------------------------\n // Rule 3 — A node without `route` must have a next target\n // (a fork never has a route, so it is held to the same \"needs an exit path\" rule as a step)\n // -----------------------------------------------------------------------\n for (const [i, node] of def.steps.entries()) {\n if (node === undefined) continue\n const hasRoute = !isForkDef(node) && node.route !== undefined\n if (!hasRoute) {\n // Non-last nodes have implicit next = the following node; they satisfy rule 3\n // Last node must have explicit next or be unreachable via rule 8\n const isLast = i === def.steps.length - 1\n if (isLast && node.next === undefined) {\n violations.push(\n `step \"${node.name}\" has no route, no explicit .next(), and no following step — no exit path`,\n )\n }\n }\n }\n\n // -----------------------------------------------------------------------\n // Rule 4 — A step cannot have both `route` and `.next()`\n // -----------------------------------------------------------------------\n for (const step of stepNodes) {\n if (step.route !== undefined && step.next !== undefined) {\n violations.push(`step \"${step.name}\" has both route and .next() — these are mutually exclusive`)\n }\n }\n\n // -----------------------------------------------------------------------\n // Rule 5 — No duplicate step names\n // -----------------------------------------------------------------------\n const seen = new Set<string>()\n for (const step of def.steps) {\n if (seen.has(step.name)) {\n violations.push(`duplicate step name \"${step.name}\"`)\n }\n seen.add(step.name)\n }\n\n // -----------------------------------------------------------------------\n // Rule 6 — All `.to(name)` targets, `.next()` targets, and `onError` target\n // must reference a declared step\n // -----------------------------------------------------------------------\n for (const step of stepNodes) {\n for (const transition of step.transitions) {\n if (transition.target.kind === 'step') {\n if (!names.has(transition.target.name)) {\n violations.push(\n `step \"${step.name}\" has .on(\"${transition.signal}\").to(\"${transition.target.name}\") but step \"${transition.target.name}\" is not declared`,\n )\n }\n }\n }\n }\n\n for (const node of def.steps) {\n if (node.next !== undefined) {\n if (!names.has(node.next)) {\n violations.push(\n `step \"${node.name}\" has .next(\"${node.next}\") but step \"${node.next}\" is not declared`,\n )\n }\n }\n }\n\n if (def.onError !== undefined) {\n if (!names.has(def.onError)) {\n violations.push(`onError target \"${def.onError}\" is not a declared step`)\n }\n }\n\n // -----------------------------------------------------------------------\n // Rule 7 — The loop must have an entry (`.start()`) and at least one exit (`.end()`)\n // -----------------------------------------------------------------------\n if (def.startCalled === false) {\n violations.push(`loop is missing .start() — call l.start() before declaring steps`)\n }\n\n if (def.startCalled && def.entryStep === undefined) {\n violations.push(`l.start() was called but no step was declared after it — declare at least one step`)\n }\n\n // Check for at least one exit (.end())\n let hasExit = false\n for (const step of stepNodes) {\n for (const transition of step.transitions) {\n if (transition.target.kind === 'end') {\n hasExit = true\n break\n }\n }\n if (hasExit) break\n }\n\n if (!hasExit) {\n violations.push(`loop has no exit — add at least one .on(\"<signal>\").end()`)\n }\n\n // -----------------------------------------------------------------------\n // Rule 8 — No unreachable steps\n // -----------------------------------------------------------------------\n // Only checked if def.entryStep !== undefined (rule 7 covers missing entry)\n if (def.entryStep !== undefined) {\n // BFS from entryStep to find all reachable steps\n const reachable = new Set<string>([def.entryStep])\n const queue: string[] = [def.entryStep]\n\n // Also mark onError target as reachable upfront\n if (def.onError !== undefined) {\n reachable.add(def.onError)\n if (!queue.includes(def.onError)) {\n queue.push(def.onError)\n }\n }\n\n while (queue.length > 0) {\n const currentName = queue.shift()!\n const currentNode = def.steps.find((s) => s.name === currentName)\n\n if (!currentNode) continue\n\n // Add all steps reachable via signal transitions (a fork has none — it never routes)\n if (!isForkDef(currentNode)) {\n for (const transition of currentNode.transitions) {\n if (transition.target.kind === 'step') {\n if (!reachable.has(transition.target.name)) {\n reachable.add(transition.target.name)\n queue.push(transition.target.name)\n }\n }\n }\n }\n\n // Add next target if explicit or implicit (a fork never has a route)\n const hasRoute = !isForkDef(currentNode) && currentNode.route !== undefined\n if (hasRoute) {\n // Step has route, so no implicit next\n if (currentNode.next !== undefined && !reachable.has(currentNode.next)) {\n reachable.add(currentNode.next)\n queue.push(currentNode.next)\n }\n } else {\n // Node has no route: follow explicit next or implicit next\n if (currentNode.next !== undefined) {\n if (!reachable.has(currentNode.next)) {\n reachable.add(currentNode.next)\n queue.push(currentNode.next)\n }\n } else {\n // Implicit next: the following node in def.steps, if any\n const currentIndex = def.steps.findIndex((s) => s.name === currentName)\n if (currentIndex !== -1 && currentIndex < def.steps.length - 1) {\n const nextNode = def.steps[currentIndex + 1]\n if (nextNode !== undefined) {\n const nextNodeName = nextNode.name\n if (!reachable.has(nextNodeName)) {\n reachable.add(nextNodeName)\n queue.push(nextNodeName)\n }\n }\n }\n }\n }\n }\n\n // Check for unreachable steps\n for (const step of def.steps) {\n if (!reachable.has(step.name)) {\n violations.push(`step \"${step.name}\" is unreachable from the entry step \"${def.entryStep}\"`)\n }\n }\n }\n\n // -----------------------------------------------------------------------\n // Rule 9 (derived) — A step without `route` must not declare `.on()` signal transitions\n // -----------------------------------------------------------------------\n for (const step of stepNodes) {\n if (step.route === undefined && step.transitions.length > 0) {\n violations.push(\n `step \"${step.name}\" has .on() transitions but no route — .on() is only valid when route is set`,\n )\n }\n }\n\n return violations\n}\n","import type { FieldDefinition, StateFromSchema } from './state-field.js'\nimport type { RequiredMarker, RuntimeMarker, DeepWithMarkers } from './ctx-markers.js'\nimport type { LoopBuilder, LoopDefinition } from '../loop/loop-dsl.js'\nimport { createLoopBuilder, extractLoopDefinition } from '../loop/loop-dsl.js'\nimport { validateLoop } from '../loop/loop-validator.js'\n\n// -----------------------------------------------------------------------\n// Harness type — accumulated at the type level across provide() calls\n// -----------------------------------------------------------------------\n\n/**\n * Immutable builder that accumulates context-slot declarations, store bindings,\n * and the loop definition for an agent. Produced by {@link createHarness} and\n * consumed by {@link createAgent}.\n *\n * The four type parameters track what has been declared so far:\n * - `Ctx` — the full context shape expected by step functions.\n * - `State` — the state record shape derived from the schema passed to `createHarness()`.\n * - `Req` — keys declared as {@link required} (must be supplied to `createAgent`).\n * - `Run` — keys declared as {@link runtime} (must be supplied to `agent.run()`).\n *\n * Each call returns a **new** `Harness` instance; the original is unchanged.\n *\n * @example\n * ```ts\n * const h = createHarness<Ctx>()(schema)\n * .provide('llm', required())\n * .provide('model', 'claude-3-5-haiku-20241022')\n * .store({ session: new InMemorySessionStore() })\n * .loop(l => {\n * l.start().step('run', { run, route }).on('done').end()\n * })\n * ```\n */\nexport type Harness<\n Ctx,\n State,\n Req extends keyof Ctx = never,\n Run extends keyof Ctx = never,\n> = {\n /**\n * Declare a context slot.\n *\n * - Pass {@link required} to require the value at `createAgent()` time.\n * - Pass {@link runtime} to require the value at `agent.run()` time.\n * - Pass any concrete value (or a deep object mixing in markers) to bind it now.\n */\n provide<K extends keyof Ctx>(key: K, value: RequiredMarker): Harness<Ctx, State, Req | K, Run>\n provide<K extends keyof Ctx>(key: K, value: RuntimeMarker): Harness<Ctx, State, Req, Run | K>\n provide<K extends keyof Ctx>(key: K, value: DeepWithMarkers<Ctx[K]>): Harness<Ctx, State, Req, Run>\n\n /**\n * Bind session store(s). Pass `{ session: myStore }` to enable persistence and\n * interrupt/resume across processes.\n */\n // store() Req/Run are not affected at the type level; nested markers are runtime-validated only (F2 spike constraint)\n store(stores: DeepWithMarkers<{ session?: unknown } & Record<string, unknown>>): Harness<Ctx, State, Req, Run>\n\n /**\n * Define the execution loop using the {@link LoopBuilder} DSL.\n *\n * @param builder - Callback that receives a `LoopBuilder` and uses it to\n * declare steps, transitions, and the entry point.\n */\n // loop() parameter is LoopBuilder<State, Ctx> after F4 implementation\n loop(builder: (l: LoopBuilder<State, Ctx>) => void): Harness<Ctx, State, Req, Run>\n\n /**\n * Return the frozen {@link LoopDefinition} captured when {@link loop} was called.\n *\n * @throws {LoopNotDefinedError} if `h.loop()` has not been called on this harness instance.\n */\n definition(): LoopDefinition\n}\n\n// -----------------------------------------------------------------------\n// ProviderEntry — one entry produced by each provide() or store() call\n// -----------------------------------------------------------------------\n\nexport interface ProviderEntry {\n readonly kind: 'provide' | 'store'\n readonly key: string\n readonly value: unknown\n}\n\n// -----------------------------------------------------------------------\n// HarnessInternals — the structural contract between HarnessBuilder and createAgent (F5)\n// -----------------------------------------------------------------------\n\n// _req, _run, _state are type witnesses: never assigned at runtime, carry type-level info to F5\nexport interface HarnessInternals<\n Ctx,\n State,\n Req extends keyof Ctx,\n Run extends keyof Ctx,\n> {\n readonly stateSchema: Record<string, FieldDefinition<unknown>> | undefined\n readonly providers: readonly ProviderEntry[]\n readonly loopDef: LoopDefinition | undefined\n readonly _req: Req | undefined\n readonly _run: Run | undefined\n readonly _state: State | undefined\n}\n\n// -----------------------------------------------------------------------\n// Internal accessor — used by createAgent (F5) to unwrap internals\n// -----------------------------------------------------------------------\n\n// symbol key is module-private; external code cannot read or forge the internals slot\nconst _internals = Symbol('_internals')\n\nexport type HarnessWithInternals<\n Ctx,\n State,\n Req extends keyof Ctx,\n Run extends keyof Ctx,\n> = Harness<Ctx, State, Req, Run> & {\n readonly [_internals]: HarnessInternals<Ctx, State, Req, Run>\n}\n\nexport function getInternals<\n Ctx,\n State,\n Req extends keyof Ctx,\n Run extends keyof Ctx,\n>(harness: Harness<Ctx, State, Req, Run>): HarnessInternals<Ctx, State, Req, Run> {\n if (harness === null || typeof harness !== 'object' || !(_internals in harness)) {\n throw new HarnessInternalsError()\n }\n return (harness as HarnessWithInternals<Ctx, State, Req, Run>)[_internals] // as: `_internals in harness` check above guarantees the symbol key is present\n}\n\n// -----------------------------------------------------------------------\n// Error class\n// -----------------------------------------------------------------------\n\n/** @internal Thrown when {@link getInternals} is called on a non-harness value. */\nexport class HarnessInternalsError extends Error {\n constructor() {\n super('value is not a HarnessBuilder instance — was it created by createHarness?')\n this.name = 'HarnessInternalsError'\n }\n}\n\n/**\n * Thrown by {@link Harness.definition} when `h.loop()` has not been called yet.\n */\nexport class LoopNotDefinedError extends Error {\n constructor() {\n super('loop is not defined — call h.loop() before accessing h.definition()')\n this.name = 'LoopNotDefinedError'\n }\n}\n\n// -----------------------------------------------------------------------\n// createHarness — the public factory\n// -----------------------------------------------------------------------\n\n/**\n * Create a harness builder for the given context type.\n *\n * Call the returned function (optionally with a state schema) to get the\n * {@link Harness} builder on which you chain `.provide()`, `.store()`, and `.loop()`.\n *\n * @example\n * ```ts\n * interface Ctx { llm: LLM; model: string }\n * const schema = { messages: field<string[]>({ default: () => [] }) }\n *\n * const h = createHarness<Ctx>()(schema)\n * ```\n */\nexport function createHarness<Ctx = any>(): <S extends object = {}>( // any: allows createHarness() without an explicit Ctx type parameter\n stateSchema?: S,\n) => Harness<Ctx, StateFromSchema<S>> {\n return <S extends object = {}>(stateSchema?: S): Harness<Ctx, StateFromSchema<S>> => {\n const internals: HarnessInternals<Ctx, StateFromSchema<S>, never, never> = {\n stateSchema: stateSchema as Record<string, FieldDefinition<unknown>> | undefined, // as: S extends object; cast to internal schema representation\n providers: Object.freeze([]),\n loopDef: undefined,\n _req: undefined,\n _run: undefined,\n _state: undefined,\n }\n\n return createBuilderInstance(internals)\n }\n}\n\nfunction createBuilderInstance<\n Ctx,\n State,\n Req extends keyof Ctx = never,\n Run extends keyof Ctx = never,\n>(internals: HarnessInternals<Ctx, State, Req, Run>): HarnessWithInternals<Ctx, State, Req, Run> {\n const builder: any = { // any: TypeScript cannot infer overloaded call signatures from object literal method definitions\n provide<K extends keyof Ctx>(\n key: K,\n value: RequiredMarker | RuntimeMarker | DeepWithMarkers<Ctx[K]>,\n ): Harness<Ctx, State, any, any> { // any: Req/Run accumulation is tracked at the type level via overloads; method body uses any to avoid inference conflicts\n const newProviders = Object.freeze([\n ...internals.providers,\n { kind: 'provide' as const, key: String(key), value },\n ])\n const newInternals: HarnessInternals<Ctx, State, any, any> = { // any: same reason as return type annotation above\n stateSchema: internals.stateSchema,\n providers: newProviders,\n loopDef: internals.loopDef,\n _req: undefined,\n _run: undefined,\n _state: undefined,\n }\n return createBuilderInstance(newInternals)\n },\n\n store(stores: DeepWithMarkers<{ session?: unknown } & Record<string, unknown>>): Harness<Ctx, State, Req, Run> {\n const newProviders = Object.freeze([\n ...internals.providers,\n { kind: 'store' as const, key: '__store__', value: stores },\n ])\n const newInternals: HarnessInternals<Ctx, State, Req, Run> = {\n stateSchema: internals.stateSchema,\n providers: newProviders,\n loopDef: internals.loopDef,\n _req: undefined,\n _run: undefined,\n _state: undefined,\n }\n return createBuilderInstance(newInternals)\n },\n\n loop(builderFn: (l: LoopBuilder<State, Ctx>) => void): Harness<Ctx, State, Req, Run> {\n const lb = createLoopBuilder<State, Ctx>()\n builderFn(lb)\n const def = extractLoopDefinition(lb as LoopBuilder<unknown, unknown>) // as: generic S/Ctx erased for internal storage\n validateLoop(def)\n const newInternals: HarnessInternals<Ctx, State, Req, Run> = {\n stateSchema: internals.stateSchema,\n providers: internals.providers,\n loopDef: def,\n _req: undefined,\n _run: undefined,\n _state: undefined,\n }\n return createBuilderInstance(newInternals)\n },\n\n definition(): LoopDefinition {\n if (internals.loopDef === undefined) {\n throw new LoopNotDefinedError()\n }\n return internals.loopDef\n },\n\n [_internals]: internals,\n }\n\n return builder\n}\n","import type { RunRef } from './session-store.js'\n\n/**\n * Identifies the agent and session for run-level observer callbacks.\n */\nexport interface RunContext {\n readonly agentId: string\n readonly sessionId: string\n /**\n * The UUID for this specific run invocation. Always present in RunContext\n * passed to observer methods.\n */\n readonly runId: string\n /**\n * Optional parent run UUID for cross-process trace correlation. Present\n * when parentRunId was passed to agent.run() resources. Absent for top-level\n * runs or when not provided by the caller.\n */\n readonly parentRunId?: string\n /**\n * The physical instance ID of the agent process, if configured via\n * `createAgent()` options. Absent when `instanceId` was not provided.\n */\n readonly instanceId?: string\n /**\n * Branch-name path (outermost to innermost), present only when this context describes a\n * fork branch's own nested run rather than the top-level run. A branch is implemented as\n * its own recursive runLoop call, so it fires onRunStart/onRunEnd on the same observer as\n * the top-level run, under the same runId — this field is what makes those distinguishable\n * from the real top-level pair. Absent for the top-level run.\n */\n readonly branchPath?: readonly string[]\n /**\n * The run this one continues: the run that paused the session (on an interrupt, a stop or\n * an unhandled error), with the carrier its observer produced. Present on a resumed\n * top-level run only — never on a fork branch's context, never together with `branchedFrom` or\n * `continuedFrom`.\n */\n readonly resumedFrom?: RunRef\n /**\n * The run this session was branched from (`SessionStore.branch`), in the source session.\n * Present on the branched session's first top-level run only.\n */\n readonly branchedFrom?: RunRef & { readonly sessionId: string }\n /**\n * The previous turn's run, when this run starts a new turn on a session whose last run\n * completed. Present on the top-level run only — never together with `resumedFrom` or\n * `branchedFrom`.\n */\n readonly continuedFrom?: RunRef\n /**\n * The request (turn) this run belongs to — the `requestId` passed to `agent.run()`, kept by\n * every resume of that turn. Present on every context of the run, fork branches included.\n * Absent for keyless turns and when the agent has no session store.\n */\n readonly requestId?: string\n}\n\n/**\n * Identifies the agent, session, and current step for step-level observer callbacks.\n */\nexport interface StepContext {\n readonly agentId: string\n readonly sessionId: string\n /**\n * The runId of the run this step belongs to — the same value as `RunContext.runId`. Steps\n * inside fork branches carry the top-level run's id (tell branches apart with `branchPath`).\n * A resumed run has a new id. Empty string only when the loop is driven without a runId\n * (direct `runLoop` use), as for `RunContext.runId`.\n */\n readonly runId: string\n readonly stepName: string\n /**\n * Branch-name path (outermost to innermost), present only when this step runs inside a\n * fork branch. Absent for a step at the top level of the loop (including the fork node\n * itself, which is one atomic step from the outer run's point of view).\n */\n readonly branchPath?: readonly string[]\n}\n\n/**\n * Where execution goes after a step settles.\n *\n * - `step` — the next step to run (a route target, `.next()`, the implicit next step, the\n * `l.onError()` fallback, or the join after a fork).\n * - `end` — the loop ended via `.end()` (inside a fork branch: the branch ended).\n * - `pause` — the run paused (interrupt, stop, or an unhandled error) and can be continued later.\n * - `throw` — a graph-definition error (`UnknownSignalError`, `NoNextStepError`,\n * `MissingReducerError`) is about to reject the run.\n */\nexport type StepSettledNext =\n | { readonly kind: 'step'; readonly name: string }\n | { readonly kind: 'end' }\n | { readonly kind: 'pause' }\n | { readonly kind: 'throw' }\n\n/**\n * Payload of {@link Observer.onStepSettled}: everything known about one step once its\n * outcome and destination are final. Optional keys are omitted, never set to `undefined`.\n */\nexport interface StepSettledEvent {\n /** `'stopped'` only occurs on fork nodes whose branches were stopped without an interrupt. */\n readonly outcome: 'ok' | 'error' | 'interrupt' | 'stopped'\n /** From `onStepStart` until the destination is known — includes `route()`. */\n readonly durationMs: number\n /**\n * The value `run()` returned, present iff it was applied to state. The raw reference,\n * unfiltered — it may be aliased into state, so copy it before the next step if you keep it.\n */\n readonly update?: Record<string, unknown>\n /** Present iff `route()` was called and returned a signal. */\n readonly signal?: string\n readonly next: StepSettledNext\n /** Present iff `outcome` is `'error'`. */\n readonly error?: Error\n /** Present iff `outcome` is `'interrupt'` on a plain (non-fork) step. */\n readonly interrupt?: { readonly interruptId: string; readonly prompt: unknown }\n /**\n * Fork nodes only, when every branch ended done or paused (not when the fork failed):\n * each branch in declaration order.\n */\n readonly fork?: {\n readonly branches: readonly { readonly name: string; readonly status: 'done' | 'paused'; readonly touchedKeys: readonly string[] }[]\n }\n}\n\n/**\n * What {@link Observer.wrap} is asked to enclose.\n *\n * - `step` — one step's `run()`. Hooks (`onStepStart`, `onStepEnd`, …) and `route()` run outside it.\n * - `event` — a call inside a step that an event already opened, named by that event's `type`\n * (e.g. `'tool.call'`, `'llm.request'`), with a `payload` carrying the id the event used\n * (e.g. `{ toolCallId }`, `{ callId }`). Requested via `ctx.within()` or `TelemetryContext.within()`.\n */\nexport type WrapScope =\n | { readonly kind: 'step' }\n | { readonly kind: 'event'; readonly type: string; readonly payload: unknown }\n\n/**\n * Observability hook interface. All methods are optional — implement only\n * the hooks you need.\n *\n * Pass an `Observer` implementation in `agent.run()` resources under the key\n * `'observer'`, or bind it to an {@link ObserverAware} slot before running.\n *\n * LLM adapters emit `'llm.response'` events via `onEvent` carrying an\n * `LLMUsageEvent` payload for token tracking.\n *\n * @example\n * ```ts\n * const obs: Observer = {\n * onRunStart: (ctx) => console.log('run started', ctx.sessionId),\n * onEvent: (ctx, type, payload) => metrics.record(type, payload),\n * }\n * agent.run({}, { llm, observer: obs })\n * ```\n */\nexport interface Observer {\n /** Called once when a run begins, before the first step executes. */\n onRunStart?: (ctx: RunContext) => void\n /**\n * Called once when a run settles — completed, stopped, paused, or rejected by a thrown error\n * (a graph-definition error or a throwing callback).\n *\n * When the run ends because of an error, `signal` is `'$error'` and `error` holds it: the error\n * a step's `run` or `route` threw, or a failed fork's branch error, when no `onError` step\n * handled it (the run resolves paused); or the original thrown value when the run rejects (it\n * rejects right after). `error` is absent on every other ending. A route may also return\n * `'$error'` as an ordinary signal; that ending has no `error` key, so test for `error`, not\n * for the signal.\n */\n onRunEnd?: (ctx: RunContext, event: { signal: string; durationMs: number; error?: unknown }) => void\n /** Called immediately before each step's `run` function is invoked. */\n onStepStart?: (ctx: StepContext) => void\n /** Called after a step completes successfully. */\n onStepEnd?: (ctx: StepContext, event: { durationMs: number }) => void\n /** Called when a step's `run` function throws. */\n onStepError?: (ctx: StepContext, event: { error: unknown; durationMs: number }) => void\n /** Called when a step issues a `ctx.interrupt()`. */\n onInterrupt?: (ctx: StepContext, event: { prompt: unknown; interruptId: string }) => void\n /**\n * Called for arbitrary named events emitted by step code via `ctx.emit()` or\n * by LLM adapters (e.g. `'llm.response'`).\n */\n onEvent?: (ctx: StepContext, type: string, payload: unknown) => void\n /**\n * Called exactly once per step, on every path, once the step's outcome and destination\n * are final: after `onStepEnd` / `onStepError` / `onInterrupt` (when that hook fires on the\n * path) and before `onRunEnd`. Also fires for fork nodes and for steps inside fork branches\n * (with `ctx.branchPath`). Not fired when a run stops before starting a step.\n */\n onStepSettled?: (ctx: StepContext, event: StepSettledEvent) => void\n /**\n * Run `fn` inside this observer's scope — e.g. make a span the active context so code in\n * `fn` (auto-instrumented clients, sub agents) nests under it. The only hook that encloses\n * work rather than being notified about it.\n *\n * Call `fn` at most once and return its promise. The harness never trusts the wrapper:\n * `fn` always runs exactly once, and the caller always gets `fn`'s own result. A wrapper\n * that throws before calling `fn` is reported via `onObserverError` (hook name `'wrap'`) and\n * `fn` runs unwrapped; one that never calls `fn` just loses its scope; one that swallows or\n * replaces `fn`'s result is ignored. A wrapper error after `fn` was called is reported too,\n * unless it is `fn`'s own rejection passed through.\n *\n * Not guarded: a wrapper that never settles hangs the step it encloses.\n */\n wrap?: <T>(ctx: StepContext, scope: WrapScope, fn: () => Promise<T>) => Promise<T>\n /**\n * Called once per top-level run, right after `onRunStart` (never for a fork branch). Return\n * an opaque string map that lets a later run refer back to this one — e.g. the run's trace\n * context. Core saves it on the run's record and hands it back as `RunContext.resumedFrom.carrier`\n * (or `branchedFrom.carrier`, `continuedFrom.carrier`) to the run that continues or branches from it. Return\n * `undefined` for nothing. Only string values are kept; a throw is reported via\n * `onObserverError` (hook name `'carry'`) and counts as `undefined`.\n */\n carry?: (ctx: RunContext) => Record<string, string> | undefined\n}\n\n/**\n * The telemetry a resource needs to attribute an `invoke()` call to the correct\n * run and step: the run's {@link Observer} and the current {@link StepContext}.\n *\n * The harness passes this per call rather than storing it on the resource instance,\n * so concurrently-running fork branches that share one instance never race on it —\n * each call carries its own context by value.\n */\nexport interface TelemetryContext {\n /**\n * The run's observer, fault-isolated: a hook that throws is reported via `onObserverError`\n * and never reaches the caller. Not the object passed to `agent.run()` itself.\n */\n readonly observer: Observer\n readonly stepContext: StepContext\n /**\n * Run `fn` inside the observer's scope for the event `type` (e.g. `'llm.request'`), whose\n * `payload` carries that event's id (e.g. `{ callId }`). Bound to this step. A passthrough\n * when the observer has no `wrap`; wrapper faults are isolated as for {@link Observer.wrap}.\n */\n within<T>(type: string, payload: unknown, fn: () => Promise<T>): Promise<T>\n}\n\n/**\n * Implemented by resources (e.g. LLM adapters) that emit per-step telemetry.\n *\n * The harness calls {@link ObserverAware.withTelemetry} at the start of each step for every\n * slot that exposes it, and installs the returned value as that slot on the step's `ctx`.\n * Step code then calls the returned view (e.g. `ctx.llm.invoke(...)`) with no telemetry\n * arguments, and the view forwards the {@link TelemetryContext} into the call it wraps — so\n * telemetry travels *with the call* rather than living in mutable instance state.\n *\n * The return is typed `unknown` because core exports no LLM-domain type; a concrete adapter\n * narrows it (e.g. to its `LLM` view). The harness treats the returned value as an opaque\n * slot, exactly as it treats every provided slot.\n */\nexport interface ObserverAware {\n /**\n * Return a view of this resource scoped to the given telemetry. The harness installs\n * the returned value as the resource's slot on the step's `ctx` before calling `step.run`.\n * Called once per step (and once per step per branch), so each concurrent branch gets its\n * own scoped view and there is no shared field to race on.\n */\n withTelemetry(ctx: TelemetryContext): unknown\n}\n\n/**\n * Combine multiple {@link Observer} instances into one. Each hook on the\n * composite forwards to all constituent observers in order.\n *\n * @example\n * ```ts\n * const observer = composeObservers([otelObserver, metricsObserver])\n * ```\n */\n/**\n * Identifies which observer hook threw. Passed to an {@link ObserverErrorSink}.\n */\nexport interface ObserverErrorContext {\n /** The observer hook that threw, e.g. `'onStepStart'`, `'onRunEnd'`, `'onEvent'`. */\n readonly hookName: string\n}\n\n/**\n * Opt-in sink for errors thrown by observer callbacks. Supplied under the\n * `'onObserverError'` key in `agent.run()` / `agent.resume()` resources.\n *\n * Telemetry is a side-channel: an observer that throws must never crash a run.\n * The harness routes every such throw here and continues. The sink is called at\n * most once per failed hook invocation and MUST NOT rethrow into the run — if it\n * does, the harness contains that too (see {@link safeInvoke}).\n */\nexport type ObserverErrorSink = (error: unknown, ctx: ObserverErrorContext) => void\n\n/**\n * Route an observer-hook error to the sink, or, when no sink is configured, to a\n * single `console.error` that names the hook. A sink that itself throws is\n * caught and reported the same way — it never escapes.\n */\nfunction reportObserverError(\n error: unknown,\n ctx: ObserverErrorContext,\n sink: ObserverErrorSink | undefined,\n): void {\n if (sink !== undefined) {\n try {\n sink(error, ctx)\n } catch (sinkError) {\n // A throwing sink must never crash the run, and must not vanish silently.\n console.error(`[harness] onObserverError sink threw while handling '${ctx.hookName}':`, sinkError)\n }\n return\n }\n // Default sink: visible, not silent, and names the failing hook.\n console.error(`[harness] observer hook '${ctx.hookName}' threw:`, error)\n}\n\n/**\n * Invoke one observer-hook call with fault isolation. Runs `call()`; if it\n * throws, the error is routed to `sink` (or the default) and `safeInvoke`\n * returns normally — it never rethrows into the run.\n *\n * `call` is a thunk that performs the exact hook call, e.g.\n * `() => obs?.onStepStart?.(stepCtx)`, so optional-chaining semantics are\n * preserved: when the observer or hook is absent the thunk is a no-op.\n */\nexport function safeInvoke(\n hookName: string,\n call: () => void,\n sink: ObserverErrorSink | undefined,\n): void {\n try {\n call()\n } catch (error) {\n reportObserverError(error, { hookName }, sink)\n }\n}\n\n/**\n * Like {@link safeInvoke}, for a hook that returns a value: returns what `call()` returned,\n * or `undefined` after reporting its throw.\n */\nexport function safeCall<T>(\n hookName: string,\n call: () => T,\n sink: ObserverErrorSink | undefined,\n): T | undefined {\n try {\n return call()\n } catch (error) {\n reportObserverError(error, { hookName }, sink)\n return undefined\n }\n}\n\n/**\n * Run `fn` inside `wrap` with the harness owning `fn`'s result — the isolation rule for\n * {@link Observer.wrap}. `fn` runs exactly once, whatever the wrapper does: if the wrapper\n * never calls it, it is started here. The returned promise is always `fn`'s own. Wrapper\n * errors are reported (hook name `'wrap'`) unless they are `fn`'s own rejection passed through.\n */\nexport async function runWrapped<T>(\n wrap: (inner: () => Promise<T>) => unknown,\n fn: () => Promise<T> | T,\n onObserverError: ObserverErrorSink | undefined,\n): Promise<T> {\n let p: Promise<T> | undefined\n const inner = (): Promise<T> => {\n if (p === undefined) {\n // A sync throw from fn becomes a rejection of p, so it is never taken for a wrapper error.\n p = new Promise<T>(resolve => resolve(fn()))\n // Mark p handled: fn may fail while a wrapper that didn't await it is still pending.\n p.catch(() => {})\n }\n return p\n }\n try {\n await wrap(inner)\n } catch (e) {\n // Re-read through an annotated const: control flow narrows `p` to undefined here, since it is only assigned inside `inner`.\n const started: Promise<T> | undefined = p\n const passedThrough = started !== undefined && await started.then(() => false, (err: unknown) => err === e)\n if (!passedThrough) reportObserverError(e, { hookName: 'wrap' }, onObserverError)\n }\n return inner()\n}\n\nexport function composeObservers(observers: Observer[], onObserverError?: ObserverErrorSink): Observer {\n const wrappers = observers.filter(o => o.wrap !== undefined)\n return {\n onRunStart: (ctx) => {\n for (const o of observers) safeInvoke('onRunStart', () => o.onRunStart?.(ctx), onObserverError)\n },\n onRunEnd: (ctx, event) => {\n for (const o of observers) safeInvoke('onRunEnd', () => o.onRunEnd?.(ctx, event), onObserverError)\n },\n onStepStart: (ctx) => {\n for (const o of observers) safeInvoke('onStepStart', () => o.onStepStart?.(ctx), onObserverError)\n },\n onStepEnd: (ctx, event) => {\n for (const o of observers) safeInvoke('onStepEnd', () => o.onStepEnd?.(ctx, event), onObserverError)\n },\n onStepError: (ctx, event) => {\n for (const o of observers) safeInvoke('onStepError', () => o.onStepError?.(ctx, event), onObserverError)\n },\n onInterrupt: (ctx, event) => {\n for (const o of observers) safeInvoke('onInterrupt', () => o.onInterrupt?.(ctx, event), onObserverError)\n },\n onEvent: (ctx, type, payload) => {\n for (const o of observers) safeInvoke('onEvent', () => o.onEvent?.(ctx, type, payload), onObserverError)\n },\n onStepSettled: (ctx, event) => {\n for (const o of observers) safeInvoke('onStepSettled', () => o.onStepSettled?.(ctx, event), onObserverError)\n },\n // Each observer isolated on its own; later keys win.\n carry: (ctx) => {\n let merged: Record<string, string> | undefined\n for (const o of observers) {\n const carried: unknown = safeCall('carry', () => o.carry?.(ctx), onObserverError)\n if (typeof carried !== 'object' || carried === null || Array.isArray(carried)) continue\n merged = Object.assign(merged ?? {}, carried)\n }\n return merged\n },\n // First observer outermost; each layer isolated on its own by runWrapped.\n wrap: <T>(ctx: StepContext, scope: WrapScope, fn: () => Promise<T>): Promise<T> => {\n const layer = (i: number): Promise<T> =>\n i === wrappers.length\n ? fn()\n : runWrapped(inner => wrappers[i]!.wrap!(ctx, scope, inner), () => layer(i + 1), onObserverError)\n return layer(0)\n },\n }\n}\n","// -----------------------------------------------------------------------\n// InterruptPause — internal control-flow signal between ctx-interrupt and loop-executor\n// -----------------------------------------------------------------------\n\nexport class InterruptPause extends Error {\n readonly interruptId: string\n readonly prompt: unknown\n\n constructor(interruptId: string, prompt: unknown) {\n super(`interrupt requested for id \"${interruptId}\"`)\n this.name = 'InterruptPause'\n this.interruptId = interruptId\n this.prompt = prompt\n }\n}\n\n// -----------------------------------------------------------------------\n// isInterruptPause — type guard used by runLoop\n// -----------------------------------------------------------------------\n\nexport function isInterruptPause(error: unknown): error is InterruptPause {\n return error instanceof InterruptPause\n}\n\n// -----------------------------------------------------------------------\n// createInterruptFn — factory for ctx.interrupt()\n// -----------------------------------------------------------------------\n\nexport function createInterruptFn(\n state: Record<string, unknown>,\n callCountRef: { current: number },\n branchPath?: readonly string[],\n): (prompt: unknown, id?: string) => Promise<unknown> {\n const prefix = branchPath !== undefined && branchPath.length > 0 ? `${branchPath.join(':')}:` : ''\n return async (prompt: unknown, id?: string): Promise<unknown> => {\n const isAutoId = id === undefined\n const effectiveId = isAutoId ? `$auto:${prefix}${callCountRef.current}` : id\n\n // only auto-id calls increment the counter\n if (isAutoId) {\n callCountRef.current++\n }\n\n const responses = state.$interruptResponses as Record<string, unknown>\n\n if (effectiveId in responses) {\n return responses[effectiveId]\n }\n\n state.$interrupt = { interruptId: effectiveId, prompt }\n throw new InterruptPause(effectiveId, prompt)\n }\n}\n","import { safeInvoke, type Observer, type ObserverErrorSink, type StepContext } from './observer.js'\n\n/**\n * Create the ctx.emit function for a single runLoop invocation.\n * Returns a synchronous, fire-and-forget dispatcher.\n * Fires the matching listener (if registered) AND observer.onEvent (if observer\n * is set and stepCtxRef.current is non-null) independently for each call.\n */\nexport function createEmitFn(\n listeners: Record<string, (payload: unknown) => void>,\n observer?: Observer,\n stepCtxRef?: { current: StepContext | null },\n onObserverError?: ObserverErrorSink,\n): (name: string, payload?: unknown) => void {\n return (name: string, payload?: unknown): void => {\n listeners[name]?.(payload)\n if (observer !== undefined && stepCtxRef !== undefined && stepCtxRef.current !== null) {\n const ctx = stepCtxRef.current\n safeInvoke('onEvent', () => observer.onEvent?.(ctx, name, payload), onObserverError)\n }\n }\n}\n\n/**\n * Extract the listeners map from agent.run() resources.\n * Returns an empty object if the 'listeners' key is absent or not a plain object.\n */\nexport function extractRunListeners(\n resources: Record<string, unknown>,\n): Record<string, (payload: unknown) => void> {\n const raw = resources['listeners']\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n return {}\n }\n // plain object: return as-is; listener values are not validated\n return raw as Record<string, (payload: unknown) => void> // as: duck-typed plain object confirmed above; values are caller's responsibility\n}\n","import { runWrapped, type Observer, type ObserverErrorSink, type StepContext } from './observer.js'\n\n/**\n * Create a `within(type, payload, fn)` function: runs `fn` inside `observer.wrap` with an\n * `event` scope for the step `currentStep()` returns at call time. A passthrough (`fn()`) when\n * there is no observer, no `wrap`, or no current step. Used for both `ctx.within` (current step\n * of a runLoop) and `TelemetryContext.within` (bound to one step).\n */\nexport function createWithinFn(\n observer: Observer | undefined,\n currentStep: () => StepContext | null,\n onObserverError: ObserverErrorSink | undefined,\n): <T>(type: string, payload: unknown, fn: () => Promise<T>) => Promise<T> {\n return <T>(type: string, payload: unknown, fn: () => Promise<T>): Promise<T> => {\n const wrap = observer?.wrap\n const stepCtx = currentStep()\n if (wrap === undefined || stepCtx === null) return fn()\n return runWrapped(inner => wrap(stepCtx, { kind: 'event', type, payload }, inner), fn, onObserverError)\n }\n}\n\n/**\n * Run one step's `run()` inside `observer.wrap` with the `step` scope, or call it directly when\n * the observer has no `wrap`.\n */\nexport function runStepScope<T>(\n observer: Observer | undefined,\n stepCtx: StepContext,\n fn: () => Promise<T> | T,\n onObserverError: ObserverErrorSink | undefined,\n): Promise<T> | T {\n const wrap = observer?.wrap\n if (wrap === undefined) return fn()\n return runWrapped(inner => wrap(stepCtx, { kind: 'step' }, inner), fn, onObserverError)\n}\n","import type { LoopDefinition, ForkDef, BranchDef } from '../loop/loop-dsl.js'\nimport { isForkDef } from '../loop/loop-dsl.js'\nimport type { FieldDefinition } from '../harness/state-field.js'\nimport { composeObservers, safeCall, safeInvoke, type Observer, type ObserverErrorSink, type RunContext, type StepContext, type StepSettledEvent, type TelemetryContext } from '../agent/observer.js'\nimport { createInterruptFn, isInterruptPause } from '../agent/ctx-interrupt.js'\nimport { createEmitFn } from '../agent/ctx-emit.js'\nimport { createWithinFn, runStepScope } from '../agent/ctx-within.js'\nimport type { RunCarrier, RunRef } from '../agent/session-store.js'\n\n// A shared no-op observer, so a telemetry-scoped slot always receives a well-formed\n// observer even when the run configured none.\nconst NOOP_OBSERVER: Observer = {}\n\n// -----------------------------------------------------------------------\n// Cursor — a plain step name, or (once a fork is paused) a composite pointer\n// into that fork's branches. See HANDOVER-fork-join.md §4 / Phase 3.\n// -----------------------------------------------------------------------\n\nexport type Cursor = string | ForkCursor\n\n/**\n * Persisted/returned shape of a paused fork. Always lists every branch of the fork, in\n * declaration order (never completion order — see decision #8). A branch never appears\n * with an 'errored' status: an uncaught branch error always escalates to whole-fork\n * failure (decision #9) rather than sitting here as a persisted per-branch state.\n */\nexport interface ForkCursor {\n readonly kind: 'fork'\n readonly fork: string\n readonly branches: readonly BranchCursor[]\n}\n\nexport type BranchCursor =\n | {\n readonly name: string\n readonly status: 'done'\n readonly state: Record<string, unknown>\n readonly touchedKeys: readonly string[]\n }\n | {\n readonly name: string\n readonly status: 'paused'\n readonly state: Record<string, unknown>\n readonly cursor: Cursor\n readonly touchedKeys: readonly string[]\n }\n\n/** Structural type guard distinguishing a ForkCursor from a plain step-name cursor. */\nexport function isForkCursor(cursor: Cursor): cursor is ForkCursor {\n return typeof cursor !== 'string'\n}\n\n// -----------------------------------------------------------------------\n// LoopResult\n// -----------------------------------------------------------------------\n\nexport interface LoopResult {\n readonly state: Record<string, unknown>\n readonly signal: string | null\n readonly cursor: Cursor | null\n readonly paused: boolean\n /** What the run's observer returned from `carry`. Top-level runs only; absent when nothing was carried. */\n readonly carrier?: RunCarrier\n}\n\n// -----------------------------------------------------------------------\n// Error classes\n// -----------------------------------------------------------------------\n\nexport class UnknownSignalError extends Error {\n readonly step: string\n readonly signal: string\n constructor(step: string, signal: string) {\n super(`step \"${step}\" emitted signal \"${signal}\" with no matching .on() transition`)\n this.name = 'UnknownSignalError'\n this.step = step\n this.signal = signal\n }\n}\n\nexport class NoNextStepError extends Error {\n readonly step: string\n constructor(step: string) {\n super(\n `step \"${step}\" has no route, no explicit next, and is the last declared step — execution cannot continue`,\n )\n this.name = 'NoNextStepError'\n this.step = step\n }\n}\n\n/**\n * Thrown when a fork's branches, once all done, have more than one branch touching the\n * same state key with no `field({ reduce })` declared for it (decision #7). Like\n * UnknownSignalError/NoNextStepError, this is a graph-definition bug — it propagates\n * uncaught rather than routing through `$error`/`onError`.\n */\nexport class MissingReducerError extends Error {\n readonly fork: string\n readonly key: string\n readonly branches: readonly string[]\n constructor(fork: string, key: string, branches: readonly string[]) {\n super(\n `fork \"${fork}\": state key \"${key}\" was touched by multiple branches (${branches.join(', ')}) but has no reducer declared — add field({ reduce }) for \"${key}\"`,\n )\n this.name = 'MissingReducerError'\n this.fork = fork\n this.key = key\n this.branches = branches\n }\n}\n\n// -----------------------------------------------------------------------\n// Private helpers\n// -----------------------------------------------------------------------\n\nfunction buildImplicitNextMap(graph: LoopDefinition): Map<string, string | null> {\n const map = new Map<string, string | null>()\n for (let i = 0; i < graph.steps.length; i++) {\n const step = graph.steps[i]!\n const next = i + 1 < graph.steps.length ? graph.steps[i + 1]!.name : null\n map.set(step.name, next)\n }\n return map\n}\n\nfunction applyUpdate(\n state: Record<string, unknown>,\n update: Record<string, unknown>,\n schema: Record<string, FieldDefinition<any>> | undefined, // any: FieldDefinition uses invariant T; any is required for heterogeneous schema maps\n touchedKeys?: Set<string>,\n): void {\n for (const [key, value] of Object.entries(update)) {\n if (key === '$error' || key === '$interrupt' || key === '$interruptResponses') continue\n const reducer = schema?.[key]?.reduce\n if (reducer !== undefined) {\n state[key] = reducer(state[key], value)\n } else {\n state[key] = value\n }\n touchedKeys?.add(key)\n }\n}\n\n/**\n * Fires onStepSettled for one step, stamping durationMs from the step's start. Skips building\n * the event entirely when no observer listens.\n */\nfunction fireSettled(\n obs: Observer | undefined,\n stepCtx: StepContext,\n stepStart: number,\n fields: Omit<StepSettledEvent, 'durationMs'>,\n onObserverError: ObserverErrorSink | undefined,\n): void {\n const hook = obs?.onStepSettled\n if (hook === undefined) return\n const event: StepSettledEvent = { ...fields, durationMs: Date.now() - stepStart }\n safeInvoke('onStepSettled', () => hook(stepCtx, event), onObserverError)\n}\n\n/** The StepContext for a step of this runLoop: the run's identity plus the step name. */\nfunction stepContextOf(runCtx: RunContext, stepName: string): StepContext {\n return {\n agentId: runCtx.agentId,\n sessionId: runCtx.sessionId,\n runId: runCtx.runId,\n stepName,\n ...(runCtx.branchPath !== undefined ? { branchPath: runCtx.branchPath } : {}),\n }\n}\n\nfunction asError(e: unknown): Error {\n return e instanceof Error ? e : new Error(String(e))\n}\n\n// -----------------------------------------------------------------------\n// Public API\n// -----------------------------------------------------------------------\n\nexport interface LoopCallbacks {\n onBeforeStep?: (name: string, state: Record<string, unknown>) => void\n onAfterStep?: (name: string, state: Record<string, unknown>) => void\n onError?: (error: unknown, stepName: string) => void\n onComplete?: (state: Record<string, unknown>, signal: string) => void\n onInterrupt?: (prompt: unknown, interruptId: string) => void\n /**\n * Listeners for user-emitted events (ctx.emit). Keyed by event name.\n * A missing key means ctx.emit(name) is a no-op for that name.\n */\n listeners?: Record<string, (payload: unknown) => void>\n /** Observer for structured telemetry. All lifecycle methods are optional. F16b. */\n observer?: Observer\n /**\n * Opt-in sink for errors thrown by observer callbacks. When a hook throws, the\n * error is routed here (or, if absent, to a default `console.error`) and the\n * run continues — a telemetry fault never aborts a run.\n */\n onObserverError?: ObserverErrorSink\n /**\n * The UUID for this specific invocation. Included in RunContext for observer\n * methods. Absent when no observer is active (observer is still consistent).\n */\n runId?: string\n /**\n * Optional parent run UUID for cross-process trace correlation.\n * Included in RunContext when provided.\n */\n parentRunId?: string\n /**\n * Pre-filtered, keyed list of ObserverAware slots that expose `withTelemetry`.\n * At every step start, before invoking step.run, the loop installs\n * `ctx[key] = slot.withTelemetry({ observer, stepContext })` so telemetry travels with\n * the call. Wrapping always reads from the stored real `slot`, never a prior wrapped\n * value, so re-scoping each step (and each branch, on its own ctx) is safe under concurrency.\n */\n telemetrySlots?: ReadonlyArray<{ key: string; slot: { withTelemetry(ctx: TelemetryContext): unknown } }>\n /**\n * Internal: when set, applyUpdate records every key it writes into this Set.\n * Used by fork dispatch to track which keys a single branch touched, for the\n * declaration-order fold at the join (decisions #6/7/8). Not for external use —\n * a normal top-level runLoop call never sets this.\n */\n touchedKeys?: Set<string>\n /**\n * Internal: branch-name path (outermost to innermost) this runLoop call is running as, if\n * any. Absent for a top-level (non-branch) runLoop call. Two consumers:\n * - qualifies auto-generated interrupt ids ($auto:N -> $auto:branch:N) so sibling branches'\n * default ids can't collide once exposed outside their own runLoop call (Phase 4);\n * - carried onto StepContext/RunContext so an observer can tell a branch's own step/run\n * events apart from the top-level run's (Phase 7) — see HANDOVER-fork-join.md §4.\n */\n branchPath?: readonly string[]\n /** The run this one continues. Put on the top-level RunContext only, never on a branch's. */\n resumedFrom?: RunRef\n /** The run this session was branched from. Put on the top-level RunContext only, never on a branch's. */\n branchedFrom?: RunRef & { sessionId: string }\n /** The previous turn's run. Put on the top-level RunContext only, never on a branch's. */\n continuedFrom?: RunRef\n /** The request (turn) this run belongs to. Put on every RunContext, branches included. */\n requestId?: string\n}\n\n/**\n * What `carry` returned, reduced to what a record can hold: a frozen copy of its string\n * entries, or `undefined` when it is not a plain map or has none.\n */\nfunction normalizeCarrier(carried: unknown): RunCarrier | undefined {\n if (typeof carried !== 'object' || carried === null || Array.isArray(carried)) return undefined\n const entries = Object.entries(carried).filter(([, v]) => typeof v === 'string')\n return entries.length > 0 ? Object.freeze(Object.fromEntries(entries) as Record<string, string>) : undefined\n}\n\ntype Ctx = Record<string, unknown> & {\n readonly agentId: string\n readonly sessionId: string\n readonly signal?: AbortSignal\n}\n\nexport async function runLoop(\n graph: LoopDefinition,\n state: Record<string, unknown>,\n ctx: Ctx,\n schema: Record<string, FieldDefinition<any>> | undefined, // any: see applyUpdate comment\n shouldStop?: () => boolean,\n startCursor?: Cursor,\n callbacks?: LoopCallbacks,\n): Promise<LoopResult> {\n const { onBeforeStep, onAfterStep, onError, onComplete, onInterrupt } = callbacks ?? {}\n const obs = callbacks?.observer\n const onObserverError = callbacks?.onObserverError\n const implicitNextMap = buildImplicitNextMap(graph)\n\n // Initialize framework-reserved fields if absent\n if (!('$error' in state)) state.$error = null\n if (!('$interrupt' in state)) state.$interrupt = null\n if (!('$interruptResponses' in state)) state.$interruptResponses = {}\n\n const runStart = Date.now()\n const branchPath = callbacks?.branchPath\n const isBranch = branchPath !== undefined && branchPath.length > 0\n const runCtx: RunContext = {\n agentId: ctx.agentId,\n sessionId: ctx.sessionId,\n runId: typeof callbacks?.runId === 'string' ? callbacks.runId : '',\n ...(typeof callbacks?.parentRunId === 'string' ? { parentRunId: callbacks.parentRunId } : {}),\n ...(typeof callbacks?.requestId === 'string' ? { requestId: callbacks.requestId } : {}),\n ...(typeof ctx.instanceId === 'string' ? { instanceId: ctx.instanceId } : {}),\n ...(isBranch ? { branchPath } : {}),\n // Branch runLoops receive the outer callbacks by spread, so the refs are dropped here.\n ...(!isBranch && callbacks?.resumedFrom !== undefined ? { resumedFrom: callbacks.resumedFrom } : {}),\n ...(!isBranch && callbacks?.branchedFrom !== undefined ? { branchedFrom: callbacks.branchedFrom } : {}),\n ...(!isBranch && callbacks?.continuedFrom !== undefined ? { continuedFrom: callbacks.continuedFrom } : {}),\n }\n safeInvoke('onRunStart', () => obs?.onRunStart?.(runCtx), onObserverError)\n // The run's own context is fixed from onRunStart on, so the observer is asked once, right here.\n const carrier = isBranch ? undefined : normalizeCarrier(safeCall('carry', () => obs?.carry?.(runCtx), onObserverError))\n const withCarrier = (result: LoopResult): LoopResult => carrier !== undefined ? { ...result, carrier } : result\n // The one place a run ends, so onRunEnd fires exactly once on every path — including a throw.\n let runEnded = false\n // `failure` is passed only on the endings caused by an error, so the event has an `error`\n // key exactly then — even when the thrown value is undefined.\n const endRun = (signal: string, failure?: { error: unknown }): void => {\n runEnded = true\n const event = { signal, durationMs: Date.now() - runStart, ...(failure !== undefined ? { error: failure.error } : {}) }\n safeInvoke('onRunEnd', () => obs?.onRunEnd?.(runCtx, event), onObserverError)\n }\n\n // callCountRef is shared between createInterruptFn and the per-step reset below\n const callCountRef = { current: 0 }\n const stepCtxRef: { current: StepContext | null } = { current: null }\n // mutate ctx in-place so step.run receives the same object reference (invariant for callers)\n ;(ctx as Record<string, unknown>)['interrupt'] = createInterruptFn(state, callCountRef, callbacks?.branchPath) // as: Record<string, unknown> allows adding framework-injected fields to ctx\n ;(ctx as Record<string, unknown>)['emit'] = createEmitFn(callbacks?.listeners ?? {}, obs, stepCtxRef, onObserverError) // as: see interrupt line comment\n ;(ctx as Record<string, unknown>)['within'] = createWithinFn(obs, () => stepCtxRef.current, onObserverError) // as: see interrupt line comment\n // What telemetry-scoped slots (LLM adapters) call hooks on: the run's observer, fault-isolated\n // like every core call site, so an observer that throws on an adapter event never fails the step.\n const telemetryObserver = obs !== undefined ? composeObservers([obs], onObserverError) : NOOP_OBSERVER\n\n let cursor: Cursor = startCursor ?? graph.entryStep!\n\n try {\n while (true) {\n if (shouldStop?.()) {\n endRun('$stopped')\n return withCarrier({ state, signal: null, cursor, paused: true })\n }\n\n // Resuming a previously-paused fork: cursor is a composite ForkCursor, not a step name.\n if (isForkCursor(cursor)) {\n const forkCursor: ForkCursor = cursor\n const forkNode = graph.steps.find(s => s.name === forkCursor.fork)!\n if (!isForkDef(forkNode)) {\n // Graph changed shape between pause and resume — treat like any other unresolvable cursor.\n throw new NoNextStepError(forkCursor.fork)\n }\n onBeforeStep?.(forkNode.name, { ...state })\n const outcome = await handleFork(\n forkNode, forkCursor.branches, state, ctx, schema, shouldStop, callbacks, obs, runCtx, endRun, implicitNextMap, graph,\n )\n if (outcome.done) {\n return withCarrier(outcome.result)\n }\n cursor = outcome.nextCursor\n continue\n }\n\n // pass a shallow snapshot so onBeforeStep observers see pre-run values even after state is mutated\n onBeforeStep?.(cursor, { ...state })\n\n const node = graph.steps.find(s => s.name === cursor)!\n if (isForkDef(node)) {\n const outcome = await handleFork(\n node, undefined, state, ctx, schema, shouldStop, callbacks, obs, runCtx, endRun, implicitNextMap, graph,\n )\n if (outcome.done) {\n return withCarrier(outcome.result)\n }\n cursor = outcome.nextCursor\n continue\n }\n const step = node\n\n // reset per-step counter before run (even for decision nodes, per design)\n callCountRef.current = 0\n\n const stepCtx = stepContextOf(runCtx, cursor)\n stepCtxRef.current = stepCtx\n const stepStart = Date.now()\n safeInvoke('onStepStart', () => obs?.onStepStart?.(stepCtx), onObserverError)\n if (callbacks?.telemetrySlots !== undefined) {\n const telemetry: TelemetryContext = {\n observer: telemetryObserver,\n stepContext: stepCtx,\n within: createWithinFn(obs, () => stepCtx, onObserverError),\n }\n for (const { key, slot } of callbacks.telemetrySlots) {\n ;(ctx as Record<string, unknown>)[key] = slot.withTelemetry(telemetry)\n }\n }\n\n let runSucceeded = false\n // The run's return value once applied to state — reported as onStepSettled's `update`.\n let applied: Record<string, unknown> | undefined\n const settle = (fields: Omit<StepSettledEvent, 'durationMs'>): void =>\n fireSettled(obs, stepCtx, stepStart, { ...fields, ...(applied !== undefined ? { update: applied } : {}) }, onObserverError)\n\n if (step.run !== undefined) {\n // capture whether responses exist before the run; only clear interrupt state if they did\n const hadResponses = Object.keys(state.$interruptResponses as Record<string, unknown>).length > 0\n try {\n const run = step.run\n const update = await runStepScope(obs, stepCtx, () => run(\n state as unknown as Parameters<typeof run>[0],\n ctx as Parameters<typeof run>[1],\n ), onObserverError)\n applyUpdate(state, update as Record<string, unknown>, schema, callbacks?.touchedKeys)\n applied = update as Record<string, unknown>\n // clear interrupt state only after a step that had stored responses to replay\n if (hadResponses) {\n state.$interrupt = null\n state.$interruptResponses = {}\n }\n runSucceeded = true\n } catch (e) {\n if (isInterruptPause(e)) {\n // InterruptPause was caught: $interrupt already written by createInterruptFn\n onInterrupt?.(e.prompt, e.interruptId)\n safeInvoke('onInterrupt', () => obs?.onInterrupt?.(stepCtx, { prompt: e.prompt, interruptId: e.interruptId }), onObserverError)\n settle({ outcome: 'interrupt', interrupt: { interruptId: e.interruptId, prompt: e.prompt }, next: { kind: 'pause' } })\n endRun('$interrupt')\n return withCarrier({ state, signal: '$interrupt', cursor, paused: true })\n }\n // domain error: normalize to Error and set $error; do not rethrow\n state.$error = e instanceof Error ? e : new Error(String(e))\n onError?.(state.$error, cursor)\n safeInvoke('onStepError', () => obs?.onStepError?.(stepCtx, { error: state.$error, durationMs: Date.now() - stepStart }), onObserverError)\n }\n }\n\n if (runSucceeded) {\n // clear $error after a successful run, before calling route\n state.$error = null\n onAfterStep?.(cursor, state)\n safeInvoke('onStepEnd', () => obs?.onStepEnd?.(stepCtx, { durationMs: Date.now() - stepStart }), onObserverError)\n }\n\n // route is called when: route exists AND (run succeeded, step has no run, OR step opted in\n // to error routing via optin: '$error' in the step config)\n const callRoute =\n step.route !== undefined &&\n (runSucceeded || step.run === undefined || step.errorAware)\n\n if (callRoute) {\n // callRoute implies step.route !== undefined; non-null assertion is sound here\n const routeFn = step.route!\n let signal: string\n try {\n signal = routeFn(state as unknown as Parameters<typeof routeFn>[0])\n } catch (e) {\n // route itself threw — treat as terminal error; state update from run already stands\n state.$error = e instanceof Error ? e : new Error(String(e))\n settle({ outcome: 'error', error: state.$error as Error, next: { kind: 'pause' } })\n endRun('$error', { error: state.$error })\n return withCarrier({ state, signal: '$error', cursor, paused: true })\n }\n // An error-aware route runs after a failed run: the step still settles as an error.\n const routed = runSucceeded || step.run === undefined\n ? { outcome: 'ok' as const, signal }\n : { outcome: 'error' as const, signal, error: state.$error as Error }\n const transition = step.transitions.find(t => t.signal === signal)\n if (transition === undefined) {\n const unknownSignal = new UnknownSignalError(cursor, signal)\n settle({ outcome: 'error', signal, error: unknownSignal, next: { kind: 'throw' } })\n throw unknownSignal\n }\n if (transition.target.kind === 'end') {\n settle({ ...routed, next: { kind: 'end' } })\n onComplete?.(state, signal)\n endRun(signal)\n return withCarrier({ state, signal, cursor: null, paused: false })\n }\n settle({ ...routed, next: { kind: 'step', name: transition.target.name } })\n cursor = transition.target.name\n } else if (step.run !== undefined && !runSucceeded) {\n // run threw, route bypassed (not error-aware) or no route: apply l.onError() fallback or pause\n if (graph.onError !== undefined) {\n settle({ outcome: 'error', error: state.$error as Error, next: { kind: 'step', name: graph.onError } })\n cursor = graph.onError\n } else {\n settle({ outcome: 'error', error: state.$error as Error, next: { kind: 'pause' } })\n endRun('$error', { error: state.$error })\n return withCarrier({ state, signal: '$error', cursor, paused: true })\n }\n } else {\n const next = step.next ?? implicitNextMap.get(cursor) ?? null\n if (next === null) {\n const noNext = new NoNextStepError(cursor)\n settle({ outcome: 'error', error: noNext, next: { kind: 'throw' } })\n throw noNext\n }\n settle({ outcome: 'ok', next: { kind: 'step', name: next } })\n cursor = next\n }\n }\n } catch (e) {\n // A run that rejects still ends: observers pairing onRunStart/onRunEnd must not be left open.\n if (!runEnded) endRun('$error', { error: e })\n throw e\n }\n}\n\n// -----------------------------------------------------------------------\n// Fork dispatch (Phase 3 — see HANDOVER-fork-join.md)\n// -----------------------------------------------------------------------\n\ninterface BranchOutcome {\n readonly name: string\n readonly result: LoopResult\n readonly touchedKeys: ReadonlySet<string>\n}\n\n/**\n * Runs (or fast-forwards) one branch. When `prior` is a 'done' BranchCursor, the branch\n * already completed in an earlier runLoop call — nothing to execute, its stored state and\n * touched keys just carry forward to the fold. Otherwise the branch is dispatched fresh\n * (prior undefined) or resumed (prior is 'paused') via a private, independent runLoop call.\n */\nasync function runBranch(\n branch: BranchDef,\n prior: BranchCursor | undefined,\n outerState: Record<string, unknown>,\n outerCtx: Ctx,\n schema: Record<string, FieldDefinition<any>> | undefined,\n shouldStop: (() => boolean) | undefined,\n branchSignal: AbortSignal,\n branchCallbacks: LoopCallbacks | undefined,\n): Promise<BranchOutcome> {\n if (prior !== undefined && prior.status === 'done') {\n return {\n name: branch.name,\n result: { state: prior.state, signal: null, cursor: null, paused: false },\n touchedKeys: new Set(prior.touchedKeys),\n }\n }\n\n const touchedKeys = new Set<string>(prior?.status === 'paused' ? prior.touchedKeys : [])\n // Private copy: branches never share the live state object (decision #8).\n const privateState = prior !== undefined ? { ...prior.state } : { ...outerState }\n const privateCtx: Ctx = { ...outerCtx, signal: branchSignal }\n const branchStartCursor = prior?.status === 'paused' ? prior.cursor : undefined\n const branchPath = [...(branchCallbacks?.branchPath ?? []), branch.name]\n\n const result = await runLoop(\n branch.definition,\n privateState,\n privateCtx,\n schema,\n shouldStop,\n branchStartCursor,\n { ...branchCallbacks, touchedKeys, branchPath },\n )\n\n return { name: branch.name, result, touchedKeys }\n}\n\ntype ForkBranchSummary = NonNullable<StepSettledEvent['fork']>['branches'][number]\n\ninterface ForkDispatchResult {\n readonly kind: 'success' | 'paused' | 'failed'\n readonly forkCursor?: ForkCursor\n /** Set when kind is 'success': every branch, done, in declaration order. */\n readonly branches?: readonly ForkBranchSummary[]\n /**\n * Set when kind is 'paused': true if at least one paused branch is waiting on an interrupt\n * (at any depth — a nested fork reports '$interrupt' only under the same rule), false if\n * every paused branch was only stopped.\n */\n readonly interrupted?: boolean\n readonly error?: Error\n}\n\n/**\n * Dispatches every branch of a fork concurrently (fresh, or resuming from `priorBranches`),\n * then classifies the outcome: 'failed' if any branch failed uncaught (fail-fast — siblings'\n * AbortSignals are triggered, best-effort, decision #9), 'paused' if any branch is still\n * paused with none failed (decision #11), or 'success' once every branch is 'done', in which\n * case this also performs the declaration-order fold into outerState (decisions #6/7/8).\n * A 'paused' result is flagged `interrupted` when a paused branch is waiting on an interrupt\n * rather than just stopped.\n */\nasync function dispatchFork(\n forkNode: ForkDef,\n priorBranches: readonly BranchCursor[] | undefined,\n outerState: Record<string, unknown>,\n outerCtx: Ctx,\n schema: Record<string, FieldDefinition<any>> | undefined,\n shouldStop: (() => boolean) | undefined,\n callbacks: LoopCallbacks | undefined,\n): Promise<ForkDispatchResult> {\n const priorByName = new Map((priorBranches ?? []).map(b => [b.name, b] as const))\n\n const localAborts = forkNode.branches.map(() => new AbortController())\n const outerSignal = outerCtx.signal\n const branchSignals = forkNode.branches.map((_, i) =>\n outerSignal !== undefined ? AbortSignal.any([outerSignal, localAborts[i]!.signal]) : localAborts[i]!.signal,\n )\n\n // Branch-internal steps must not drive the outer \"current step\" (a fork is one atomic\n // step for that purpose) or fire the outer onComplete (a branch's .end() ends the\n // branch, not the run — decision #3). Destructure (rather than override with undefined)\n // to satisfy exactOptionalPropertyTypes: an omitted key, not a key set to undefined.\n const { onBeforeStep: _outerOnBeforeStep, onAfterStep: _outerOnAfterStep, onComplete: _outerOnComplete, ...branchCallbacksRest } = callbacks ?? {}\n const branchCallbacksBase: LoopCallbacks | undefined = callbacks !== undefined ? branchCallbacksRest : undefined\n\n // allSettled, not all: a branch that throws must not leave its siblings running (and\n // reporting steps) after the fork has settled — they are cancelled and awaited first.\n const settled = await Promise.allSettled(\n forkNode.branches.map(async (branch, i) => {\n const prior = priorByName.get(branch.name)\n let outcome: BranchOutcome\n try {\n outcome = await runBranch(branch, prior, outerState, outerCtx, schema, shouldStop, branchSignals[i]!, branchCallbacksBase)\n } catch (e) {\n for (const controller of localAborts) controller.abort()\n throw e\n }\n if (outcome.result.paused && outcome.result.signal === '$error') {\n // Fail-fast: cancel siblings (best-effort — cooperative, via AbortSignal).\n for (const controller of localAborts) controller.abort()\n }\n return outcome\n }),\n )\n // Declaration-order-first rejection, so the thrown error never depends on completion order.\n const rejected = settled.find((r): r is PromiseRejectedResult => r.status === 'rejected')\n if (rejected !== undefined) throw rejected.reason\n const outcomes = settled.map(r => (r as PromiseFulfilledResult<BranchOutcome>).value)\n\n const failed = outcomes.find(o => o.result.paused && o.result.signal === '$error')\n if (failed !== undefined) {\n return { kind: 'failed', error: failed.result.state.$error as Error }\n }\n\n const anyPaused = outcomes.some(o => o.result.paused)\n if (anyPaused) {\n const branches: BranchCursor[] = outcomes.map((o) => {\n if (o.result.paused) {\n return {\n name: o.name,\n status: 'paused',\n state: o.result.state,\n cursor: o.result.cursor!,\n touchedKeys: [...o.touchedKeys],\n }\n }\n return {\n name: o.name,\n status: 'done',\n state: o.result.state,\n touchedKeys: [...o.touchedKeys],\n }\n })\n const interrupted = outcomes.some(o => o.result.paused && o.result.signal === '$interrupt')\n return { kind: 'paused', forkCursor: { kind: 'fork', fork: forkNode.name, branches }, interrupted }\n }\n\n // All branches done — fold into outerState, declaration order (decision #8).\n const keyOwners = new Map<string, string[]>()\n for (const outcome of outcomes) {\n for (const key of outcome.touchedKeys) {\n const owners = keyOwners.get(key) ?? []\n owners.push(outcome.name)\n keyOwners.set(key, owners)\n }\n }\n\n for (const outcome of outcomes) {\n for (const key of outcome.touchedKeys) {\n const owners = keyOwners.get(key)!\n if (owners.length > 1) {\n const reducer = schema?.[key]?.reduce\n if (reducer === undefined) {\n throw new MissingReducerError(forkNode.name, key, owners)\n }\n outerState[key] = reducer(outerState[key], outcome.result.state[key])\n } else {\n outerState[key] = outcome.result.state[key]\n }\n }\n }\n\n return {\n kind: 'success',\n branches: outcomes.map(o => ({ name: o.name, status: 'done' as const, touchedKeys: [...o.touchedKeys] })),\n }\n}\n\ntype ForkStepOutcome =\n | { readonly done: true; readonly result: LoopResult }\n | { readonly done: false; readonly nextCursor: string }\n\n/**\n * Wraps dispatchFork with the same telemetry/onError/onComplete-adjacent handling a plain\n * step gets, and translates its result into either a terminal LoopResult (paused or failed-\n * and-unhandled) or the next cursor to continue the outer while-loop with.\n */\nasync function handleFork(\n forkNode: ForkDef,\n priorBranches: readonly BranchCursor[] | undefined,\n state: Record<string, unknown>,\n ctx: Ctx,\n schema: Record<string, FieldDefinition<any>> | undefined,\n shouldStop: (() => boolean) | undefined,\n callbacks: LoopCallbacks | undefined,\n obs: Observer | undefined,\n runCtx: RunContext,\n endRun: (signal: string, failure?: { error: unknown }) => void,\n implicitNextMap: Map<string, string | null>,\n graph: LoopDefinition,\n): Promise<ForkStepOutcome> {\n const stepCtx = stepContextOf(runCtx, forkNode.name)\n const stepStart = Date.now()\n const onObserverError = callbacks?.onObserverError\n safeInvoke('onStepStart', () => obs?.onStepStart?.(stepCtx), onObserverError)\n\n let dispatch: ForkDispatchResult\n try {\n dispatch = await dispatchFork(forkNode, priorBranches, state, ctx, schema, shouldStop, callbacks)\n } catch (e) {\n fireSettled(obs, stepCtx, stepStart, { outcome: 'error', error: asError(e), next: { kind: 'throw' } }, onObserverError)\n throw e\n }\n\n if (dispatch.kind === 'paused') {\n const fork = {\n branches: dispatch.forkCursor!.branches.map(b => ({ name: b.name, status: b.status, touchedKeys: b.touchedKeys })),\n }\n // Only an interrupt pending somewhere below makes the fork resumable via resume(); a fork\n // whose branches were merely stopped settles exactly like a plain stop.\n if (dispatch.interrupted === true) {\n fireSettled(obs, stepCtx, stepStart, { outcome: 'interrupt', next: { kind: 'pause' }, fork }, onObserverError)\n endRun('$interrupt')\n return { done: true, result: { state, signal: '$interrupt', cursor: dispatch.forkCursor!, paused: true } }\n }\n fireSettled(obs, stepCtx, stepStart, { outcome: 'stopped', next: { kind: 'pause' }, fork }, onObserverError)\n endRun('$stopped')\n return { done: true, result: { state, signal: null, cursor: dispatch.forkCursor!, paused: true } }\n }\n\n if (dispatch.kind === 'failed') {\n state.$error = dispatch.error!\n callbacks?.onError?.(state.$error, forkNode.name)\n safeInvoke('onStepError', () => obs?.onStepError?.(stepCtx, { error: state.$error, durationMs: Date.now() - stepStart }), onObserverError)\n if (graph.onError !== undefined) {\n fireSettled(obs, stepCtx, stepStart, { outcome: 'error', error: state.$error as Error, next: { kind: 'step', name: graph.onError } }, onObserverError)\n return { done: false, nextCursor: graph.onError }\n }\n fireSettled(obs, stepCtx, stepStart, { outcome: 'error', error: state.$error as Error, next: { kind: 'pause' } }, onObserverError)\n endRun('$error', { error: state.$error })\n return { done: true, result: { state, signal: '$error', cursor: forkNode.name, paused: true } }\n }\n\n // success\n state.$error = null\n safeInvoke('onStepEnd', () => obs?.onStepEnd?.(stepCtx, { durationMs: Date.now() - stepStart }), onObserverError)\n callbacks?.onAfterStep?.(forkNode.name, state)\n const next = forkNode.next ?? implicitNextMap.get(forkNode.name) ?? null\n if (next === null) {\n const noNext = new NoNextStepError(forkNode.name)\n fireSettled(obs, stepCtx, stepStart, { outcome: 'error', error: noNext, next: { kind: 'throw' } }, onObserverError)\n throw noNext\n }\n fireSettled(obs, stepCtx, stepStart, { outcome: 'ok', next: { kind: 'step', name: next }, fork: { branches: dispatch.branches! } }, onObserverError)\n return { done: false, nextCursor: next }\n}\n","import type { Cursor, BranchCursor } from '../loop/loop-executor.js'\nimport { isForkCursor } from '../loop/loop-executor.js'\n\ntype SchemaLike = Record<string, {\n readonly default?: (() => unknown) | undefined\n // any on reduce params: function parameter contravariance means typed reducers (e.g. (current: string[]) => string[])\n // are not assignable to (current: unknown) => unknown; any erases the bound safely for runtime use\n readonly reduce?: ((current: any, next: any) => unknown) | undefined // any: see above\n}>\n\n// -----------------------------------------------------------------------\n// ClaimOptions — lease duration passed to claim() and extendClaim()\n// -----------------------------------------------------------------------\n\n/**\n * Options passed to {@link SessionStore.claim}.\n *\n * `ttlMs` is the initial lease duration in milliseconds. The claim expires\n * if not renewed within this window — enabling crash recovery by other instances.\n */\nexport interface ClaimOptions {\n /** Lease duration in milliseconds. Must be a positive integer. */\n readonly ttlMs: number\n}\n\n/** Whether `value` is a usable claim TTL: a finite number of milliseconds greater than 0. */\nexport function isValidTtlMs(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value > 0\n}\n\n/**\n * Claim TTL used when no `claimOptions` is given: `HARNESS_CLAIM_TTL_MS` when it holds a\n * valid TTL, else 30 000. Read on every call; an invalid value is ignored.\n */\nexport function defaultClaimTtlMs(): number {\n const ttlMs = Number(process.env['HARNESS_CLAIM_TTL_MS'])\n return isValidTtlMs(ttlMs) ? ttlMs : 30_000\n}\n\n// -----------------------------------------------------------------------\n// Lease — distributed lease handle returned by claim() and extendClaim()\n// -----------------------------------------------------------------------\n\n/**\n * A successfully acquired distributed lease on a session.\n *\n * Returned by {@link SessionStore.claim} when no other instance holds the\n * session. The framework holds this object for the duration of the run and\n * passes it to {@link SessionStore.release} and {@link SessionStore.extendClaim}.\n */\nexport interface Lease {\n /**\n * Wall-clock expiry timestamp (milliseconds since epoch).\n * The framework checks `Date.now() >= lease.expiresAt` at each step boundary\n * to detect TTL expiry without contacting the store.\n */\n readonly expiresAt: number\n /**\n * The `agentId` this lease was issued for.\n * Stored in the claim record for stuck-lease diagnosis.\n */\n readonly agentId: string\n /**\n * The `sessionId` this lease covers.\n */\n readonly sessionId: string\n /**\n * The `instanceId` of the holder, if provided to `createAgent()`.\n * Written into the store's claim record for operational diagnostics.\n * Absent when `instanceId` was not configured.\n */\n readonly instanceId?: string\n /**\n * Store-implementation-specific token — e.g. a Redis key name, a lock token,\n * or a database row ID. Opaque to the framework; passed back unmodified on\n * `release` and `extendClaim` calls so the store can locate the record.\n */\n readonly token: unknown\n}\n\n// -----------------------------------------------------------------------\n// StoredRunMetadata — operational metadata written into StoredRun\n// -----------------------------------------------------------------------\n\n/**\n * Operational metadata written by the framework into every {@link StoredRun}.\n *\n * The framework writes only `instanceId`. All other fields are reserved for\n * domain-specific operational annotations (tenantId, region, requestId, etc.).\n */\nexport interface StoredRunMetadata {\n /** The `instanceId` of the instance that produced this run. Absent when not configured. */\n instanceId?: string\n /** Open extension point — domain-specific fields. */\n [key: string]: unknown\n}\n\n// -----------------------------------------------------------------------\n// RunRef — a pointer back to an earlier run\n// -----------------------------------------------------------------------\n\n/**\n * Opaque string map an observer's `carry` hook returns for a run (e.g. a trace\n * context). Core stores it on the run's record and hands it back to later runs; it never\n * reads it.\n */\nexport type RunCarrier = Readonly<Record<string, string>>\n\n/** Points at one earlier run, with the carrier that run's observer produced (if any). */\nexport interface RunRef {\n readonly runId: string\n /** Absent when that run had no observer that carries, or its `carry` returned nothing. */\n readonly carrier?: RunCarrier\n}\n\n// -----------------------------------------------------------------------\n// SessionStore — the persistence contract\n// -----------------------------------------------------------------------\n\n/**\n * Persistence contract for agent sessions.\n *\n * Implementations must be safe to call concurrently for **different** sessions;\n * concurrent calls for the **same** session are prevented by the harness concurrency guards.\n *\n * `loadHistory` and `branch` are optional extensions:\n * - `loadHistory` — full run history for a session (used by branching and debugging tools).\n * - `branch` — fork a session at a specific past run, returning a new session ID.\n */\nexport interface SessionStore {\n /**\n * Load the most recent {@link StoredRun} for the given session, or `null` if\n * the session has never been saved.\n */\n load(agentId: string, sessionId: string): Promise<StoredRun | null>\n\n /**\n * Persist a run record as a conditional write.\n *\n * Implementations must compare `run.version` against the version of the\n * currently stored record before writing:\n * - If the stored version equals `run.version - 1` (or there is no stored\n * record and `run.version === 0`), the write succeeds.\n * - Otherwise, another writer committed a newer version concurrently — the\n * implementation must throw `ConcurrentModificationError`.\n */\n save(agentId: string, sessionId: string, run: StoredRun): Promise<void>\n\n /**\n * Return the full ordered run history for a session, oldest first.\n * Optional — omit if your store does not support history.\n */\n loadHistory?(agentId: string, sessionId: string): Promise<StoredRun[]>\n\n /**\n * Fork the session at the state captured by `runId`, returning a new session ID\n * whose initial state equals the forked run's `finalState`.\n * Optional — omit if your store does not support branching.\n *\n * Save the new session's version-0 record as a seed the next run continues: `phase: 'paused'`,\n * no `step`, both states equal to the source run's `finalState`, and `branchedFrom` set to the\n * source session, `runId` and the source run's `carrier` (when it has one). When the source is\n * itself such a seed, copy its `branchedFrom` instead (or leave it out if it has none): a seed's\n * own `runId` never ran. The seed has no `carrier` and no `requestId` of its own.\n *\n * @throws {@link BranchNotFoundError} when `runId` is not found in history.\n */\n branch?(agentId: string, sessionId: string, runId: string): Promise<string>\n\n /**\n * Attempt to acquire a distributed claim on the session before starting a run.\n *\n * - Returns a {@link Lease} when the claim is acquired.\n * - Returns `null` when another instance already holds the claim — the framework\n * throws {@link SessionBusyError} immediately without starting any LLM work.\n *\n * Optional — stores that do not support distributed locking omit this method.\n * The framework checks for its presence before calling it.\n */\n claim?(agentId: string, sessionId: string, options: ClaimOptions): Promise<Lease | null>\n\n /**\n * Release a held claim after the run settles.\n *\n * Called by the framework after `save()` completes (or after an error that\n * prevents saving). Stores may use this to remove the lock record immediately\n * rather than waiting for TTL expiry.\n *\n * Optional — omit if your store does not support claim/release.\n */\n release?(lease: Lease): Promise<void>\n\n /**\n * Extend the TTL of an active claim.\n *\n * Called by `ctx.keepAlive()` (both one-shot and background interval modes).\n * The store must update `expiresAt` on the claim record; the new expiry is\n * `Date.now() + options.ttlMs`. The returned `Lease` object carries the updated\n * `expiresAt`; the framework replaces its held reference with the returned value.\n *\n * Optional — omit if your store does not support claim/release.\n */\n extendClaim?(lease: Lease, options: ClaimOptions): Promise<Lease>\n\n /**\n * The newest run of the session whose `requestId` equals `requestId`, or `null` when there is none.\n *\n * Core calls it only from `agent.run()` with a `requestId` that the latest run does not carry,\n * so a late retry of an earlier request is replayed instead of run again. Without it, core\n * dedupes against the latest run only.\n *\n * Optional — omit if your store keeps no history.\n */\n findRequest?(agentId: string, sessionId: string, requestId: string): Promise<StoredRun | null>\n}\n\n// -----------------------------------------------------------------------\n// StoredRun — the per-run serialized record (replaces StoredSession)\n// -----------------------------------------------------------------------\n\n/**\n * Serializable snapshot of a single agent run, written to the store after\n * every run settles (either `'paused'` on an interrupt or `'completed'`).\n *\n * - `phase: 'paused'` — the run paused on an interrupt; `step` is the step that\n * issued the interrupt and `signal` is `'$interrupt'`. `step` is a plain step name,\n * or (when the run paused inside a fork) a composite `ForkCursor` carrying every\n * branch's own state/cursor — see `Cursor` in `loop-executor.ts` and\n * HANDOVER-fork-join.md §4/Phase 5. A plain-string `step` from before fork/join\n * existed is still a valid `Cursor`, so old rows load and resume unchanged.\n * - `phase: 'completed'` — the loop exited normally; `signal` holds the exit\n * signal (or is absent when the loop ended without emitting a signal).\n */\nexport interface StoredRun {\n readonly agentId: string\n readonly runId: string\n readonly sessionId: string\n readonly version: number\n readonly startedAt: string\n readonly settledAt: string\n readonly phase: 'paused' | 'completed'\n readonly initialState: Record<string, unknown>\n readonly finalState: Record<string, unknown>\n readonly signal?: string\n readonly step?: Cursor\n /**\n * Operational metadata written by the framework.\n *\n * The framework writes `instanceId` when configured; all other fields are\n * domain-defined. Absent for runs produced before this field was added.\n */\n readonly metadata?: StoredRunMetadata\n /**\n * What the run's observer returned from `carry` (e.g. its trace context). Describes this\n * run only. Absent when no observer carried anything.\n */\n readonly carrier?: RunCarrier\n /**\n * Set by `SessionStore.branch` on the seed record of a branched session: the run it was\n * branched from, in the source session. The branched session's first run reports it as\n * `RunContext.branchedFrom`.\n */\n readonly branchedFrom?: RunRef & { readonly sessionId: string }\n /**\n * The request (turn) this run belongs to: the `requestId` passed to `agent.run()`, inherited by\n * every resume of that turn. Absent for keyless turns, branch seeds and runs saved before this\n * field was added.\n */\n readonly requestId?: string\n}\n\n// -----------------------------------------------------------------------\n// SessionPhase — the agent.status() query result\n// -----------------------------------------------------------------------\n\n/**\n * Discriminated union returned by {@link Agent.status} describing the lifecycle\n * phase of a session.\n *\n * - `'fresh'` — no run has been stored yet.\n * - `'in-flight'` — a run is currently executing (in-process guard only; not\n * detectable cross-process from the store alone).\n * - `'paused'` — the last run settled on an interrupt; `step` identifies the\n * step that issued the interrupt. When the run paused inside a fork, `step` is\n * the fork's own name (not the richer per-branch detail — see `pendingInterrupts`).\n * - `'completed'` — the last run exited the loop; `signal` is the exit signal.\n */\nexport type SessionPhase =\n | { readonly phase: 'fresh' }\n | { readonly phase: 'in-flight'; readonly step: null }\n | {\n readonly phase: 'paused'\n readonly signal?: string\n readonly step: string\n /**\n * Every interrupt currently awaiting a response, one per paused branch when the run\n * paused inside a fork (a single-element array for a plain, non-forked pause). Lets a\n * caller discover and resolve each one — via `Agent.resume(response, sessionId, id)` —\n * independently; the session stays `'paused'` until every entry is resolved.\n */\n readonly pendingInterrupts: readonly PendingInterrupt[]\n }\n | { readonly phase: 'completed'; readonly signal?: string }\n\n/** One outstanding `ctx.interrupt()` call awaiting a response. See {@link SessionPhase}. */\nexport interface PendingInterrupt {\n readonly interruptId: string\n readonly prompt: unknown\n /**\n * The step that raised this interrupt. For a forked pause this is a `/`-joined\n * breadcrumb (`\"<fork>/<branch>/<step>\"`, recursing further for nested forks) —\n * same style as the validator's own fork/branch violation paths.\n */\n readonly step: string\n}\n\n// -----------------------------------------------------------------------\n// collectPendingInterrupts — recursively finds every paused branch's own $interrupt\n// -----------------------------------------------------------------------\n\nexport function collectPendingInterrupts(cursor: Cursor | undefined, state: Record<string, unknown>): PendingInterrupt[] {\n if (cursor !== undefined && isForkCursor(cursor)) {\n const result: PendingInterrupt[] = []\n for (const branch of cursor.branches) {\n if (branch.status !== 'paused') continue\n const paused = branch as Extract<BranchCursor, { status: 'paused' }>\n for (const pi of collectPendingInterrupts(paused.cursor, paused.state)) {\n result.push({ ...pi, step: `${cursor.fork}/${paused.name}/${pi.step}` })\n }\n }\n return result\n }\n\n const interrupt = state['$interrupt'] as { interruptId: string; prompt: unknown } | null | undefined\n if (interrupt === null || interrupt === undefined) return []\n const step = typeof cursor === 'string' ? cursor : ''\n return [{ interruptId: interrupt.interruptId, prompt: interrupt.prompt, step }]\n}\n\n// -----------------------------------------------------------------------\n// storedSessionToPhase — converts a raw load result to SessionPhase\n// -----------------------------------------------------------------------\n\nexport function storedSessionToPhase(loaded: StoredRun | null): SessionPhase {\n if (loaded === null) {\n return { phase: 'fresh' }\n }\n\n if (loaded.phase === 'paused') {\n // A paused fork's step is a composite ForkCursor — project it to the fork's own name;\n // pendingInterrupts carries the full per-branch detail.\n const step = loaded.step === undefined ? '' : isForkCursor(loaded.step) ? loaded.step.fork : loaded.step\n const pendingInterrupts = collectPendingInterrupts(loaded.step, loaded.finalState)\n if (loaded.signal !== undefined) {\n return { phase: 'paused', step, signal: loaded.signal, pendingInterrupts }\n }\n return { phase: 'paused', step, pendingInterrupts }\n }\n\n // completed\n if (loaded.signal !== undefined) {\n return { phase: 'completed', signal: loaded.signal }\n }\n return { phase: 'completed' }\n}\n\n// -----------------------------------------------------------------------\n// initializeState — state merge for fresh sessions and resumptions\n// -----------------------------------------------------------------------\n\nexport function initializeState(\n stored: StoredRun | null,\n initialStateArg: Record<string, unknown>,\n schema: SchemaLike | undefined,\n): Record<string, unknown> {\n const argKeys = new Set(Object.keys(initialStateArg))\n\n if (stored === null) {\n return buildFreshState(initialStateArg, argKeys, schema)\n }\n\n return buildResumedState(stored, initialStateArg, argKeys, schema)\n}\n\nfunction buildFreshState(\n initialStateArg: Record<string, unknown>,\n argKeys: Set<string>,\n schema: SchemaLike | undefined,\n): Record<string, unknown> {\n const result: Record<string, unknown> = { ...initialStateArg }\n\n if (schema === undefined || Object.keys(schema).length === 0) {\n return result\n }\n\n for (const key of Object.keys(schema)) {\n if (argKeys.has(key)) {\n // initialStateArg wins — already in result via spread\n continue\n }\n const field = schema[key]\n if (field !== undefined && field.default !== undefined) {\n result[key] = field.default()\n }\n }\n\n return result\n}\n\nfunction buildResumedState(\n stored: StoredRun,\n initialStateArg: Record<string, unknown>,\n argKeys: Set<string>,\n schema: SchemaLike | undefined,\n): Record<string, unknown> {\n const result: Record<string, unknown> = { ...stored.finalState }\n\n // Apply initialStateArg fields on top of stored state\n for (const key of argKeys) {\n const fieldDef = schema?.[key]\n if (fieldDef?.reduce !== undefined) {\n result[key] = fieldDef.reduce(stored.finalState[key], initialStateArg[key])\n } else {\n result[key] = initialStateArg[key]\n }\n }\n\n // Apply schema defaults for keys absent from both stored.finalState and initialStateArg\n if (schema !== undefined) {\n for (const key of Object.keys(schema)) {\n if (argKeys.has(key)) continue\n if (key in stored.finalState) continue\n const field = schema[key]\n if (field !== undefined && field.default !== undefined) {\n result[key] = field.default()\n }\n }\n }\n\n return result\n}\n","/**\n * Thrown by {@link Agent.run} or {@link Agent.resume} when the given session\n * is already executing a run in the same process.\n *\n * Wait for the in-flight {@link RunHandle} to settle before starting a new run.\n */\nexport class SessionInFlightError extends Error {\n /** The session that was already in-flight. */\n readonly sessionId: string\n\n constructor(sessionId: string) {\n super(`session \"${sessionId}\" is already in-flight`)\n this.name = 'SessionInFlightError'\n this.sessionId = sessionId\n }\n}\n\n/**\n * Thrown by {@link Agent.run} when the session is paused on an unanswered\n * interrupt. Call {@link Agent.resume} (or `handle.resume()`) instead.\n */\nexport class SessionPendingInterruptError extends Error {\n /** The session that is awaiting an interrupt response. */\n readonly sessionId: string\n\n constructor(sessionId: string) {\n super(`session \"${sessionId}\" is paused on an interrupt — use agent.resume() instead of agent.run()`)\n this.name = 'SessionPendingInterruptError'\n this.sessionId = sessionId\n }\n}\n\n/**\n * Thrown by the harness when the session store's `load()` call rejects.\n * The original error is available on the `cause` property.\n */\nexport class StoreLoadError extends Error {\n readonly cause: unknown\n\n constructor(cause: unknown) {\n super('session store failed to load session')\n this.name = 'StoreLoadError'\n this.cause = cause\n }\n}\n\n/**\n * Thrown by {@link Agent.run} when `store.claim()` returns `null` —\n * another instance already holds the session claim.\n *\n * The caller may inspect `retryAfter` to implement a `429 Retry-After`\n * response or a retry backoff. How to respond is not the framework's concern.\n */\nexport class SessionBusyError extends Error {\n /** The session that is currently claimed by another instance. */\n readonly sessionId: string\n /**\n * Hint: earliest time (milliseconds since epoch) when a retry may succeed.\n * Derived from the original claim's `expiresAt`. Present when the store\n * includes expiry information in a busy response; absent otherwise.\n */\n // declare: avoids useDefineForClassFields emitting an undefined own property initializer;\n // the field is only written when retryAfter is provided (exactOptionalPropertyTypes guard)\n declare readonly retryAfter?: number\n\n constructor(sessionId: string, retryAfter?: number) {\n super(`session \"${sessionId}\" is currently claimed by another instance`)\n this.name = 'SessionBusyError'\n this.sessionId = sessionId\n // conditional assignment: avoids producing retryAfter: undefined as an own property\n // which exactOptionalPropertyTypes forbids at call sites\n if (retryAfter !== undefined) this.retryAfter = retryAfter\n }\n}\n\n/**\n * Thrown by the framework at a step boundary when the active lease has expired\n * without renewal.\n *\n * The run stops without saving state — the session remains at its last\n * checkpoint, allowing another instance to claim and resume it.\n */\nexport class LeaseExpiredError extends Error {\n /** The session whose lease expired. */\n readonly sessionId: string\n\n constructor(sessionId: string) {\n super(`lease for session \"${sessionId}\" has expired — run stopped without saving`)\n this.name = 'LeaseExpiredError'\n this.sessionId = sessionId\n }\n}\n\n","import type { SessionStore, Lease } from './session-store.js'\n\n/**\n * A mutable reference to the currently held lease.\n * `null` when claim/lease is not in use (no-store or store without claim()).\n * Updated in-place by `extendClaim()` responses.\n */\nexport type LeaseRef = { current: Lease | null }\n\n/**\n * Options for background renewal mode.\n */\nexport interface KeepAliveOptions {\n /**\n * Renewal interval in milliseconds. A background timer calls\n * `store.extendClaim()` at this cadence.\n * Must be less than the original claim `ttlMs` to ensure renewal\n * reaches the store before expiry.\n */\n readonly every: number\n}\n\n/**\n * The stop function returned by `ctx.keepAlive({ every })`.\n * Always call this in a `finally` block to cancel the background timer.\n */\nexport type StopFn = () => void\n\n/**\n * The `ctx.keepAlive` function type injected into the step ctx.\n *\n * - Called with no arguments: one-shot TTL extension. Returns a Promise.\n * - Called with `{ every: ms }`: starts a background interval renewal timer.\n * Returns a `StopFn` synchronously.\n */\nexport type KeepAliveFn =\n ((() => Promise<void>) & ((options: KeepAliveOptions) => StopFn))\n\n/**\n * Create the `ctx.keepAlive` function for a single run.\n *\n * @param leaseRef - Mutable reference to the active lease.\n * @param store - The session store, or `undefined` when no store configured.\n * @param originalTtlMs - The `ttlMs` from the `ClaimOptions` used in the initial claim.\n * @returns The `keepAlive` function to inject into step `ctx`.\n */\nexport function createKeepAliveFn(\n leaseRef: LeaseRef,\n store: SessionStore | undefined,\n originalTtlMs: number,\n): KeepAliveFn {\n function keepAlive(options?: KeepAliveOptions): Promise<void> | StopFn {\n const isBackground = typeof options === 'object' && options !== null && 'every' in options\n const extendClaim = store?.extendClaim\n\n if (isBackground) {\n // background renewal mode\n if (leaseRef.current === null || typeof extendClaim !== 'function') {\n // no-op: no active lease or store doesn't support extendClaim\n return noopStop\n }\n\n let handle: ReturnType<typeof setInterval> | null = setInterval(() => {\n if (leaseRef.current === null) {\n // lease was released after timer started — skip but keep timer running\n return\n }\n // swallow errors — timer must continue regardless of extendClaim failures\n void (async () => {\n try {\n const renewed = await extendClaim.call(store, leaseRef.current!, { ttlMs: originalTtlMs })\n leaseRef.current = renewed\n } catch {\n /* swallow: expiry check at step boundary is the safety net */\n }\n })()\n }, options.every)\n\n return function stop() {\n if (handle !== null) {\n clearInterval(handle)\n handle = null\n }\n }\n }\n\n // one-shot mode\n if (leaseRef.current === null || typeof extendClaim !== 'function') {\n return Promise.resolve()\n }\n\n const snapshot = leaseRef.current\n return (async () => {\n const renewed = await extendClaim.call(store, snapshot, { ttlMs: originalTtlMs })\n leaseRef.current = renewed\n })()\n }\n\n // as: overloaded function — runtime discriminates on options presence\n return keepAlive as KeepAliveFn\n}\n\nfunction noopStop(): void {\n // no-op stop: no timer was started\n}\n","import type { FieldDefinition } from '../harness/state-field.js'\nimport type { ProviderEntry } from '../harness/harness-builder.js'\nimport type { LoopDefinition } from '../loop/loop-dsl.js'\nimport type { LoopCallbacks, LoopResult } from '../loop/loop-executor.js'\nimport { runLoop } from '../loop/loop-executor.js'\nimport type { Observer, ObserverErrorSink, TelemetryContext } from './observer.js'\nimport {\n type SessionStore,\n type StoredRun,\n type StoredRunMetadata,\n type SessionPhase,\n initializeState,\n storedSessionToPhase,\n collectPendingInterrupts,\n defaultClaimTtlMs,\n} from './session-store.js'\nimport { StoreLoadError, LeaseExpiredError, SessionPendingInterruptError } from './concurrency-errors.js'\nimport { createKeepAliveFn, type LeaseRef } from './ctx-keep-alive.js'\n\n// -----------------------------------------------------------------------\n// SessionRunOptions — optional parameters for runWithSession\n// -----------------------------------------------------------------------\n\nexport interface SessionRunOptions {\n /**\n * What started this run: `'run'` (`agent.run()`, the default) or `'resume'` (a store-backed\n * resume, after its response was injected). Only `'run'` is rejected on a pending interrupt.\n */\n readonly mode?: RunMode\n /**\n * The caller's `requestId` (mode `'run'` only): the turn this run belongs to and its\n * idempotency key. Ignored without a store.\n */\n readonly requestId?: string\n /** Checked at the top of each loop iteration; returning true halts the run. */\n readonly shouldStop?: () => boolean\n /**\n * Called if the session store fails. `phase` is `'load'` (store failed at run start),\n * `'persist'` (store failed at run end/pause), or `'claim'` (claim returned null or threw).\n * Run result is still returned when phase is 'persist'.\n */\n readonly onStoreError?: (error: unknown, phase: 'load' | 'persist' | 'claim') => void\n /** Called just before each step executes. Used by RunHandle to track currentStep and fire onBeforeStep. */\n readonly onBeforeStep?: (name: string, state: Record<string, unknown>) => void\n /** Called after a step's run completes successfully and applyUpdate has been applied. */\n readonly onAfterStep?: (name: string, state: Record<string, unknown>) => void\n /** Called immediately when a step's run throws a non-interrupt error, before error routing. */\n readonly onError?: (error: unknown, stepName: string) => void\n /** Called when the loop exits via .on(signal).end() (paused: false). */\n readonly onComplete?: (state: Record<string, unknown>, signal: string) => void\n /** Called when ctx.interrupt() pauses the run (isInterruptPause is true). */\n readonly onInterrupt?: (prompt: unknown, interruptId: string) => void\n /** Listeners for user-emitted events (ctx.emit). Keyed by event name. */\n readonly listeners?: Record<string, (payload: unknown) => void>\n /** Structured telemetry observer for this run. All methods optional. F16b. */\n readonly observer?: Observer\n /** Opt-in sink for errors thrown by observer callbacks; passed through to runLoop callbacks. */\n readonly onObserverError?: ObserverErrorSink\n /**\n * Active lease reference. The factory closes over this ref; it is updated\n * in-place by `extendClaim()` calls. Absent when no claim is in use.\n */\n readonly leaseRef?: LeaseRef\n /**\n * The `instanceId` from `AgentOptions`, if provided. Written into\n * `StoredRun.metadata` on every terminal save and into `RunContext` for observers.\n */\n readonly instanceId?: string\n /**\n * The original claim `ttlMs` — passed to `createKeepAliveFn` as `originalTtlMs`\n * so `ctx.keepAlive()` uses the same TTL for renewals. Defaults to `defaultClaimTtlMs()` when absent.\n */\n readonly claimTtlMs?: number\n /**\n * Optional parent run UUID — set when parentRunId was passed as a resource\n * to agent.run(). Threaded through to RunContext for cross-process trace\n * correlation. Absent for top-level runs.\n */\n readonly parentRunId?: string\n /**\n * Pre-filtered, keyed list of ObserverAware slots that expose `withTelemetry`.\n * Passed through to runLoop callbacks, which per step install\n * `ctx[key] = slot.withTelemetry({ observer, stepContext })`. Absent when no slots\n * expose `withTelemetry`.\n */\n readonly telemetrySlots?: ReadonlyArray<{ key: string; slot: { withTelemetry(ctx: TelemetryContext): unknown } }>\n}\n\n// -----------------------------------------------------------------------\n// resolveSessionStore — extract SessionStore from storeEntries\n// -----------------------------------------------------------------------\n\nexport function resolveSessionStore(\n storeEntries: readonly ProviderEntry[],\n overrides?: Record<string, unknown>,\n): SessionStore | undefined {\n let result: SessionStore | undefined = undefined\n\n for (const entry of storeEntries) {\n if (entry.kind !== 'store') continue\n\n const value = entry.value\n if (value === null || typeof value !== 'object') continue\n\n const rec = value as Record<string, unknown> // as: TypeScript cannot narrow `object` to `Record<string, unknown>` for index access\n if (!('session' in rec)) continue\n\n // Prefer override when provided (fulfils a required() marker declared at harness-build time)\n const rawSession = rec['session']\n const session = (overrides !== undefined && 'session' in overrides) ? overrides['session'] : rawSession\n if (session === null || typeof session !== 'object') continue\n\n const s = session as Record<string, unknown> // as: same narrowing needed to index into the duck-typed session object\n if (typeof s['load'] === 'function' && typeof s['save'] === 'function') {\n // last valid store wins\n result = session as unknown as SessionStore // as: duck-typing confirmed above; no instanceof available for a structural interface\n }\n }\n\n return result\n}\n\n// -----------------------------------------------------------------------\n// querySessionPhase — implements agent.status() query\n// -----------------------------------------------------------------------\n\nexport async function querySessionPhase(\n store: SessionStore | undefined,\n agentId: string,\n sessionId: string,\n): Promise<SessionPhase> {\n if (store === undefined) {\n return { phase: 'fresh' }\n }\n\n const loaded = await store.load(agentId, sessionId)\n return storedSessionToPhase(loaded)\n}\n\n// -----------------------------------------------------------------------\n// runRefsOf — which earlier run the next run continues or branches from\n// -----------------------------------------------------------------------\n\n/**\n * A paused record with a cursor is a run that paused: the next run resumes it. A paused\n * record without one is a branch seed (`SessionStore.branch` writes no `step`): the next run\n * is the branched session's first. A completed record is the previous turn: the next run\n * continues the conversation from it. Only the loaded record's own carrier is passed on.\n */\nfunction runRefsOf(loaded: StoredRun | null): Pick<LoopCallbacks, 'resumedFrom' | 'branchedFrom' | 'continuedFrom'> {\n if (loaded === null) return {}\n const ref = { runId: loaded.runId, ...(loaded.carrier !== undefined ? { carrier: loaded.carrier } : {}) }\n if (loaded.phase === 'completed') return { continuedFrom: ref }\n if (loaded.step !== undefined) return { resumedFrom: ref }\n return loaded.branchedFrom !== undefined ? { branchedFrom: loaded.branchedFrom } : {}\n}\n\n// -----------------------------------------------------------------------\n// decideRun — what a run does with the session's latest stored row\n// -----------------------------------------------------------------------\n\nexport type RunMode = 'run' | 'resume'\n\nexport type RunDecision =\n /** No stored run: fresh state from the input, from the entry step. */\n | { readonly action: 'start' }\n /** The last turn completed: its state without the system fields, input merged, from the entry step. */\n | { readonly action: 'new-turn' }\n /** A paused run: from its cursor (the entry step for a branch seed), input merged or not. */\n | { readonly action: 'continue'; readonly mergeInput: boolean }\n /** Return `row`'s current outcome; run nothing. */\n | { readonly action: 'replay'; readonly row: StoredRun }\n | { readonly action: 'reject'; readonly error: SessionPendingInterruptError }\n\n/**\n * What a run does with the session's latest stored run (`loaded`) and, when the caller's\n * `requestId` names an earlier request, that request's newest run (`older`).\n *\n * A resume continues the paused run without merging (a completed row is only reachable in a\n * race and is replayed). A `run()` with the latest run's `requestId` is a retry: replay what it\n * has, or continue a stopped turn without merging its input again. A `run()` for an earlier\n * request is only replayed. Anything else is a new turn: a completed session starts the next\n * turn, an unanswered interrupt rejects it, and a stopped session continues with the input merged.\n */\nexport function decideRun(args: {\n readonly loaded: StoredRun | null\n readonly older: StoredRun | null\n readonly mode: RunMode\n readonly requestId?: string | undefined\n readonly sessionId: string\n}): RunDecision {\n const { loaded, older, mode, requestId, sessionId } = args\n if (loaded === null) return { action: 'start' }\n const pending = loaded.phase === 'paused' && collectPendingInterrupts(loaded.step, loaded.finalState).length > 0\n\n if (mode === 'resume') {\n return loaded.phase === 'completed' ? { action: 'replay', row: loaded } : { action: 'continue', mergeInput: false }\n }\n if (requestId !== undefined && loaded.requestId === requestId) {\n if (loaded.phase === 'completed' || pending) return { action: 'replay', row: loaded }\n return { action: 'continue', mergeInput: false }\n }\n if (older !== null) return { action: 'replay', row: older }\n\n if (loaded.phase === 'completed') return { action: 'new-turn' }\n if (pending) return { action: 'reject', error: new SessionPendingInterruptError(sessionId) }\n return { action: 'continue', mergeInput: true }\n}\n\n/** The completed run's state without the system fields; the loop sets them to their initial values. */\nfunction withoutSystemFields(loaded: StoredRun): StoredRun {\n const { $error: _error, $interrupt: _interrupt, $interruptResponses: _responses, ...finalState } = loaded.finalState\n return { ...loaded, finalState }\n}\n\n// -----------------------------------------------------------------------\n// runWithSession — full session lifecycle wrapper around runLoop\n// -----------------------------------------------------------------------\n\nexport async function runWithSession(\n store: SessionStore | undefined,\n agentId: string,\n sessionId: string,\n runId: string,\n graph: LoopDefinition,\n initialStateArg: Record<string, unknown>,\n schema: Record<string, FieldDefinition<any>> | undefined, // any: FieldDefinition uses invariant T; heterogeneous schema maps require any\n ctx: Record<string, unknown> & { readonly agentId: string; readonly sessionId: string },\n options?: SessionRunOptions,\n): Promise<LoopResult> {\n // Inject keepAlive into ctx — no-op when no lease is active (leaseRef.current === null)\n const leaseRef = options?.leaseRef ?? { current: null }\n const keepAlive = createKeepAliveFn(leaseRef, store, options?.claimTtlMs ?? defaultClaimTtlMs())\n ;(ctx as Record<string, unknown>)['keepAlive'] = keepAlive // mutate in-place like runLoop does for interrupt/emit\n\n // Build composedShouldStop — checks caller predicate AND lease expiry\n let leaseExpired = false\n const composedShouldStop = (): boolean => {\n if (options?.shouldStop?.() === true) return true\n if (leaseRef.current !== null && leaseRef.current.expiresAt <= Date.now()) {\n leaseExpired = true\n return true\n }\n return false\n }\n\n // mode and requestId decide the run here; they are not loop callbacks\n const { mode = 'run', requestId: callerRequestId, ...loopOptions } = options ?? {}\n\n if (store === undefined) {\n const state = initializeState(null, initialStateArg, schema)\n const result = await runLoop(graph, state, ctx, schema, composedShouldStop, undefined, {\n ...loopOptions,\n runId,\n ...(options?.parentRunId !== undefined ? { parentRunId: options.parentRunId } : {}),\n })\n if (leaseExpired) {\n const expiredError = new LeaseExpiredError(sessionId)\n options?.onStoreError?.(expiredError, 'claim')\n throw expiredError\n }\n return result\n }\n\n const requestId = mode === 'run' ? callerRequestId : undefined\n const fail = (error: unknown): LoopResult => {\n const failState = initializeState(null, initialStateArg, schema)\n failState['$error'] = error\n return { state: failState, signal: '$error', paused: false, cursor: null }\n }\n\n // Load phase — on failure: fire onStoreError('load') and return synthetic error result\n // Run never begins; 'await run' always resolves (never rejects) per docs/agent.md guarantee.\n // A requestId the latest run does not carry may name an earlier request: look it up too.\n let loaded: StoredRun | null\n let older: StoredRun | null = null\n try {\n loaded = await store.load(agentId, sessionId)\n if (requestId !== undefined && loaded !== null && loaded.requestId !== requestId && typeof store.findRequest === 'function') {\n older = await store.findRequest(agentId, sessionId, requestId)\n }\n } catch (error: unknown) {\n const storeError = new StoreLoadError(error)\n options?.onStoreError?.(storeError, 'load')\n return fail(storeError)\n }\n\n const decision = decideRun({ loaded, older, mode, requestId, sessionId })\n\n // A caller error, not a store error: no onStoreError, nothing runs, nothing is saved\n if (decision.action === 'reject') return fail(decision.error)\n\n // Replay returns the request's current outcome without executing\n if (decision.action === 'replay') {\n const { row } = decision\n return {\n state: row.finalState,\n signal: row.signal ?? null,\n cursor: row.step ?? null,\n paused: row.phase === 'paused',\n }\n }\n\n // The turn this run belongs to: the caller's on run(), the paused turn's own on resume\n const segmentRequestId = mode === 'run' ? requestId : loaded?.requestId\n\n // Merge stored snapshot (or null for fresh) with caller-supplied initial state\n const base = decision.action === 'new-turn' && loaded !== null ? withoutSystemFields(loaded) : loaded\n const input = decision.action === 'continue' && !decision.mergeInput ? {} : initialStateArg\n const state = initializeState(base, input, schema)\n // Snapshot before runLoop — runLoop mutates state in place so we must copy before execution\n const initialStateSnapshot = { ...state }\n const startedAt = new Date().toISOString()\n\n // Execute — errors from runLoop propagate uncaught (except LeaseExpiredError handled below)\n const result = await runLoop(graph, state, ctx, schema, composedShouldStop, loaded?.step, {\n ...loopOptions,\n runId,\n ...(options?.parentRunId !== undefined ? { parentRunId: options.parentRunId } : {}),\n ...(segmentRequestId !== undefined ? { requestId: segmentRequestId } : {}),\n ...runRefsOf(loaded),\n })\n\n // Lease-expired path — do NOT persist; signal error to caller\n if (leaseExpired) {\n const expiredError = new LeaseExpiredError(sessionId)\n options?.onStoreError?.(expiredError, 'claim')\n throw expiredError\n }\n\n const settledAt = new Date().toISOString()\n\n // Build optional metadata\n const metadata: StoredRunMetadata | undefined =\n options?.instanceId !== undefined ? { instanceId: options.instanceId } : undefined\n\n // Terminal save — errors are swallowed; LoopResult is always returned\n try {\n const version = (loaded?.version ?? -1) + 1\n if (result.paused) {\n const saved: StoredRun = {\n agentId,\n runId,\n sessionId,\n version,\n startedAt,\n settledAt,\n phase: 'paused',\n initialState: initialStateSnapshot,\n finalState: result.state,\n step: result.cursor!,\n ...(result.signal !== null ? { signal: result.signal } : {}),\n ...(metadata !== undefined ? { metadata } : {}),\n ...(result.carrier !== undefined ? { carrier: result.carrier } : {}),\n ...(segmentRequestId !== undefined ? { requestId: segmentRequestId } : {}),\n }\n await store.save(agentId, sessionId, saved)\n } else {\n const saved: StoredRun = {\n agentId,\n runId,\n sessionId,\n version,\n startedAt,\n settledAt,\n phase: 'completed',\n initialState: initialStateSnapshot,\n finalState: result.state,\n ...(result.signal !== null ? { signal: result.signal } : {}),\n ...(metadata !== undefined ? { metadata } : {}),\n ...(result.carrier !== undefined ? { carrier: result.carrier } : {}),\n ...(segmentRequestId !== undefined ? { requestId: segmentRequestId } : {}),\n }\n await store.save(agentId, sessionId, saved)\n }\n } catch (error) {\n options?.onStoreError?.(error, 'persist')\n // terminal save error is swallowed; LoopResult is returned to caller regardless\n }\n\n return result\n}\n","import type { ClaimOptions, Lease, SessionStore } from './session-store.js'\nimport type { SessionRunOptions } from './session-lifecycle.js'\nimport type { RunOutcome } from './run-handle.js'\nimport type { LeaseRef } from './ctx-keep-alive.js'\nimport { SessionBusyError, StoreLoadError, LeaseExpiredError } from './concurrency-errors.js'\n\n/** The lease fields a body spreads into `runWithSession` options. `{}` when no claim was taken. */\nexport type LeaseRunOptions = Pick<SessionRunOptions, 'leaseRef' | 'claimTtlMs'>\n\n/** An `$error` outcome: a fresh `failState()` with `$error` set to `error`. */\nexport function failOutcome(failState: () => Record<string, unknown>, error: unknown): RunOutcome {\n const state = failState()\n state['$error'] = error\n return { state, signal: '$error' }\n}\n\n/**\n * Run `body` under a claim on the session, when the store supports claims.\n *\n * - claim rejects → `onStoreError(StoreLoadError, 'claim')`, resolves `$error`; body not run\n * - claim returns `null` → `onStoreError(SessionBusyError, 'claim')`, resolves `$error`; body not run\n * - body throws `LeaseExpiredError` → resolves `$error` (already reported by `runWithSession`)\n * - any other body error rejects\n *\n * The lease is released after body settles; release errors are swallowed.\n */\nexport async function runClaimed(args: {\n readonly store: SessionStore | undefined\n readonly agentId: string\n readonly sessionId: string\n readonly claimOptions: ClaimOptions\n readonly onStoreError?: SessionRunOptions['onStoreError']\n readonly failState: () => Record<string, unknown>\n readonly body: (lease: LeaseRunOptions) => Promise<RunOutcome>\n}): Promise<RunOutcome> {\n const { store, agentId, sessionId, claimOptions, onStoreError, failState, body } = args\n const fail = (error: unknown): RunOutcome => failOutcome(failState, error)\n\n let leaseRef: LeaseRef | undefined = undefined\n if (typeof store?.claim === 'function') {\n let lease: Lease | null\n try {\n lease = await store.claim(agentId, sessionId, claimOptions)\n } catch (claimError: unknown) {\n const loadError = new StoreLoadError(claimError)\n onStoreError?.(loadError, 'claim')\n return fail(loadError)\n }\n if (lease === null) {\n const busyError = new SessionBusyError(sessionId)\n onStoreError?.(busyError, 'claim')\n return fail(busyError)\n }\n leaseRef = { current: lease }\n }\n\n try {\n return await body(leaseRef !== undefined ? { leaseRef, claimTtlMs: claimOptions.ttlMs } : {})\n } catch (error: unknown) {\n if (error instanceof LeaseExpiredError) return fail(error)\n throw error\n } finally {\n if (leaseRef !== undefined && typeof store?.release === 'function') {\n try { await store.release(leaseRef.current!) } catch { /* swallow */ }\n }\n }\n}\n\n/**\n * Lenient parse of a `claimOptions` resource: an object with a numeric `ttlMs` is used as is,\n * anything else gives `fallback`.\n */\nexport function parseClaimOptions(raw: unknown, fallback: ClaimOptions): ClaimOptions {\n return typeof raw === 'object' && raw !== null &&\n typeof (raw as Record<string, unknown>)['ttlMs'] === 'number' // as: index access on a narrowed object\n ? (raw as ClaimOptions) // as: ttlMs confirmed numeric above\n : fallback\n}\n","import type { SessionStore, StoredRun } from './session-store.js'\nimport type { Cursor, ForkCursor, BranchCursor } from '../loop/loop-executor.js'\nimport { isForkCursor } from '../loop/loop-executor.js'\nimport type { SessionRunOptions } from './session-lifecycle.js'\nimport type { RunOutcome } from './run-handle.js'\nimport { StoreLoadError } from './concurrency-errors.js'\nimport { failOutcome } from './claim-scope.js'\n\n// -----------------------------------------------------------------------\n// NoInterruptError\n// -----------------------------------------------------------------------\n\n/**\n * Thrown by {@link RunHandle.resume} or {@link Agent.resume} when the session\n * is not currently paused on a matching interrupt.\n *\n * Common causes: the run has not yet settled, the session does not exist,\n * or the supplied `interruptId` does not match the pending interrupt.\n */\nexport class NoInterruptError extends Error {\n constructor() {\n super(\n 'resume() called but the session is not paused on a matching interrupt — ' +\n 'verify the session exists, its phase is \"paused\", and interruptId matches',\n )\n this.name = 'NoInterruptError'\n }\n}\n\n// -----------------------------------------------------------------------\n// injectInterruptResponseIntoState — locates and answers one pending interrupt\n// -----------------------------------------------------------------------\n\n/** Result of {@link injectInterruptResponseIntoState}. */\nexport interface InjectResult {\n readonly cursor: Cursor | undefined\n readonly state: Record<string, unknown>\n /** `false` when no pending interrupt (at any depth) matched `interruptId`. */\n readonly found: boolean\n}\n\nfunction injectIntoForkCursor(cursor: ForkCursor, interruptId: string, response: unknown): ForkCursor | null {\n let matched = false\n const branches: BranchCursor[] = cursor.branches.map((branch) => {\n if (matched || branch.status !== 'paused') return branch\n const paused = branch as Extract<BranchCursor, { status: 'paused' }>\n const branchInterrupt = paused.state['$interrupt'] as { interruptId: string } | null | undefined\n if (branchInterrupt !== null && branchInterrupt !== undefined && branchInterrupt.interruptId === interruptId) {\n matched = true\n const existing = (paused.state['$interruptResponses'] as Record<string, unknown>) ?? {}\n return {\n ...paused,\n state: { ...paused.state, $interrupt: null, $interruptResponses: { ...existing, [interruptId]: response } },\n }\n }\n if (isForkCursor(paused.cursor)) {\n const nested = injectIntoForkCursor(paused.cursor, interruptId, response)\n if (nested !== null) {\n matched = true\n return { ...paused, cursor: nested }\n }\n }\n return branch\n })\n return matched ? { ...cursor, branches } : null\n}\n\n/**\n * Locates the pending interrupt matching `interruptId` — either at the top level (plain,\n * non-forked pause) or inside a paused branch of a `ForkCursor`, recursing into nested forks\n * (decision #13) — and returns an updated `cursor`/`state` with the response injected.\n * `found: false` and both inputs unchanged when nothing matches.\n */\nexport function injectInterruptResponseIntoState(\n cursor: Cursor | undefined,\n state: Record<string, unknown>,\n interruptId: string,\n response: unknown,\n): InjectResult {\n if (cursor !== undefined && isForkCursor(cursor)) {\n const updated = injectIntoForkCursor(cursor, interruptId, response)\n return updated === null\n ? { cursor, state, found: false }\n : { cursor: updated, state, found: true }\n }\n\n const interrupt = state['$interrupt'] as { interruptId: string } | null | undefined\n if (interrupt === null || interrupt === undefined || interrupt.interruptId !== interruptId) {\n return { cursor, state, found: false }\n }\n\n const existing = (state['$interruptResponses'] as Record<string, unknown>) ?? {}\n return {\n cursor,\n state: { ...state, $interrupt: null, $interruptResponses: { ...existing, [interruptId]: response } },\n found: true,\n }\n}\n\n// -----------------------------------------------------------------------\n// injectInterruptResponse\n// -----------------------------------------------------------------------\n\nexport async function injectInterruptResponse(\n store: SessionStore,\n agentId: string,\n sessionId: string,\n interruptId: string,\n response: unknown,\n): Promise<void> {\n const loaded = await store.load(agentId, sessionId)\n\n if (loaded === null) throw new NoInterruptError()\n if (loaded.phase !== 'paused') throw new NoInterruptError()\n\n const result = injectInterruptResponseIntoState(loaded.step, loaded.finalState, interruptId, response)\n if (!result.found) throw new NoInterruptError()\n\n const updated: StoredRun = {\n agentId: loaded.agentId,\n runId: loaded.runId,\n sessionId: loaded.sessionId,\n version: loaded.version + 1,\n startedAt: loaded.startedAt,\n settledAt: loaded.settledAt,\n phase: 'paused',\n initialState: loaded.initialState,\n finalState: result.state,\n ...(result.cursor !== undefined ? { step: result.cursor } : {}),\n ...(loaded.signal !== undefined ? { signal: loaded.signal } : {}),\n ...(loaded.metadata !== undefined ? { metadata: loaded.metadata } : {}),\n ...(loaded.carrier !== undefined ? { carrier: loaded.carrier } : {}),\n ...(loaded.branchedFrom !== undefined ? { branchedFrom: loaded.branchedFrom } : {}),\n ...(loaded.requestId !== undefined ? { requestId: loaded.requestId } : {}),\n }\n\n await store.save(agentId, sessionId, updated)\n}\n\n// -----------------------------------------------------------------------\n// injectThenRun — the inject step shared by both store-backed resume paths\n// -----------------------------------------------------------------------\n\n/**\n * Write the interrupt response into the stored session, then call `run`.\n *\n * - `NoInterruptError` rejects (the session is not paused on that interrupt)\n * - any other inject failure → `onStoreError(StoreLoadError, 'claim')`, resolves `$error`; `run` not called\n */\nexport async function injectThenRun(args: {\n readonly store: SessionStore\n readonly agentId: string\n readonly sessionId: string\n readonly interruptId: string\n readonly response: unknown\n readonly onStoreError?: SessionRunOptions['onStoreError']\n readonly failState: () => Record<string, unknown>\n readonly run: () => Promise<RunOutcome>\n}): Promise<RunOutcome> {\n const { store, agentId, sessionId, interruptId, response, onStoreError, failState, run } = args\n try {\n await injectInterruptResponse(store, agentId, sessionId, interruptId, response)\n } catch (injectError: unknown) {\n if (injectError instanceof NoInterruptError) throw injectError\n const storeError = new StoreLoadError(injectError)\n onStoreError?.(storeError, 'claim')\n return failOutcome(failState, storeError)\n }\n return run()\n}\n","/**\n * The resolved value of a {@link RunHandle} promise: the final state and the\n * signal that caused the loop to exit.\n *\n * `signal` is `null` when the loop exited via `.end()` without an explicit signal,\n * `'$interrupt'` when paused on an interrupt, or any custom signal string returned\n * by a route function.\n */\nexport interface RunOutcome {\n readonly state: Record<string, unknown>\n readonly signal: string | null\n}\n\n/**\n * Handle returned synchronously by {@link Agent.run} and {@link Agent.resume}.\n *\n * Implements `PromiseLike<RunOutcome>` so it can be `await`-ed directly.\n *\n * @example\n * ```ts\n * const handle = agent.run({}, { llm })\n * console.log(handle.sessionId) // available immediately\n * const { state, signal } = await handle\n * ```\n */\nexport interface RunHandle extends PromiseLike<RunOutcome> {\n /** Cancel the in-flight run at the next safe point between steps. Idempotent. */\n stop(): void\n\n /**\n * Provide a response to a pending `ctx.interrupt()` call and start a new run.\n * Returns a new {@link RunHandle} for the resumed execution.\n *\n * Throws {@link NoInterruptError} when the run has not settled on `signal: '$interrupt'`.\n *\n * @param response - The value to deliver as the interrupt response.\n * @param interruptId - The `interruptId` from `state.$interrupt`.\n */\n resume(response: unknown, interruptId: string): RunHandle\n\n /** The session identity for this run. */\n readonly sessionId: string\n\n /**\n * Unique identifier for this specific invocation.\n * One UUID per `agent.run()` or `agent.resume()` call.\n */\n readonly runId: string\n\n /**\n * The name of the step currently executing in this process.\n * `null` before the first step runs, after execution settles, and always\n * when inspected cross-process.\n */\n readonly currentStep: string | null\n}\n\nimport { NoInterruptError } from './interrupt-resume.js'\n\nexport function createRunHandle(\n sessionId: string,\n runId: string,\n execution: Promise<RunOutcome>,\n stopFlag: { stopped: boolean },\n stepRef: { current: string | null },\n resumeFn?: (response: unknown, interruptId: string) => RunHandle,\n): RunHandle {\n let settledOutcome: RunOutcome | null = null\n\n // NOTE: raw .then(onFulfilled, onRejected) is intentional here — NOT a coding-standards\n // violation. async/await requires wrapping in a new async function, which changes control\n // flow and does not populate `settledOutcome` as a side-effect at resolution time.\n // .then() attaches handlers to an already-running Promise, allowing us to capture the\n // fulfilled RunOutcome into the closure variable synchronously within the callback at the\n // moment of resolution. run.resume() reads settledOutcome synchronously, so this is the\n // only correct pattern; replacing it with async/await would break synchronous access.\n const settled = execution.then(\n (outcome: RunOutcome): RunOutcome => {\n settledOutcome = outcome\n stepRef.current = null\n return outcome\n },\n (err: unknown): RunOutcome => {\n stepRef.current = null\n throw err\n },\n )\n\n const handle: RunHandle = {\n then<TResult1 = RunOutcome, TResult2 = never>(\n onfulfilled?: ((value: RunOutcome) => TResult1 | PromiseLike<TResult1>) | null | undefined,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null | undefined,\n ): Promise<TResult1 | TResult2> {\n return settled.then(onfulfilled, onrejected)\n },\n\n stop(): void {\n stopFlag.stopped = true\n },\n\n resume(response: unknown, interruptId: string): RunHandle {\n // backward-compatibility: 4-arg handle (no resumeFn) + unsettled → old stub error\n if (settledOutcome === null && resumeFn === undefined) {\n throw new Error('not implemented — requires F9')\n }\n if (settledOutcome === null) {\n throw new NoInterruptError()\n }\n if (settledOutcome.signal !== '$interrupt') {\n throw new NoInterruptError()\n }\n if (resumeFn === undefined) {\n throw new NoInterruptError()\n }\n return resumeFn(response, interruptId)\n },\n\n get sessionId(): string {\n return sessionId\n },\n\n get runId(): string {\n return runId\n },\n\n get currentStep(): string | null {\n return stepRef.current\n },\n }\n\n return handle\n}\n","import {\n getInternals,\n type Harness,\n type HarnessInternals,\n type ProviderEntry,\n} from '../harness/harness-builder.js'\nimport { isRequiredMarker, isRuntimeMarker } from '../harness/ctx-markers.js'\nimport type { LoopDefinition } from '../loop/loop-dsl.js'\nimport type { FieldDefinition } from '../harness/state-field.js'\nimport type { SessionPhase, RunCarrier, ClaimOptions } from './session-store.js'\nimport { resolveSessionStore, runWithSession, querySessionPhase, type SessionRunOptions } from './session-lifecycle.js'\nimport { runLoop } from '../loop/loop-executor.js'\nimport type { Cursor } from '../loop/loop-executor.js'\nimport { createRunHandle, type RunHandle, type RunOutcome } from './run-handle.js'\nimport { NoInterruptError, injectInterruptResponseIntoState, injectThenRun } from './interrupt-resume.js'\nimport { SessionInFlightError, SessionPendingInterruptError } from './concurrency-errors.js'\nimport { randomUUID } from 'node:crypto'\nimport { extractRunEvents } from './event-callbacks.js'\nimport { extractRunListeners } from './ctx-emit.js'\nimport type { Observer, ObserverErrorSink, TelemetryContext } from './observer.js'\nimport { initializeState, defaultClaimTtlMs, isValidTtlMs } from './session-store.js'\nimport { runClaimed, parseClaimOptions } from './claim-scope.js'\n\n// -----------------------------------------------------------------------\n// Module-level constants\n// -----------------------------------------------------------------------\n\n/**\n * Pre-filter the provided slots down to the telemetry-aware ones, keyed by their ctx key.\n * The loop installs `ctx[key] = slot.withTelemetry({ observer, stepContext })` per step.\n */\nfunction buildTelemetrySlots(\n entries: Iterable<readonly [string, unknown]>,\n): Array<{ key: string; slot: { withTelemetry(ctx: TelemetryContext): unknown } }> {\n const out: Array<{ key: string; slot: { withTelemetry(ctx: TelemetryContext): unknown } }> = []\n for (const [key, slot] of entries) {\n if (slot !== null && typeof slot === 'object' && typeof (slot as Record<string, unknown>)['withTelemetry'] === 'function') { // as: duck-typed structural check\n out.push({ key, slot: slot as { withTelemetry(ctx: TelemetryContext): unknown } }) // as: narrowed by duck-type check on line above\n }\n }\n return out\n}\n\n// -----------------------------------------------------------------------\n// Module-private helpers\n// -----------------------------------------------------------------------\n\nfunction extractRunObserver(resources: Record<string, unknown>): Observer | undefined {\n const raw = resources['observer']\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined\n return raw as Observer // as: duck-typed plain object confirmed; methods not validated\n}\n\nfunction extractRunErrorSink(resources: Record<string, unknown>): ObserverErrorSink | undefined {\n const raw = resources['onObserverError']\n return typeof raw === 'function' ? (raw as ObserverErrorSink) : undefined // as: duck-typed function confirmed\n}\n\n/** Options passed to createAgent(). */\nexport interface AgentOptions {\n /**\n * Stable identifier for the process or replica running this agent instance.\n * Written to `StoredRun.metadata` on every save and propagated to observers\n * via `RunContext.instanceId`.\n */\n readonly instanceId?: string\n /**\n * Concrete store instances for slots declared with `required()` inside `h.store()`.\n * Keyed by the store key used in the harness (e.g. `{ session: myStore }`).\n */\n readonly stores?: Record<string, unknown>\n /**\n * Default claim options for every run and resume of this agent, used when the call passes none.\n * Resolution: per-call `claimOptions` → this → `HARNESS_CLAIM_TTL_MS` → 30 000 ms.\n * `ttlMs` must be a finite number greater than 0; otherwise `createAgent` throws `InvalidClaimOptionsError`.\n */\n readonly claimOptions?: ClaimOptions\n}\n\n// -----------------------------------------------------------------------\n// Agent — the minimal public object returned by createAgent\n// -----------------------------------------------------------------------\n\nexport interface Agent {\n /** The agent's unique identifier, as provided to createAgent(). */\n readonly id: string\n\n /**\n * Start a run. Returns a RunHandle synchronously before execution begins.\n *\n * Reserved `resources` keys that shape the session:\n * - `sessionId?: string` — the conversation thread; a random UUID when absent\n * - `requestId?: string` — this turn and its idempotency key. With a session store, a call whose\n * `requestId` the session already ran returns that request's current outcome without running\n * it again; without one, every call is a new turn. Ignored when the agent has no session store\n *\n * Both must be non-empty strings when given; otherwise `run` throws `InvalidRunResourceError`.\n */\n run(initialState: Record<string, unknown>, resources: Record<string, unknown>): RunHandle\n\n /**\n * Cross-process entry point for responding to a pending interrupt.\n * Returns a RunHandle synchronously; the execution promise performs the resume.\n *\n * The optional fourth argument `resources` accepts:\n * - `observer?: Observer` — structured telemetry for the resumed run (see Observability)\n * - `parentRunId?: string` — the caller's run id, as for `run()`; set on this resumed run's\n * `RunContext` only (a later `handle.resume()` on the returned handle does not inherit it)\n * - `events?.onStoreError?` — raw store-error callback (unchanged from prior shape)\n * - `claimOptions?: ClaimOptions` — claim TTL for this resume, parsed like `agent.run()`'s; falls back\n * to `AgentOptions.claimOptions`, then `HARNESS_CLAIM_TTL_MS`, then 30 000 ms. A later `handle.resume()`\n * on the returned handle reuses it\n */\n resume(\n response: unknown,\n sessionId: string,\n interruptId: string,\n resources?: Record<string, unknown>,\n ): RunHandle\n\n /**\n * Query the session store for the current phase of a session.\n */\n status(sessionId: string): Promise<SessionPhase>\n}\n\n// -----------------------------------------------------------------------\n// AgentInternals — the resolved internal state\n// -----------------------------------------------------------------------\n\nexport interface AgentInternals {\n readonly agentId: string\n readonly resolvedProviders: ReadonlyMap<string, unknown>\n readonly storeEntries: readonly ProviderEntry[]\n readonly loopDef: LoopDefinition\n readonly stateSchema: Record<string, FieldDefinition<unknown>> | undefined\n /** Keys declared as runtime() in the harness — must be filled in agent.run() resources. */\n readonly runtimeKeys: ReadonlySet<string>\n /** Keys declared as required() in the harness — must NOT appear in agent.run() resources. */\n readonly requiredKeys: ReadonlySet<string>\n}\n\n// -----------------------------------------------------------------------\n// Error classes\n// -----------------------------------------------------------------------\n\n/** Thrown by {@link createAgent} when the harness has no `.loop()` declaration. */\nexport class MissingLoopError extends Error {\n constructor() {\n super('harness has no loop — call h.loop() before createAgent(id, h, slots)')\n this.name = 'MissingLoopError'\n }\n}\n\n/** Thrown by {@link createAgent} when a `required()` slot is absent from `slots`. */\nexport class MissingSlotError extends Error {\n /** The missing slot key. */\n readonly key: string\n\n constructor(key: string) {\n super(`required slot \"${key}\" was not provided in createAgent slots`)\n this.name = 'MissingSlotError'\n this.key = key\n }\n}\n\n/** Thrown by {@link createAgent} when a `runtime()` slot is passed in `slots` instead of `agent.run()`. */\nexport class RuntimeSlotInAgentError extends Error {\n /** The offending slot key. */\n readonly key: string\n\n constructor(key: string) {\n super(`slot \"${key}\" is a runtime() slot — provide it in agent.run(), not createAgent()`)\n this.name = 'RuntimeSlotInAgentError'\n this.key = key\n }\n}\n\n/** Thrown by {@link createAgent} when `slots` contains a key not declared in the harness. */\nexport class UnknownSlotError extends Error {\n /** The unknown slot key. */\n readonly key: string\n\n constructor(key: string) {\n super(`slot \"${key}\" is not declared in the harness — remove it or add h.provide(\"${key}\", required())`)\n this.name = 'UnknownSlotError'\n this.key = key\n }\n}\n\n/** @internal Thrown when `getAgentInternals` is called on a non-agent value. */\nexport class AgentInternalsError extends Error {\n constructor() {\n super('value was not produced by createAgent — cannot read AgentInternals')\n this.name = 'AgentInternalsError'\n }\n}\n\n/** Thrown by {@link Agent.run} when a `runtime()` slot is absent from `resources`. */\nexport class MissingRuntimeSlotError extends Error {\n /** The missing runtime slot key. */\n readonly key: string\n constructor(key: string) {\n super(`runtime slot \"${key}\" was not provided in agent.run() resources`)\n this.name = 'MissingRuntimeSlotError'\n this.key = key\n }\n}\n\n/** Thrown by {@link Agent.run} when a `required()` slot is passed in `resources` instead of `createAgent()`. */\nexport class RequiredSlotInRunError extends Error {\n /** The offending slot key. */\n readonly key: string\n constructor(key: string) {\n super(`slot \"${key}\" is a required() slot — provide it in createAgent(), not agent.run()`)\n this.name = 'RequiredSlotInRunError'\n this.key = key\n }\n}\n\n/** Thrown by {@link Agent.run} when `resources` contains a key that was not declared as `runtime()`. */\nexport class UnknownRunSlotError extends Error {\n /** The unknown resource key. */\n readonly key: string\n constructor(key: string) {\n super(`slot \"${key}\" is not a runtime() slot — do not pass it in agent.run() resources`)\n this.name = 'UnknownRunSlotError'\n this.key = key\n }\n}\n\n/** Thrown by {@link createAgent} when a `required()` store marker has no matching entry in `agentOptions.stores`. */\nexport class MissingStoreSlotError extends Error {\n /** The store key (e.g. `\"session\"`) that was not provided. */\n readonly key: string\n constructor(key: string) {\n super(`required store slot \"${key}\" was not provided in createAgent options.stores`)\n this.name = 'MissingStoreSlotError'\n this.key = key\n }\n}\n\n/** Thrown by {@link createAgent} when `agentOptions.stores` contains a key that is not declared as `required()` in the harness. */\nexport class UnexpectedStoreSlotError extends Error {\n /** The unexpected store key. */\n readonly key: string\n constructor(key: string) {\n super(`store slot \"${key}\" was not declared as required() in the harness — do not pass it in options.stores`)\n this.name = 'UnexpectedStoreSlotError'\n this.key = key\n }\n}\n\nfunction describeValue(value: unknown): string {\n return typeof value === 'string' ? JSON.stringify(value) : String(value)\n}\n\n/** Thrown by {@link createAgent} when `agentOptions.claimOptions.ttlMs` is not a finite number greater than 0. */\nexport class InvalidClaimOptionsError extends Error {\n /** The rejected `ttlMs` value, as given. */\n readonly ttlMs: unknown\n constructor(ttlMs: unknown) {\n super(`claimOptions.ttlMs must be a finite number of milliseconds greater than 0 — got ${describeValue(ttlMs)} in createAgent options`)\n this.name = 'InvalidClaimOptionsError'\n this.ttlMs = ttlMs\n }\n}\n\n/** Thrown by `agent.run()` when `sessionId` or `requestId` is given but is not a non-empty string. */\nexport class InvalidRunResourceError extends Error {\n /** The resource key that was rejected. */\n readonly key: 'sessionId' | 'requestId'\n /** The rejected value, as given. */\n readonly value: unknown\n constructor(key: 'sessionId' | 'requestId', value: unknown) {\n super(`${key} must be a non-empty string — got ${describeValue(value)} in agent.run() resources`)\n this.name = 'InvalidRunResourceError'\n this.key = key\n this.value = value\n }\n}\n\n/** A `sessionId` / `requestId` resource: `undefined` when absent, the string when valid; throws otherwise. */\nfunction readIdResource(resources: Record<string, unknown>, key: 'sessionId' | 'requestId'): string | undefined {\n const value = resources[key]\n if (value === undefined) return undefined\n if (typeof value !== 'string' || value.length === 0) throw new InvalidRunResourceError(key, value)\n return value\n}\n\n// -----------------------------------------------------------------------\n// Module-private symbol for AttachInternals\n// -----------------------------------------------------------------------\n\nconst _agentInternals = Symbol('_agentInternals')\n\ntype AgentWithInternals = Agent & {\n readonly [_agentInternals]: AgentInternals\n}\n\n// -----------------------------------------------------------------------\n// createAgent — the public factory\n// -----------------------------------------------------------------------\n\n/** What a resume run gets besides the response; each key omitted when not given. */\ninterface ResumeResources {\n readonly onStoreError?: (error: unknown, phase: 'load' | 'persist' | 'claim') => void\n readonly observer?: Observer\n readonly onObserverError?: ObserverErrorSink\n readonly telemetrySlots?: ReadonlyArray<{ key: string; slot: { withTelemetry(ctx: TelemetryContext): unknown } }>\n readonly parentRunId?: string\n /** Resolved once by the call that started the resume chain; every link claims with it. */\n readonly claimOptions: ClaimOptions\n}\n\n/**\n * Instantiate an agent from a fully-configured {@link Harness}.\n *\n * Validates that all `required()` slots are present in `slots`, that no\n * `runtime()` slots are passed here, and that the harness has a loop defined.\n *\n * @param id - A stable, human-readable identifier for this agent (used as the\n * first argument to every store operation).\n * @param h - The harness produced by `createHarness()...loop()`.\n * @param slots - Values for every slot declared with `required()` in the harness.\n * @param options - Optional agent-level options (e.g., instanceId).\n *\n * @throws {@link MissingLoopError} when `h.loop()` was never called.\n * @throws {@link MissingSlotError} when a `required()` slot is absent from `slots`.\n * @throws {@link RuntimeSlotInAgentError} when a `runtime()` slot is passed in `slots`.\n * @throws {@link UnknownSlotError} when `slots` contains a key not declared in the harness.\n *\n * @example\n * ```ts\n * const agent = createAgent('my-agent', h, { llm: new Claude('claude-3-5-haiku-20241022') })\n * const handle = agent.run({}, {})\n * const { state, signal } = await handle\n * ```\n */\nexport function createAgent<Ctx, State, Req extends keyof Ctx, Run extends keyof Ctx>(\n id: string,\n h: Harness<Ctx, State, Req, Run>,\n slots: Pick<Ctx, Req>,\n agentOptions?: AgentOptions,\n): Agent {\n // Get harness internals; propagate HarnessInternalsError if h is not a real Harness\n const internals: HarnessInternals<Ctx, State, Req, Run> = getInternals(h)\n\n // Validation 1: loop exists\n if (internals.loopDef === undefined) {\n throw new MissingLoopError()\n }\n\n // Build a map of provider entries with kind 'provide' for slot validation\n const providerMap = new Map<string, ProviderEntry>()\n for (const entry of internals.providers) {\n if (entry.kind === 'provide') {\n providerMap.set(entry.key, entry)\n }\n }\n\n // Validation 2: no unknown keys in slots\n for (const key of Object.keys(slots)) {\n if (!providerMap.has(key)) {\n throw new UnknownSlotError(key)\n }\n }\n\n // Validation 3: no runtime() markers in slots\n for (const key of Object.keys(slots)) {\n const entry = providerMap.get(key)\n if (entry && isRuntimeMarker(entry.value)) {\n throw new RuntimeSlotInAgentError(key)\n }\n }\n\n // Validation 4: all required() slots are provided\n for (const entry of internals.providers) {\n if (entry.kind === 'provide' && isRequiredMarker(entry.value)) {\n if (!(entry.key in slots)) {\n throw new MissingSlotError(entry.key)\n }\n }\n }\n\n // Validation 5: the agent-level claim TTL, if given\n let agentClaimOptions: ClaimOptions | undefined = undefined\n if (agentOptions?.claimOptions !== undefined) {\n const ttlMs = (agentOptions.claimOptions as { ttlMs?: unknown } | null)?.ttlMs // as: untyped callers may pass null\n if (!isValidTtlMs(ttlMs)) throw new InvalidClaimOptionsError(ttlMs)\n agentClaimOptions = { ttlMs } // a copy: later changes to the caller's object do not apply\n }\n const fallbackClaimOptions = (): ClaimOptions => agentClaimOptions ?? { ttlMs: defaultClaimTtlMs() }\n\n // Build resolvedProviders map: iterate all providers in order, last-registered-wins\n const resolvedProviders = new Map<string, unknown>()\n const storeEntries: ProviderEntry[] = []\n const runtimeKeys = new Set<string>()\n const requiredKeys = new Set<string>()\n\n for (const entry of internals.providers) {\n if (entry.kind === 'store') {\n storeEntries.push(entry)\n } else if (entry.kind === 'provide') {\n if (isRequiredMarker(entry.value)) {\n // Replace required() marker with the slot value\n resolvedProviders.set(entry.key, (slots as Record<string, unknown>)[entry.key]) // as: Req extends keyof Ctx erases to plain index at runtime\n requiredKeys.add(entry.key)\n } else if (isRuntimeMarker(entry.value)) {\n runtimeKeys.add(entry.key)\n // runtime() markers are not included in resolvedProviders\n } else {\n // Concrete value: include as-is\n resolvedProviders.set(entry.key, entry.value)\n }\n }\n }\n\n // Validate the 'session' store slot — the only store key with framework-managed lifecycle.\n // Other store keys (user-defined, future ctx.store.<name>) are not processed here.\n let sessionIsRequired = false\n for (const entry of storeEntries) {\n const storeValue = entry.value\n if (storeValue === null || typeof storeValue !== 'object') continue\n const storeRec = storeValue as Record<string, unknown> // as: same narrowing as resolveSessionStore\n if ('session' in storeRec && isRequiredMarker(storeRec['session'])) {\n sessionIsRequired = true // last-registered store entry wins, consistent with resolveSessionStore\n }\n }\n const sessionStoreOverride = agentOptions?.stores?.['session']\n const storeOverrides: Record<string, unknown> = {}\n if (sessionIsRequired) {\n if (sessionStoreOverride === undefined) throw new MissingStoreSlotError('session')\n storeOverrides['session'] = sessionStoreOverride\n } else if (sessionStoreOverride !== undefined) {\n throw new UnexpectedStoreSlotError('session')\n }\n\n // Resolve session store from store entries at construction time\n const capturedStore = resolveSessionStore(\n storeEntries,\n Object.keys(storeOverrides).length > 0 ? storeOverrides : undefined,\n )\n\n // Construct AgentInternals\n const agentInternals: AgentInternals = {\n agentId: id,\n resolvedProviders,\n storeEntries,\n loopDef: internals.loopDef, // Guaranteed to be non-undefined by validation 1\n stateSchema: internals.stateSchema,\n runtimeKeys,\n requiredKeys,\n }\n\n // Reserved keys are skipped during agent.run() resource validation\n const reservedRunKeys = new Set(['sessionId', 'requestId', 'signal', 'events', 'listeners', 'observer', 'onObserverError', 'claimOptions', 'parentRunId'])\n\n // one per agent instance; tracks all session IDs currently executing\n const inFlightSessions = new Set<string>()\n\n // one per agent instance; tracks session IDs paused on an unanswered interrupt, only when there is no\n // session store (with a store, the stored row decides). Cleared when agent.resume() or run.resume() is\n // called; populated when a run settles with signal: \"$interrupt\"\n const interruptPendingSessions = new Set<string>()\n\n // A resume's own initial state is empty; its $error state never carries the original run's initialState\n const resumeFailState = (): Record<string, unknown> => initializeState(null, {}, agentInternals.stateSchema)\n\n // -----------------------------------------------------------------------\n // makeAgentResumeHandle — factory for cross-process resume RunHandles\n // -----------------------------------------------------------------------\n\n const makeAgentResumeHandle = (\n resp: unknown,\n sId: string,\n iId: string,\n resumeResources: ResumeResources,\n ): RunHandle => {\n const { onStoreError, observer, onObserverError, telemetrySlots, parentRunId, claimOptions } = resumeResources\n let _stopped = false\n const abortController = new AbortController()\n const flag = {\n get stopped(): boolean { return _stopped },\n set stopped(v: boolean) { _stopped = v; if (v) abortController.abort() },\n }\n const ref: { current: string | null } = { current: null }\n const rId = randomUUID()\n\n const exec = (async (): Promise<RunOutcome> => {\n await Promise.resolve()\n try {\n return await runClaimed({\n store: capturedStore,\n agentId: id,\n sessionId: sId,\n claimOptions,\n ...(onStoreError !== undefined ? { onStoreError } : {}),\n failState: resumeFailState,\n body: async (lease) => {\n if (capturedStore === undefined) throw new NoInterruptError()\n const store = capturedStore\n return injectThenRun({\n store,\n agentId: id,\n sessionId: sId,\n interruptId: iId,\n response: resp,\n ...(onStoreError !== undefined ? { onStoreError } : {}),\n failState: resumeFailState,\n run: async () => {\n const agentCtx: Record<string, unknown> & { readonly agentId: string; readonly sessionId: string; readonly runId: string; readonly signal: AbortSignal } = {\n ...Object.fromEntries(agentInternals.resolvedProviders),\n agentId: id,\n sessionId: sId,\n runId: rId,\n signal: abortController.signal,\n ...(agentOptions?.instanceId !== undefined ? { instanceId: agentOptions.instanceId } : {}),\n }\n const r = await runWithSession(\n store,\n id,\n sId,\n rId,\n agentInternals.loopDef,\n {},\n agentInternals.stateSchema,\n agentCtx,\n {\n mode: 'resume',\n shouldStop: () => flag.stopped,\n onBeforeStep: (n: string) => { ref.current = n },\n ...(onStoreError !== undefined ? { onStoreError } : {}),\n ...lease,\n ...(observer !== undefined ? { observer } : {}),\n ...(onObserverError !== undefined ? { onObserverError } : {}),\n ...(telemetrySlots !== undefined && telemetrySlots.length > 0 ? { telemetrySlots } : {}),\n ...(agentOptions?.instanceId !== undefined ? { instanceId: agentOptions.instanceId } : {}),\n ...(parentRunId !== undefined ? { parentRunId } : {}),\n },\n )\n return { state: r.state, signal: r.signal }\n },\n })\n },\n })\n } finally {\n inFlightSessions.delete(sId)\n }\n })()\n\n const resumeFn = (r: unknown, i: string): RunHandle => {\n // Synchronous fence — same invariant as agent.resume()\n if (inFlightSessions.has(sId)) throw new SessionInFlightError(sId)\n interruptPendingSessions.delete(sId)\n inFlightSessions.add(sId)\n // Same resources as this resume, except parentRunId: the caller's run id is stale by now.\n const { parentRunId: _staleParentRunId, ...inherited } = resumeResources\n return makeAgentResumeHandle(r, sId, i, inherited)\n }\n return createRunHandle(sId, rId, exec, flag, ref, resumeFn)\n }\n\n // Create and return Agent with attached internals\n const agent: AgentWithInternals = {\n id,\n run: (initialState: Record<string, unknown>, resources: Record<string, unknown>): RunHandle => {\n // Validation pass 1: unknown keys (not reserved, not runtime, not required)\n for (const key of Object.keys(resources)) {\n if (reservedRunKeys.has(key)) continue\n if (!agentInternals.runtimeKeys.has(key) && !agentInternals.requiredKeys.has(key)) {\n throw new UnknownRunSlotError(key)\n }\n }\n\n // Validation pass 2: required() keys passed in resources\n for (const key of Object.keys(resources)) {\n if (reservedRunKeys.has(key)) continue\n if (agentInternals.requiredKeys.has(key)) {\n throw new RequiredSlotInRunError(key)\n }\n }\n\n // Validation pass 3: missing runtime() keys\n for (const key of agentInternals.runtimeKeys) {\n if (!(key in resources)) {\n throw new MissingRuntimeSlotError(key)\n }\n }\n\n // Session and request IDs — validated before the in-flight fence, so a bad value never holds it\n const sessionId = readIdResource(resources, 'sessionId') ?? randomUUID()\n const requestId = readIdResource(resources, 'requestId')\n\n // Run ID — unique per agent.run() invocation, available synchronously on RunHandle\n const runId = randomUUID()\n\n // Synchronous concurrency fences — must precede any await (per docs/agent.md Concurrency section)\n if (inFlightSessions.has(sessionId)) throw new SessionInFlightError(sessionId)\n if (capturedStore === undefined && interruptPendingSessions.has(sessionId)) throw new SessionPendingInterruptError(sessionId)\n inFlightSessions.add(sessionId)\n\n // AbortSignal and stop-flag wiring\n let _stopped = false\n const abortController = new AbortController()\n const stopFlag = {\n get stopped(): boolean { return _stopped },\n set stopped(v: boolean) { _stopped = v; if (v) abortController.abort() },\n }\n const rawSignal = resources['signal']\n let ctxSignal: AbortSignal = abortController.signal\n if (rawSignal instanceof AbortSignal) {\n ctxSignal = rawSignal\n rawSignal.addEventListener('abort', () => { stopFlag.stopped = true; abortController.abort() }, { once: true })\n if (rawSignal.aborted) stopFlag.stopped = true\n }\n\n // Fresh stepRef per call for currentStep tracking\n const stepRef: { current: string | null } = { current: null }\n\n // Assemble ctx: resolvedProviders merged with runtime slots and sessionId, runId, and signal\n const runtimeSlots: Record<string, unknown> = {}\n for (const key of agentInternals.runtimeKeys) {\n if (reservedRunKeys.has(key)) continue // reserved keys are consumed by framework, not injected into ctx\n runtimeSlots[key] = resources[key]\n }\n const ctx: Record<string, unknown> & { readonly agentId: string; readonly sessionId: string; readonly runId: string; readonly signal: AbortSignal } = {\n ...Object.fromEntries(agentInternals.resolvedProviders),\n ...runtimeSlots,\n agentId: id,\n sessionId,\n runId,\n signal: ctxSignal,\n ...(agentOptions?.instanceId !== undefined ? { instanceId: agentOptions.instanceId } : {}),\n }\n\n // Extract event callbacks and listeners from resources (reserved keys)\n const events = extractRunEvents(resources)\n const listeners = extractRunListeners(resources)\n\n const observer = extractRunObserver(resources)\n const onObserverError = extractRunErrorSink(resources)\n // Pre-filter telemetry-aware slots (keyed). The loop installs a per-step scoped view\n // of each at ctx[key] before step.run. resolvedProviders first, runtimeSlots second,\n // so a runtime slot wins the same key — matching ctx assembly order.\n const telemetrySlots = buildTelemetrySlots([\n ...agentInternals.resolvedProviders.entries(),\n ...Object.entries(runtimeSlots),\n ])\n\n // Extract parentRunId from resources (reserved key)\n const parentRunId =\n typeof resources['parentRunId'] === 'string' ? resources['parentRunId'] : undefined\n\n // Resolved once here so every handle.resume() on this run claims with the same TTL\n const claimOptions = parseClaimOptions(resources['claimOptions'], fallbackClaimOptions())\n\n const options: SessionRunOptions = {\n mode: 'run',\n ...(requestId !== undefined ? { requestId } : {}),\n shouldStop: () => stopFlag.stopped,\n onBeforeStep: (name: string, state: Record<string, unknown>) => {\n stepRef.current = name\n events.onBeforeStep?.(name, state)\n },\n // spread optional event callbacks only when defined (exactOptionalPropertyTypes requires omission, not undefined)\n ...(events.onStoreError !== undefined ? { onStoreError: events.onStoreError } : {}),\n ...(events.onAfterStep !== undefined ? { onAfterStep: events.onAfterStep } : {}),\n ...(events.onError !== undefined ? { onError: events.onError } : {}),\n ...(events.onComplete !== undefined ? { onComplete: events.onComplete } : {}),\n ...(events.onInterrupt !== undefined ? { onInterrupt: events.onInterrupt } : {}),\n ...(Object.keys(listeners).length > 0 ? { listeners } : {}),\n ...(observer !== undefined ? { observer } : {}),\n ...(onObserverError !== undefined ? { onObserverError } : {}),\n ...(agentOptions?.instanceId !== undefined ? { instanceId: agentOptions.instanceId } : {}),\n ...(parentRunId !== undefined ? { parentRunId } : {}),\n ...(telemetrySlots.length > 0 ? { telemetrySlots } : {}),\n }\n\n // lastResult captures the LoopResult for same-process in-memory resume chaining\n let lastResult: { state: Record<string, unknown>; cursor: Cursor | null; runId: string; carrier?: RunCarrier } | null = null\n\n // Launch execution asynchronously — agent.run() returns before any async work begins\n const execution = (async (): Promise<RunOutcome> => {\n // Yield so agent.run() can return the RunHandle before any loop iteration starts\n await Promise.resolve()\n\n try {\n return await runClaimed({\n store: capturedStore,\n agentId: id,\n sessionId,\n claimOptions,\n ...(events.onStoreError !== undefined ? { onStoreError: events.onStoreError } : {}),\n failState: () => initializeState(null, initialState, agentInternals.stateSchema),\n body: async (lease) => {\n const r = await runWithSession(\n capturedStore,\n id,\n sessionId,\n runId,\n agentInternals.loopDef,\n initialState,\n agentInternals.stateSchema,\n ctx,\n { ...options, ...lease },\n )\n if (capturedStore === undefined && r.signal === '$interrupt') interruptPendingSessions.add(sessionId)\n lastResult = { state: r.state, cursor: r.cursor, runId, ...(r.carrier !== undefined ? { carrier: r.carrier } : {}) }\n return { state: r.state, signal: r.signal }\n },\n })\n } finally {\n inFlightSessions.delete(sessionId)\n }\n })()\n\n // buildResumeFn — creates a recursive resumeFn for same-process chaining via run.resume()\n const buildResumeFn = (): ((response: unknown, interruptId: string) => RunHandle) => {\n return (response: unknown, interruptId: string): RunHandle => {\n // Synchronous fence — same invariant as agent.run()\n if (inFlightSessions.has(sessionId)) throw new SessionInFlightError(sessionId)\n interruptPendingSessions.delete(sessionId)\n inFlightSessions.add(sessionId)\n\n let _resumeStopped = false\n const resumeAbortController = new AbortController()\n const resumeStopFlag = {\n get stopped(): boolean { return _resumeStopped },\n set stopped(v: boolean) { _resumeStopped = v; if (v) resumeAbortController.abort() },\n }\n const resumeStepRef: { current: string | null } = { current: null }\n const resumeRunId = randomUUID()\n\n const resumeExecution = (async (): Promise<RunOutcome> => {\n await Promise.resolve()\n try {\n // Create a new ctx for this resume invocation with updated runId and signal\n const resumeCtx: Record<string, unknown> & { readonly agentId: string; readonly sessionId: string; readonly runId: string; readonly signal: AbortSignal } = {\n ...ctx,\n runId: resumeRunId,\n signal: resumeAbortController.signal,\n }\n\n if (capturedStore !== undefined) {\n // Store-backed path: claim, inject the response, reload and re-run, release\n const store = capturedStore\n const onStoreError = events.onStoreError\n return await runClaimed({\n store,\n agentId: id,\n sessionId,\n claimOptions,\n ...(onStoreError !== undefined ? { onStoreError } : {}),\n failState: resumeFailState,\n body: (lease) => injectThenRun({\n store,\n agentId: id,\n sessionId,\n interruptId,\n response,\n ...(onStoreError !== undefined ? { onStoreError } : {}),\n failState: resumeFailState,\n run: async () => {\n const r = await runWithSession(\n store,\n id,\n sessionId,\n resumeRunId,\n agentInternals.loopDef,\n {},\n agentInternals.stateSchema,\n resumeCtx,\n {\n mode: 'resume',\n shouldStop: () => resumeStopFlag.stopped,\n onBeforeStep: (n: string, s: Record<string, unknown>) => {\n resumeStepRef.current = n\n events.onBeforeStep?.(n, s)\n },\n // spread optional event callbacks only when defined (exactOptionalPropertyTypes requires omission, not undefined)\n ...(events.onStoreError !== undefined ? { onStoreError: events.onStoreError } : {}),\n ...(events.onAfterStep !== undefined ? { onAfterStep: events.onAfterStep } : {}),\n ...(events.onError !== undefined ? { onError: events.onError } : {}),\n ...(events.onComplete !== undefined ? { onComplete: events.onComplete } : {}),\n ...(events.onInterrupt !== undefined ? { onInterrupt: events.onInterrupt } : {}),\n ...(Object.keys(listeners).length > 0 ? { listeners } : {}),\n ...(observer !== undefined ? { observer } : {}),\n ...(onObserverError !== undefined ? { onObserverError } : {}),\n ...(telemetrySlots.length > 0 ? { telemetrySlots } : {}),\n ...(agentOptions?.instanceId !== undefined ? { instanceId: agentOptions.instanceId } : {}),\n ...lease,\n },\n )\n lastResult = { state: r.state, cursor: r.cursor, runId: resumeRunId, ...(r.carrier !== undefined ? { carrier: r.carrier } : {}) }\n return { state: r.state, signal: r.signal }\n },\n }),\n })\n }\n\n // Same-process in-memory path: locate the pending interrupt (top-level, or\n // inside a paused fork branch) and re-run from cursor.\n const prev = lastResult\n if (prev === null) throw new NoInterruptError()\n const injected = injectInterruptResponseIntoState(prev.cursor ?? undefined, prev.state, interruptId, response)\n if (!injected.found) throw new NoInterruptError()\n const state = injected.state\n const cursor = injected.cursor\n const r = await runLoop(\n agentInternals.loopDef,\n state,\n resumeCtx,\n agentInternals.stateSchema,\n () => resumeStopFlag.stopped,\n cursor,\n {\n runId: resumeRunId,\n resumedFrom: { runId: prev.runId, ...(prev.carrier !== undefined ? { carrier: prev.carrier } : {}) },\n onBeforeStep: (n: string, s: Record<string, unknown>) => {\n resumeStepRef.current = n\n events.onBeforeStep?.(n, s)\n },\n ...(events.onAfterStep !== undefined ? { onAfterStep: events.onAfterStep } : {}),\n ...(events.onError !== undefined ? { onError: events.onError } : {}),\n ...(events.onComplete !== undefined ? { onComplete: events.onComplete } : {}),\n ...(events.onInterrupt !== undefined ? { onInterrupt: events.onInterrupt } : {}),\n ...(Object.keys(listeners).length > 0 ? { listeners } : {}),\n ...(observer !== undefined ? { observer } : {}),\n ...(onObserverError !== undefined ? { onObserverError } : {}),\n ...(telemetrySlots.length > 0 ? { telemetrySlots } : {}),\n },\n )\n if (r.signal === '$interrupt') interruptPendingSessions.add(sessionId)\n lastResult = { state: r.state, cursor: r.cursor, runId: resumeRunId, ...(r.carrier !== undefined ? { carrier: r.carrier } : {}) }\n return { state: r.state, signal: r.signal }\n } finally {\n inFlightSessions.delete(sessionId)\n }\n })()\n\n return createRunHandle(sessionId, resumeRunId, resumeExecution, resumeStopFlag, resumeStepRef, buildResumeFn())\n }\n }\n\n return createRunHandle(sessionId, runId, execution, stopFlag, stepRef, buildResumeFn())\n },\n\n resume: (\n response: unknown,\n sessionId: string,\n interruptId: string,\n resources?: Record<string, unknown>,\n ): RunHandle => {\n // SessionInFlightError fence is first — before any extraction or binding (Invariant 3)\n if (inFlightSessions.has(sessionId)) throw new SessionInFlightError(sessionId)\n interruptPendingSessions.delete(sessionId)\n inFlightSessions.add(sessionId)\n const events = extractRunEvents(resources ?? {})\n const observer = extractRunObserver(resources ?? {})\n const onObserverError = extractRunErrorSink(resources ?? {})\n // Build telemetrySlots from resolvedProviders only (no runtime slots in resume path)\n const telemetrySlots = buildTelemetrySlots(agentInternals.resolvedProviders.entries())\n const parentRunId = resources?.['parentRunId']\n const claimOptions = parseClaimOptions(resources?.['claimOptions'], fallbackClaimOptions())\n return makeAgentResumeHandle(response, sessionId, interruptId, {\n claimOptions,\n ...(events.onStoreError !== undefined ? { onStoreError: events.onStoreError } : {}),\n ...(observer !== undefined ? { observer } : {}),\n ...(onObserverError !== undefined ? { onObserverError } : {}),\n ...(telemetrySlots.length > 0 ? { telemetrySlots } : {}),\n ...(typeof parentRunId === 'string' ? { parentRunId } : {}),\n })\n },\n\n status: (sessionId: string) => querySessionPhase(capturedStore, id, sessionId),\n [_agentInternals]: agentInternals,\n }\n\n return agent\n}\n\n// -----------------------------------------------------------------------\n// getAgentInternals — accessor for AgentInternals\n// -----------------------------------------------------------------------\n\nexport function getAgentInternals(agent: Agent): AgentInternals {\n if (agent === null || typeof agent !== 'object' || !(_agentInternals in agent)) {\n throw new AgentInternalsError()\n }\n return (agent as AgentWithInternals)[_agentInternals] // as: _agentInternals in agent guard above guarantees the symbol key is present\n}\n","/**\n * Framework-fired event callbacks for a single agent.run() invocation.\n * All fields are optional — omit any you do not need.\n * Callbacks are fire-and-forget; their return value is ignored.\n * Scoped to the run — released when the run settles.\n *\n * Note: user-emitted events (formerly onLlmCall etc.) are replaced by\n * ctx.emit(name, payload) + the 'listeners' resource key. See agent.md.\n */\nexport interface RunEvents {\n /** Called just before a step's run function is invoked. */\n onBeforeStep?: (name: string, state: Record<string, unknown>) => void\n /** Called just after a step's run function completes successfully (state update applied). */\n onAfterStep?: (name: string, state: Record<string, unknown>) => void\n /**\n * Called when the loop exits normally via .on(signal).end().\n * Not called for paused outcomes (stop, abort, error, interrupt).\n */\n onComplete?: (state: Record<string, unknown>, signal: string) => void\n /**\n * Called immediately when a step's run throws a non-interrupt error, before error routing.\n * Fires regardless of how the error is ultimately handled. Does not affect routing or state.\n */\n onError?: (error: unknown, stepName: string) => void\n /**\n * Called when ctx.interrupt() pauses the run (i.e. when isInterruptPause is true).\n * Fires with the prompt and interruptId from the InterruptPause exception, before the\n * run resolves with signal: \"$interrupt\".\n */\n onInterrupt?: (prompt: unknown, interruptId: string) => void\n /**\n * Called if the session store fails at load, persist, or claim phase.\n * phase: 'load' — store failed at run start (run never executed).\n * phase: 'persist' — store failed at run end (run completed but state not saved).\n * phase: 'claim' — store.claim() returned null (busy) or threw (network error).\n */\n onStoreError?: (error: unknown, phase: 'load' | 'persist' | 'claim') => void\n}\n\n/**\n * Extract and validate the events object from agent.run() resources.\n * Returns an empty RunEvents if no events key is present.\n */\nexport function extractRunEvents(resources: Record<string, unknown>): RunEvents {\n const raw = resources['events']\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n return {}\n }\n // plain object: return as-is; callbacks are optional and missing keys are undefined\n return raw as RunEvents // as: duck-typed plain object confirmed above; RunEvents fields are all optional\n}\n"],"mappings":";AAoDO,SAAS,MAAS,SAA+C;AACtE,SAAO,EAAE,GA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