@statelyai/agent 2.0.0-alpha.26 → 2.0.0-alpha.28

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 (54) hide show
  1. package/dist/ai-sdk.cjs +4 -4
  2. package/dist/ai-sdk.d.cts +6 -6
  3. package/dist/ai-sdk.d.mts +6 -6
  4. package/dist/ai-sdk.mjs +4 -4
  5. package/dist/{decision-CM9CYZ6t.cjs → decision-CmM8-HHz.cjs} +10 -9
  6. package/dist/{decision-DzSv1NpD.mjs → decision-RQ0iv0oZ.mjs} +10 -9
  7. package/dist/{event-log-store-Ba2fsc4E.mjs → event-log-store-2pAFiWuc.mjs} +1 -1
  8. package/dist/{event-log-store-DvOcs10J.d.cts → event-log-store-2xzFmgr2.d.cts} +1 -1
  9. package/dist/{event-log-store-DxyVgnas.d.mts → event-log-store-BIPOz-di.d.mts} +1 -1
  10. package/dist/{event-log-store-DQmImLYk.cjs → event-log-store-C-COhIXP.cjs} +1 -1
  11. package/dist/index.cjs +13 -195
  12. package/dist/index.d.cts +25 -105
  13. package/dist/index.d.mts +25 -105
  14. package/dist/index.mjs +12 -189
  15. package/dist/log.cjs +1 -1
  16. package/dist/log.d.cts +1 -1
  17. package/dist/log.d.mts +1 -1
  18. package/dist/log.mjs +1 -1
  19. package/dist/machines.cjs +4 -7
  20. package/dist/machines.d.cts +5 -7
  21. package/dist/machines.d.mts +5 -7
  22. package/dist/machines.mjs +4 -7
  23. package/dist/openai.cjs +3 -3
  24. package/dist/openai.d.cts +5 -5
  25. package/dist/openai.d.mts +5 -5
  26. package/dist/openai.mjs +3 -3
  27. package/dist/otel.cjs +2 -2
  28. package/dist/otel.d.cts +3 -3
  29. package/dist/otel.d.mts +3 -3
  30. package/dist/otel.mjs +2 -2
  31. package/dist/{run-agent-CG343kFs.d.mts → run-agent-ByO-Bxyd.d.cts} +184 -179
  32. package/dist/{run-agent-BOfoJg5B.d.cts → run-agent-COXXc0RW.d.mts} +184 -179
  33. package/dist/{run-agent-Cb1-LS5P.cjs → run-agent-Dmf8GV2d.cjs} +539 -737
  34. package/dist/{run-agent-DvDQd4If.mjs → run-agent-xNTxpt82.mjs} +537 -705
  35. package/dist/{setup-agent-CFW-jPI8.mjs → setup-agent-BuanDXeh.mjs} +6 -28
  36. package/dist/{setup-agent-CPf7MxnG.cjs → setup-agent-DV4cTou-.cjs} +6 -28
  37. package/dist/testing.cjs +276 -27
  38. package/dist/testing.d.cts +17 -15
  39. package/dist/testing.d.mts +17 -15
  40. package/dist/testing.mjs +260 -12
  41. package/dist/{text-logic-Bl_ZRxDi.mjs → text-logic-CIqHAmBi.mjs} +10 -26
  42. package/dist/{text-logic-BFEOxyxv.d.cts → text-logic-D-czVPYp.d.mts} +27 -28
  43. package/dist/{text-logic-hZSiRUo1.d.mts → text-logic-IjfYy9DP.d.cts} +27 -28
  44. package/dist/{text-logic-C8xyr6Ag.cjs → text-logic-f5F5sCdc.cjs} +9 -43
  45. package/dist/{types-B1Qs2q3q.d.cts → types-BgNbNKnJ.d.mts} +3 -3
  46. package/dist/{types-tA3SdczG.d.mts → types-hR5f5YXa.d.cts} +3 -3
  47. package/dist/{utils-C2DPqomn.d.mts → utils-_q7F-AZu.d.mts} +2 -2
  48. package/dist/{utils-ceStNCOh.d.cts → utils-o4YRdHJX.d.cts} +2 -2
  49. package/dist/validate.cjs +0 -8
  50. package/dist/validate.mjs +0 -8
  51. package/package.json +3 -3
  52. package/readme.md +26 -18
  53. package/schemas/agent-workflow.json +0 -8
  54. package/skills/generate-machine/SKILL.md +6 -8
@@ -1,4 +1,4 @@
1
- import { _ as StandardSchemaV1, c as AllowedEvents, h as InferOutput, i as AgentToolChoice, n as AgentMessage, s as AgentTools, u as ChosenEvent } from "./types-tA3SdczG.mjs";
1
+ import { _ as StandardSchemaV1, c as AllowedEvents, h as InferOutput, i as AgentToolChoice, n as AgentMessage, s as AgentTools, u as ChosenEvent } from "./types-hR5f5YXa.cjs";
2
2
  import { AnyMachineSnapshot, AnyStateMachine, AsyncActorLogic, EventFromLogic, EventObject, MachineSnapshot } from "xstate";
3
3
 
4
4
  //#region src/errors.d.ts
@@ -77,7 +77,7 @@ interface AgentEventDescriptor {
77
77
  /** Registered schemas, as attached to a machine by `setupAgent`/`createAgentSchemas`. */
78
78
  interface AgentSchemas {
79
79
  events?: Record<string, StandardSchemaV1>;
80
- /** Machine input schema; `runAgent` validates `options.input` against it. */
80
+ /** Machine input schema; the runtime validates the run's `input` against it. */
81
81
  input?: StandardSchemaV1;
82
82
  }
83
83
  /** Shared options threaded through step discovery ({@link getAgentRequests}/{@link getAcceptedEvents}) — snapshot for event legality, event schemas for payload validation/tool schemas, and registered actor source logics. */
@@ -94,7 +94,7 @@ type ParsedAgentEvent<TSource> = TSource extends AnyStateMachine ? EventFromLogi
94
94
  /**
95
95
  * Parses a wire payload (a request body, a socket frame) into an
96
96
  * event typed as the machine's event union, so it can go straight to
97
- * `runAgent({ event })` / `actor.send(...)` without a cast. Pass the machine
97
+ * `runToQuiescence(runtime, { event })` / `actor.send(...)` without a cast. Pass the machine
98
98
  * itself, or any snapshot of it.
99
99
  *
100
100
  * It checks exactly what a schema can check: the payload is an object with a
@@ -111,7 +111,8 @@ type ParsedAgentEvent<TSource> = TSource extends AnyStateMachine ? EventFromLogi
111
111
  * @example
112
112
  * ```ts
113
113
  * const event = parseAgentEvent(machine, await request.json());
114
- * const result = await runAgent(machine, { store, threadId, event, executors });
114
+ * const runtime = createAgentRuntime(machine, { store, threadId, executors });
115
+ * const result = await runToQuiescence(runtime, { event });
115
116
  * ```
116
117
  */
117
118
  declare function parseAgentEvent<TSource extends AnyStateMachine | AnyMachineSnapshot>(source: TSource, payload: unknown, options?: Pick<AgentRequestOptions, "events" | "schemas">): ParsedAgentEvent<TSource>;
@@ -190,7 +191,7 @@ interface DecisionLogicConfig<TInputSchema extends StandardSchemaV1 = StandardSc
190
191
  }
191
192
  /**
192
193
  * Actor logic for a decision: an async effect that resolves to exactly one
193
- * currently-legal {@link ChosenEvent} (never a plain value). Under `runAgent`
194
+ * currently-legal {@link ChosenEvent} (never a plain value). Under `createAgentRuntime`
194
195
  * the chosen event is delivered to the invoking actor automatically — the
195
196
  * transition it triggers usually exits the invoking state and ends the invoke.
196
197
  * Built by {@link createDecisionLogic}. Register it under `actors:` to reuse/export/
@@ -208,7 +209,7 @@ interface DecisionLogic<TInputSchema extends StandardSchemaV1 = StandardSchemaV1
208
209
  * run, resolves to exactly one currently-legal {@link ChosenEvent} by
209
210
  * calling the host `decide` executor (passed here as `execute`, or supplied
210
211
  * later via {@link DecisionLogic.withExecutor}, `machine.provide(...)`, or
211
- * `runAgent`'s `decide` option). Register the result under `actors:` and
212
+ * `createAgentRuntime`'s `executors.decide`). Register the result under `actors:` and
212
213
  * invoke it by name; for a one-off, state-local decision, prefer the
213
214
  * `agent.decide` builtin invoke instead — it needs no separate declaration
214
215
  * and types `allowedEvents` against the machine's own event schemas.
@@ -264,10 +265,10 @@ interface AgentDecisionRequest {
264
265
  stopSequences?: string[];
265
266
  metadata?: Record<string, unknown>;
266
267
  /**
267
- * The `runAgent` run this decision belongs to (`run_<n>`, matching trace
268
- * events), injected by runAgent like `signal` (symmetric with the text
268
+ * The run this decision belongs to (`run_<n>`, matching trace
269
+ * events), injected by the runtime like `signal` (symmetric with the text
269
270
  * executors' `info.runId`). Runtime-only correlation for executor
270
- * middleware; unset off the runAgent path. Per-attempt context is already
271
+ * middleware; unset off the runtime path. Per-attempt context is already
271
272
  * on the request: `id` is the durable invoke id and `attempts.length` is
272
273
  * the current attempt index.
273
274
  */
@@ -362,7 +363,7 @@ declare function renderDecisionAttempts(request: Pick<AgentDecisionRequest, "eve
362
363
  * `onResult`/event-sourcing but never affects validation. Like text
363
364
  * executors' `{ result, ...extras }`, any extra keys (finish reason,
364
365
  * …) flow untouched to `onResult`'s `raw`; `usage` is the one core reads —
365
- * report this attempt's tokens there and `runAgent` folds them into the run's
366
+ * report this attempt's tokens there and the runtime folds them into the run's
366
367
  * aggregated {@link AgentUsage}.
367
368
  */
368
369
  type AgentDecisionExecutor = (request: AgentExecutorDecisionRequest, info?: AgentRequestExecutorInfo) => PromiseLike<{
@@ -493,7 +494,7 @@ interface AgentTextRequest<TMetadata = Record<string, unknown>, TMessage = any>
493
494
  * `stopWhen: stepCountIs(maxSteps)`.
494
495
  *
495
496
  * This is a REQUEST budget, distinct from the machine-level `maxTurns` a
496
- * preset uses for its own turn budget, and from `runAgent`'s run-wide
497
+ * preset uses for its own turn budget, and from `createAgentRuntime`'s run-wide
497
498
  * `maxModelCalls`.
498
499
  */
499
500
  maxSteps?: number;
@@ -506,9 +507,9 @@ interface AgentTextRequest<TMetadata = Record<string, unknown>, TMessage = any>
506
507
  metadata?: TMetadata;
507
508
  }
508
509
  /**
509
- * Aggregated model-call usage for ONE `runAgent` call — the run-level total
510
- * attached to every settled {@link RunAgentResult} (and therefore to
511
- * `runAgent`'s `{ output, snapshot, persist, usage }`).
510
+ * Aggregated model-call usage for ONE run — the run-level total
511
+ * attached to every settled {@link AgentRunResult} (and therefore to
512
+ * `runToQuiescence`'s `{ output, snapshot, persist, usage }`).
512
513
  *
513
514
  * - `modelCalls` counts every model/decision call this run made (each decision
514
515
  * retry counts separately) — the same seam `maxModelCalls` budgets. Always a
@@ -542,7 +543,7 @@ type AgentCallUsage = Omit<AgentUsage, "modelCalls">;
542
543
  * - `'content-filter'` — a safety filter stopped it.
543
544
  * - `'other'` — anything else, including a provider error the adapter mapped.
544
545
  *
545
- * Adapters set it on their executor result; `runAgent` copies it onto the
546
+ * Adapters set it on their executor result; the runtime copies it onto the
546
547
  * `request.end` trace event. A provider's own string stays on the result's
547
548
  * `raw`.
548
549
  */
@@ -550,7 +551,7 @@ type AgentFinishReason = "stop" | "length" | "tool-calls" | "content-filter" | "
550
551
  /**
551
552
  * Reads a settled call's {@link AgentFinishReason} off a RAW executor result's
552
553
  * `finishReason` field — the finish-reason sibling of {@link getCallUsage},
553
- * applied by `runAgent` before it puts the reason on the `request.end` trace.
554
+ * applied by the runtime before it puts the reason on the `request.end` trace.
554
555
  * A provider's `'error'` normalizes to `'other'`; anything else the union does
555
556
  * not name (an un-normalized provider string, a missing field) returns
556
557
  * `undefined`.
@@ -559,7 +560,7 @@ declare function getCallFinishReason(raw: unknown): AgentFinishReason | undefine
559
560
  /**
560
561
  * Reads a settled call's per-call {@link AgentCallUsage} off a RAW executor
561
562
  * result's `usage` field, keeping only finite numbers — the same normalization
562
- * `runAgent` applies before it delivers `'@agent.usage'`. Returns `undefined`
563
+ * the runtime applies before it delivers `'@agent.usage'`. Returns `undefined`
563
564
  * when the result reports no usage at all. Works for our `{ result, usage }`
564
565
  * shape, for a raw Vercel AI SDK result (its `LanguageModelUsage` carries
565
566
  * the same flat field names), and for any custom executor that follows the
@@ -689,8 +690,7 @@ interface TextLogic<TInputSchema extends StandardSchemaV1 = StandardSchemaV1, TO
689
690
  * result under `actors:` and invoke it by name (equivalent to what
690
691
  * `setupAgent({ requests })` builds internally for each request entry). Pass
691
692
  * `execute` here, or bind it later with `.withExecutor(...)`, a runtime
692
- * adapter's `machine.provide(...)`, or `runAgent`'s `generateText`/
693
- * `streamText` options.
693
+ * adapter's `machine.provide(...)`, or `createAgentRuntime`'s `executors`.
694
694
  *
695
695
  * @example
696
696
  * ```ts
@@ -732,7 +732,7 @@ declare function bindRequestExecutor<TInputSchema extends StandardSchemaV1, TOut
732
732
  * without it is a runtime error.
733
733
  *
734
734
  * `usage` is the one passthrough field core reads: report this call's tokens
735
- * there and `runAgent` folds them into the run's aggregated
735
+ * there and the runtime folds them into the run's aggregated
736
736
  * {@link AgentUsage}. Optional — an executor that reports nothing still counts
737
737
  * toward `modelCalls`.
738
738
  */
@@ -744,16 +744,15 @@ type AgentRequestExecutorResult<TOutput = unknown, TMessage = unknown> = {
744
744
  [key: string]: unknown;
745
745
  };
746
746
  /**
747
- * Optional second argument passed to executors by `runAgent`. The step path
748
- * (`executeAgentRequest`) never passes this — chunk streaming only exists on
749
- * the live path, where `onChunk` (§3.1) needs a way to reach the executor.
747
+ * Optional second argument passed to executors by `createAgentRuntime`: the
748
+ * request's abort signal, and `onChunk` for streamed requests.
750
749
  */
751
750
  interface AgentRequestExecutorInfo {
752
751
  onChunk?: (chunk: string) => void;
753
752
  signal?: AbortSignal;
754
753
  /**
755
- * The `runAgent` run this call belongs to (`run_<n>`, matching trace
756
- * events). Undefined off the runAgent path (bare `provideExecutors` /
754
+ * The run this call belongs to (`run_<n>`, matching trace
755
+ * events). Undefined off the runtime path (bare `provideExecutors` /
757
756
  * direct `TextLogic.execute`). Lets executor middleware (caching, rate
758
757
  * limits, span parenting) correlate calls without side channels.
759
758
  */
@@ -780,7 +779,7 @@ interface AgentRequestExecutorInfo {
780
779
  * lineage id, so cache on `callKey` together with a fingerprint of the
781
780
  * request and reuse a cached result only when the request also matches.
782
781
  *
783
- * Undefined off the `runAgent` path, and for a log with no `executionId`.
782
+ * Undefined off the `createAgentRuntime` path, and for a log with no `executionId`.
784
783
  */
785
784
  callKey?: string;
786
785
  }
@@ -803,11 +802,11 @@ type AgentExecutorTextRequest<TMetadata = Record<string, unknown>> = Omit<AgentT
803
802
  type AgentRequestExecutor<TResult extends AgentRequestExecutorResult = AgentRequestExecutorResult> = (request: AgentExecutorTextRequest, info?: AgentRequestExecutorInfo) => TResult | PromiseLike<TResult>;
804
803
  /**
805
804
  * The full set of host executors a machine's agent actors are resolved
806
- * with — passed to `runAgent`, `executeAgentRequest`, and
805
+ * with — passed to `createAgentRuntime`, `executeAgentRequest`, and
807
806
  * `TextLogic.execute`. Every slot is optional: `generateText` is needed only
808
807
  * if the machine has a `mode: 'generate'` text request, `streamText` only for
809
808
  * a `mode: 'stream'` request, and `decide` only for a decision — omitting
810
- * a slot the machine actually needs is a clear bind-time error (see `runAgent`
809
+ * a slot the machine actually needs is a clear bind-time error (see `createAgentRuntime`
811
810
  * and `provideExecutors`). Adapter result sets (`AiSdkExecutors`,
812
811
  * `OpenAiCompatExecutors`) re-require all three.
813
812
  */
@@ -126,7 +126,7 @@ function findNonSerializableContextPaths(context, limit = 5) {
126
126
  * their prompts or executors hash identically; adding/removing/retargeting a
127
127
  * state or transition changes the hash.
128
128
  *
129
- * Used by {@link runAgent} to stamp settled snapshots with a `version` and to
129
+ * Used by {@link createAgentRuntime} to stamp settled snapshots with a `version` and to
130
130
  * detect a structurally-edited machine on resume. It is a change detector, not
131
131
  * a cryptographic digest — collisions are possible but unlikely for real
132
132
  * configs. Declare `createMachine({ version })` to pin an explicit version instead.
@@ -137,7 +137,7 @@ function getMachineStructuralHash(machine) {
137
137
  /**
138
138
  * The version a machine is stamped with everywhere: an explicitly declared
139
139
  * `createMachine({ version })` when present, else its
140
- * {@link getMachineStructuralHash}. Single source of truth so `runAgent`,
140
+ * {@link getMachineStructuralHash}. Single source of truth so `createAgentRuntime`,
141
141
  * `provideExecutors`/`traceTransitions` trace envelopes agree.
142
142
  * @internal
143
143
  */
@@ -328,7 +328,7 @@ function validateSchemaSync(schema, value) {
328
328
  * Registered execution options, keyed on BOTH the machine object and its root
329
329
  * `config` object. `config` is shared by reference across `machine.provide(...)`
330
330
  * (unlike the machine itself), so the `config` key is what lets a machine
331
- * rebound by `runAgent` — or by any host `.provide(...)` — still resolve the
331
+ * rebound by `createAgentRuntime` — or by any host `.provide(...)` — still resolve the
332
332
  * schemas/actors `setupAgent` registered. Always write through
333
333
  * {@link setAgentExecutionOptions} and read through
334
334
  * {@link getAgentExecutionOptions}.
@@ -348,7 +348,7 @@ function setAgentExecutionOptions(machine, options) {
348
348
  }
349
349
  /**
350
350
  * Reads the options registered for `machine`, falling back to the root `config`
351
- * key so a `.provide(...)`-rebound machine (e.g. the one behind a `runAgent`
351
+ * key so a `.provide(...)`-rebound machine (e.g. the one behind a `runToQuiescence`
352
352
  * result snapshot) resolves the same pack.
353
353
  */
354
354
  function getAgentExecutionOptions(machine) {
@@ -358,24 +358,9 @@ function getAgentExecutionOptions(machine) {
358
358
  const config = machineConfigKey(machine);
359
359
  return config ? agentExecutionOptions.get(config) : void 0;
360
360
  }
361
- /**
362
- * Machine-carried wait-state predicates, keyed on the machine's root `config`
363
- * object. `config` is shared by reference across `machine.provide(...)` (unlike
364
- * the machine object itself), so a predicate registered here travels with the
365
- * machine through `.provide` — which is why it is keyed on `config`, not the
366
- * machine. Set by `setupAgent({ isIdle })` in `createMachine` and by
367
- * `setupAgent.fromConfig` (its `isIdle` option or the config's
368
- * `idleTags`), read by `runAgent` before its structural default.
369
- */
370
- const machineIdlePredicates = /* @__PURE__ */ new WeakMap();
371
- /** Reads the {@link machineIdlePredicates} predicate carried by `machine` (via its root `config`), if any. */
372
- function getMachineIdlePredicate(machine) {
373
- const config = machine.config;
374
- return config ? machineIdlePredicates.get(config) : void 0;
375
- }
376
361
  const unboundPlaceholderLogics = /* @__PURE__ */ new WeakSet();
377
362
  /** Text/decision logics created WITH their own executor (withExecutor or the
378
- * factory's second arg) — these are runnable as-is, so runAgent's bind check
363
+ * factory's second arg) — these are runnable as-is, so the runtime's bind check
379
364
  * must not reject them as direct-object invoke srcs. */
380
365
  const executorBoundLogics = /* @__PURE__ */ new WeakSet();
381
366
  function missingActor(src) {
@@ -409,7 +394,7 @@ const AGENT_FINISH_REASONS = new Set([
409
394
  /**
410
395
  * Reads a settled call's {@link AgentFinishReason} off a RAW executor result's
411
396
  * `finishReason` field — the finish-reason sibling of {@link getCallUsage},
412
- * applied by `runAgent` before it puts the reason on the `request.end` trace.
397
+ * applied by the runtime before it puts the reason on the `request.end` trace.
413
398
  * A provider's `'error'` normalizes to `'other'`; anything else the union does
414
399
  * not name (an un-normalized provider string, a missing field) returns
415
400
  * `undefined`.
@@ -431,7 +416,7 @@ const AGENT_USAGE_TOKEN_FIELDS = [
431
416
  /**
432
417
  * Reads a settled call's per-call {@link AgentCallUsage} off a RAW executor
433
418
  * result's `usage` field, keeping only finite numbers — the same normalization
434
- * `runAgent` applies before it delivers `'@agent.usage'`. Returns `undefined`
419
+ * the runtime applies before it delivers `'@agent.usage'`. Returns `undefined`
435
420
  * when the result reports no usage at all. Works for our `{ result, usage }`
436
421
  * shape, for a raw Vercel AI SDK result (its `LanguageModelUsage` carries
437
422
  * the same flat field names), and for any custom executor that follows the
@@ -586,8 +571,7 @@ function resolveTextLogicValue(value, args) {
586
571
  * result under `actors:` and invoke it by name (equivalent to what
587
572
  * `setupAgent({ requests })` builds internally for each request entry). Pass
588
573
  * `execute` here, or bind it later with `.withExecutor(...)`, a runtime
589
- * adapter's `machine.provide(...)`, or `runAgent`'s `generateText`/
590
- * `streamText` options.
574
+ * adapter's `machine.provide(...)`, or `createAgentRuntime`'s `executors`.
591
575
  *
592
576
  * @example
593
577
  * ```ts
@@ -640,7 +624,7 @@ function createTextLogic(config, execute) {
640
624
  };
641
625
  const logic = (0, xstate.createAsyncLogic)({ run: async ({ input, signal, system, self }, enq) => {
642
626
  const resolvedRequest = request(input);
643
- if (!execute) throw new Error("Text logic has no host execution. Pass an executor as the second argument to createTextLogic(...), provide a runtime adapter, or bind it through runAgent/provideExecutors, or execute the XState effect in your host.");
627
+ if (!execute) throw new Error("Text logic has no host execution. Pass an executor as the second argument to createTextLogic(...), provide a runtime adapter, or bind it through createAgentRuntime/provideExecutors, or execute the XState effect in your host.");
644
628
  const result = await execute({
645
629
  input,
646
630
  request: resolvedRequest,
@@ -897,12 +881,6 @@ Object.defineProperty(exports, "djb2Hex", {
897
881
  return djb2Hex;
898
882
  }
899
883
  });
900
- Object.defineProperty(exports, "executeAgentTextRequest", {
901
- enumerable: true,
902
- get: function() {
903
- return executeAgentTextRequest;
904
- }
905
- });
906
884
  Object.defineProperty(exports, "executorBoundLogics", {
907
885
  enumerable: true,
908
886
  get: function() {
@@ -951,12 +929,6 @@ Object.defineProperty(exports, "getJsonSchemaSync", {
951
929
  return getJsonSchemaSync;
952
930
  }
953
931
  });
954
- Object.defineProperty(exports, "getMachineIdlePredicate", {
955
- enumerable: true,
956
- get: function() {
957
- return getMachineIdlePredicate;
958
- }
959
- });
960
932
  Object.defineProperty(exports, "getMachineStructuralHash", {
961
933
  enumerable: true,
962
934
  get: function() {
@@ -1005,12 +977,6 @@ Object.defineProperty(exports, "isUnboundPlaceholder", {
1005
977
  return isUnboundPlaceholder;
1006
978
  }
1007
979
  });
1008
- Object.defineProperty(exports, "machineIdlePredicates", {
1009
- enumerable: true,
1010
- get: function() {
1011
- return machineIdlePredicates;
1012
- }
1013
- });
1014
980
  Object.defineProperty(exports, "missingActor", {
1015
981
  enumerable: true,
1016
982
  get: function() {
@@ -28,7 +28,7 @@ type InferOutput<T> = T extends StandardSchemaV1<any, infer O> ? O : never;
28
28
  * passes in, before defaults are filled and transforms applied. Standard Schema
29
29
  * carries both sides (`~standard.types.input` / `.output`), so a schema
30
30
  * declaring a defaulted field makes that field optional here and required in
31
- * {@link InferOutput} — which is exactly the split between what `runAgent`
31
+ * {@link InferOutput} — which is exactly the split between what a run
32
32
  * accepts as machine `input` and what the `context` factory then sees.
33
33
  */
34
34
  type InferInput<T> = T extends StandardSchemaV1<infer I, any> ? I : never;
@@ -39,7 +39,7 @@ type InferInput<T> = T extends StandardSchemaV1<infer I, any> ? I : never;
39
39
  * `createActor`'s `input` option and the `context: ({ input })` factory, so the
40
40
  * caller-facing and factory-facing sides cannot differ there. `setupAgent`'s
41
41
  * `createMachine` brands the machine's input type with the schema itself, which
42
- * lets `AgentInputFrom` recover the looser input side for `runAgent` while the
42
+ * lets `AgentInputFrom` recover the looser input side for a run's `input` while the
43
43
  * `context` factory keeps the strict validated side.
44
44
  *
45
45
  * The key is a `~`-prefixed phantom property (the same convention Standard
@@ -229,7 +229,7 @@ type AllowedEventPattern<TEvent extends string = string> = TEvent | "*" | EventW
229
229
  * omitting `allowedEvents` means "all currently-legal events." A resolver
230
230
  * function can therefore only ever narrow, never widen, the real surface.
231
231
  * Wildcards expand against the live snapshot, so they need a snapshot-aware
232
- * host (`runAgent` or the step path).
232
+ * host (`createAgentRuntime`).
233
233
  */
234
234
  type AllowedEvents<TEvent extends string = string, TInput = unknown> = AllowedEventPattern<TEvent> | readonly AllowedEventPattern<TEvent>[] | ((args: {
235
235
  input: TInput;
@@ -28,7 +28,7 @@ type InferOutput<T> = T extends StandardSchemaV1<any, infer O> ? O : never;
28
28
  * passes in, before defaults are filled and transforms applied. Standard Schema
29
29
  * carries both sides (`~standard.types.input` / `.output`), so a schema
30
30
  * declaring a defaulted field makes that field optional here and required in
31
- * {@link InferOutput} — which is exactly the split between what `runAgent`
31
+ * {@link InferOutput} — which is exactly the split between what a run
32
32
  * accepts as machine `input` and what the `context` factory then sees.
33
33
  */
34
34
  type InferInput<T> = T extends StandardSchemaV1<infer I, any> ? I : never;
@@ -39,7 +39,7 @@ type InferInput<T> = T extends StandardSchemaV1<infer I, any> ? I : never;
39
39
  * `createActor`'s `input` option and the `context: ({ input })` factory, so the
40
40
  * caller-facing and factory-facing sides cannot differ there. `setupAgent`'s
41
41
  * `createMachine` brands the machine's input type with the schema itself, which
42
- * lets `AgentInputFrom` recover the looser input side for `runAgent` while the
42
+ * lets `AgentInputFrom` recover the looser input side for a run's `input` while the
43
43
  * `context` factory keeps the strict validated side.
44
44
  *
45
45
  * The key is a `~`-prefixed phantom property (the same convention Standard
@@ -229,7 +229,7 @@ type AllowedEventPattern<TEvent extends string = string> = TEvent | "*" | EventW
229
229
  * omitting `allowedEvents` means "all currently-legal events." A resolver
230
230
  * function can therefore only ever narrow, never widen, the real surface.
231
231
  * Wildcards expand against the live snapshot, so they need a snapshot-aware
232
- * host (`runAgent` or the step path).
232
+ * host (`createAgentRuntime`).
233
233
  */
234
234
  type AllowedEvents<TEvent extends string = string, TInput = unknown> = AllowedEventPattern<TEvent> | readonly AllowedEventPattern<TEvent>[] | ((args: {
235
235
  input: TInput;
@@ -1,4 +1,4 @@
1
- import { C as UserMessage, S as ToolResultPart, _ as StandardSchemaV1, b as ToolCallPart, f as FilePart, l as AssistantMessage, n as AgentMessage, p as ImagePart, v as SystemMessage, x as ToolMessage, y as TextPart } from "./types-tA3SdczG.mjs";
1
+ import { C as UserMessage, S as ToolResultPart, _ as StandardSchemaV1, b as ToolCallPart, f as FilePart, l as AssistantMessage, n as AgentMessage, p as ImagePart, v as SystemMessage, x as ToolMessage, y as TextPart } from "./types-BgNbNKnJ.mjs";
2
2
  import { AnyMachineSnapshot, AnyStateMachine, StateValue } from "xstate";
3
3
 
4
4
  //#region src/utils.d.ts
@@ -13,7 +13,7 @@ declare function getMessageText(message: AgentMessage): string;
13
13
  * their prompts or executors hash identically; adding/removing/retargeting a
14
14
  * state or transition changes the hash.
15
15
  *
16
- * Used by {@link runAgent} to stamp settled snapshots with a `version` and to
16
+ * Used by {@link createAgentRuntime} to stamp settled snapshots with a `version` and to
17
17
  * detect a structurally-edited machine on resume. It is a change detector, not
18
18
  * a cryptographic digest — collisions are possible but unlikely for real
19
19
  * configs. Declare `createMachine({ version })` to pin an explicit version instead.
@@ -1,4 +1,4 @@
1
- import { C as UserMessage, S as ToolResultPart, _ as StandardSchemaV1, b as ToolCallPart, f as FilePart, l as AssistantMessage, n as AgentMessage, p as ImagePart, v as SystemMessage, x as ToolMessage, y as TextPart } from "./types-B1Qs2q3q.cjs";
1
+ import { C as UserMessage, S as ToolResultPart, _ as StandardSchemaV1, b as ToolCallPart, f as FilePart, l as AssistantMessage, n as AgentMessage, p as ImagePart, v as SystemMessage, x as ToolMessage, y as TextPart } from "./types-hR5f5YXa.cjs";
2
2
  import { AnyMachineSnapshot, AnyStateMachine, StateValue } from "xstate";
3
3
 
4
4
  //#region src/utils.d.ts
@@ -13,7 +13,7 @@ declare function getMessageText(message: AgentMessage): string;
13
13
  * their prompts or executors hash identically; adding/removing/retargeting a
14
14
  * state or transition changes the hash.
15
15
  *
16
- * Used by {@link runAgent} to stamp settled snapshots with a `version` and to
16
+ * Used by {@link createAgentRuntime} to stamp settled snapshots with a `version` and to
17
17
  * detect a structurally-edited machine on resume. It is a change detector, not
18
18
  * a cryptographic digest — collisions are possible but unlikely for real
19
19
  * configs. Declare `createMachine({ version })` to pin an explicit version instead.
package/dist/validate.cjs CHANGED
@@ -81,14 +81,6 @@ var agent_workflow_default = {
81
81
  "propertyNames": { "$ref": "#/$defs/Identifier" },
82
82
  "additionalProperties": { "$ref": "#/$defs/State" }
83
83
  },
84
- "idleTags": {
85
- "description": "State tags that mark an intentional wait for an external event (a human approval, an inbound webhook, ...). Lowered by setupAgent.fromConfig(...) into a snapshot.hasTag(...) idle predicate so runAgent settles those states idle deterministically. Every listed tag must appear in some state's 'tags'.",
86
- "type": "array",
87
- "items": {
88
- "type": "string",
89
- "minLength": 1
90
- }
91
- },
92
84
  "meta": { "$ref": "#/$defs/JsonObject" }
93
85
  },
94
86
  additionalProperties: false,
package/dist/validate.mjs CHANGED
@@ -57,14 +57,6 @@ var agent_workflow_default = {
57
57
  "propertyNames": { "$ref": "#/$defs/Identifier" },
58
58
  "additionalProperties": { "$ref": "#/$defs/State" }
59
59
  },
60
- "idleTags": {
61
- "description": "State tags that mark an intentional wait for an external event (a human approval, an inbound webhook, ...). Lowered by setupAgent.fromConfig(...) into a snapshot.hasTag(...) idle predicate so runAgent settles those states idle deterministically. Every listed tag must appear in some state's 'tags'.",
62
- "type": "array",
63
- "items": {
64
- "type": "string",
65
- "minLength": 1
66
- }
67
- },
68
60
  "meta": { "$ref": "#/$defs/JsonObject" }
69
61
  },
70
62
  additionalProperties: false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statelyai/agent",
3
- "version": "2.0.0-alpha.26",
3
+ "version": "2.0.0-alpha.28",
4
4
  "description": "Make invalid agent actions impossible. Agent logic as state machines: deterministic, inspectable, resumable, runs anywhere.",
5
5
  "keywords": [
6
6
  "agent",
@@ -144,7 +144,7 @@
144
144
  "typescript": "^5.9.3",
145
145
  "valibot": "^1.4.2",
146
146
  "vitest": "^4.1.11",
147
- "xstate": "6.0.0-alpha.57",
147
+ "xstate": "6.0.0-alpha.64",
148
148
  "zod": "^4.4.3"
149
149
  },
150
150
  "peerDependencies": {
@@ -152,7 +152,7 @@
152
152
  "ai": "^7.0.0",
153
153
  "ajv": "^8.20.0",
154
154
  "openai": ">=5.0.0 <8",
155
- "xstate": ">=6.0.0-alpha.57 <6.0.0"
155
+ "xstate": "6.0.0-alpha.64"
156
156
  },
157
157
  "peerDependenciesMeta": {
158
158
  "@opentelemetry/api": {
package/readme.md CHANGED
@@ -16,7 +16,7 @@ Stately Agent 2 is in alpha. APIs may change before the stable release.
16
16
 
17
17
  ## Three starting points
18
18
 
19
- - **Author a new agent.** Build a machine from states, decisions, and typed requests; run it locally with `runAgent`, test it with no API key, then use it in any framework or runtime with zero machine changes. See the [Quickstart](docs/quickstart.md) and [Use in any stack](docs/any-stack.md).
19
+ - **Author a new agent.** Build a machine from states, decisions, and typed requests; run it locally with `runToQuiescence`, test it with no API key, then use it in any framework or runtime with zero machine changes. See the [Quickstart](docs/quickstart.md) and [Use in any stack](docs/any-stack.md).
20
20
  - **Retrofit an existing agent.** Turn a `while` loop into a machine: your SDK calls, tools, and retry code become the executors; the machine replaces only the control flow. See [Migrating from a hand-rolled loop](docs/from-a-loop.md).
21
21
  - **Copy a known pattern.** ReAct, reflection, plan-and-execute, RAG, supervisor, and more, each a single runnable file you lift in 60 seconds. See [Agent patterns](docs/patterns.md).
22
22
 
@@ -25,9 +25,11 @@ Stately Agent 2 is in alpha. APIs may change before the stable release.
25
25
  <!-- install command matching the package prerelease channel and package.json peers -->
26
26
 
27
27
  ```sh
28
- pnpm add @statelyai/agent@alpha xstate@alpha zod
28
+ pnpm add @statelyai/agent@alpha xstate@6.0.0-alpha.64 zod
29
29
  ```
30
30
 
31
+ XState is pinned while its experimental durable restoration API evolves.
32
+
31
33
  For the optional Vercel AI SDK executor:
32
34
 
33
35
  ```sh
@@ -50,12 +52,12 @@ Requirements:
50
52
 
51
53
  ## Quick start
52
54
 
53
- <!-- refund decision example using setupAgent, agent.decide, a machine guard, and the AI SDK runAgent host -->
55
+ <!-- refund decision example using setupAgent, agent.decide, a machine guard, and the AI SDK runToQuiescence host -->
54
56
 
55
57
  This agent reviews refund requests. The model may propose an automatic refund, but the state machine owns the $100 limit.
56
58
 
57
59
  ```ts
58
- import { runAgent, setupAgent } from "@statelyai/agent";
60
+ import { createAgentRuntime, runToQuiescence, setupAgent } from "@statelyai/agent";
59
61
  import { z } from "zod";
60
62
 
61
63
  const agentSetup = setupAgent({
@@ -106,15 +108,19 @@ const refundMachine = agentSetup.createMachine({
106
108
  },
107
109
  });
108
110
 
109
- const result = await runAgent(refundMachine, {
110
- input: {
111
- request: "I was charged twice for the same order.",
112
- amount: 75,
111
+ const result = await runToQuiescence(
112
+ createAgentRuntime(refundMachine, {
113
+ // An executor is a plain function, so this run needs no API key and no
114
+ // provider package.
115
+ executors: { decide: async () => ({ event: { type: "AUTO_REFUND" } }) },
116
+ }),
117
+ {
118
+ input: {
119
+ request: "I was charged twice for the same order.",
120
+ amount: 75,
121
+ },
113
122
  },
114
- // An executor is a plain function, so this run needs no API key and no
115
- // provider package.
116
- executors: { decide: async () => ({ event: { type: "AUTO_REFUND" } }) },
117
- });
123
+ );
118
124
 
119
125
  if (result.status === "done") {
120
126
  console.log(result.output);
@@ -135,10 +141,12 @@ To call a real model, leave the machine unchanged and swap the executors:
135
141
  import { openai } from "@ai-sdk/openai";
136
142
  import { createAiSdkExecutors } from "@statelyai/agent/ai-sdk";
137
143
 
138
- const liveResult = await runAgent(refundMachine, {
139
- input: { request: "I was charged twice for the same order.", amount: 75 },
140
- executors: createAiSdkExecutors({ models: { fast: openai("gpt-5.4-mini") } }),
141
- });
144
+ const liveResult = await runToQuiescence(
145
+ createAgentRuntime(refundMachine, {
146
+ executors: createAiSdkExecutors({ models: { fast: openai("gpt-5.4-mini") } }),
147
+ }),
148
+ { input: { request: "I was charged twice for the same order.", amount: 75 } },
149
+ );
142
150
  ```
143
151
 
144
152
  For a machine with several requests, the executor routes on `request.name`, or `MockLanguageModelV3` from `ai/test` stands in for the provider behind `createAiSdkExecutors`. See [Evals](docs/evals.md#testing-without-a-provider).
@@ -149,7 +157,7 @@ Passing the same `models` map to `setupAgent({ models })` types the machine's mo
149
157
 
150
158
  ```mermaid
151
159
  flowchart LR
152
- M["Agent machine<br/>states · guards · requests"] -->|request| R["runAgent"]
160
+ M["Agent machine<br/>states · guards · requests"] -->|request| R["runToQuiescence"]
153
161
  R -->|executor call| E["Host executors<br/>generateText · streamText · decide"]
154
162
  E -->|API call| L["Model"]
155
163
  L -->|result| E
@@ -171,7 +179,7 @@ The core concepts (machines owning control flow, bounded model decisions, typed
171
179
  - [Chameleon](examples/chameleon) combines hidden information, sequential turns, and a human vote.
172
180
  - [Snapshot migration](examples/snapshot-migration) uses XState's native `version` and `migrate` contract.
173
181
  - [Portable XState loop](examples/portable-xstate-loop) runs the artifact through native transitions and effects.
174
- - [Framework-owned storage](examples/file-snapshot-store) persists native XState snapshots in application code.
182
+ - [Application-owned storage](examples/file-snapshot-store) persists native XState snapshots in application code.
175
183
  - [Tool calling](examples/review-tool-calls) keeps tools and message history in the AI SDK's native format.
176
184
  - [Ticket triage](examples/triage) returns structured data from a model request.
177
185
  - [JSON agent](examples/json-agent) runs a machine defined as data.
@@ -71,14 +71,6 @@
71
71
  "$ref": "#/$defs/State"
72
72
  }
73
73
  },
74
- "idleTags": {
75
- "description": "State tags that mark an intentional wait for an external event (a human approval, an inbound webhook, ...). Lowered by setupAgent.fromConfig(...) into a snapshot.hasTag(...) idle predicate so runAgent settles those states idle deterministically. Every listed tag must appear in some state's 'tags'.",
76
- "type": "array",
77
- "items": {
78
- "type": "string",
79
- "minLength": 1
80
- }
81
- },
82
74
  "meta": {
83
75
  "$ref": "#/$defs/JsonObject"
84
76
  }
@@ -144,9 +144,7 @@ function validateGeneratedConfig(candidate: unknown): AgentWorkflowConfig {
144
144
  const result = validateAgentConfig(candidate);
145
145
  if (result.valid) return candidate as AgentWorkflowConfig;
146
146
  throw new Error(
147
- result.errors
148
- .map((error) => `${error.path || "(root)"} ${error.message}`)
149
- .join("\n"),
147
+ result.errors.map((error) => `${error.path || "(root)"} ${error.message}`).join("\n"),
150
148
  );
151
149
  }
152
150
  ```
@@ -243,13 +241,13 @@ Keep the cap at ~3. A config that fails three schema-shaped repairs is usually a
243
241
  Deliver the config JSON plus how to run it:
244
242
 
245
243
  ```ts
246
- import { runAgent } from "@statelyai/agent";
244
+ import { runToQuiescence } from "@statelyai/agent";
247
245
  import { createAiSdkExecutors } from "@statelyai/agent/ai-sdk";
248
246
 
249
- const result = await runAgent(machine, {
250
- input: { ticket: "Export downloads a 0-byte CSV on Safari." },
251
- executors: createAiSdkExecutors({ resolveModel }),
252
- });
247
+ const result = await runToQuiescence(
248
+ createAgentRuntime(machine, { executors: createAiSdkExecutors({ resolveModel }) }),
249
+ { input: { ticket: "Export downloads a 0-byte CSV on Safari." } },
250
+ );
253
251
  ```
254
252
 
255
253
  Say which gates passed, list any warning-severity lint diagnostics, and report the dry-run status. Model refs are strings, so the host supplies `resolveModel`.