@statelyai/agent 2.0.0-alpha.18 → 2.0.0-alpha.20

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-BfhSgCc6.mjs} +48 -28
  6. package/dist/{decision-DnQCQPew.cjs → decision-DhsKLYAI.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 +458 -109
  12. package/dist/index.d.cts +209 -81
  13. package/dist/index.d.mts +209 -81
  14. package/dist/index.mjs +455 -108
  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-r9OD4z8F.d.cts → run-agent--4bbms-D.d.cts} +121 -48
  23. package/dist/{run-agent-DQIDikfd.d.mts → run-agent-CwmzAZwj.d.mts} +121 -48
  24. package/dist/{setup-agent-BrE2zFDy.mjs → setup-agent-BOcSpsIq.mjs} +38 -28
  25. package/dist/{setup-agent-C3ETi_HZ.cjs → setup-agent-gISRLxRe.cjs} +44 -33
  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-VcWqO-Cl.d.cts → text-logic-Cavva1W6.d.cts} +24 -8
  31. package/dist/{text-logic-RvnlD-An.d.mts → text-logic-Er5KkTX6.d.mts} +24 -8
  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 +17 -3
  37. package/schemas/agent-workflow.json +2 -2
  38. package/skills/generate-machine/SKILL.md +12 -14
@@ -1,7 +1,7 @@
1
1
  import { T as WithAgentInputSchema, c as AgentTools, d as ChosenEvent, h as InferInput, n as AgentMessage, v as StandardSchemaV1 } from "./types-pJ5Hn8fv.cjs";
2
2
  import { t as AgentError } from "./errors-BQRk9eiZ.cjs";
3
- import { H as AgentRequestSource, N as AgentDecisionRequest, V as AgentRequestOptions, d as AgentTextRequest, f as AgentUsage, l as AgentRequestExecutors, p as AgentUserInput, t as AgentCallUsage, u as AgentRequestMode, z as AgentEventDescriptor } from "./text-logic-VcWqO-Cl.cjs";
4
- import { i as AgentLogEntry, o as JsonValue } from "./event-log-store-CQJq8_v4.cjs";
3
+ import { H as AgentRequestSource, N as AgentDecisionRequest, V as AgentRequestOptions, d as AgentTextRequest, f as AgentUsage, l as AgentRequestExecutors, p as AgentUserInput, t as AgentCallUsage, u as AgentRequestMode, z as AgentEventDescriptor } from "./text-logic-Cavva1W6.cjs";
4
+ import { i as AgentLogEntry, o as JsonValue } from "./event-log-store-Bz7HDBkE.cjs";
5
5
  import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, ExecutableActionObject, InputFrom, InspectionEvent, OutputFrom, Snapshot, SnapshotFrom, createActor } from "xstate";
6
6
 
7
7
  //#region src/internal/registry.d.ts
@@ -240,8 +240,6 @@ interface AgentEventLogDiff<TMachine extends AnyStateMachine> {
240
240
  effectChanges: AgentEffectDiff;
241
241
  }
242
242
  declare function replay<TMachine extends AnyStateMachine>(machine: TMachine, entries: readonly AgentLogEntry[], options?: ReplayOptions): ReplayResult<TMachine>;
243
- /** Requires and checks every entry's recorded state/effect hashes. */
244
- declare function verifyReplay<TMachine extends AnyStateMachine>(machine: TMachine, entries: readonly AgentLogEntry[], options?: Omit<ReplayOptions, "verify">): ReplayResult<TMachine>;
245
243
  /** Structural event-tail, logical-state, and owed-effect comparison. */
246
244
  declare function diffEventLogs<TMachine extends AnyStateMachine>(machine: TMachine, parentEntries: readonly AgentLogEntry[], forkEntries: readonly AgentLogEntry[], options?: ReplayOptions): AgentEventLogDiff<TMachine>;
247
245
  //#endregion
@@ -271,7 +269,7 @@ type AgentStepRequest = AgentRequest | AgentDecisionRequest;
271
269
  * present. Accepts either a `kind: 'text'` `AgentEffect` (the step-path shape
272
270
  * from `getAgentEffects`) or an {@link AgentRequest} envelope.
273
271
  * **Text-only**: passing a `kind: 'decision'` request throws, directing the
274
- * caller to `resolveDecision(request, executors.decide, ...)` instead. Always
272
+ * caller to `resolveDecision(request, executors, ...)` instead. Always
275
273
  * returns both the normalized `output` and the `raw` executor result (tool
276
274
  * calls, usage, finish reason — needed for observability and event-sourced
277
275
  * replay).
@@ -341,8 +339,7 @@ interface AgentStateRequest {
341
339
  * {@link getAcceptedEvents}). A programmer/integration error, in the same
342
340
  * class as runAgent's bind-time throws — it throws rather than settling an
343
341
  * `error` result. A type-legal event a guard rejects is NOT this error (the
344
- * machine simply takes no transition). Opt out with
345
- * {@link RunAgentOptions.onIllegalResumeEvent} `'ignore'`.
342
+ * machine simply takes no transition). Always enforced; there is no opt-out.
346
343
  */
347
344
  declare class AgentIllegalResumeEventError extends AgentError {
348
345
  readonly eventType: string;
@@ -382,8 +379,8 @@ interface AgentUserInputExecutor {
382
379
  }
383
380
  /**
384
381
  * The run's machine identity, stamped onto every settled snapshot's `agentMeta`.
385
- * `machineId` is the machine's `id`; `version` is
386
- * {@link RunAgentOptions.machineVersion} or the
382
+ * `machineId` is the machine's `id`; `version` is the machine's own
383
+ * `version` (XState's `createMachine({ version })`) or, when unversioned, the
387
384
  * {@link getMachineStructuralHash} of the machine. Trace events and the
388
385
  * `onMessage` info arg carry the same identity flattened, as
389
386
  * `machineId`/`machineVersion`.
@@ -400,7 +397,7 @@ interface AgentRunMeta {
400
397
  interface AgentMessageInfo {
401
398
  runId: string;
402
399
  machineId: string;
403
- /** {@link RunAgentOptions.machineVersion}, else the machine's own `version`, else its structural hash. */
400
+ /** The machine's own `version`, else its structural hash. */
404
401
  machineVersion: string;
405
402
  }
406
403
  /**
@@ -416,7 +413,7 @@ type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
416
413
  runId: string;
417
414
  seq: number;
418
415
  timestamp: string;
419
- machineId: string; /** {@link RunAgentOptions.machineVersion}, else the machine's own `version`, else its structural hash. */
416
+ machineId: string; /** The machine's own `version`, else its structural hash. */
420
417
  machineVersion: string;
421
418
  } & ({
422
419
  type: "run.start";
@@ -516,7 +513,7 @@ declare const TRACE_ENVELOPE_KEYS: readonly ["schemaVersion", "runId", "seq", "t
516
513
  * in a JSONL file). Live values are sanitized rather than trusted:
517
514
  *
518
515
  * - Snapshots (`run.start`, `machine.transition`, `run.end`) go through the
519
- * same JSON round-trip as {@link persistSnapshot}, so what lands on disk is
516
+ * same JSON round-trip as `machine.getPersistedSnapshot(...)`, so what lands on disk is
520
517
  * what a resume would see.
521
518
  * - `request.end`'s `raw` (a provider SDK object, frequently cyclic) is DROPPED
522
519
  * unless `includeRaw` is set, in which case it is sanitized like everything
@@ -582,27 +579,11 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
582
579
  * (or an event-log store) and resume from the log alone.
583
580
  */
584
581
  events?: readonly AgentLogEntry[];
585
- /**
586
- * How to handle a resume `event` the restored state cannot accept (a
587
- * type-level check via {@link getAcceptedEvents}, only applied when resuming
588
- * from a `snapshot`). `'throw'` (default) throws {@link AgentIllegalResumeEventError}
589
- * before delivering the event; `'ignore'` restores the older silent behavior
590
- * (the event is sent and the machine drops it). A type-legal event a guard
591
- * rejects is never an illegal resume event.
592
- */
593
- onIllegalResumeEvent?: "throw" | "ignore";
594
- /**
595
- * The version stamped onto every settled snapshot's `agentMeta` and compared
596
- * against an incoming snapshot's stamp on resume. Defaults to the machine's
597
- * own `version` (XState's `createMachine({ version })` prop) when set, else
598
- * {@link getMachineStructuralHash} of the machine (a structural fingerprint
599
- * that changes on any edit). Set `version` on the machine — or this option —
600
- * to control migration boundaries yourself.
601
- */
602
- machineVersion?: string;
603
582
  /**
604
583
  * How to handle a resume `snapshot` whose stamped `agentMeta.version` differs
605
- * from the current machine's version. `'throw'` (default) throws
584
+ * from the current machine's `version` (XState's `createMachine({ version })`
585
+ * prop — the single source of truth; an unversioned machine falls back to its
586
+ * {@link getMachineStructuralHash}). `'throw'` (default) throws
606
587
  * {@link AgentSnapshotVersionMismatchError} with `from`/`to`; `'warn'`
607
588
  * `console.warn`s once and proceeds; `'ignore'` proceeds silently. Ignored
608
589
  * when {@link migrateSnapshot} is provided (that runs instead), and never
@@ -614,6 +595,12 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
614
595
  * version mismatches the current machine's: receives the incoming snapshot
615
596
  * and `{ from, to }`, and its return value is used as the snapshot to resume
616
597
  * from. A throw propagates.
598
+ *
599
+ * Prefer XState's own `createMachine({ version, migrate })` hook when the
600
+ * migration belongs to the machine: a machine that declares `migrate` is left
601
+ * to xstate, and runAgent neither throws nor rewrites the snapshot's version
602
+ * before restore. This option stays for host-owned migrations (a machine you
603
+ * do not control, or a migration that needs run-scoped context).
617
604
  */
618
605
  migrateSnapshot?: (snapshot: Snapshot<unknown>, info: {
619
606
  from: string;
@@ -635,7 +622,7 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
635
622
  * Host override for detecting a snapshot that is an INTENTIONAL wait for an
636
623
  * external event — the deterministic replacement for the timing heuristic
637
624
  * runAgent uses to settle idle. Resolution order: this option (host override)
638
- * → the machine-carried predicate declared via `setupAgent({ isSuspended })`
625
+ * → the machine-carried predicate declared via `setupAgent({ isIdle })`
639
626
  * → the timing heuristic (when neither is present). When the resolved
640
627
  * predicate returns true and nothing is in flight (no live requests/
641
628
  * invokes; the `agent.userInput` placeholder exemption still applies), runAgent
@@ -645,7 +632,7 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
645
632
  * exactly as before (with a one-time dev warning suggesting a predicate).
646
633
  * Declare your own signal, e.g. `(s) => s.hasTag('awaiting-review')`.
647
634
  */
648
- isSuspended?: (snapshot: AnyMachineSnapshot) => boolean;
635
+ isIdle?: (snapshot: AnyMachineSnapshot) => boolean;
649
636
  /**
650
637
  * The override to runAgent's DEFAULT contract. By default agent work is
651
638
  * whatever the machine *invokes* (`agent.generateText`, TextLogic,
@@ -655,23 +642,16 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
655
642
  * tags, a lookup table keyed by state value, wherever you keep them. Return
656
643
  * nothing to settle idle (human-wait states).
657
644
  *
658
- * There is no blessed source for the prompts — this is a recipe seam.
659
- * Prompts-in-descriptions, copy-paste and adapt:
645
+ * There is no blessed source for the prompts — this is a recipe seam. The
646
+ * shipped prompts-in-descriptions recipe is {@link getSnapshotRequests}:
660
647
  *
661
648
  * ```ts
662
- * getRequests: (snapshot) =>
663
- * snapshot._nodes
664
- * .filter((node) => node.description && !node.tags.includes('waiting'))
665
- * .map((node) => ({
666
- * model: 'writer',
667
- * prompt: node.description!,
668
- * kind: node.tags.includes('decision') ? 'decision' : 'text',
669
- * // single-outcome states advance deterministically; else `decide`
670
- * onDone: node.ownEvents.length === 1 ? { type: node.ownEvents[0] } : undefined,
671
- * allowedEvents: node.ownEvents,
672
- * })),
649
+ * getRequests: (snapshot) => getSnapshotRequests(snapshot, { model: 'writer' }),
673
650
  * ```
674
651
  *
652
+ * Reach for {@link getSnapshotNodes} when you want to build requests some
653
+ * other way — between them, host code never touches `snapshot._nodes`.
654
+ *
675
655
  * Each request runs per {@link AgentStateRequest.kind}, appends to the
676
656
  * run's message log (see {@link RunAgentOptions.messages}), and advances
677
657
  * the machine per {@link AgentStateRequest.onDone} — explicitly named/
@@ -768,11 +748,84 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
768
748
  inspect?: ((inspectionEvent: InspectionEvent) => void) | {
769
749
  next?: (inspectionEvent: InspectionEvent) => void;
770
750
  };
771
- /** Caps the number of model/decision calls this run may make (each retry of a decision counts separately); exceeding it settles `{ status: 'error', cause: 'max-model-calls' }`. Default 100. */
751
+ /**
752
+ * Caps the number of model/decision calls this run may make (each retry of a
753
+ * decision counts separately). Default 100. The overrun is thrown into the
754
+ * invoke that would have made the call, as an
755
+ * {@link AgentMaxModelCallsExceededError} with `code: 'max-model-calls'` — so
756
+ * an `onError` can branch on it and route to a degraded state. Unhandled, it
757
+ * settles `{ status: 'error', cause: 'max-model-calls' }`.
758
+ */
772
759
  maxModelCalls?: number;
773
760
  /** Aborts the run; settles `{ status: 'error', cause: 'aborted' }` with `signal.reason` as the error. */
774
761
  signal?: AbortSignal;
775
762
  }
763
+ /**
764
+ * One active state node of a snapshot, as {@link getSnapshotRequests} and
765
+ * {@link getSnapshotNodes} surface it: the prompt-bearing `description`, the
766
+ * `tags` a recipe branches on, the state `meta`, and `ownEvents` (the event
767
+ * types this node itself declares transitions for). The shape hosts used to
768
+ * reach for through the private `snapshot._nodes` array.
769
+ */
770
+ interface AgentSnapshotNode {
771
+ /** The node's full id (e.g. `writer.drafting`). */
772
+ id: string;
773
+ /** The node's own key (e.g. `drafting`). */
774
+ key: string;
775
+ /** The node's `description` — the prompt, in the prompts-in-descriptions recipe. */
776
+ description?: string;
777
+ tags: string[];
778
+ meta?: unknown;
779
+ /** Event types this node declares transitions for (xstate's `ownEvents`). */
780
+ ownEvents: string[];
781
+ /** True when the node has no child states. */
782
+ leaf: boolean;
783
+ }
784
+ /**
785
+ * The active state nodes of a snapshot, as plain {@link AgentSnapshotNode}
786
+ * descriptors. The escape hatch under {@link getSnapshotRequests}: use it when
787
+ * your `getRequests` hook needs to build requests some other way, so host code
788
+ * never touches xstate's private `snapshot._nodes`.
789
+ */
790
+ declare function getSnapshotNodes(snapshot: AnyMachineSnapshot): AgentSnapshotNode[];
791
+ /** Options for {@link getSnapshotRequests}. */
792
+ interface GetSnapshotRequestsOptions {
793
+ /** Executor model name every produced request carries. */
794
+ model: string;
795
+ /**
796
+ * Which active nodes produce a request. Default: every node with a
797
+ * `description` that is NOT tagged `'waiting'` (a human-wait state settles
798
+ * idle instead).
799
+ */
800
+ filter?: (node: AgentSnapshotNode) => boolean;
801
+ /**
802
+ * Shapes (or drops, by returning `undefined`) each node's request before it
803
+ * is returned — set `system`, `allowedEvents`, a custom `onDone`, …
804
+ */
805
+ map?: (request: AgentStateRequest, node: AgentSnapshotNode) => AgentStateRequest | undefined;
806
+ }
807
+ /**
808
+ * Builds the {@link AgentStateRequest}s for a snapshot straight from its active
809
+ * state nodes — the prompts-in-descriptions recipe as a function, so a
810
+ * {@link RunAgentOptions.getRequests} hook is one line and never reaches into
811
+ * xstate's private `snapshot._nodes`:
812
+ *
813
+ * ```ts
814
+ * runAgent(machine, {
815
+ * executors,
816
+ * getRequests: (snapshot) => getSnapshotRequests(snapshot, { model: 'writer' }),
817
+ * });
818
+ * ```
819
+ *
820
+ * Each described active node becomes one request: `prompt` from the node's
821
+ * `description`, `kind: 'decision'` when it is tagged `'decision'`, `system`
822
+ * from `meta.role` when present, `allowedEvents` scoped to the node's own
823
+ * events, and an explicit `onDone` when the node has exactly one own event
824
+ * (single-outcome states advance deterministically; anything else falls
825
+ * through to a `decide` call). Nodes tagged `'waiting'` produce nothing, so the
826
+ * run settles idle for a human. Override any of it with `filter`/`map`.
827
+ */
828
+ declare function getSnapshotRequests(snapshot: AnyMachineSnapshot, options: GetSnapshotRequestsOptions): AgentStateRequest[];
776
829
  /**
777
830
  * The outcome of a {@link runAgent} call — always exactly one of three
778
831
  * variants, never a throw for a waiting or failed machine (programmer
@@ -848,6 +901,26 @@ type RunAgentResult<TMachine extends AnyStateMachine> = RunAgentOutcome<TMachine
848
901
  * - `'stopped'` — the actor was stopped externally (`status === 'stopped'`).
849
902
  */
850
903
  type RunAgentErrorCause = "aborted" | "max-model-calls" | "decision-exhausted" | "machine" | "stopped";
904
+ /**
905
+ * Thrown into the invoke that would have made the call once
906
+ * {@link RunAgentOptions.maxModelCalls} is spent. It reaches the machine
907
+ * through the normal error channel, so an invoke's `onError` can branch on it
908
+ * (`error.code === 'max-model-calls'`, the same string the settled result's
909
+ * `cause` uses) and route to a degraded/finish state instead of failing the
910
+ * run. Unhandled, it settles `{ status: 'error', cause: 'max-model-calls' }`.
911
+ *
912
+ * ```ts
913
+ * onError: [
914
+ * { guard: ({ event }) => event.error?.code === 'max-model-calls', target: 'budgetSpent' },
915
+ * { target: 'failed' },
916
+ * ]
917
+ * ```
918
+ */
919
+ declare class AgentMaxModelCallsExceededError extends AgentError {
920
+ /** The budget that was exceeded (`options.maxModelCalls`). */
921
+ readonly maxModelCalls: number;
922
+ constructor(maxModelCalls: number);
923
+ }
851
924
  /**
852
925
  * The machine input a run accepts, which is the schema's *pre*-validation side.
853
926
  *
@@ -1022,4 +1095,4 @@ declare function inspectTransitions(handler: (snapshot: AnyMachineSnapshot, acto
1022
1095
  */
1023
1096
  declare function traceTransitions<TMachine extends AnyStateMachine = AnyStateMachine>(onTrace: (event: AgentTraceEvent<TMachine>) => void): (inspectionEvent: InspectionEvent) => void;
1024
1097
  //#endregion
1025
- export { AgentEffect as A, ReplayResult as B, traceTransitions as C, executeAgentRequest as D, AgentStepRequest as E, AgentReplayMachineMismatchError as F, replay as G, diffEventLogs as H, AgentUsageEvent as I, verifyReplay as K, CreateReplayEntryOptions as L, AgentEventLogDiff as M, AgentLogPatchOperation as N, AGENT_INIT_EVENT_TYPE as O, AgentReplayDivergenceError as P, GetAgentEffectsOptions as R, serializeTraceEvent as S, AgentRequest as T, getAgentEffects as U, createReplayEntry as V, initEntry as W, RunAgentResult as _, AgentInputFrom as a, inspectTransitions as b, AgentSnapshotVersionMismatchError as c, GenerateResult as d, InspectedActorRef as f, RunAgentOptions as g, RunAgentErrorCause as h, AgentIllegalResumeEventError as i, AgentEffectDiff as j, AGENT_USAGE_EVENT_TYPE as k, AgentTraceEvent as l, PendingUserInput as m, AgentActorSession as n, AgentMessageInfo as o, JsonSerializableTraceEvent as p, AgentIdleError as r, AgentRunMeta as s, AGENT_TRACE_SCHEMA_VERSION as t, AgentUserInputExecutor as u, createAgentActor as v, AgentStateRequest as w, runAgent as x, generateResult as y, ReplayOptions as z };
1098
+ export { AgentRequest as A, AgentReplayMachineMismatchError as B, getSnapshotNodes as C, serializeTraceEvent as D, runAgent as E, AgentEffect as F, ReplayResult as G, CreateReplayEntryOptions as H, AgentEffectDiff as I, getAgentEffects as J, createReplayEntry as K, AgentEventLogDiff as L, executeAgentRequest as M, AGENT_INIT_EVENT_TYPE as N, traceTransitions as O, AGENT_USAGE_EVENT_TYPE as P, AgentLogPatchOperation as R, generateResult as S, inspectTransitions as T, GetAgentEffectsOptions as U, AgentUsageEvent as V, ReplayOptions as W, replay as X, initEntry as Y, PendingUserInput as _, AgentInputFrom as a, RunAgentResult as b, AgentRunMeta as c, AgentTraceEvent as d, AgentUserInputExecutor as f, JsonSerializableTraceEvent as g, InspectedActorRef as h, AgentIllegalResumeEventError as i, AgentStepRequest as j, AgentStateRequest as k, AgentSnapshotNode as l, GetSnapshotRequestsOptions as m, AgentActorSession as n, AgentMaxModelCallsExceededError as o, GenerateResult as p, diffEventLogs as q, AgentIdleError as r, AgentMessageInfo as s, AGENT_TRACE_SCHEMA_VERSION as t, AgentSnapshotVersionMismatchError as u, RunAgentErrorCause as v, getSnapshotRequests as w, createAgentActor as x, RunAgentOptions as y, AgentReplayDivergenceError as z };
@@ -1,7 +1,7 @@
1
1
  import { T as WithAgentInputSchema, c as AgentTools, d as ChosenEvent, h as InferInput, n as AgentMessage, v as StandardSchemaV1 } from "./types-DYpK3QF4.mjs";
2
2
  import { t as AgentError } from "./errors-C9rxnWbX.mjs";
3
- import { H as AgentRequestSource, N as AgentDecisionRequest, V as AgentRequestOptions, d as AgentTextRequest, f as AgentUsage, l as AgentRequestExecutors, p as AgentUserInput, t as AgentCallUsage, u as AgentRequestMode, z as AgentEventDescriptor } from "./text-logic-RvnlD-An.mjs";
4
- import { i as AgentLogEntry, o as JsonValue } from "./event-log-store-BrC9Q1xW.mjs";
3
+ import { H as AgentRequestSource, N as AgentDecisionRequest, V as AgentRequestOptions, d as AgentTextRequest, f as AgentUsage, l as AgentRequestExecutors, p as AgentUserInput, t as AgentCallUsage, u as AgentRequestMode, z as AgentEventDescriptor } from "./text-logic-Er5KkTX6.mjs";
4
+ import { i as AgentLogEntry, o as JsonValue } from "./event-log-store-hrA1vqtN.mjs";
5
5
  import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, ExecutableActionObject, InputFrom, InspectionEvent, OutputFrom, Snapshot, SnapshotFrom, createActor } from "xstate";
6
6
 
7
7
  //#region src/internal/registry.d.ts
@@ -240,8 +240,6 @@ interface AgentEventLogDiff<TMachine extends AnyStateMachine> {
240
240
  effectChanges: AgentEffectDiff;
241
241
  }
242
242
  declare function replay<TMachine extends AnyStateMachine>(machine: TMachine, entries: readonly AgentLogEntry[], options?: ReplayOptions): ReplayResult<TMachine>;
243
- /** Requires and checks every entry's recorded state/effect hashes. */
244
- declare function verifyReplay<TMachine extends AnyStateMachine>(machine: TMachine, entries: readonly AgentLogEntry[], options?: Omit<ReplayOptions, "verify">): ReplayResult<TMachine>;
245
243
  /** Structural event-tail, logical-state, and owed-effect comparison. */
246
244
  declare function diffEventLogs<TMachine extends AnyStateMachine>(machine: TMachine, parentEntries: readonly AgentLogEntry[], forkEntries: readonly AgentLogEntry[], options?: ReplayOptions): AgentEventLogDiff<TMachine>;
247
245
  //#endregion
@@ -271,7 +269,7 @@ type AgentStepRequest = AgentRequest | AgentDecisionRequest;
271
269
  * present. Accepts either a `kind: 'text'` `AgentEffect` (the step-path shape
272
270
  * from `getAgentEffects`) or an {@link AgentRequest} envelope.
273
271
  * **Text-only**: passing a `kind: 'decision'` request throws, directing the
274
- * caller to `resolveDecision(request, executors.decide, ...)` instead. Always
272
+ * caller to `resolveDecision(request, executors, ...)` instead. Always
275
273
  * returns both the normalized `output` and the `raw` executor result (tool
276
274
  * calls, usage, finish reason — needed for observability and event-sourced
277
275
  * replay).
@@ -341,8 +339,7 @@ interface AgentStateRequest {
341
339
  * {@link getAcceptedEvents}). A programmer/integration error, in the same
342
340
  * class as runAgent's bind-time throws — it throws rather than settling an
343
341
  * `error` result. A type-legal event a guard rejects is NOT this error (the
344
- * machine simply takes no transition). Opt out with
345
- * {@link RunAgentOptions.onIllegalResumeEvent} `'ignore'`.
342
+ * machine simply takes no transition). Always enforced; there is no opt-out.
346
343
  */
347
344
  declare class AgentIllegalResumeEventError extends AgentError {
348
345
  readonly eventType: string;
@@ -382,8 +379,8 @@ interface AgentUserInputExecutor {
382
379
  }
383
380
  /**
384
381
  * The run's machine identity, stamped onto every settled snapshot's `agentMeta`.
385
- * `machineId` is the machine's `id`; `version` is
386
- * {@link RunAgentOptions.machineVersion} or the
382
+ * `machineId` is the machine's `id`; `version` is the machine's own
383
+ * `version` (XState's `createMachine({ version })`) or, when unversioned, the
387
384
  * {@link getMachineStructuralHash} of the machine. Trace events and the
388
385
  * `onMessage` info arg carry the same identity flattened, as
389
386
  * `machineId`/`machineVersion`.
@@ -400,7 +397,7 @@ interface AgentRunMeta {
400
397
  interface AgentMessageInfo {
401
398
  runId: string;
402
399
  machineId: string;
403
- /** {@link RunAgentOptions.machineVersion}, else the machine's own `version`, else its structural hash. */
400
+ /** The machine's own `version`, else its structural hash. */
404
401
  machineVersion: string;
405
402
  }
406
403
  /**
@@ -416,7 +413,7 @@ type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
416
413
  runId: string;
417
414
  seq: number;
418
415
  timestamp: string;
419
- machineId: string; /** {@link RunAgentOptions.machineVersion}, else the machine's own `version`, else its structural hash. */
416
+ machineId: string; /** The machine's own `version`, else its structural hash. */
420
417
  machineVersion: string;
421
418
  } & ({
422
419
  type: "run.start";
@@ -516,7 +513,7 @@ declare const TRACE_ENVELOPE_KEYS: readonly ["schemaVersion", "runId", "seq", "t
516
513
  * in a JSONL file). Live values are sanitized rather than trusted:
517
514
  *
518
515
  * - Snapshots (`run.start`, `machine.transition`, `run.end`) go through the
519
- * same JSON round-trip as {@link persistSnapshot}, so what lands on disk is
516
+ * same JSON round-trip as `machine.getPersistedSnapshot(...)`, so what lands on disk is
520
517
  * what a resume would see.
521
518
  * - `request.end`'s `raw` (a provider SDK object, frequently cyclic) is DROPPED
522
519
  * unless `includeRaw` is set, in which case it is sanitized like everything
@@ -582,27 +579,11 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
582
579
  * (or an event-log store) and resume from the log alone.
583
580
  */
584
581
  events?: readonly AgentLogEntry[];
585
- /**
586
- * How to handle a resume `event` the restored state cannot accept (a
587
- * type-level check via {@link getAcceptedEvents}, only applied when resuming
588
- * from a `snapshot`). `'throw'` (default) throws {@link AgentIllegalResumeEventError}
589
- * before delivering the event; `'ignore'` restores the older silent behavior
590
- * (the event is sent and the machine drops it). A type-legal event a guard
591
- * rejects is never an illegal resume event.
592
- */
593
- onIllegalResumeEvent?: "throw" | "ignore";
594
- /**
595
- * The version stamped onto every settled snapshot's `agentMeta` and compared
596
- * against an incoming snapshot's stamp on resume. Defaults to the machine's
597
- * own `version` (XState's `createMachine({ version })` prop) when set, else
598
- * {@link getMachineStructuralHash} of the machine (a structural fingerprint
599
- * that changes on any edit). Set `version` on the machine — or this option —
600
- * to control migration boundaries yourself.
601
- */
602
- machineVersion?: string;
603
582
  /**
604
583
  * How to handle a resume `snapshot` whose stamped `agentMeta.version` differs
605
- * from the current machine's version. `'throw'` (default) throws
584
+ * from the current machine's `version` (XState's `createMachine({ version })`
585
+ * prop — the single source of truth; an unversioned machine falls back to its
586
+ * {@link getMachineStructuralHash}). `'throw'` (default) throws
606
587
  * {@link AgentSnapshotVersionMismatchError} with `from`/`to`; `'warn'`
607
588
  * `console.warn`s once and proceeds; `'ignore'` proceeds silently. Ignored
608
589
  * when {@link migrateSnapshot} is provided (that runs instead), and never
@@ -614,6 +595,12 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
614
595
  * version mismatches the current machine's: receives the incoming snapshot
615
596
  * and `{ from, to }`, and its return value is used as the snapshot to resume
616
597
  * from. A throw propagates.
598
+ *
599
+ * Prefer XState's own `createMachine({ version, migrate })` hook when the
600
+ * migration belongs to the machine: a machine that declares `migrate` is left
601
+ * to xstate, and runAgent neither throws nor rewrites the snapshot's version
602
+ * before restore. This option stays for host-owned migrations (a machine you
603
+ * do not control, or a migration that needs run-scoped context).
617
604
  */
618
605
  migrateSnapshot?: (snapshot: Snapshot<unknown>, info: {
619
606
  from: string;
@@ -635,7 +622,7 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
635
622
  * Host override for detecting a snapshot that is an INTENTIONAL wait for an
636
623
  * external event — the deterministic replacement for the timing heuristic
637
624
  * runAgent uses to settle idle. Resolution order: this option (host override)
638
- * → the machine-carried predicate declared via `setupAgent({ isSuspended })`
625
+ * → the machine-carried predicate declared via `setupAgent({ isIdle })`
639
626
  * → the timing heuristic (when neither is present). When the resolved
640
627
  * predicate returns true and nothing is in flight (no live requests/
641
628
  * invokes; the `agent.userInput` placeholder exemption still applies), runAgent
@@ -645,7 +632,7 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
645
632
  * exactly as before (with a one-time dev warning suggesting a predicate).
646
633
  * Declare your own signal, e.g. `(s) => s.hasTag('awaiting-review')`.
647
634
  */
648
- isSuspended?: (snapshot: AnyMachineSnapshot) => boolean;
635
+ isIdle?: (snapshot: AnyMachineSnapshot) => boolean;
649
636
  /**
650
637
  * The override to runAgent's DEFAULT contract. By default agent work is
651
638
  * whatever the machine *invokes* (`agent.generateText`, TextLogic,
@@ -655,23 +642,16 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
655
642
  * tags, a lookup table keyed by state value, wherever you keep them. Return
656
643
  * nothing to settle idle (human-wait states).
657
644
  *
658
- * There is no blessed source for the prompts — this is a recipe seam.
659
- * Prompts-in-descriptions, copy-paste and adapt:
645
+ * There is no blessed source for the prompts — this is a recipe seam. The
646
+ * shipped prompts-in-descriptions recipe is {@link getSnapshotRequests}:
660
647
  *
661
648
  * ```ts
662
- * getRequests: (snapshot) =>
663
- * snapshot._nodes
664
- * .filter((node) => node.description && !node.tags.includes('waiting'))
665
- * .map((node) => ({
666
- * model: 'writer',
667
- * prompt: node.description!,
668
- * kind: node.tags.includes('decision') ? 'decision' : 'text',
669
- * // single-outcome states advance deterministically; else `decide`
670
- * onDone: node.ownEvents.length === 1 ? { type: node.ownEvents[0] } : undefined,
671
- * allowedEvents: node.ownEvents,
672
- * })),
649
+ * getRequests: (snapshot) => getSnapshotRequests(snapshot, { model: 'writer' }),
673
650
  * ```
674
651
  *
652
+ * Reach for {@link getSnapshotNodes} when you want to build requests some
653
+ * other way — between them, host code never touches `snapshot._nodes`.
654
+ *
675
655
  * Each request runs per {@link AgentStateRequest.kind}, appends to the
676
656
  * run's message log (see {@link RunAgentOptions.messages}), and advances
677
657
  * the machine per {@link AgentStateRequest.onDone} — explicitly named/
@@ -768,11 +748,84 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
768
748
  inspect?: ((inspectionEvent: InspectionEvent) => void) | {
769
749
  next?: (inspectionEvent: InspectionEvent) => void;
770
750
  };
771
- /** Caps the number of model/decision calls this run may make (each retry of a decision counts separately); exceeding it settles `{ status: 'error', cause: 'max-model-calls' }`. Default 100. */
751
+ /**
752
+ * Caps the number of model/decision calls this run may make (each retry of a
753
+ * decision counts separately). Default 100. The overrun is thrown into the
754
+ * invoke that would have made the call, as an
755
+ * {@link AgentMaxModelCallsExceededError} with `code: 'max-model-calls'` — so
756
+ * an `onError` can branch on it and route to a degraded state. Unhandled, it
757
+ * settles `{ status: 'error', cause: 'max-model-calls' }`.
758
+ */
772
759
  maxModelCalls?: number;
773
760
  /** Aborts the run; settles `{ status: 'error', cause: 'aborted' }` with `signal.reason` as the error. */
774
761
  signal?: AbortSignal;
775
762
  }
763
+ /**
764
+ * One active state node of a snapshot, as {@link getSnapshotRequests} and
765
+ * {@link getSnapshotNodes} surface it: the prompt-bearing `description`, the
766
+ * `tags` a recipe branches on, the state `meta`, and `ownEvents` (the event
767
+ * types this node itself declares transitions for). The shape hosts used to
768
+ * reach for through the private `snapshot._nodes` array.
769
+ */
770
+ interface AgentSnapshotNode {
771
+ /** The node's full id (e.g. `writer.drafting`). */
772
+ id: string;
773
+ /** The node's own key (e.g. `drafting`). */
774
+ key: string;
775
+ /** The node's `description` — the prompt, in the prompts-in-descriptions recipe. */
776
+ description?: string;
777
+ tags: string[];
778
+ meta?: unknown;
779
+ /** Event types this node declares transitions for (xstate's `ownEvents`). */
780
+ ownEvents: string[];
781
+ /** True when the node has no child states. */
782
+ leaf: boolean;
783
+ }
784
+ /**
785
+ * The active state nodes of a snapshot, as plain {@link AgentSnapshotNode}
786
+ * descriptors. The escape hatch under {@link getSnapshotRequests}: use it when
787
+ * your `getRequests` hook needs to build requests some other way, so host code
788
+ * never touches xstate's private `snapshot._nodes`.
789
+ */
790
+ declare function getSnapshotNodes(snapshot: AnyMachineSnapshot): AgentSnapshotNode[];
791
+ /** Options for {@link getSnapshotRequests}. */
792
+ interface GetSnapshotRequestsOptions {
793
+ /** Executor model name every produced request carries. */
794
+ model: string;
795
+ /**
796
+ * Which active nodes produce a request. Default: every node with a
797
+ * `description` that is NOT tagged `'waiting'` (a human-wait state settles
798
+ * idle instead).
799
+ */
800
+ filter?: (node: AgentSnapshotNode) => boolean;
801
+ /**
802
+ * Shapes (or drops, by returning `undefined`) each node's request before it
803
+ * is returned — set `system`, `allowedEvents`, a custom `onDone`, …
804
+ */
805
+ map?: (request: AgentStateRequest, node: AgentSnapshotNode) => AgentStateRequest | undefined;
806
+ }
807
+ /**
808
+ * Builds the {@link AgentStateRequest}s for a snapshot straight from its active
809
+ * state nodes — the prompts-in-descriptions recipe as a function, so a
810
+ * {@link RunAgentOptions.getRequests} hook is one line and never reaches into
811
+ * xstate's private `snapshot._nodes`:
812
+ *
813
+ * ```ts
814
+ * runAgent(machine, {
815
+ * executors,
816
+ * getRequests: (snapshot) => getSnapshotRequests(snapshot, { model: 'writer' }),
817
+ * });
818
+ * ```
819
+ *
820
+ * Each described active node becomes one request: `prompt` from the node's
821
+ * `description`, `kind: 'decision'` when it is tagged `'decision'`, `system`
822
+ * from `meta.role` when present, `allowedEvents` scoped to the node's own
823
+ * events, and an explicit `onDone` when the node has exactly one own event
824
+ * (single-outcome states advance deterministically; anything else falls
825
+ * through to a `decide` call). Nodes tagged `'waiting'` produce nothing, so the
826
+ * run settles idle for a human. Override any of it with `filter`/`map`.
827
+ */
828
+ declare function getSnapshotRequests(snapshot: AnyMachineSnapshot, options: GetSnapshotRequestsOptions): AgentStateRequest[];
776
829
  /**
777
830
  * The outcome of a {@link runAgent} call — always exactly one of three
778
831
  * variants, never a throw for a waiting or failed machine (programmer
@@ -848,6 +901,26 @@ type RunAgentResult<TMachine extends AnyStateMachine> = RunAgentOutcome<TMachine
848
901
  * - `'stopped'` — the actor was stopped externally (`status === 'stopped'`).
849
902
  */
850
903
  type RunAgentErrorCause = "aborted" | "max-model-calls" | "decision-exhausted" | "machine" | "stopped";
904
+ /**
905
+ * Thrown into the invoke that would have made the call once
906
+ * {@link RunAgentOptions.maxModelCalls} is spent. It reaches the machine
907
+ * through the normal error channel, so an invoke's `onError` can branch on it
908
+ * (`error.code === 'max-model-calls'`, the same string the settled result's
909
+ * `cause` uses) and route to a degraded/finish state instead of failing the
910
+ * run. Unhandled, it settles `{ status: 'error', cause: 'max-model-calls' }`.
911
+ *
912
+ * ```ts
913
+ * onError: [
914
+ * { guard: ({ event }) => event.error?.code === 'max-model-calls', target: 'budgetSpent' },
915
+ * { target: 'failed' },
916
+ * ]
917
+ * ```
918
+ */
919
+ declare class AgentMaxModelCallsExceededError extends AgentError {
920
+ /** The budget that was exceeded (`options.maxModelCalls`). */
921
+ readonly maxModelCalls: number;
922
+ constructor(maxModelCalls: number);
923
+ }
851
924
  /**
852
925
  * The machine input a run accepts, which is the schema's *pre*-validation side.
853
926
  *
@@ -1022,4 +1095,4 @@ declare function inspectTransitions(handler: (snapshot: AnyMachineSnapshot, acto
1022
1095
  */
1023
1096
  declare function traceTransitions<TMachine extends AnyStateMachine = AnyStateMachine>(onTrace: (event: AgentTraceEvent<TMachine>) => void): (inspectionEvent: InspectionEvent) => void;
1024
1097
  //#endregion
1025
- export { AgentEffect as A, ReplayResult as B, traceTransitions as C, executeAgentRequest as D, AgentStepRequest as E, AgentReplayMachineMismatchError as F, replay as G, diffEventLogs as H, AgentUsageEvent as I, verifyReplay as K, CreateReplayEntryOptions as L, AgentEventLogDiff as M, AgentLogPatchOperation as N, AGENT_INIT_EVENT_TYPE as O, AgentReplayDivergenceError as P, GetAgentEffectsOptions as R, serializeTraceEvent as S, AgentRequest as T, getAgentEffects as U, createReplayEntry as V, initEntry as W, RunAgentResult as _, AgentInputFrom as a, inspectTransitions as b, AgentSnapshotVersionMismatchError as c, GenerateResult as d, InspectedActorRef as f, RunAgentOptions as g, RunAgentErrorCause as h, AgentIllegalResumeEventError as i, AgentEffectDiff as j, AGENT_USAGE_EVENT_TYPE as k, AgentTraceEvent as l, PendingUserInput as m, AgentActorSession as n, AgentMessageInfo as o, JsonSerializableTraceEvent as p, AgentIdleError as r, AgentRunMeta as s, AGENT_TRACE_SCHEMA_VERSION as t, AgentUserInputExecutor as u, createAgentActor as v, AgentStateRequest as w, runAgent as x, generateResult as y, ReplayOptions as z };
1098
+ export { AgentRequest as A, AgentReplayMachineMismatchError as B, getSnapshotNodes as C, serializeTraceEvent as D, runAgent as E, AgentEffect as F, ReplayResult as G, CreateReplayEntryOptions as H, AgentEffectDiff as I, getAgentEffects as J, createReplayEntry as K, AgentEventLogDiff as L, executeAgentRequest as M, AGENT_INIT_EVENT_TYPE as N, traceTransitions as O, AGENT_USAGE_EVENT_TYPE as P, AgentLogPatchOperation as R, generateResult as S, inspectTransitions as T, GetAgentEffectsOptions as U, AgentUsageEvent as V, ReplayOptions as W, replay as X, initEntry as Y, PendingUserInput as _, AgentInputFrom as a, RunAgentResult as b, AgentRunMeta as c, AgentTraceEvent as d, AgentUserInputExecutor as f, JsonSerializableTraceEvent as g, InspectedActorRef as h, AgentIllegalResumeEventError as i, AgentStepRequest as j, AgentStateRequest as k, AgentSnapshotNode as l, GetSnapshotRequestsOptions as m, AgentActorSession as n, AgentMaxModelCallsExceededError as o, GenerateResult as p, diffEventLogs as q, AgentIdleError as r, AgentMessageInfo as s, AGENT_TRACE_SCHEMA_VERSION as t, AgentSnapshotVersionMismatchError as u, RunAgentErrorCause as v, getSnapshotRequests as w, createAgentActor as x, RunAgentOptions as y, AgentReplayDivergenceError as z };