@statelyai/agent 2.0.0-alpha.17 → 2.0.0-alpha.19

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.
Files changed (38) hide show
  1. package/dist/ai-sdk.cjs +4 -2
  2. package/dist/ai-sdk.d.cts +1 -1
  3. package/dist/ai-sdk.d.mts +1 -1
  4. package/dist/ai-sdk.mjs +3 -2
  5. package/dist/{decision-C11xuud2.mjs → decision-DsIkEuHz.mjs} +48 -28
  6. package/dist/{decision-DnQCQPew.cjs → decision-t26zsnSR.cjs} +64 -43
  7. package/dist/{event-log-store-CQJq8_v4.d.cts → event-log-store-Bz7HDBkE.d.cts} +11 -12
  8. package/dist/{event-log-store-B-1fcfkT.mjs → event-log-store-DmIDosD6.mjs} +22 -14
  9. package/dist/{event-log-store-yquOV1TX.cjs → event-log-store-a_TKy1gk.cjs} +22 -14
  10. package/dist/{event-log-store-BrC9Q1xW.d.mts → event-log-store-hrA1vqtN.d.mts} +11 -12
  11. package/dist/index.cjs +266 -109
  12. package/dist/index.d.cts +148 -80
  13. package/dist/index.d.mts +148 -80
  14. package/dist/index.mjs +262 -107
  15. package/dist/machines.cjs +13 -17
  16. package/dist/machines.d.cts +14 -17
  17. package/dist/machines.d.mts +14 -17
  18. package/dist/machines.mjs +13 -17
  19. package/dist/otel.cjs +1 -0
  20. package/dist/otel.d.cts +1 -1
  21. package/dist/otel.d.mts +1 -1
  22. package/dist/{run-agent-BxjGaVpL.d.cts → run-agent--4bbms-D.d.cts} +121 -48
  23. package/dist/{run-agent-COHoCgQd.d.mts → run-agent-CwmzAZwj.d.mts} +121 -48
  24. package/dist/{setup-agent-D_EyJ0Ik.cjs → setup-agent-BFA4VKpN.cjs} +51 -33
  25. package/dist/{setup-agent-CTg57Pa4.mjs → setup-agent-CPFPN06s.mjs} +45 -28
  26. package/dist/sqlite.cjs +3 -9
  27. package/dist/sqlite.d.cts +1 -1
  28. package/dist/sqlite.d.mts +1 -1
  29. package/dist/sqlite.mjs +3 -9
  30. package/dist/{text-logic-BFX5q7fM.d.cts → text-logic-Cavva1W6.d.cts} +25 -9
  31. package/dist/{text-logic-DQW8_DWW.d.mts → text-logic-Er5KkTX6.d.mts} +25 -9
  32. package/dist/validate.cjs +436 -0
  33. package/dist/validate.d.cts +31 -0
  34. package/dist/validate.d.mts +31 -0
  35. package/dist/validate.mjs +411 -0
  36. package/package.json +15 -1
  37. package/schemas/agent-workflow.json +2 -2
  38. package/skills/generate-machine/SKILL.md +12 -14
package/dist/index.d.cts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { C as ToolResultPart, S as ToolMessage, T as WithAgentInputSchema, _ as NormalizedEventSchemas, a as AgentToolChoice, b as TextPart, c as AgentTools, d as ChosenEvent, f as EventUnion, g as InferOutput, h as InferInput, i as AgentTool, l as AllowedEvents, m as ImagePart, n as AgentMessage, o as AgentToolDescriptor, p as FilePart, r as AgentSnapshotStore, s as AgentToolExecute, t as AgentEventSchemaInputMap, u as AssistantMessage, v as StandardSchemaV1, w as UserMessage, x as ToolCallPart, y as SystemMessage } from "./types-pJ5Hn8fv.cjs";
2
2
  import { t as AgentError } from "./errors-BQRk9eiZ.cjs";
3
- import { A as AgentDecisionExecutor, B as AgentEventToolNameResolver, C as buildEnvelopeSchema, D as parseModelRef, E as getCallUsage, F as DecisionLogicConfig, H as AgentRequestSource, I as ResolveDecisionOptions, L as renderDecisionAttempts, M as AgentDecisionInput, N as AgentDecisionRequest, O as parseOutput, P as DecisionAttempt, R as resolveDecision, S as bindRequestExecutor, T as getAgentOutputMode, U as getAcceptedEvents, V as AgentRequestOptions, W as parseAgentEvent, _ as StructuredOutputEnvelope, a as AgentOutputMode, b as TextLogicExecuteArgs, c as AgentRequestExecutorResult, d as AgentTextRequest, f as AgentUsage, g as BuiltinAgentActors, h as AiSdkShapedTextResult, i as AgentModelRef, j as AgentDecisionExhaustedError, k as parseStructuredEnvelope, l as AgentRequestExecutors, m as AiSdkShapedStreamResult, n as AgentExecutorTextRequest, o as AgentRequestExecutor, p as AgentUserInput, r as AgentModelMap, s as AgentRequestExecutorInfo, t as AgentCallUsage, u as AgentRequestMode, v as TextLogic, w as createTextLogic, x as TextLogicExecutor, y as TextLogicConfig, z as AgentEventDescriptor } from "./text-logic-BFX5q7fM.cjs";
4
- import { a as AgentLogVerification, c as assertAgentLogEntry, d as assertEventLogStoreConformance, i as AgentLogEntry, l as assertJsonSerializable, n as AgentEventLogConflictError, o as JsonValue, r as AgentEventLogStore, s as NonSerializableAgentEventError, t as AGENT_EVENT_SCHEMA_VERSION, u as createInMemoryEventLogStore } from "./event-log-store-CQJq8_v4.cjs";
5
- import { A as AgentEffect, B as ReplayResult, C as traceTransitions, D as executeAgentRequest, E as AgentStepRequest, F as AgentReplayMachineMismatchError, G as replay, H as diffEventLogs, I as AgentUsageEvent, K as verifyReplay, L as CreateReplayEntryOptions, M as AgentEventLogDiff, N as AgentLogPatchOperation, O as AGENT_INIT_EVENT_TYPE, P as AgentReplayDivergenceError, R as GetAgentEffectsOptions, S as serializeTraceEvent, T as AgentRequest, U as getAgentEffects, V as createReplayEntry, W as initEntry, _ as RunAgentResult, a as AgentInputFrom, b as inspectTransitions, c as AgentSnapshotVersionMismatchError, d as GenerateResult, f as InspectedActorRef, g as RunAgentOptions, h as RunAgentErrorCause, i as AgentIllegalResumeEventError, j as AgentEffectDiff, k as AGENT_USAGE_EVENT_TYPE, l as AgentTraceEvent, m as PendingUserInput, n as AgentActorSession, o as AgentMessageInfo, p as JsonSerializableTraceEvent, r as AgentIdleError, s as AgentRunMeta, t as AGENT_TRACE_SCHEMA_VERSION, u as AgentUserInputExecutor, v as createAgentActor, w as AgentStateRequest, x as runAgent, y as generateResult, z as ReplayOptions } from "./run-agent-BxjGaVpL.cjs";
3
+ import { A as AgentDecisionExecutor, B as AgentEventToolNameResolver, C as buildEnvelopeSchema, D as parseModelRef, E as getCallUsage, F as DecisionLogicConfig, G as parseAgentEvent, H as AgentRequestSource, I as ResolveDecisionOptions, L as renderDecisionAttempts, M as AgentDecisionInput, N as AgentDecisionRequest, O as parseOutput, P as DecisionAttempt, R as resolveDecision, S as bindRequestExecutor, T as getAgentOutputMode, U as AgentSchemas, V as AgentRequestOptions, W as getAcceptedEvents, _ as StructuredOutputEnvelope, a as AgentOutputMode, b as TextLogicExecuteArgs, c as AgentRequestExecutorResult, d as AgentTextRequest, f as AgentUsage, g as BuiltinAgentActors, h as AiSdkShapedTextResult, i as AgentModelRef, j as AgentDecisionExhaustedError, k as parseStructuredEnvelope, l as AgentRequestExecutors, m as AiSdkShapedStreamResult, n as AgentExecutorTextRequest, o as AgentRequestExecutor, p as AgentUserInput, r as AgentModelMap, s as AgentRequestExecutorInfo, t as AgentCallUsage, u as AgentRequestMode, v as TextLogic, w as createTextLogic, x as TextLogicExecutor, y as TextLogicConfig, z as AgentEventDescriptor } from "./text-logic-Cavva1W6.cjs";
4
+ import { a as AgentLogVerification, c as assertAgentLogEntry, d as assertEventLogStoreConformance, i as AgentLogEntry, l as assertJsonSerializable, n as AgentEventLogConflictError, o as JsonValue, r as AgentEventLogStore, s as NonSerializableAgentEventError, t as AGENT_EVENT_SCHEMA_VERSION, u as createInMemoryEventLogStore } from "./event-log-store-Bz7HDBkE.cjs";
5
+ import { A as AgentRequest, B as AgentReplayMachineMismatchError, C as getSnapshotNodes, D as serializeTraceEvent, E as runAgent, F as AgentEffect, G as ReplayResult, H as CreateReplayEntryOptions, I as AgentEffectDiff, J as getAgentEffects, K as createReplayEntry, L as AgentEventLogDiff, M as executeAgentRequest, N as AGENT_INIT_EVENT_TYPE, O as traceTransitions, P as AGENT_USAGE_EVENT_TYPE, R as AgentLogPatchOperation, S as generateResult, T as inspectTransitions, U as GetAgentEffectsOptions, V as AgentUsageEvent, W as ReplayOptions, X as replay, Y as initEntry, _ as PendingUserInput, a as AgentInputFrom, b as RunAgentResult, c as AgentRunMeta, d as AgentTraceEvent, f as AgentUserInputExecutor, g as JsonSerializableTraceEvent, h as InspectedActorRef, i as AgentIllegalResumeEventError, j as AgentStepRequest, k as AgentStateRequest, l as AgentSnapshotNode, m as GetSnapshotRequestsOptions, n as AgentActorSession, o as AgentMaxModelCallsExceededError, p as GenerateResult, q as diffEventLogs, r as AgentIdleError, s as AgentMessageInfo, t as AGENT_TRACE_SCHEMA_VERSION, u as AgentSnapshotVersionMismatchError, v as RunAgentErrorCause, w as getSnapshotRequests, x as createAgentActor, y as RunAgentOptions, z as AgentReplayDivergenceError } from "./run-agent--4bbms-D.cjs";
6
6
  import { AnyActorLogic, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, EventFromLogic, EventObject, InputFrom, MachineContext, MetaObject, NonReducibleUnknown, SetupReturnFromConfig, SetupStateSchema, SnapshotFrom, StateValue } from "xstate";
7
7
 
8
8
  //#region src/messages.d.ts
@@ -99,14 +99,14 @@ interface AgentWorkflowConfig {
99
99
  /**
100
100
  * State tags that mark an INTENTIONAL wait for an external event (a human
101
101
  * approval, an inbound webhook, …) — the declarative form of `setupAgent({
102
- * isSuspended })`, since a config cannot carry a function. Lowered to a
102
+ * isIdle })`, since a config cannot carry a function. Lowered to a
103
103
  * `snapshot.hasTag(...)`-any-of predicate so `runAgent` settles those
104
104
  * snapshots idle deterministically instead of using its timing heuristic.
105
105
  * Every listed tag must appear in some state's `tags` — an unused tag is a
106
- * build-time error. A `fromConfig(config, { isSuspended })` option takes
107
- * precedence; a `runAgent({ isSuspended })` host override beats both.
106
+ * build-time error. A `fromConfig(config, { isIdle })` option takes
107
+ * precedence; a `runAgent({ isIdle })` host override beats both.
108
108
  */
109
- suspendedTags?: string[];
109
+ idleTags?: string[];
110
110
  meta?: Record<string, unknown>;
111
111
  }
112
112
  /** A `requests` entry in {@link AgentWorkflowConfig} — the JSON equivalent of a `setupAgent({ requests })` `TextLogicConfig`. Fields beyond `input`/`output`/`tools`/`mode`/`description` are `unknown` because they accept template-expression strings (see {@link AgentWorkflowConfig}). */
@@ -241,14 +241,14 @@ interface FromConfigOptions {
241
241
  actions?: Record<string, (params: any) => unknown>;
242
242
  /**
243
243
  * Detects a snapshot that is an INTENTIONAL wait for an external event —
244
- * the same machine-carried predicate `setupAgent({ isSuspended })` declares
244
+ * the same machine-carried predicate `setupAgent({ isIdle })` declares
245
245
  * for TS-authored machines, registered here because a function cannot live
246
246
  * in the workflow config itself. Takes precedence over the config's
247
- * declarative {@link AgentWorkflowConfig.suspendedTags}; a
248
- * `runAgent({ isSuspended })` host override beats both. Travels with the
247
+ * declarative {@link AgentWorkflowConfig.idleTags}; a
248
+ * `runAgent({ isIdle })` host override beats both. Travels with the
249
249
  * machine through `machine.provide(...)`.
250
250
  */
251
- isSuspended?: (snapshot: AnyMachineSnapshot) => boolean;
251
+ isIdle?: (snapshot: AnyMachineSnapshot) => boolean;
252
252
  }
253
253
  //#endregion
254
254
  //#region src/setup-agent.d.ts
@@ -412,14 +412,14 @@ type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string,
412
412
  /**
413
413
  * Detects a snapshot that is an INTENTIONAL wait for an external event (a
414
414
  * human approval, an inbound webhook, …) — the machine's own declaration of
415
- * what "suspended" means for it, so `runAgent` settles those snapshots idle
415
+ * what "idle" means for it, so `runAgent` settles those snapshots idle
416
416
  * deterministically instead of using its timing heuristic. Travels with the
417
- * machine through `machine.provide(...)`. A `runAgent({ isSuspended })` host
417
+ * machine through `machine.provide(...)`. A `runAgent({ isIdle })` host
418
418
  * override takes precedence; with neither, `runAgent` falls back to the timing
419
419
  * heuristic. Declare your own signal — e.g. `(s) => s.hasTag('awaiting-review')`
420
420
  * or `(s) => getStateMeta(s).interaction !== undefined`.
421
421
  */
422
- isSuspended?: (snapshot: AnyMachineSnapshot) => boolean;
422
+ isIdle?: (snapshot: AnyMachineSnapshot) => boolean;
423
423
  };
424
424
  type SetupAgentXStateResult<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, AgentSetupStateSchema> = Record<string, AgentSetupStateSchema>> = SetupReturnFromConfig<AgentSetupXStateConfig<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, ResolveAgentStateSchemas<TContextSchema, TStateSchemas>>>;
425
425
  /**
@@ -521,6 +521,18 @@ declare namespace setupAgent {
521
521
  */
522
522
  function fromConfig(config: AgentWorkflowConfig, options: FromConfigOptions): FromConfigResult;
523
523
  }
524
+ /**
525
+ * The schema pack a machine was built with — `setupAgent(...).createMachine`
526
+ * and `setupAgent.fromConfig(...)` both register one, so hosts can read a
527
+ * machine's input/event schemas at runtime without knowing how it was
528
+ * authored. Returns `undefined` for machines not built by either (a plain
529
+ * xstate `createMachine`/`setup` machine).
530
+ *
531
+ * Registration is keyed on the machine object, so a machine returned by
532
+ * `machine.provide(...)` carries no pack — read it from the machine the setup
533
+ * returned.
534
+ */
535
+ declare function getAgentSchemas(machine: AnyStateMachine): AgentSchemas | undefined;
524
536
  //#endregion
525
537
  //#region src/agent-run.d.ts
526
538
  /**
@@ -644,9 +656,12 @@ interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMac
644
656
  * Throws at bind time if a source needs an executor kind that `executors` does
645
657
  * not provide.
646
658
  *
647
- * `provideExecutors` does not descend into invoked child state machines: a string-keyed child
648
- * machine source is left untouched, so a child with its own agent invokes needs
649
- * its own `provideExecutors(...)` (or `runAgent`, which does rebind children).
659
+ * Executor inheritance is RECURSIVE, exactly as in `runAgent`: a string-keyed
660
+ * invoked child machine is rebound too, so its own text/decision requests — at
661
+ * any depth reach the same host executors. A direct-object invoke `src`
662
+ * cannot be swapped via `.provide`, so nothing under one inherits; bind those
663
+ * with `.withExecutor(...)` or register the child as a string-keyed source. A
664
+ * source that already carries its own executor is never overwritten.
650
665
  */
651
666
  declare function provideExecutors<TMachine extends AnyStateMachine>(machine: TMachine, executors: AgentRequestExecutors, options?: ProvideExecutorsOptions<TMachine>): TMachine;
652
667
  //#endregion
@@ -665,10 +680,18 @@ interface AgentLintDiagnostic {
665
680
  path: string;
666
681
  message: string;
667
682
  }
668
- /** Options for {@link lintAgentMachine}. Reserved for future check selection. */
683
+ /** Options for {@link lintAgentMachine}. */
669
684
  interface LintAgentMachineOptions {
670
685
  /** Skip these check codes entirely. */
671
686
  disable?: AgentLintDiagnostic["code"][];
687
+ /**
688
+ * Throw {@link AgentLintError} on failing diagnostics instead of returning
689
+ * them. Fails on error-severity findings; add `warnings: true` to fail on
690
+ * warnings too.
691
+ */
692
+ throw?: boolean;
693
+ /** With `throw: true`, also fail on warning-severity findings. Default: errors only. */
694
+ warnings?: boolean;
672
695
  }
673
696
  /**
674
697
  * Runs static structural checks over a built agent machine and returns the
@@ -681,20 +704,28 @@ interface LintAgentMachineOptions {
681
704
  * call this to catch dead states, undeliverable decisions, un-rebindable
682
705
  * invoke srcs, and output-contract gaps before ever running it.
683
706
  *
707
+ * Pass `{ throw: true }` for the one-liner form used in tests and generation
708
+ * loops: it returns silently when the machine is clean and throws
709
+ * {@link AgentLintError} (findings on `.diagnostics`) on error-severity
710
+ * findings, or on warnings too with `{ throw: true, warnings: true }`.
711
+ *
684
712
  * @example
685
713
  * ```ts
686
714
  * const errors = lintAgentMachine(machine).filter((d) => d.severity === 'error');
687
715
  * if (errors.length) throw new Error(errors.map((e) => `${e.path}: ${e.message}`).join('\n'));
688
716
  * ```
717
+ *
718
+ * @example Throwing form
719
+ * ```ts
720
+ * test('agent machine is structurally sound', () => {
721
+ * lintAgentMachine(machine, { throw: true });
722
+ * });
723
+ * ```
689
724
  */
690
725
  declare function lintAgentMachine(machine: AnyStateMachine, options?: LintAgentMachineOptions): AgentLintDiagnostic[];
691
- /** Options for {@link assertAgentMachine}. */
692
- interface AssertAgentMachineOptions extends LintAgentMachineOptions {
693
- /** Also fail on warning-severity findings. Default: errors only. */
694
- warnings?: boolean;
695
- }
696
726
  /**
697
- * Thrown by {@link assertAgentMachine} when lint finds failing diagnostics.
727
+ * Thrown by `lintAgentMachine(machine, { throw: true })` when lint finds
728
+ * failing diagnostics.
698
729
  * `diagnostics` holds the findings; the message lists them one per finding,
699
730
  * so a test runner's failure output reads like the CLI's lint report.
700
731
  */
@@ -702,20 +733,6 @@ declare class AgentLintError extends AgentError {
702
733
  readonly diagnostics: AgentLintDiagnostic[];
703
734
  constructor(machineId: string, diagnostics: AgentLintDiagnostic[]);
704
735
  }
705
- /**
706
- * Asserts a machine passes {@link lintAgentMachine}: returns silently when
707
- * clean, throws {@link AgentLintError} (with the findings on `.diagnostics`)
708
- * otherwise. Fails on error-severity findings; set `warnings: true` to fail on
709
- * warnings too. The one-liner for tests and generation loops:
710
- *
711
- * @example
712
- * ```ts
713
- * test('agent machine is structurally sound', () => {
714
- * assertAgentMachine(machine);
715
- * });
716
- * ```
717
- */
718
- declare function assertAgentMachine(machine: AnyStateMachine, options?: AssertAgentMachineOptions): void;
719
736
  /**
720
737
  * Scripted responses for a {@link simulateAgent} playthrough. Each channel is a
721
738
  * by-`src` map of FIFO queues, consumed in the order the machine reaches the
@@ -724,13 +741,17 @@ declare function assertAgentMachine(machine: AnyStateMachine, options?: AssertAg
724
741
  * `setupAgent({ requests })` key, or `agent.generateText`/`agent.streamText`).
725
742
  * - `decisions` — the {@link ChosenEvent} to apply for a decision request,
726
743
  * keyed by decision src (usually `agent.decide`).
727
- * - `invokes` — output values for scripted invokes (notably `agent.userInput`,
728
- * and any other actor whose output must be canned), keyed by src.
744
+ * - `invokes` — output values for scripted invokes (any actor whose output must
745
+ * be canned), keyed by src.
746
+ * - `userInput` — a flat FIFO queue of answers for `agent.userInput`, the
747
+ * shorthand for `invokes: { 'agent.userInput': [...] }`. Entries here are
748
+ * consumed before that src's `invokes` queue.
729
749
  */
730
750
  interface SimulationScript {
731
751
  text?: Record<string, unknown[]>;
732
752
  decisions?: Record<string, ChosenEvent[]>;
733
753
  invokes?: Record<string, unknown[]>;
754
+ userInput?: unknown[];
734
755
  }
735
756
  /** One entry in a {@link SimulateAgentResult.trail}: the state after this step, plus what drove the step. */
736
757
  interface SimulationTrailEntry {
@@ -786,8 +807,17 @@ interface ExplorePathsOptions {
786
807
  maxDepth?: number;
787
808
  /** Total path cap before exploration stops (reported via `hitPathCap`). Default 200. */
788
809
  maxPaths?: number;
789
- /** Canned outputs for text/userInput invokes, keyed by src. A missing src halts that branch with a `needs-output` note. */
790
- textOutputs?: Record<string, unknown>;
810
+ /**
811
+ * Canned output for each text request, keyed by src (the
812
+ * `setupAgent({ requests })` key, or `agent.generateText`/`agent.streamText`).
813
+ * One value per src, reused every time that src is reached. A missing src
814
+ * halts that branch with a `needs-output` terminal.
815
+ */
816
+ text?: Record<string, unknown>;
817
+ /** Canned output for scripted invokes, keyed by src. Same one-value-per-src rule as `text`. */
818
+ invokes?: Record<string, unknown>;
819
+ /** Canned output for `agent.userInput`, the shorthand for `invokes['agent.userInput']`. */
820
+ userInput?: unknown;
791
821
  }
792
822
  /** A single explored path's terminal outcome. */
793
823
  interface AgentPathTerminal {
@@ -819,9 +849,10 @@ interface AgentPathReport {
819
849
  * depth, model-free, and reports which states are reached and how each path
820
850
  * terminates. At each decision request it forks one branch per candidate event
821
851
  * (guard-rejected candidates are counted in `prunedByGuard`, not explored); at
822
- * an idle wait it forks per externally-accepted event. Text/`userInput` invokes
823
- * are resolved from `textOutputs` (a by-src canned-output map) — a missing src
824
- * halts that branch with a `needs-output` terminal rather than throwing.
852
+ * an idle wait it forks per externally-accepted event. Text requests resolve
853
+ * from `text`, other invokes from `invokes` (or `userInput` for
854
+ * `agent.userInput`) all by-src canned-output maps, and a missing src halts
855
+ * that branch with a `needs-output` terminal rather than throwing.
825
856
  *
826
857
  * Combinatorics are bounded by `maxDepth` (default 8) and `maxPaths` (default
827
858
  * 200, reported via `hitPathCap`).
@@ -835,19 +866,21 @@ interface AgentPathReport {
835
866
  declare function explorePaths(machine: AnyStateMachine, options?: ExplorePathsOptions): Promise<AgentPathReport>;
836
867
  /** The result of a {@link canReach} query. */
837
868
  interface CanReachResult {
838
- canReach: boolean;
869
+ /** True when the target state was reached within the exploration bounds. */
870
+ reachable: boolean;
839
871
  /** When reachable, the sequence of chosen/applied events that gets there. */
840
872
  witness?: ChosenEvent[];
841
873
  }
842
874
  /**
843
875
  * Answers "can the machine reach `statePath`?" by exploring its branches (a
844
- * thin wrapper over {@link explorePaths}). Returns `{ canReach: true, witness }`
845
- * with the event sequence that reaches it, or `{ canReach: false }`.
876
+ * thin wrapper over {@link explorePaths}). Returns
877
+ * `{ reachable: true, witness }` with the event sequence that reaches it, or
878
+ * `{ reachable: false }`.
846
879
  *
847
880
  * @example
848
881
  * ```ts
849
- * const { canReach, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
850
- * // canReach → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
882
+ * const { reachable, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
883
+ * // reachable → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
851
884
  * ```
852
885
  */
853
886
  declare function canReach(machine: AnyStateMachine, statePath: string, options?: ExplorePathsOptions): Promise<CanReachResult>;
@@ -972,13 +1005,40 @@ type ScriptedDecisionEntry = ScriptedDecisionValue | ((request: AgentDecisionReq
972
1005
  * `{ output, usage }`), wrap it once more: `{ output: { output: '…' } }`.
973
1006
  */
974
1007
  type ScriptedTextEntry = ((request: AgentTextRequest, info?: AgentRequestExecutorInfo) => unknown) | string | number | boolean | null | object;
975
- /** The script {@link createScriptedExecutors} plays back. */
1008
+ /**
1009
+ * One entry in the `userInput` queue: the string the simulated human typed, or
1010
+ * a function of the {@link AgentUserInput} request (its `prompt`/`metadata`)
1011
+ * returning one.
1012
+ */
1013
+ type ScriptedUserInputEntry = string | ((input: AgentUserInput) => string | PromiseLike<string>);
1014
+ /**
1015
+ * The script {@link createScriptedExecutors} plays back.
1016
+ *
1017
+ * The key names match `simulateAgent`'s script (`decisions`, `text`,
1018
+ * `invokes`, `userInput`), but the shapes differ by design: `simulateAgent`
1019
+ * drives the pure step path and keys each channel BY SRC
1020
+ * (`text: { summarize: [...] }`), while these executors sit behind the real
1021
+ * executor contract, where one flat FIFO queue per channel is the ergonomic
1022
+ * form — route per request inside a function entry (`request.name`) when one
1023
+ * script must serve several requests. There is no `invokes` queue here:
1024
+ * non-`userInput` invokes are plain actors, supplied via `actors`.
1025
+ */
976
1026
  interface ScriptedExecutorsScript {
977
1027
  /** Answers for `decide` requests, consumed in order. */
978
1028
  decisions?: ScriptedDecisionEntry[];
979
1029
  /** Answers for text requests, consumed in order. `generateText` and `streamText` share this one queue. */
980
1030
  text?: ScriptedTextEntry[];
1031
+ /** Answers for `agent.userInput` requests, consumed in order. */
1032
+ userInput?: ScriptedUserInputEntry[];
981
1033
  }
1034
+ /**
1035
+ * What {@link createScriptedExecutors} returns: the full executor set, plus a
1036
+ * `userInput` handler for `runAgent`'s own `userInput` option (the builtin
1037
+ * `agent.userInput` actor is not an executor slot).
1038
+ */
1039
+ type ScriptedExecutors = Required<AgentRequestExecutors> & {
1040
+ userInput: (input: AgentUserInput) => Promise<string>;
1041
+ };
982
1042
  /**
983
1043
  * Keyless executors that replay a script instead of calling a model. Every
984
1044
  * slot is provided, so any machine binds; a request with no entry left throws a
@@ -1007,18 +1067,16 @@ interface ScriptedExecutorsScript {
1007
1067
  * decisions: [(request) => ({ type: request.events[0]!.type })],
1008
1068
  * });
1009
1069
  * ```
1070
+ *
1071
+ * @example Scripted human input
1072
+ * ```ts
1073
+ * const scripted = createScriptedExecutors({ userInput: ['ship it'] });
1074
+ * await runAgent(machine, { executors: scripted, userInput: scripted.userInput });
1075
+ * ```
1010
1076
  */
1011
- declare function createScriptedExecutors(script?: ScriptedExecutorsScript): Required<AgentRequestExecutors>;
1077
+ declare function createScriptedExecutors(script?: ScriptedExecutorsScript): ScriptedExecutors;
1012
1078
  //#endregion
1013
1079
  //#region src/utils.d.ts
1014
- /**
1015
- * Deep-clones a snapshot to a plain-JSON value via a `JSON` round-trip, the
1016
- * shape you persist and later feed back to `runAgent({ snapshot })`. Asserts
1017
- * JSON-serializability: functions, `undefined`, and other non-JSON values are
1018
- * dropped or throw exactly as `JSON.stringify`/`JSON.parse` would. Returns a
1019
- * plain-JSON deep clone, not a live snapshot.
1020
- */
1021
- declare function persistSnapshot<TSnapshot>(snapshot: TSnapshot): TSnapshot;
1022
1080
  /**
1023
1081
  * A stable, dependency-free structural fingerprint of a machine — a short hex
1024
1082
  * `djb2` hash over its **structural** config only: state ids/nesting, transition
@@ -1031,7 +1089,7 @@ declare function persistSnapshot<TSnapshot>(snapshot: TSnapshot): TSnapshot;
1031
1089
  * Used by {@link runAgent} to stamp settled snapshots with a `version` and to
1032
1090
  * detect a structurally-edited machine on resume. It is a change detector, not
1033
1091
  * a cryptographic digest — collisions are possible but unlikely for real
1034
- * configs. Pass an explicit `machineVersion` to `runAgent` to override it.
1092
+ * configs. Declare `createMachine({ version })` to pin an explicit version instead.
1035
1093
  */
1036
1094
  declare function getMachineStructuralHash(machine: AnyStateMachine): string;
1037
1095
  /** Builds a {@link UserMessage} from a string or multimodal content parts. */
@@ -1051,8 +1109,15 @@ type MetaOfSnapshot<TSnapshot extends {
1051
1109
  *
1052
1110
  * `snapshot.getMeta()` is keyed by state id; a leaf machine has one active
1053
1111
  * state, but parallel/nested machines can have several. This shallow-merges
1054
- * every active state's meta into one object (later/deeper entries win) and
1055
- * returns `{}` when no active state declares meta.
1112
+ * every active state's meta into one object and returns `{}` when no active
1113
+ * state declares meta.
1114
+ *
1115
+ * Merge order is fixed and does not depend on XState's internal node order:
1116
+ * entries are sorted by structural depth (the state node's distance from the
1117
+ * root, regardless of custom `id` strings), then by state id lexicographically,
1118
+ * and merged in that order. So a deeper state's key wins over an ancestor's,
1119
+ * and between equal-depth parallel siblings the later state id alphabetically
1120
+ * wins.
1056
1121
  *
1057
1122
  * The return type is recovered from the snapshot's own `getMeta()` type, so a
1058
1123
  * schema-typed machine (`setupAgent({ meta })`) yields the meta schema's
@@ -1107,20 +1172,17 @@ declare function getJsonSchemaSync(schema?: StandardSchemaV1): Record<string, un
1107
1172
  //#endregion
1108
1173
  //#region src/seam.d.ts
1109
1174
  /**
1110
- * Which model call is under test: the Nth call addressed either by request
1111
- * `name` (the `setupAgent({ requests })` key or `createTextLogic({ name })`,
1112
- * the better developer handle) or by `model` key (the `defineModels` key) for
1113
- * requests that carry no name.
1175
+ * Which model call is under test: the Nth call with this request `name` (the
1176
+ * `setupAgent({ requests })` key, or `createTextLogic({ name })`). Name the
1177
+ * requests you want to score a seam is a developer-facing handle, not a
1178
+ * model binding, so there is no addressing by model key.
1114
1179
  */
1115
- type SeamRef = {
1116
- /** The request's registered `name`. */request: string;
1117
- model?: undefined; /** 0-based occurrence among the calls matching this key. Default `0`. */
1180
+ interface SeamRef {
1181
+ /** The request's registered `name`. */
1182
+ request: string;
1183
+ /** 0-based occurrence among the calls with this name. Default `0`. */
1118
1184
  occurrence?: number;
1119
- } | {
1120
- /** The `defineModels` key the request names. */model: string;
1121
- request?: undefined; /** 0-based occurrence among the calls matching this key. Default `0`. */
1122
- occurrence?: number;
1123
- };
1185
+ }
1124
1186
  /**
1125
1187
  * One idle pause, handed to {@link RunSeamOptions.respond} so the simulated
1126
1188
  * user answers off the machine's own state rather than a fixed transcript — a
@@ -1160,11 +1222,17 @@ interface RunSeamOptions<TMachine extends AnyStateMachine> {
1160
1222
  * by model.
1161
1223
  *
1162
1224
  * Entries follow {@link ScriptedTextEntry} conventions (a value, an
1163
- * `{ output, usage? }` envelope, or a function of the request). The LAST
1164
- * entry of a queue repeats, so a live seam that sends the run down a longer
1165
- * branch still finds an answer instead of running dry.
1225
+ * `{ output, usage? }` envelope, or a function of the request). A queue that
1226
+ * runs dry throws; set {@link RunSeamOptions.repeatLast} to replay its last
1227
+ * entry instead.
1166
1228
  */
1167
1229
  scripts?: Record<string, ScriptedTextEntry[]>;
1230
+ /**
1231
+ * Replay the LAST entry of a queue once it is exhausted, so a live seam that
1232
+ * sends the run down a longer branch still finds an answer. Off by default:
1233
+ * a dry queue throws, the same as every other scripted surface.
1234
+ */
1235
+ repeatLast?: boolean;
1168
1236
  /** The call under test. */
1169
1237
  seam: SeamRef;
1170
1238
  /**
@@ -1188,7 +1256,7 @@ interface RunSeamOptions<TMachine extends AnyStateMachine> {
1188
1256
  */
1189
1257
  executors?: Partial<AgentRequestExecutors>;
1190
1258
  /** Passed through to `runAgent`: the deterministic idle-state predicate. */
1191
- isSuspended?: RunAgentOptions<TMachine>["isSuspended"];
1259
+ isIdle?: RunAgentOptions<TMachine>["isIdle"];
1192
1260
  /** Passed through to `runAgent`: actor implementations merged onto the machine. */
1193
1261
  actors?: RunAgentOptions<TMachine>["actors"];
1194
1262
  }
@@ -1241,4 +1309,4 @@ interface RunSeamResult<TMachine extends AnyStateMachine> {
1241
1309
  */
1242
1310
  declare function runSeam<TMachine extends AnyStateMachine>(machine: TMachine, options: RunSeamOptions<TMachine>): Promise<RunSeamResult<TMachine>>;
1243
1311
  //#endregion
1244
- export { AGENT_EVENT_SCHEMA_VERSION, AGENT_INIT_EVENT_TYPE, AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, type AgentActorSession, type AgentCallUsage, type AgentDecisionExecutor, AgentDecisionExhaustedError, type AgentDecisionInput, type AgentDecisionRequest, type AgentEffect, type AgentEffectDiff, AgentError, type AgentEventDescriptor, AgentEventLogConflictError, type AgentEventLogDiff, type AgentEventLogStore, type AgentEventToolNameResolver, type AgentExecutorTextRequest, AgentIdleError, AgentIllegalResumeEventError, type AgentInputFrom, type AgentLintDiagnostic, AgentLintError, type AgentLintSeverity, type AgentLogEntry, type AgentLogPatchOperation, type AgentLogVerification, type AgentMessage, type AgentMessageInfo, type AgentModelRef, type AgentOutputMode, type AgentPathReport, type AgentPathTerminal, AgentReplayDivergenceError, AgentReplayMachineMismatchError, type AgentRequest, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestOptions, type AgentRequestSource, type AgentRun, type AgentRunMeta, type AgentSchemaPack, type AgentSnapshotStore, AgentSnapshotVersionMismatchError, type AgentStateRequest, type AgentStepRequest, type AgentTextRequest, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentTools, type AgentTraceEvent, type AgentUsage, type AgentUsageEvent, type AgentUsageEventPayload, type AgentUserInput, type AgentUserInputExecutor, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AiSdkShapedStreamResult, type AiSdkShapedTextResult, type AllowedEvents, type AssertAgentMachineOptions, type AssistantMessage, type CanReachResult, type ChosenEvent, type CreateReplayEntryOptions, type DecisionAttempt, type DecisionLogicConfig, type ExplorePathsOptions, type FilePart, type FromConfigOptions, type FromConfigResult, type GenerateResult, type GetAgentEffectsOptions, type ImagePart, type InferInput, type InferOutput, type InspectedActorRef, type JsonSerializableTraceEvent, type JsonValue, type LintAgentMachineOptions, type MatchTrajectoryOptions, NonSerializableAgentEventError, type PendingUserInput, type ProvideExecutorsOptions, type ReplayOptions, type ReplayResult, type ResolveDecisionOptions, type RunAgentErrorCause, type RunAgentOptions, type RunAgentResult, type RunSeamOptions, type RunSeamResult, type SchemaCompiler, type ScriptedDecisionEntry, type ScriptedDecisionValue, type ScriptedExecutorsScript, type ScriptedTextEntry, type SeamRef, type SeamSlice, type SeamTurn, type SimulateAgentOptions, type SimulateAgentResult, type SimulationScript, type SimulationTrailEntry, type StandardSchemaV1, type StructuredOutputEnvelope, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultPart, type TrajectoryEvent, type TrajectoryItem, type TrajectoryMatch, type TrajectoryMiss, type UserMessage, type WithAgentUsageEvent, appendMessages, assertAgentLogEntry, assertAgentMachine, assertEventLogStoreConformance, assertJsonSerializable, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentActor, createAgentRun, createAgentSchemas, createInMemoryEventLogStore, createReplayEntry, createScriptedExecutors, createTextLogic, diffEventLogs, executeAgentRequest, explorePaths, generateResult, getAcceptedEvents, getAgentEffects, getAgentMessages, getAgentOutputMode, getCallUsage, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getStateMeta, initEntry, inspectTransitions, isStandardSchema, lintAgentMachine, matchesTrajectory, messagesSchema, parseAgentEvent, parseModelRef, parseOutput, parseStructuredEnvelope, persistSnapshot, provideExecutors, renderDecisionAttempts, replay, resolveDecision, runAgent, runSeam, serializeTraceEvent, setupAgent, simulateAgent, systemMessage, toolMessage, traceTransitions, userMessage, verifyReplay };
1312
+ export { AGENT_EVENT_SCHEMA_VERSION, AGENT_INIT_EVENT_TYPE, AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, type AgentActorSession, type AgentCallUsage, type AgentDecisionExecutor, AgentDecisionExhaustedError, type AgentDecisionInput, type AgentDecisionRequest, type AgentEffect, type AgentEffectDiff, AgentError, type AgentEventDescriptor, AgentEventLogConflictError, type AgentEventLogDiff, type AgentEventLogStore, type AgentEventToolNameResolver, type AgentExecutorTextRequest, AgentIdleError, AgentIllegalResumeEventError, type AgentInputFrom, type AgentLintDiagnostic, AgentLintError, type AgentLintSeverity, type AgentLogEntry, type AgentLogPatchOperation, type AgentLogVerification, AgentMaxModelCallsExceededError, type AgentMessage, type AgentMessageInfo, type AgentModelRef, type AgentOutputMode, type AgentPathReport, type AgentPathTerminal, AgentReplayDivergenceError, AgentReplayMachineMismatchError, type AgentRequest, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestOptions, type AgentRequestSource, type AgentRun, type AgentRunMeta, type AgentSchemaPack, type AgentSchemas, type AgentSnapshotNode, type AgentSnapshotStore, AgentSnapshotVersionMismatchError, type AgentStateRequest, type AgentStepRequest, type AgentTextRequest, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentTools, type AgentTraceEvent, type AgentUsage, type AgentUsageEvent, type AgentUsageEventPayload, type AgentUserInput, type AgentUserInputExecutor, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AiSdkShapedStreamResult, type AiSdkShapedTextResult, type AllowedEvents, type AssistantMessage, type CanReachResult, type ChosenEvent, type CreateReplayEntryOptions, type DecisionAttempt, type DecisionLogicConfig, type ExplorePathsOptions, type FilePart, type FromConfigOptions, type FromConfigResult, type GenerateResult, type GetAgentEffectsOptions, type GetSnapshotRequestsOptions, type ImagePart, type InferInput, type InferOutput, type InspectedActorRef, type JsonSerializableTraceEvent, type JsonValue, type LintAgentMachineOptions, type MatchTrajectoryOptions, NonSerializableAgentEventError, type PendingUserInput, type ProvideExecutorsOptions, type ReplayOptions, type ReplayResult, type ResolveDecisionOptions, type RunAgentErrorCause, type RunAgentOptions, type RunAgentResult, type RunSeamOptions, type RunSeamResult, type SchemaCompiler, type ScriptedDecisionEntry, type ScriptedDecisionValue, type ScriptedExecutors, type ScriptedExecutorsScript, type ScriptedTextEntry, type ScriptedUserInputEntry, type SeamRef, type SeamSlice, type SeamTurn, type SimulateAgentOptions, type SimulateAgentResult, type SimulationScript, type SimulationTrailEntry, type StandardSchemaV1, type StructuredOutputEnvelope, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultPart, type TrajectoryEvent, type TrajectoryItem, type TrajectoryMatch, type TrajectoryMiss, type UserMessage, type WithAgentUsageEvent, appendMessages, assertAgentLogEntry, assertEventLogStoreConformance, assertJsonSerializable, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentActor, createAgentRun, createAgentSchemas, createInMemoryEventLogStore, createReplayEntry, createScriptedExecutors, createTextLogic, diffEventLogs, executeAgentRequest, explorePaths, generateResult, getAcceptedEvents, getAgentEffects, getAgentMessages, getAgentOutputMode, getAgentSchemas, getCallUsage, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getSnapshotNodes, getSnapshotRequests, getStateMeta, initEntry, inspectTransitions, isStandardSchema, lintAgentMachine, matchesTrajectory, messagesSchema, parseAgentEvent, parseModelRef, parseOutput, parseStructuredEnvelope, provideExecutors, renderDecisionAttempts, replay, resolveDecision, runAgent, runSeam, serializeTraceEvent, setupAgent, simulateAgent, systemMessage, toolMessage, traceTransitions, userMessage };