@statelyai/agent 1.1.6 → 2.0.0-alpha.5

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 (84) hide show
  1. package/LICENSE +21 -0
  2. package/dist/ai-sdk.cjs +249 -0
  3. package/dist/ai-sdk.d.cts +168 -0
  4. package/dist/ai-sdk.d.mts +168 -0
  5. package/dist/ai-sdk.mjs +241 -0
  6. package/dist/cli.cjs +63 -0
  7. package/dist/cli.d.cts +1 -0
  8. package/dist/cli.d.mts +1 -0
  9. package/dist/cli.mjs +64 -0
  10. package/dist/decision-FTmbqSEe.mjs +938 -0
  11. package/dist/decision-pC-bY2DE.cjs +1231 -0
  12. package/dist/index.cjs +54 -0
  13. package/dist/index.d.cts +1217 -0
  14. package/dist/index.d.mts +1194 -405
  15. package/dist/index.mjs +3 -588
  16. package/dist/openai-compat.cjs +319 -0
  17. package/dist/openai-compat.d.cts +98 -0
  18. package/dist/openai-compat.d.mts +98 -0
  19. package/dist/openai-compat.mjs +312 -0
  20. package/dist/src-CjpHDU8F.mjs +2445 -0
  21. package/dist/src-DcRsWPfV.cjs +2564 -0
  22. package/dist/text-logic-1ZQkO3zr.d.cts +682 -0
  23. package/dist/text-logic-2EMJIS-n.d.mts +682 -0
  24. package/dist/types-BHjeDdch.d.cts +208 -0
  25. package/dist/types-Cq1YlAQ6.d.mts +208 -0
  26. package/dist/utils-CWUCa3pF.d.mts +108 -0
  27. package/dist/utils-lK1wnL2i.d.cts +108 -0
  28. package/dist/zod.cjs +31 -0
  29. package/dist/zod.d.cts +30 -0
  30. package/dist/zod.d.mts +30 -0
  31. package/dist/zod.mjs +30 -0
  32. package/package.json +109 -28
  33. package/readme.md +144 -6
  34. package/schemas/agent-workflow.json +527 -0
  35. package/.changeset/README.md +0 -8
  36. package/.changeset/config.json +0 -11
  37. package/.env.template +0 -3
  38. package/.github/actions/ci-setup/action.yml +0 -24
  39. package/.github/workflows/release.yml +0 -46
  40. package/.vscode/launch.json +0 -28
  41. package/CHANGELOG.md +0 -222
  42. package/dist/index.d.ts +0 -428
  43. package/dist/index.js +0 -621
  44. package/examples/chatbot.ts +0 -71
  45. package/examples/cot.ts +0 -89
  46. package/examples/email.ts +0 -118
  47. package/examples/example.ts +0 -81
  48. package/examples/goal.ts +0 -94
  49. package/examples/helpers/helpers.ts +0 -17
  50. package/examples/helpers/loader.ts +0 -32
  51. package/examples/helpers/runner.ts +0 -27
  52. package/examples/joke.ts +0 -225
  53. package/examples/multi.ts +0 -103
  54. package/examples/newspaper.ts +0 -324
  55. package/examples/number.ts +0 -102
  56. package/examples/raffle.ts +0 -105
  57. package/examples/sandbox.ts +0 -28
  58. package/examples/simple.ts +0 -39
  59. package/examples/support.ts +0 -147
  60. package/examples/ticTacToe.ts +0 -224
  61. package/examples/todo.ts +0 -137
  62. package/examples/tutor.ts +0 -100
  63. package/examples/verify.ts +0 -120
  64. package/examples/weather.ts +0 -178
  65. package/examples/wiki.ts +0 -30
  66. package/examples/word.ts +0 -171
  67. package/src/adapters/vercel.ts +0 -7
  68. package/src/agent-experimental.ts +0 -221
  69. package/src/agent.test.ts +0 -506
  70. package/src/agent.ts +0 -300
  71. package/src/decision.test.ts +0 -179
  72. package/src/decision.ts +0 -84
  73. package/src/index.ts +0 -4
  74. package/src/memory.ts +0 -25
  75. package/src/planners/shortestPathPlanner.ts +0 -22
  76. package/src/planners/simplePlanner.ts +0 -139
  77. package/src/schemas.ts +0 -11
  78. package/src/strategies/chain-of-note.ts +0 -155
  79. package/src/templates/defaultText.ts +0 -18
  80. package/src/text.ts +0 -241
  81. package/src/types.ts +0 -499
  82. package/src/utils.ts +0 -72
  83. package/tsconfig.json +0 -109
  84. package/vitest.config.ts +0 -9
package/dist/index.d.mts CHANGED
@@ -1,428 +1,1217 @@
1
- import { EventObject, AnyStateMachine, AnyEventObject, AnyActorRef, SnapshotFrom, EventFrom, PromiseActorLogic, ActorLogic, TransitionSnapshot, Values, ActorRefFrom, Subscription, StateValue, ObservableActorLogic } from 'xstate';
2
- import { SomeZodObject, ZodType, TypeOf } from 'zod';
3
- import { generateText, streamText, LanguageModel, CoreMessage, GenerateTextResult, StreamTextResult, CoreTool } from 'ai';
1
+ import { C as ToolCallPart, D as UserMessage, E as ToolResultPart, S as TextPart, T as ToolResultOutput, _ as ImagePart, a as AgentToolDescriptor, b as StandardSchemaV1, c as AgentTools, d as AssistantMessage, f as ChosenEvent, g as FilePart, h as EventUnion, i as AgentToolChoice, l as AllowedEventPattern, m as EventPayload, n as AgentSnapshotStore, o as AgentToolExecute, p as DataContent, r as AgentTool, s as AgentToolSchema, t as AgentMessage, u as AllowedEvents, v as InferOutput, w as ToolMessage, x as SystemMessage, y as ProviderOptions } from "./types-Cq1YlAQ6.mjs";
2
+ import { A as AgentPlanInput, B as AgentEventDescriptor, C as createTextLogic, D as AgentDecisionExecutor, E as parseOutput, F as DecisionLogicConfig, G as getAcceptedEvents, H as AgentRequestOptions, I as PLAN_DONE_EVENT_TYPE, K as matchesEventPattern, L as ResolveDecisionOptions, M as DecisionAttempt, N as DecisionExhaustedError, O as AgentDecisionInput, P as DecisionLogic, R as renderDecisionAttempts, S as buildEnvelopeSchema, T as isStructuredOutputSchema, U as AgentRequestSource, V as AgentEventToolNameResolver, W as EVENT_TOOL_PREFIX, _ as TextLogicExecuteArgs, a as AgentRequestExecutorInfo, b as TextLogicOutput, c as AgentRequestMode, d as AiSdkShapedStreamResult, f as AiSdkShapedTextResult, g as TextLogicConfig, h as TextLogic, i as AgentRequestExecutor, j as AgentPlanOutput, k as AgentDecisionRequest, l as AgentTextRequest, m as StructuredOutputEnvelope, n as AgentModelRef, o as AgentRequestExecutorResult, p as BuiltinAgentActors, q as parseAgentEvent, r as AgentOutputMode, s as AgentRequestExecutors, t as AgentModelMap, u as AgentUserInput, v as TextLogicExecutor, w as getAgentOutputMode, x as bindRequestExecutor, y as TextLogicInput, z as resolveDecision } from "./text-logic-2EMJIS-n.mjs";
3
+ import { a as getMachineStructuralHash, c as persistSnapshot, d as userMessage, f as validateSchemaSync, i as getJsonSchemaSync, l as systemMessage, n as getAgentMessages, o as getStateMeta, r as getJsonSchema, s as isStandardSchema, t as assistantMessage, u as toolMessage } from "./utils-CWUCa3pF.mjs";
4
+ import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, InputFrom, InspectionEvent, MachineContext, MetaObject, NonReducibleUnknown, OutputFrom, SetupReturnFromConfig, SetupStateSchema, Snapshot, SnapshotFrom } from "xstate";
4
5
 
5
- type ZodEventMapping = {
6
- [eventType: string]: SomeZodObject;
6
+ //#region src/messages.d.ts
7
+ /**
8
+ * Builds a transition-function result that appends one or more
9
+ * {@link AgentMessage}s to a context's `messages` array. `resolve` is either
10
+ * a message (or array of messages) or a function of `{ context, event }`
11
+ * returning them; the returned function is meant to be used directly as (or
12
+ * composed into) a transition's result, e.g. `on: { USER_REPLIED:
13
+ * agent.appendMessages(({ event }) => userMessage(event.text)) }`. Requires
14
+ * `messages: AgentMessage[]` on context — see {@link messagesSchema} for a
15
+ * ready-made schema for that field.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * on: {
20
+ * USER_REPLIED: appendMessages(({ event }) => userMessage(event.text)),
21
+ * }
22
+ * ```
23
+ */
24
+ declare function appendMessages<TContext extends {
25
+ messages: AgentMessage[];
26
+ }, TEvent extends EventObject>(resolve: AgentMessage | AgentMessage[] | ((args: {
27
+ context: TContext;
28
+ event: TEvent;
29
+ }) => AgentMessage | AgentMessage[])): (args: {
30
+ context: TContext;
31
+ event: TEvent;
32
+ }) => {
33
+ context: {
34
+ messages: AgentMessage[];
35
+ };
7
36
  };
8
- type ZodContextMapping = {
9
- [contextKey: string]: ZodType;
37
+ /**
38
+ * A {@link StandardSchemaV1} validating an `AgentMessage[]` context field —
39
+ * checks that every message has a known `role` (`system`/`user`/`assistant`/
40
+ * `tool`) and that `content` is either a string (where the role allows it) or
41
+ * an array of parts with a known `type`. Use it directly as a context
42
+ * schema's `messages` field when authoring with `createAgentSchemas`.
43
+ */
44
+ declare const messagesSchema: StandardSchemaV1<AgentMessage[]>;
45
+ //#endregion
46
+ //#region src/workflow-config.d.ts
47
+ type JsonSchemaObject = {
48
+ type?: string | string[];
49
+ properties?: Record<string, JsonSchemaObject>;
50
+ required?: string[];
51
+ items?: JsonSchemaObject;
52
+ enum?: unknown[];
53
+ const?: unknown;
54
+ additionalProperties?: unknown;
55
+ [key: string]: unknown;
10
56
  };
11
-
12
- type GenerateTextOptions = Parameters<typeof generateText>[0];
13
- type StreamTextOptions = Parameters<typeof streamText>[0];
14
- type AgentPlanInput<TEvent extends EventObject> = Omit<GenerateTextOptions, 'prompt' | 'messages' | 'tools'> & {
15
- /**
16
- * The currently observed state.
17
- */
18
- state: ObservedState;
19
- /**
20
- * The goal for the agent to accomplish.
21
- * The agent will create a plan based on this goal.
22
- */
23
- goal: string;
24
- /**
25
- * The events that the agent can trigger. This is a mapping of
26
- * event types to Zod event schemas.
27
- */
28
- events: ZodEventMapping;
29
- /**
30
- * The state machine that represents the environment the agent
31
- * is interacting with.
32
- */
33
- machine?: AnyStateMachine;
34
- /**
35
- * The previous plan.
36
- */
37
- previousPlan?: AgentPlan<TEvent>;
57
+ /**
58
+ * Compiles a JSON Schema object (from an `AgentWorkflowConfig`) into a
59
+ * runtime `StandardSchemaV1` validator. `setupAgent.fromConfig(...)` calls
60
+ * this once per schema in the config (context/events/input/output/meta,
61
+ * request input/output) — bring your own engine (Ajv, @cfworker/json-schema,
62
+ * a compiled-Zod-from-JSON-Schema pipeline, ...). Core intentionally ships no
63
+ * JSON Schema engine.
64
+ */
65
+ type SchemaCompiler = (jsonSchema: Record<string, unknown>, name: string) => StandardSchemaV1;
66
+ /**
67
+ * Serializable JSON/YAML machine definition the config a database, visual
68
+ * editor, or LLM could produce and hand to `setupAgent.fromConfig(config, {
69
+ * compileSchema })` to get back the same kind of `AnyStateMachine`
70
+ * TypeScript `setupAgent(...)` authoring would build. JS/TS authoring should
71
+ * use `setupAgent(...)` directly instead of this JSON form. Any `unknown`-
72
+ * typed field here (`model`, `guard`, action `params`, …) accepts either a
73
+ * literal JSON value or a `"{{ path.to.value }}"` template-expression string
74
+ * resolved against `{ context, event, input, output }` at machine-build/
75
+ * transition time — see the sibling `evaluateWorkflowConfigValue` lowering.
76
+ */
77
+ interface AgentWorkflowConfig {
78
+ key?: string;
79
+ id?: string;
80
+ version?: string;
81
+ description?: string;
82
+ schemas?: {
83
+ input?: JsonSchemaObject;
84
+ context?: JsonSchemaObject;
85
+ events?: Record<string, JsonSchemaObject>;
86
+ emitted?: Record<string, JsonSchemaObject>;
87
+ output?: JsonSchemaObject;
88
+ meta?: JsonSchemaObject;
89
+ };
90
+ context?: Record<string, unknown>;
91
+ requests?: Record<string, AgentWorkflowRequestConfig>;
92
+ actors?: Record<string, AgentWorkflowActorConfig>;
93
+ initial: string;
94
+ states: Record<string, AgentWorkflowStateConfig>;
95
+ meta?: Record<string, unknown>;
96
+ }
97
+ /** 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}). */
98
+ interface AgentWorkflowRequestConfig {
99
+ mode?: AgentRequestMode;
100
+ description?: string;
101
+ model: unknown;
102
+ system?: unknown;
103
+ prompt?: unknown;
104
+ messages?: unknown;
105
+ input: JsonSchemaObject;
106
+ output: JsonSchemaObject;
107
+ tools?: AgentTools;
108
+ toolChoice?: AgentToolChoice | unknown;
109
+ /** Opt into the structured-output envelope's `reasoning` field (see `AgentTextRequest.reasoning`). */
110
+ reasoning?: boolean;
111
+ temperature?: unknown;
112
+ maxOutputTokens?: unknown;
113
+ topP?: unknown;
114
+ topK?: unknown;
115
+ seed?: unknown;
116
+ stopSequences?: unknown;
117
+ metadata?: unknown;
118
+ }
119
+ /** An `actors` entry in {@link AgentWorkflowConfig} — declares a placeholder actor source (by key) with no host execution wired from JSON; provide it via `machine.provide({ actorSources })` after `setupAgent.fromConfig(...)`. */
120
+ interface AgentWorkflowActorConfig {
121
+ input?: JsonSchemaObject;
122
+ output?: JsonSchemaObject;
123
+ description?: string;
124
+ }
125
+ /** A `states` entry in {@link AgentWorkflowConfig} — the JSON equivalent of an XState state node config. */
126
+ interface AgentWorkflowStateConfig {
127
+ description?: string;
128
+ type?: "parallel" | "history" | "final" | "choice";
129
+ initial?: string;
130
+ states?: Record<string, AgentWorkflowStateConfig>;
131
+ choice?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
132
+ invoke?: AgentWorkflowInvokeConfig | AgentWorkflowInvokeConfig[];
133
+ on?: Record<string, AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[]>;
134
+ always?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
135
+ onDone?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
136
+ after?: Record<string, AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[]>;
137
+ entry?: AgentWorkflowActionConfig | AgentWorkflowActionConfig[];
138
+ exit?: AgentWorkflowActionConfig | AgentWorkflowActionConfig[];
139
+ tags?: string[];
140
+ output?: unknown;
141
+ meta?: Record<string, unknown>;
142
+ }
143
+ /**
144
+ * An `invoke` entry in {@link AgentWorkflowStateConfig}. For `src:
145
+ * 'agent.decide'`, the chosen event is delivered automatically — its
146
+ * transition usually exits the state and ends the invoke, so an `onDone` is
147
+ * rarely needed; declare one only to observe a chosen event whose transition
148
+ * stays in-state. `onError` handles retries-exhausted.
149
+ */
150
+ interface AgentWorkflowInvokeConfig {
151
+ id?: string;
152
+ src: string;
153
+ input?: unknown;
154
+ onDone?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
155
+ onError?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
156
+ meta?: Record<string, unknown>;
157
+ }
158
+ /** A transition target in {@link AgentWorkflowConfig} (`on`/`always`/`onDone`/`after`/invoke `onDone`/`onError`) — the JSON equivalent of an XState transition config. `guard`, when a string, is a template expression evaluated as truthy/falsy. */
159
+ interface AgentWorkflowTransitionConfig {
160
+ target?: string | string[];
161
+ guard?: unknown;
162
+ assign?: Record<string, unknown>;
163
+ actions?: AgentWorkflowActionConfig | AgentWorkflowActionConfig[];
164
+ description?: string;
165
+ reenter?: boolean;
166
+ meta?: Record<string, unknown>;
167
+ }
168
+ /** An `entry`/`exit`/transition `actions` entry in {@link AgentWorkflowConfig} — either a named action `type` (with template-expression `params`) or a bare context `assign`. */
169
+ interface AgentWorkflowActionConfig {
170
+ type?: string;
171
+ params?: unknown;
172
+ assign?: Record<string, unknown>;
173
+ emit?: unknown;
174
+ [key: string]: unknown;
175
+ }
176
+ /** Options for `setupAgent.fromConfig(...)`. */
177
+ interface FromConfigOptions {
178
+ /**
179
+ * Compile a JSON Schema from the config into a runtime validator. Bring
180
+ * your own engine (Ajv, @cfworker/json-schema, a compiled-Zod-from-JSON-Schema
181
+ * pipeline, ...). Core intentionally ships no JSON Schema engine.
182
+ */
183
+ compileSchema: SchemaCompiler;
184
+ }
185
+ //#endregion
186
+ //#region src/setup-agent.d.ts
187
+ type Constrain<T, TConstraint> = T extends TConstraint ? T : TConstraint;
188
+ type ContextOf<TContextSchema extends StandardSchemaV1> = Constrain<InferOutput<TContextSchema>, MachineContext>;
189
+ type EventsOf<TEventSchemas extends Record<string, StandardSchemaV1>> = Constrain<EventUnion<TEventSchemas>, EventObject>;
190
+ type SetupActors<TActors extends { [K in keyof TActors]: AnyActorLogic }> = { [K in keyof TActors]: TActors[K] extends AsyncActorLogic<infer TOutput, infer TInput> ? AsyncActorLogic<TOutput, TInput> : TActors[K] };
191
+ type AgentSetupActors<TActors extends { [K in keyof TActors]: AnyActorLogic }, TEvent extends string = string, TModel extends string = string> = TActors & BuiltinAgentActors<TEvent, TModel>;
192
+ /**
193
+ * A machine's full schema set — context, event payloads, machine input/
194
+ * output, and state/transition meta — as returned by {@link createAgentSchemas}
195
+ * and retained on `setupAgent(...)`'s `result.schemas` for runtime
196
+ * validation (e.g. by the step path to validate `initialAgentStep` input, or
197
+ * by `getAcceptedEvents` to attach event payload schemas). Unlike
198
+ * `AgentSchemaConfig` (the input to `createAgentSchemas`), every field here
199
+ * is required — `events`/`input`/`output`/`meta` default to empty/unknown
200
+ * schemas when not supplied.
201
+ */
202
+ interface AgentSchemaPack<TContextSchema extends StandardSchemaV1<Record<string, unknown>> = StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1> = Record<string, StandardSchemaV1>, TInputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TMetaSchema extends StandardSchemaV1 = StandardSchemaV1<MetaObject>, TEmittedSchemas extends Record<string, StandardSchemaV1> = Record<string, StandardSchemaV1>> {
203
+ context: TContextSchema;
204
+ events: TEventSchemas;
205
+ input: TInputSchema;
206
+ output: TOutputSchema;
207
+ meta: TMetaSchema;
208
+ /** Schemas for events the machine emits (`enq.emit(...)`), keyed by event type — they type `enq.emit` in the machine and the `on` handlers of {@link runAgent}. Optional: omitted means emitted events stay untyped. */
209
+ emitted?: TEmittedSchemas;
210
+ }
211
+ type AgentSchemaConfig<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TEmittedSchemas extends Record<string, StandardSchemaV1> = Record<string, StandardSchemaV1>> = {
212
+ context: TContextSchema;
213
+ events?: TEventSchemas;
214
+ input?: TInputSchema;
215
+ output?: TOutputSchema;
216
+ meta?: TMetaSchema;
217
+ emitted?: TEmittedSchemas;
218
+ };
219
+ /**
220
+ * Builds a machine's {@link AgentSchemaPack} from a partial schema
221
+ * declaration — only `context` is required; `events`/`input`/`output`/`meta`
222
+ * default to empty/unknown schemas when omitted. Pass the result as
223
+ * `setupAgent({ schemas })`'s `schemas` (or spread the individual fields
224
+ * directly into `setupAgent({ context, events, ... })` — both forms are
225
+ * accepted).
226
+ */
227
+ declare function createAgentSchemas<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1> = {}, TInputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TMetaSchema extends StandardSchemaV1 = StandardSchemaV1<MetaObject>, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}>(schemas: AgentSchemaConfig<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>): AgentSchemaPack<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>;
228
+ type AgentRequestConfig<TInputSchema extends StandardSchemaV1 = StandardSchemaV1, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1, TMetadata = Record<string, unknown>, TModel extends string = string> = TextLogicConfig<TInputSchema, TOutputSchema, TMetadata, TModel> & {
229
+ mode?: AgentRequestMode;
230
+ };
231
+ type AgentRequestSchemaMap = Record<string, {
232
+ input: StandardSchemaV1;
233
+ output: StandardSchemaV1;
234
+ }>;
235
+ type AgentRequestInput<TRequestSchemas extends AgentRequestSchemaMap, TModel extends string = string> = { [K in keyof TRequestSchemas]: AgentRequestConfig<TRequestSchemas[K]["input"], TRequestSchemas[K]["output"], Record<string, unknown>, TModel> & {
236
+ schemas: TRequestSchemas[K];
237
+ } };
238
+ type RequestActors<TRequestSchemas extends AgentRequestSchemaMap> = { [K in keyof TRequestSchemas]: TextLogic<TRequestSchemas[K]["input"], TRequestSchemas[K]["output"]> };
239
+ type AgentAllActors<TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap> = TActors & RequestActors<TRequestSchemas>;
240
+ type AgentSetupEventsSchema<TEventSchemas extends Record<string, StandardSchemaV1>> = [keyof TEventSchemas] extends [never] ? {} : {
241
+ events: TEventSchemas;
38
242
  };
39
- type AgentPlan<TEvent extends EventObject> = {
40
- goal: string;
41
- state: ObservedState;
42
- content?: string;
43
- /**
44
- * Executes the plan based on the given `state` and resolves with
45
- * a potential next `event` to trigger to achieve the `goal`.
46
- */
47
- execute: (state: ObservedState) => Promise<TEvent | undefined>;
48
- nextEvent: TEvent | undefined;
49
- sessionId: string;
50
- timestamp: number;
243
+ type AgentSetupEmittedSchema<TEmittedSchemas extends Record<string, StandardSchemaV1>> = [keyof TEmittedSchemas] extends [never] ? {} : {
244
+ emitted: TEmittedSchemas;
51
245
  };
52
- interface TransitionData {
53
- eventType: string;
54
- description?: string;
55
- guard?: {
56
- type: string;
246
+ type AgentSetupXStateConfig<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, 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, SetupStateSchema> = Record<string, SetupStateSchema>> = {
247
+ schemas: {
248
+ context: TContextSchema;
249
+ input: TInputSchema;
250
+ output: TOutputSchema;
251
+ meta: TMetaSchema;
252
+ } & AgentSetupEventsSchema<TEventSchemas> & AgentSetupEmittedSchema<TEmittedSchemas>;
253
+ states?: TStateSchemas;
254
+ actorSources: SetupActors<AgentSetupActors<AgentAllActors<TActors, TRequestSchemas>, keyof TEventSchemas & string, AgentModelRef<TModels>>>;
255
+ actions?: NonNullable<AnySetupConfig["actions"]>;
256
+ guards?: NonNullable<AnySetupConfig["guards"]>;
257
+ delays?: NonNullable<AnySetupConfig["delays"]>;
258
+ };
259
+ type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TRequestSchemas extends AgentRequestSchemaMap, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, SetupStateSchema> = Record<string, SetupStateSchema>> = ({
260
+ schemas: AgentSchemaPack<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>;
261
+ } | AgentSchemaConfig<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>) & {
262
+ models?: TModels;
263
+ actorSources?: TActors;
264
+ /**
265
+ * Per-state schemas, mirroring xstate's `setup({ states })`: declare a
266
+ * `schemas.context` on a state to narrow `context` inside that state
267
+ * (invoke `input`, transition fns, final `output`) — e.g. mark a field
268
+ * non-null in states only reachable after it is set.
269
+ */
270
+ states?: TStateSchemas;
271
+ requests?: AgentRequestInput<TRequestSchemas, AgentModelRef<TModels>>;
272
+ actions?: NonNullable<AnySetupConfig["actions"]>;
273
+ guards?: NonNullable<AnySetupConfig["guards"]>;
274
+ delays?: NonNullable<AnySetupConfig["delays"]>;
275
+ /**
276
+ * Detects a snapshot that is an INTENTIONAL wait for an external event (a
277
+ * human approval, an inbound webhook, …) — the machine's own declaration of
278
+ * what "suspended" means for it, so `runAgent` settles those snapshots idle
279
+ * deterministically instead of using its timing heuristic. Travels with the
280
+ * machine through `machine.provide(...)`. A `runAgent({ isSuspended })` host
281
+ * override takes precedence; with neither, `runAgent` falls back to the timing
282
+ * heuristic. Declare your own signal — e.g. `(s) => s.hasTag('awaiting-review')`
283
+ * or `(s) => getStateMeta(s).interaction !== undefined`.
284
+ */
285
+ isSuspended?: (snapshot: AnyMachineSnapshot) => boolean;
286
+ };
287
+ type SetupAgentXStateResult<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, 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, SetupStateSchema> = Record<string, SetupStateSchema>> = SetupReturnFromConfig<AgentSetupXStateConfig<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>>;
288
+ /**
289
+ * The object returned by {@link setupAgent}: an xstate `setup(...)` result
290
+ * (`createMachine`, `assign`, …) extended with `schemas` (the resolved
291
+ * {@link AgentSchemaPack}), `models`, `requests` (the built request actors),
292
+ * and {@link appendMessages}. Machines created here are registered so
293
+ * `runAgent` and the free step helpers can resolve their schemas/actors
294
+ * without re-passing them each call.
295
+ */
296
+ type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, 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, SetupStateSchema> = Record<string, SetupStateSchema>> = Omit<SetupAgentXStateResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>, "createMachine"> & {
297
+ /**
298
+ * Creates the agent machine — XState's own `createMachine`, plus: the
299
+ * machine is registered so step helpers and {@link runAgent} can resolve
300
+ * its schemas/actors without re-passing them, and a single final state's
301
+ * `output` is copied to the machine root when the root declares none.
302
+ */
303
+ createMachine: SetupAgentXStateResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>["createMachine"]; /** The retained schema pack ({@link AgentSchemaPack}) for host-side validation and tooling. */
304
+ schemas: AgentSchemaPack<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>; /** The `models` registry passed to `setupAgent(...)`, if any (used to type-narrow `AgentModelRef`). */
305
+ readonly models: TModels; /** The {@link TextLogic} actors built from `setupAgent({ requests })`, keyed the same way. */
306
+ readonly requests: RequestActors<TRequestSchemas>; /** {@link appendMessages}, typed against this agent's context/event schemas. */
307
+ appendMessages(resolve: AgentMessage | AgentMessage[] | ((args: {
308
+ context: ContextOf<TContextSchema> & {
309
+ messages: AgentMessage[];
57
310
  };
58
- target?: any;
311
+ event: any;
312
+ }) => AgentMessage | AgentMessage[])): ReturnType<typeof appendMessages<ContextOf<TContextSchema> & {
313
+ messages: AgentMessage[];
314
+ }, EventsOf<TEventSchemas>>>;
315
+ };
316
+ /**
317
+ * Schema-first `setup(...)` for agent machines — the standard entry point
318
+ * for authoring a machine (the blueprint) that this library then runs (via
319
+ * {@link runAgent} or the step helpers) against host-supplied model/decision
320
+ * executors. Context, events, machine input, machine output, and
321
+ * state/transition meta are all standard schemas — no `{} as Type` casts —
322
+ * and are retained on `result.schemas` for runtime validation. Also
323
+ * registers the `agent.generateText`/`agent.streamText`/`agent.userInput`/
324
+ * `agent.decide` builtin actors and lowers `requests`/`actorSources` into the
325
+ * machine's actor sources. The result is the xstate `setup(...)` object with
326
+ * a wrapped `result.createMachine(...)` plus `result.schemas`/`models`/
327
+ * `requests`/`appendMessages` attached. Also has a
328
+ * `setupAgent.fromConfig(...)` namespace member for building a machine from
329
+ * a serializable {@link AgentWorkflowConfig} instead of this TS API.
330
+ *
331
+ * @example
332
+ * ```ts
333
+ * const schemas = createAgentSchemas({
334
+ * context: z.object({ topic: z.string(), joke: z.string().nullable() }),
335
+ * input: z.object({ topic: z.string() }),
336
+ * output: z.object({ joke: z.string() }),
337
+ * });
338
+ *
339
+ * const agent = setupAgent({
340
+ * schemas,
341
+ * actorSources: { tellJoke },
342
+ * });
343
+ *
344
+ * const jokeMachine = agent.createMachine({
345
+ * context: ({ input }) => ({ topic: input.topic, joke: null }),
346
+ * initial: 'telling',
347
+ * states: {
348
+ * telling: {
349
+ * invoke: {
350
+ * id: 'joke',
351
+ * src: 'tellJoke',
352
+ * input: ({ context }) => ({ topic: context.topic }),
353
+ * onDone: ({ output }) => ({ target: 'done', context: { joke: output } }),
354
+ * },
355
+ * },
356
+ * done: { type: 'final', output: ({ context }) => ({ joke: context.joke ?? '' }) },
357
+ * },
358
+ * });
359
+ * ```
360
+ */
361
+ declare function setupAgent<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap = {}, TInputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TMetaSchema extends StandardSchemaV1 = StandardSchemaV1<MetaObject>, TModels extends AgentModelMap = {}, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, const TStateSchemas extends Record<string, SetupStateSchema> = Record<string, SetupStateSchema>>(config: SetupAgentBaseConfig<TContextSchema, TEventSchemas, TActors, TInputSchema, TOutputSchema, TMetaSchema, TRequestSchemas, TModels, TEmittedSchemas, TStateSchemas>): SetupAgentResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>;
362
+ declare namespace setupAgent {
363
+ /**
364
+ * Builds a state machine from a serializable {@link AgentWorkflowConfig}
365
+ * (JSON/YAML) instead of the TypeScript `setupAgent(...)` API — the same
366
+ * kind of machine a database, visual editor, or LLM could produce and hand
367
+ * back. Requires a `compileSchema` (see {@link FromConfigOptions}) since
368
+ * the library bundles no JSON Schema engine itself; bring Ajv,
369
+ * @cfworker/json-schema, or another compiler that returns Standard Schema.
370
+ *
371
+ * @example
372
+ * ```ts
373
+ * const machine = setupAgent.fromConfig(workflowConfig, {
374
+ * compileSchema,
375
+ * });
376
+ * const result = await runAgent(machine, { input: { ticket }, executors: { generateText, decide } });
377
+ * ```
378
+ */
379
+ function fromConfig(config: AgentWorkflowConfig, options: FromConfigOptions): AnyStateMachine;
59
380
  }
60
- type PromptTemplate<TEvents extends EventObject> = (data: {
61
- goal: string;
62
- /**
63
- * The observed state
64
- */
65
- state?: ObservedState;
66
- /**
67
- * The context to provide.
68
- * This overrides the observed state.context, if provided.
69
- */
70
- context?: any;
71
- /**
72
- * The state machine model of the observed environment
73
- */
74
- machine?: unknown;
75
- /**
76
- * The potential next transitions that can be taken
77
- * in the state machine
78
- */
79
- transitions?: TransitionData[];
80
- /**
81
- * Past observations
82
- */
83
- observations?: AgentObservation<any>[];
84
- feedback?: AgentFeedback[];
85
- messages?: AgentMessage[];
86
- plans?: AgentPlan<TEvents>[];
87
- }) => string;
88
- type AgentPlanner<T extends AnyAgent> = (agent: T, input: AgentPlanInput<T['types']['events']>) => Promise<AgentPlan<T['types']['events']> | undefined>;
89
- type AgentDecideOptions = {
90
- goal: string;
91
- model?: LanguageModel;
92
- context?: any;
93
- state: ObservedState;
94
- machine: AnyStateMachine;
95
- execute?: (event: AnyEventObject) => Promise<void>;
96
- planner?: AgentPlanner<any>;
97
- events?: ZodEventMapping;
98
- } & Omit<Parameters<typeof generateText>[0], 'model' | 'tools' | 'prompt' | 'messages'>;
99
- interface AgentFeedback {
100
- goal?: string;
101
- observationId?: string;
102
- /**
103
- * The message correlation that the feedback is relevant for
104
- */
105
- correlationId?: string;
106
- attributes: Record<string, any>;
107
- reward: number;
108
- timestamp: number;
109
- sessionId: string;
381
+ //#endregion
382
+ //#region src/internal/registry.d.ts
383
+ type AgentExecutionOptions = Pick<AgentRequestOptions, "schemas" | "actorSources">;
384
+ //#endregion
385
+ //#region src/steps.d.ts
386
+ /**
387
+ * A pending text request surfaced by step discovery ({@link getAgentRequests}
388
+ * / {@link AgentStep.requests}): the machine has spawned a
389
+ * `TextLogic`-backed invoke and is waiting on its result. Resolve it with
390
+ * {@link executeAgentRequest} (or by hand, then feed the output into
391
+ * {@link resolveAgentStep} via `xstate.done.actor.<id>`).
392
+ */
393
+ interface AgentRequest<TInput extends AgentTextRequest = AgentTextRequest> {
394
+ kind: "text";
395
+ id: string;
396
+ src: AgentRequestSource;
397
+ mode?: AgentRequestMode;
398
+ input: TInput;
399
+ tools: AgentTools;
400
+ events: AgentEventDescriptor[];
110
401
  }
111
- interface AgentFeedbackInput {
112
- goal?: string;
113
- observationId?: string;
114
- correlationId?: string;
115
- attributes?: Record<string, any>;
116
- timestamp?: number;
117
- reward?: number;
402
+ /**
403
+ * A pending **plan** request re-surfaced by step discovery: the machine
404
+ * invoked `agent.plan`, which applies an ordered sequence of legal events
405
+ * (each one a decision) rather than a single one. Unlike text/decision
406
+ * requests — surfaced once and resolved once — a plan request **re-surfaces on
407
+ * every step** while the plan is in flight, its `events`/`applied`/
408
+ * `stepsRemaining` updated each time, until it terminates.
409
+ *
410
+ * All fields are plain serializable data. Resolve ONE decision per step from
411
+ * `events` (via {@link resolveDecision}, wiring `canTake` to
412
+ * `snapshot.can` exactly like a single decision) then apply it: a real machine
413
+ * event advances the plan (the next step re-surfaces this request); the
414
+ * reserved `agent.plan.done` move, a `stopOn` event, an exhausted budget, or no
415
+ * legal events completes it (its invoke resolves with `{ steps, stopped }`).
416
+ * {@link resolveAgentRequests} does all of this natively — one decision (or one
417
+ * completion) per call.
418
+ *
419
+ * The in-progress plan state (`applied` trail + remaining budget) lives in the
420
+ * plan invoke child's own `createLogic` snapshot `context`
421
+ * (`children.<id>.snapshot.context`), so it survives a full JSON
422
+ * `getPersistedSnapshot` → restore round-trip: a host that persists the step
423
+ * after every event and reloads resumes the plan identically.
424
+ */
425
+ interface AgentPlanRequest {
426
+ kind: "plan";
427
+ /** Durable invoke id of the `agent.plan` invoke. */
428
+ id: string;
429
+ /** Invoke src (`'agent.plan'` or a registered plan-logic source name). */
430
+ src: AgentRequestSource;
431
+ /** The resolved plan input (`model`/`system`/`prompt`/`allowedEvents`/`stopOn`/`maxSteps`/…). */
432
+ input: AgentPlanInput;
433
+ /**
434
+ * The legal candidates for the NEXT plan step: the currently
435
+ * snapshot-legal machine events (∩ declared `allowedEvents`) plus the
436
+ * reserved `agent.plan.done` move.
437
+ */
438
+ events: AgentEventDescriptor[];
439
+ /** The events applied so far in this plan, in order (the trail). */
440
+ applied: ChosenEvent[];
441
+ /** How many more events the plan may apply (`maxSteps - applied.length`). */
442
+ stepsRemaining: number;
118
443
  }
119
- type AgentMessage = CoreMessage & {
120
- timestamp: number;
121
- id: string;
122
- /**
123
- * The response ID of the message, which references
124
- * which message this message is responding to, if any.
125
- */
126
- responseId?: string;
127
- result?: GenerateTextResult<any>;
128
- sessionId: string;
129
- correlationId: string;
130
- parentCorrelationId?: string;
131
- };
132
- type AgentMessageInput = CoreMessage & {
133
- timestamp?: number;
134
- id?: string;
135
- /**
136
- * The response ID of the message, which references
137
- * which message this message is responding to, if any.
138
- */
139
- responseId?: string;
140
- correlationId?: string;
141
- parentCorrelationId?: string;
142
- result?: GenerateTextResult<any>;
143
- };
144
- interface AgentObservation<TActor extends AnyActorRef> {
145
- id: string;
146
- prevState: SnapshotFrom<TActor> | undefined;
147
- event: EventFrom<TActor>;
148
- state: SnapshotFrom<TActor>;
149
- machineHash: string | undefined;
150
- sessionId: string;
151
- timestamp: number;
444
+ /** `AgentStep.requests` element: a text, decision, or plan request. */
445
+ type AgentStepRequest = AgentRequest | AgentDecisionRequest | AgentPlanRequest;
446
+ /**
447
+ * One durable checkpoint on the step path: the machine's current snapshot,
448
+ * the executable actions that produced it, the pending
449
+ * {@link AgentStepRequest}s (text/decision work still to resolve), and
450
+ * whether the machine has reached a final state. This is the
451
+ * per-model-call-checkpoint path for durable hosts (Workflows, Temporal,
452
+ * queues, …) — a peer of `runAgent`, not a lesser version of it. Produced by
453
+ * {@link initialAgentStep}/{@link transitionAgentStep}/{@link resolveAgentStep}.
454
+ */
455
+ interface AgentStep<TSnapshot extends AnyMachineSnapshot = AnyMachineSnapshot> {
456
+ snapshot: TSnapshot;
457
+ actions: readonly {
458
+ type?: string;
459
+ params?: unknown;
460
+ }[];
461
+ requests: AgentStepRequest[];
462
+ done: boolean;
463
+ }
464
+ /**
465
+ * Starts a machine and returns its first {@link AgentStep} — the step-path
466
+ * equivalent of `initialTransition` plus request discovery. Begins the
467
+ * durable/per-model-call-checkpoint loop: resolve each `step.requests` entry
468
+ * (via {@link executeAgentRequest} for `kind: 'text'`, or
469
+ * {@link resolveDecision} for `kind: 'decision'`), then advance with
470
+ * {@link resolveAgentStep} or {@link transitionAgentStep}.
471
+ */
472
+ declare function initialAgentStep<TMachine extends AnyActorLogic>(machine: TMachine, input?: unknown, options?: Partial<AgentExecutionOptions>): AgentStep<SnapshotFrom<TMachine>>;
473
+ /**
474
+ * Applies an externally-sent event (e.g. a decision's chosen event, or a
475
+ * human's reply) and returns the next {@link AgentStep}. Accepts **either**
476
+ * a raw snapshot **or** a prior `AgentStep` as the second argument —
477
+ * `.snapshot` is unwrapped automatically, so callers can thread the whole
478
+ * step object through without manually plucking the snapshot out.
479
+ */
480
+ declare function transitionAgentStep<TMachine extends AnyActorLogic>(machine: TMachine, snapshotOrStep: SnapshotFrom<TMachine> | AgentStep<SnapshotFrom<TMachine>>, event: EventFromLogic<TMachine>, options?: Partial<AgentExecutionOptions>): AgentStep<SnapshotFrom<TMachine>>;
481
+ /**
482
+ * Applies a resolved text request's output (a `kind: 'text'`
483
+ * {@link AgentRequest} — not a decision) as a done event and returns the
484
+ * next {@link AgentStep}. For decisions, resolve with `resolveDecision`
485
+ * (which returns a {@link ChosenEvent}) and apply it with
486
+ * {@link transitionAgentStep} instead — a decision has no output value of
487
+ * its own to feed here.
488
+ */
489
+ declare function resolveAgentStep<TMachine extends AnyActorLogic>(machine: TMachine, step: AgentStep<SnapshotFrom<TMachine>>, request: Pick<AgentRequest, "id"> | string, output: unknown, options?: Partial<AgentExecutionOptions>): AgentStep<SnapshotFrom<TMachine>>;
490
+ /**
491
+ * Snapshot in, requests out: scans executable actions for spawned agent
492
+ * invokes and lowers each into an {@link AgentStepRequest}, pre-filled with
493
+ * the machine's registered `setupAgent` schemas/actorSources (so callers
494
+ * don't pass them by hand each call) — merged with any `options` passed here,
495
+ * which take precedence. The step path's public discovery primitive;
496
+ * `initialAgentStep`/`transitionAgentStep`/`resolveAgentStep` call it
497
+ * internally to populate `AgentStep.requests`.
498
+ */
499
+ declare function getAgentRequests(machine: AnyActorLogic, actions: readonly {
500
+ type?: string;
501
+ params?: unknown;
502
+ }[], snapshot?: AnyMachineSnapshot, options?: Pick<AgentRequestOptions, "eventToolName"> & Partial<AgentExecutionOptions>): AgentStepRequest[];
503
+ /**
504
+ * Resolves one **text** {@link AgentRequest} against a host's
505
+ * {@link AgentRequestExecutors} — merges the request's tools, dispatches to
506
+ * `generateText`/`streamText` per `request.mode`, and validates the result
507
+ * against `request.input.outputSchema` if present. **Text-only**: passing a
508
+ * `kind: 'decision'` request throws, directing the caller to
509
+ * `resolveDecision(request, executors.decide, ...)` instead. By default
510
+ * returns the normalized output; pass `{ verbose: true }` to also get the
511
+ * raw executor result (tool calls, usage, finish reason — needed for
512
+ * observability and event-sourced replay).
513
+ */
514
+ declare function executeAgentRequest(request: AgentRequest, executors: Partial<AgentRequestExecutors>): Promise<unknown>;
515
+ declare function executeAgentRequest(request: AgentRequest, executors: Partial<AgentRequestExecutors>, options: {
516
+ verbose: true;
517
+ }): Promise<{
518
+ output: unknown;
519
+ raw: unknown;
520
+ }>;
521
+ /**
522
+ * Options for {@link resolveAgentRequests}.
523
+ */
524
+ interface ResolveAgentRequestsOptions extends Partial<AgentExecutionOptions> {
525
+ /** Retries per decision, passed to `resolveDecision`. Default `2`. */
526
+ maxRetries?: number;
527
+ }
528
+ /**
529
+ * Resolves the current step's pending requests and returns the next
530
+ * {@link AgentStep} — one iteration of the durable step loop, collapsing the
531
+ * manual `request.kind` dispatch a host would otherwise write by hand.
532
+ *
533
+ * For each pending request, in order: a `kind: 'text'` request is run with
534
+ * {@link executeAgentRequest} then fed back via {@link resolveAgentStep}; a
535
+ * `kind: 'decision'` request is resolved with `resolveDecision` (wiring
536
+ * `canTake` to `step.snapshot.can` so guard-rejected choices retry) then
537
+ * applied with {@link transitionAgentStep}. The **current** step is re-read
538
+ * after each application — the machine may advance and its `requests` change —
539
+ * so this always resolves against the live step, never a stale list.
540
+ *
541
+ * A `kind: 'plan'` request (`agent.plan`) is resolved natively too: one plan
542
+ * step per call. It resolves a single decision from `request.events` (wiring
543
+ * `canTake` to `step.snapshot.can`, exempting the reserved `agent.plan.done`
544
+ * move and `stopOn` events), then either applies the chosen machine event and
545
+ * lets the next step re-surface the plan, or completes the plan (feeding its
546
+ * `{ steps, stopped }` output back) on the done move / a `stopOn` event / an
547
+ * exhausted budget / no legal events. The plan's applied trail is carried in
548
+ * the invoke child's snapshot, so persisting the step between calls resumes the
549
+ * plan identically.
550
+ *
551
+ * Missing the executor a request needs throws a clear error
552
+ * (`generateText`/`streamText` for text, `decide` for decisions and plans).
553
+ *
554
+ * A complete durable host is two lines:
555
+ *
556
+ * ```ts
557
+ * let step = initialAgentStep(machine, input);
558
+ * while (!step.done) step = await resolveAgentRequests(machine, step, executors);
559
+ * ```
560
+ *
561
+ * All pending **text** requests of a step are resolved in parallel
562
+ * (`Promise.all`) — parallel statechart regions are genuinely concurrent, so
563
+ * their model calls run concurrently — then their outputs apply in
564
+ * **request-array order** (deterministic for durable replay regardless of which
565
+ * call finishes first). Decisions and plans stay **one at a time**: applying
566
+ * either changes the set of legal candidates for what follows, so they cannot be
567
+ * resolved against a stale snapshot. A host that instead wants strictly
568
+ * sequential text resolution loops the manual per-request helpers
569
+ * ({@link executeAgentRequest} + {@link resolveAgentStep}) one at a time.
570
+ */
571
+ declare function resolveAgentRequests<TMachine extends AnyActorLogic>(machine: TMachine, step: AgentStep<SnapshotFrom<TMachine>>, executors: Partial<AgentRequestExecutors>, options?: ResolveAgentRequestsOptions): Promise<AgentStep<SnapshotFrom<TMachine>>>;
572
+ //#endregion
573
+ //#region src/internal/state-request-pass.d.ts
574
+ /**
575
+ * One model request read off the machine's CURRENT snapshot by a
576
+ * `RunAgentOptions.getRequests` hook. `model` is an executor model NAME — the
577
+ * same string every {@link AgentTextRequest.model} carries, resolved by the
578
+ * run's executors (e.g. a `defineModels` key when using
579
+ * `createAiSdkExecutors`) — never a model instance.
580
+ */
581
+ interface AgentStateRequest {
582
+ /** Instruction for this request's model call, appended to the run's message log as a user message. */
583
+ prompt: string;
584
+ /** System prompt for this request's model call(s). */
585
+ system?: string;
586
+ /** Executor model name (resolved by the run's executors). */
587
+ model: string;
588
+ /**
589
+ * `'text'` (default): a `generateText` call with the message log +
590
+ * `prompt`; the reply is appended to the log, then the machine is advanced
591
+ * per {@link AgentStateRequest.onDone}. `'decision'`: no text call — a
592
+ * single `decide` call (log + `prompt`) chooses the event. Use for pure
593
+ * routing states.
594
+ */
595
+ kind?: "text" | "decision";
596
+ /**
597
+ * What to send when this request's text call resolves — the EXPLICIT
598
+ * advancement contract, always an event OBJECT (the same shape
599
+ * `actor.send` takes; no string shorthand). A literal event sends exactly
600
+ * that; a function receives the text output (plus the live snapshot and
601
+ * message log) and returns the event to send — payload included — or
602
+ * `undefined` to send nothing. Omitted: a `decide` call chooses among the
603
+ * candidate events (requires a `decide` executor) — there is no implicit
604
+ * auto-send. A resolved event whose type the state does not accept throws
605
+ * (programmer error); one a guard rejects is simply not sent. Ignored for
606
+ * `kind: 'decision'` (the decide call IS the advancement).
607
+ */
608
+ onDone?: ChosenEvent | ((args: {
609
+ output: unknown;
610
+ snapshot: AnyMachineSnapshot;
611
+ messages: readonly AgentMessage[];
612
+ }) => ChosenEvent | undefined);
613
+ /** Restricts this request's candidate outcome events for the `decide` fallback (default: every currently-accepted event). */
614
+ allowedEvents?: readonly string[];
615
+ /** Trace/request id; defaults to `interpret_<n>`. */
616
+ id?: string;
617
+ }
618
+ //#endregion
619
+ //#region src/run-agent.d.ts
620
+ /**
621
+ * Thrown by {@link runAgent} when resuming with a `snapshot` + `event` whose
622
+ * `type` the restored state cannot accept (a type-level check via
623
+ * {@link getAcceptedEvents}). A programmer/integration error, in the same
624
+ * class as runAgent's bind-time throws — it throws rather than settling an
625
+ * `error` result. A type-legal event a guard rejects is NOT this error (the
626
+ * machine simply takes no transition). Opt out with
627
+ * {@link RunAgentOptions.onIllegalResumeEvent} `'ignore'`.
628
+ */
629
+ declare class IllegalResumeEventError extends Error {
630
+ readonly eventType: string;
631
+ readonly acceptedTypes: string[];
632
+ constructor(eventType: string, acceptedTypes: string[]);
633
+ }
634
+ /**
635
+ * Thrown by {@link runAgent} when resuming from a `snapshot` whose stamped
636
+ * `agentMeta.version` differs from the current machine's version, under the
637
+ * default `onVersionMismatch: 'throw'` and with no `migrateSnapshot` hook. The
638
+ * structural fingerprint of the machine changed since the snapshot was
639
+ * persisted (a state/transition/invoke was added, removed, or retargeted), so
640
+ * the snapshot may no longer resume cleanly. `from` is the snapshot's version,
641
+ * `to` the current machine's.
642
+ */
643
+ declare class SnapshotVersionMismatchError extends Error {
644
+ readonly from: string;
645
+ readonly to: string;
646
+ readonly machineId: string;
647
+ constructor(from: string, to: string, machineId: string);
152
648
  }
153
- interface AgentObservationInput {
154
- id?: string;
155
- prevState: ObservedState | undefined;
156
- event: AnyEventObject;
157
- state: ObservedState;
158
- machine?: AnyStateMachine;
159
- timestamp?: number;
649
+ /**
650
+ * Thrown by {@link runAgentToCompletion} when the run settles `idle` instead of
651
+ * `done`: the machine paused for external input. Carries the idle `snapshot`
652
+ * and `acceptedTypes` (the event types that could resume it, via
653
+ * {@link getAcceptedEvents}). Use {@link runAgent} directly when idle is an
654
+ * expected outcome you handle.
655
+ */
656
+ declare class AgentIdleError extends Error {
657
+ readonly snapshot: AnyMachineSnapshot;
658
+ readonly acceptedTypes: string[];
659
+ constructor(snapshot: AnyMachineSnapshot, acceptedTypes: string[]);
160
660
  }
161
- type AgentDecisionInput = {
162
- goal: string;
163
- model?: LanguageModel;
164
- context?: any;
165
- } & Omit<Parameters<typeof generateText>[0], 'model' | 'tools' | 'prompt'>;
166
- type AgentDecisionLogic<TEvents extends EventObject> = PromiseActorLogic<AgentPlan<TEvents> | undefined, AgentDecisionInput | string>;
167
- type AgentEmitted<TEvents extends EventObject> = {
168
- type: 'feedback';
169
- feedback: AgentFeedback;
661
+ /** Handler for `agent.userInput` invokes passed as {@link RunAgentOptions.userInput}. */
662
+ interface AgentUserInputExecutor {
663
+ (input: AgentUserInput): PromiseLike<unknown>;
664
+ }
665
+ type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
666
+ runId: string;
667
+ seq: number;
668
+ timestamp: string;
669
+ } & ({
670
+ type: "run.start";
671
+ input?: InputFrom<TMachine>;
672
+ snapshot?: Snapshot<unknown>;
673
+ event?: EventFromLogic<TMachine>;
170
674
  } | {
171
- type: 'observation';
172
- observation: AgentObservation<any>;
675
+ type: "request.start";
676
+ request: AgentStepRequest;
173
677
  } | {
174
- type: 'message';
175
- message: AgentMessage;
678
+ type: "request.end";
679
+ request: AgentStepRequest;
680
+ output: unknown;
681
+ raw: unknown;
682
+ /** The model's reasoning, lifted off the raw executor result when the
683
+ * request opted into the structured-output envelope's `reasoning` field.
684
+ * Present only when the executor surfaced a string `reasoning`. */
685
+ reasoning?: string;
176
686
  } | {
177
- type: 'plan';
178
- plan: AgentPlan<TEvents>;
179
- };
180
- type AgentLogic<TEvents extends EventObject> = ActorLogic<TransitionSnapshot<AgentMemoryContext>, {
181
- type: 'agent.feedback';
182
- feedback: AgentFeedback;
687
+ type: "request.error";
688
+ request: AgentStepRequest;
689
+ error: unknown;
183
690
  } | {
184
- type: 'agent.observe';
185
- observation: AgentObservation<any>;
691
+ type: "stream.chunk";
692
+ request: AgentRequest;
693
+ chunk: string;
186
694
  } | {
187
- type: 'agent.message';
188
- message: AgentMessage;
695
+ type: "machine.transition";
696
+ snapshot: SnapshotFrom<TMachine>;
697
+ event: EventFromLogic<TMachine>;
189
698
  } | {
190
- type: 'agent.plan';
191
- plan: AgentPlan<TEvents>;
192
- }, any, // TODO: input
193
- any, AgentEmitted<TEvents>>;
194
- type EventsFromZodEventMapping<TEventSchemas extends ZodEventMapping> = Values<{
195
- [K in keyof TEventSchemas & string]: {
196
- type: K;
197
- } & TypeOf<TEventSchemas[K]>;
198
- }>;
199
- type ContextFromZodContextMapping<TContextSchema extends ZodContextMapping> = {
200
- [K in keyof TContextSchema & string]: TypeOf<TContextSchema[K]>;
201
- };
202
- type Agent<TContext, TEvents extends EventObject> = ActorRefFrom<AgentLogic<TEvents>> & {
203
- /**
204
- * The name of the agent. All agents with the same name are related and
205
- * able to share experiences (observations, feedback) with each other.
206
- */
207
- name?: string;
208
- /**
209
- * The unique identifier for the agent.
210
- */
211
- id?: string;
212
- description?: string;
213
- events: ZodEventMapping;
214
- types: {
215
- events: TEvents;
216
- context: Compute<TContext>;
217
- };
218
- model: LanguageModel;
219
- defaultOptions: GenerateTextOptions;
220
- memory: AgentLongTermMemory | undefined;
221
- /**
222
- * The adapter used to perform LLM actions such as
223
- * `.generateText()` and `.streamText(…)`.
224
- *
225
- * Defaults to the Vercel AI SDK.
226
- */
227
- adapter: AIAdapter;
228
- /**
229
- * Resolves with an `AgentPlan` based on the information provided in the `options`, including:
230
- *
231
- * - The `goal` for the agent to achieve
232
- * - The observed current `state`
233
- * - The `machine` (e.g. a state machine) that specifies what can happen next
234
- * - Additional `context`
235
- */
236
- decide: (options: AgentDecideOptions) => Promise<AgentPlan<TEvents> | undefined>;
237
- generateText: (options: AgentGenerateTextOptions) => Promise<AgentGenerateTextResult>;
238
- streamText: (options: AgentStreamTextOptions) => Promise<AgentStreamTextResult>;
239
- addObservation: (observationInput: AgentObservationInput) => AgentObservation<any>;
240
- addMessage: (messageInput: AgentMessageInput) => AgentMessage;
241
- addFeedback: (feedbackInput: AgentFeedbackInput) => AgentFeedback;
242
- addPlan: (plan: AgentPlan<TEvents>) => void;
243
- /**
244
- * Called whenever the agent (LLM assistant) receives or sends a message.
245
- */
246
- onMessage: (callback: (message: AgentMessage) => void) => void;
247
- /**
248
- * Selects agent data from its context.
249
- *
250
- * @deprecated Select from `agent.getSnapshot().context` directly or:
251
- * - `agent.getMessages()`
252
- * - `agent.getObservations()`
253
- * - `agent.getFeedback()`
254
- * - `agent.getPlans()`
255
- */
256
- select: <T>(selector: (context: AgentMemoryContext) => T) => T;
257
- /**
258
- * Retrieves messages from the agent's short-term (local) memory.
259
- */
260
- getMessages: () => AgentMessage[];
261
- /**
262
- * Retrieves observations from the agent's short-term (local) memory.
263
- */
264
- getObservations: () => AgentObservation<Agent<TContext, TEvents>>[];
265
- /**
266
- * Retrieves feedback from the agent's short-term (local) memory.
267
- */
268
- getFeedback: () => AgentFeedback[];
269
- /**
270
- * Retrieves strategies from the agent's short-term (local) memory.
271
- */
272
- getPlans: () => AgentPlan<TEvents>[];
273
- /**
274
- * Interacts with this state machine actor by inspecting state transitions and storing them as observations.
275
- *
276
- * Observations contain the `prevState`, `event`, and current `state` of this
277
- * actor, as well as other properties that are useful when recalled.
278
- * These observations are stored in the `agent`'s short-term (local) memory
279
- * and can be retrieved via `agent.getObservations()`.
280
- *
281
- * @example
282
- * ```ts
283
- * // Only observes the actor's state transitions
284
- * agent.interact(actor);
285
- *
286
- * actor.start();
287
- * ```
288
- */
289
- interact<TActor extends AnyActorRef>(actorRef: TActor): Subscription;
290
- /**
291
- * Interacts with this state machine actor by:
292
- * 1. Inspecting state transitions and storing them as observations
293
- * 2. Deciding what to do next (which event to send the actor) based on
294
- * the agent input returned from `getInput(observation)`, if `getInput(…)` is provided as the 2nd argument.
295
- *
296
- * Observations contain the `prevState`, `event`, and current `state` of this
297
- * actor, as well as other properties that are useful when recalled.
298
- * These observations are stored in the `agent`'s short-term (local) memory
299
- * and can be retrieved via `agent.getObservations()`.
300
- *
301
- * @example
302
- * ```ts
303
- * // Observes the actor's state transitions and
304
- * // makes a decision if on the "summarize" state
305
- * agent.interact(actor, observed => {
306
- * if (observed.state.matches('summarize')) {
307
- * return {
308
- * context: observed.state.context,
309
- * goal: 'Summarize the message'
310
- * }
311
- * }
312
- * });
313
- *
314
- * actor.start();
315
- * ```
316
- */
317
- interact<TActor extends AnyActorRef>(actorRef: TActor, getInput: (observation: AgentObservation<TActor>) => AgentDecisionInput | undefined): Subscription;
318
- };
319
- type AnyAgent = Agent<any, any>;
320
- type FromAgent<T> = T | ((agent: AnyAgent) => T | Promise<T>);
321
- type CommonTextOptions = {
322
- prompt: FromAgent<string>;
323
- model?: LanguageModel;
324
- context?: Record<string, any>;
325
- messages?: FromAgent<CoreMessage[]>;
326
- template?: PromptTemplate<any>;
327
- correlationId?: string;
328
- parentCorrelationId?: string;
699
+ type: "emit";
700
+ event: EmittedFrom<TMachine>;
701
+ } | ({
702
+ type: "run.end";
703
+ status: "done";
704
+ output: OutputFrom<TMachine>;
705
+ snapshot: SnapshotFrom<TMachine>;
706
+ } | {
707
+ type: "run.end";
708
+ status: "idle";
709
+ snapshot: SnapshotFrom<TMachine>;
710
+ pendingUserInputs?: PendingUserInput[];
711
+ persistedSnapshot?: Snapshot<unknown>;
712
+ } | {
713
+ type: "run.end";
714
+ status: "error";
715
+ cause: RunAgentErrorCause;
716
+ error: unknown;
717
+ snapshot: SnapshotFrom<TMachine>;
718
+ }));
719
+ /**
720
+ * Options for {@link runAgent}.
721
+ *
722
+ * Host executors are passed as a single {@link AgentRequestExecutors}-shaped
723
+ * set under `executors` (the same shape the step path takes). Each executor
724
+ * kind is required only if the machine actually reaches a request of that kind
725
+ * — checked at bind time, before any actor runs. The whole `executors` field is
726
+ * optional: a machine whose agent sources all carry their own executor
727
+ * (`.withExecutor(...)`) needs none.
728
+ */
729
+ interface RunAgentOptions<TMachine extends AnyStateMachine> {
730
+ /**
731
+ * The host executor set backing the machine's agent actors — build it with
732
+ * `createAiSdkExecutors({ models })` from '@statelyai/agent/ai-sdk', or supply
733
+ * `{ generateText?, streamText?, decide? }` by hand. Every slot is optional
734
+ * here (unlike the step path's {@link AgentRequestExecutors}): each kind is
735
+ * bind-time-checked only when the machine actually reaches a request of that
736
+ * kind, so e.g. a stream-only machine may pass `{ streamText }` alone.
737
+ */
738
+ executors?: Partial<AgentRequestExecutors>;
739
+ /** Machine input, passed straight to `createActor(machine, { input })`. Omit when resuming via `snapshot`. */
740
+ input?: InputFrom<TMachine>;
741
+ /** A previously-settled run's `result.snapshot`, to resume from instead of starting fresh. Pair with `event` to deliver the event that unblocks the resumed idle state. */
742
+ snapshot?: Snapshot<unknown>;
743
+ /** An event to send immediately after starting/resuming the actor (e.g. the human's answer to an idle-state prompt). */
744
+ event?: EventFromLogic<TMachine>;
745
+ /**
746
+ * How to handle a resume `event` the restored state cannot accept (a
747
+ * type-level check via {@link getAcceptedEvents}, only applied when resuming
748
+ * from a `snapshot`). `'throw'` (default) throws {@link IllegalResumeEventError}
749
+ * before delivering the event; `'ignore'` restores the older silent behavior
750
+ * (the event is sent and the machine drops it). A type-legal event a guard
751
+ * rejects is never an illegal resume event.
752
+ */
753
+ onIllegalResumeEvent?: "throw" | "ignore";
754
+ /**
755
+ * The version stamped onto every settled snapshot's `agentMeta` and compared
756
+ * against an incoming snapshot's stamp on resume. Defaults to
757
+ * {@link getMachineStructuralHash} of the machine (a structural fingerprint).
758
+ * Set an explicit value (e.g. a semver or build id) to control migration
759
+ * boundaries yourself.
760
+ */
761
+ machineVersion?: string;
762
+ /**
763
+ * How to handle a resume `snapshot` whose stamped `agentMeta.version` differs
764
+ * from the current machine's version. `'throw'` (default) throws
765
+ * {@link SnapshotVersionMismatchError} with `from`/`to`; `'warn'`
766
+ * `console.warn`s once and proceeds; `'ignore'` proceeds silently. Ignored
767
+ * when {@link migrateSnapshot} is provided (that runs instead), and never
768
+ * triggers for an unstamped snapshot (no `agentMeta`).
769
+ */
770
+ onVersionMismatch?: "throw" | "warn" | "ignore";
771
+ /**
772
+ * Called instead of {@link onVersionMismatch} when a resume snapshot's
773
+ * version mismatches the current machine's: receives the incoming snapshot
774
+ * and `{ from, to }`, and its return value is used as the snapshot to resume
775
+ * from. A throw propagates.
776
+ */
777
+ migrateSnapshot?: (snapshot: Snapshot<unknown>, info: {
778
+ from: string;
779
+ to: string;
780
+ }) => Snapshot<unknown>;
781
+ /** Actor source implementations, merged onto the machine before binding — sugar for `machine.provide({ actorSources })` ahead of the run. */
782
+ actorSources?: Record<string, AnyActorLogic>;
783
+ /**
784
+ * Optional human-input handler for `agent.userInput` invokes (CLI prompt,
785
+ * web form, Slack, …). With a handler, input is gathered inline without
786
+ * settling. Without one, an `agent.userInput` invoke becomes a *pending
787
+ * placeholder*: it waits indefinitely, does not block idle detection, and
788
+ * the run settles `{ status: 'idle', pendingUserInputs, persistedSnapshot }`
789
+ * once no other work is in flight — resume by passing `persistedSnapshot`
790
+ * back as `snapshot` together with a `userInput` handler that answers it.
791
+ */
792
+ userInput?: AgentUserInputExecutor;
793
+ /**
794
+ * Host override for detecting a snapshot that is an INTENTIONAL wait for an
795
+ * external event — the deterministic replacement for the timing heuristic
796
+ * runAgent uses to settle idle. Resolution order: this option (host override)
797
+ * → the machine-carried predicate declared via `setupAgent({ isSuspended })`
798
+ * the timing heuristic (when neither is present). When the resolved
799
+ * predicate returns true and nothing is in flight (no live requests/plans/
800
+ * invokes; the `agent.userInput` placeholder exemption still applies), runAgent
801
+ * settles idle immediately, without the `setTimeout` heuristic. It does NOT
802
+ * force-settle while agent work is in flight, and whole-machine idle semantics
803
+ * are unchanged; a machine with no predicate falls back to the heuristic
804
+ * exactly as before. Declare your own signal, e.g.
805
+ * `(s) => s.hasTag('awaiting-review')`.
806
+ *
807
+ * Provisional name may change before 2.0.
808
+ */
809
+ isSuspended?: (snapshot: AnyMachineSnapshot) => boolean;
810
+ /**
811
+ * The override to runAgent's DEFAULT contract. By default agent work is
812
+ * whatever the machine *invokes* (`agent.generateText`, TextLogic,
813
+ * `agent.decide`, …). With `getRequests`, whenever the machine would
814
+ * otherwise settle idle, this hook reads the snapshot and returns the model
815
+ * request(s) to run instead — prompts from state `description`s, `meta`,
816
+ * tags, a lookup table keyed by state value, wherever you keep them. Return
817
+ * nothing to settle idle (human-wait states).
818
+ *
819
+ * There is no blessed source for the prompts — this is a recipe seam.
820
+ * Prompts-in-descriptions, copy-paste and adapt:
821
+ *
822
+ * ```ts
823
+ * getRequests: (snapshot) =>
824
+ * snapshot._nodes
825
+ * .filter((node) => node.description && !node.tags.includes('waiting'))
826
+ * .map((node) => ({
827
+ * model: 'writer',
828
+ * prompt: node.description!,
829
+ * kind: node.tags.includes('decision') ? 'decision' : 'text',
830
+ * // single-outcome states advance deterministically; else `decide`
831
+ * onDone: node.ownEvents.length === 1 ? { type: node.ownEvents[0] } : undefined,
832
+ * allowedEvents: node.ownEvents,
833
+ * })),
834
+ * ```
835
+ *
836
+ * Each request runs per {@link AgentStateRequest.kind}, appends to the
837
+ * run's message log (see {@link RunAgentOptions.messages}), and advances
838
+ * the machine per {@link AgentStateRequest.onDone} — explicitly named/
839
+ * computed event, or a `decide` call when omitted — always gated by
840
+ * `snapshot.can`. Multiple requests run concurrently (parallel regions —
841
+ * scope each with `allowedEvents`, e.g. the node's `ownEvents`). A pass
842
+ * that sends no event settles idle. Every model call counts against
843
+ * `maxModelCalls`.
844
+ */
845
+ getRequests?: (snapshot: SnapshotFrom<TMachine>, context: {
846
+ messages: readonly AgentMessage[];
847
+ }) => AgentStateRequest | readonly AgentStateRequest[] | undefined;
848
+ /**
849
+ * Adds to the run's aggregated message log (the working memory
850
+ * `getRequests` requests read and append to). The log starts as the resume
851
+ * `snapshot`'s stamped `messages` (else `[]`); an ARRAY here is APPENDED to
852
+ * that history — the safe default for folding in a user reply on resume,
853
+ * never silently erasing prior conversation. Pass a FUNCTION
854
+ * `(prior) => AgentMessage[]` to take full control (replace, filter,
855
+ * compact). The final log is stamped onto every settled result's
856
+ * `snapshot.messages` (like `agentMeta`), so persist/resume round-trips it
857
+ * with no extra wiring — read it with `getAgentMessages(snapshot)`.
858
+ */
859
+ messages?: AgentMessage[] | ((prior: AgentMessage[]) => AgentMessage[]);
860
+ /** Fires for each streamed chunk of a `mode: 'stream'` text request, alongside the {@link AgentRequest} that produced it (parallel states can interleave multiple streams). Purely observational. */
861
+ onChunk?: (chunk: string, info: {
862
+ request: AgentRequest;
863
+ }) => void;
864
+ /** Fires once per resolved text/decision request with its normalized output and the raw executor result (tool calls, usage, …) — the seam for tracing/observability and event-sourced replay logging. */
865
+ onResult?: (request: AgentStepRequest, result: {
866
+ output: unknown;
867
+ raw: unknown;
868
+ }) => void;
869
+ /** Fires a single ordered stream of run/request/chunk/transition/emit/end events. Intended for eval traces, JSONL logs, and adapter-owned telemetry/exporters. */
870
+ onTrace?: (event: AgentTraceEvent<TMachine>) => void;
871
+ /**
872
+ * Fires on every machine transition (snapshot + causing event). Pure
873
+ * observation — progress UIs, logging, tracing. Cannot send events.
874
+ */
875
+ onTransition?: (snapshot: SnapshotFrom<TMachine>, event: EventFromLogic<TMachine>) => void;
876
+ /**
877
+ * Fires for each message appended to the run's aggregated log (see
878
+ * {@link RunAgentOptions.messages}) the moment a `getRequests` request
879
+ * appends it — the live view of the log a caller otherwise only reads off
880
+ * the settled snapshot via `getAgentMessages`. Purely observational, like
881
+ * {@link onTransition}. Never fires for the seeded history, and never fires
882
+ * on a default invoke-driven run (nothing appends there).
883
+ */
884
+ onMessage?: (message: AgentMessage) => void;
885
+ /**
886
+ * Handlers for events the machine emits (`enq.emit(...)`), keyed by emitted
887
+ * event type — `'*'` catches all. Typed from the machine's `emitted`
888
+ * schemas (`setupAgent({ emitted: { ... } })`). Purely observational, like
889
+ * {@link onTransition}: the machine narrates progress on its own vocabulary
890
+ * (not xstate internals) and the host renders it — a progress UI, an SSE
891
+ * stream, a log line.
892
+ */
893
+ on?: { [TType in EmittedFrom<TMachine>["type"] | "*"]?: (emitted: EmittedFrom<TMachine> & (TType extends "*" ? unknown : {
894
+ type: TType;
895
+ })) => void };
896
+ /**
897
+ * Raw xstate inspection passthrough: fires for every inspection event in
898
+ * the whole actor system — root machine, invoked child machines, spawned
899
+ * actors — each carrying its `actorRef` (`event.actorRef.id`/`.src`). This
900
+ * is the system-wide seam {@link onTransition} (root transitions only)
901
+ * cannot give you: filter `event.type === '@xstate.transition'` and read
902
+ * `event.actorRef` to attribute a child machine's states to the child.
903
+ * Purely observational, like the other callbacks. Unlike them it also
904
+ * fires during the final settle (a child's last transition and stop events
905
+ * arrive while the run is tearing down).
906
+ */
907
+ inspect?: (inspectionEvent: InspectionEvent) => void;
908
+ /** 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. */
909
+ maxModelCalls?: number;
910
+ /** Aborts the run; settles `{ status: 'error', cause: 'aborted' }` with `signal.reason` as the error. */
911
+ signal?: AbortSignal;
912
+ }
913
+ /**
914
+ * The outcome of a {@link runAgent} call — always exactly one of three
915
+ * variants, never a throw for a waiting or failed machine (programmer
916
+ * errors like a missing executor still throw, at bind time before any actor
917
+ * runs). `done`: a final state was reached (`output` is the machine's
918
+ * `OutputFrom`). `idle`: the run settled with no in-flight work — resume by
919
+ * calling `runAgent` again with `{ snapshot, event }`. `error`: a run-level
920
+ * failure, discriminated by `cause` (`'aborted'`, `'max-model-calls'`,
921
+ * `'decision-exhausted'`, `'machine'` for any other machine error state, or
922
+ * `'stopped'` for an external stop — see {@link RunAgentErrorCause}). Every
923
+ * variant carries the final `snapshot`, and the underlying
924
+ * actor is stopped on every settle path — there is no live actor to resume;
925
+ * resume is always by snapshot.
926
+ */
927
+ /** A pending unhandled `agent.userInput` invoke surfaced on an idle settle — `id` is the invoke's id, `input` its resolved invoke input (prompt, schema, …). Answer it by resuming with a `userInput` handler. */
928
+ interface PendingUserInput {
929
+ id: string;
930
+ input: AgentUserInput | undefined;
931
+ }
932
+ type RunAgentResult<TMachine extends AnyStateMachine> = {
933
+ status: "done";
934
+ output: OutputFrom<TMachine>;
935
+ snapshot: SnapshotFrom<TMachine>;
936
+ } | {
937
+ status: "idle";
938
+ snapshot: SnapshotFrom<TMachine>; /** Present when the machine is waiting on unhandled `agent.userInput` invokes: one entry per pending invoke. */
939
+ pendingUserInputs?: PendingUserInput[];
940
+ /**
941
+ * Present alongside `pendingUserInputs`: the JSON-serializable persisted
942
+ * snapshot (in-flight children included). Persist THIS one and resume
943
+ * with `runAgent(machine, { snapshot: persistedSnapshot, userInput })` —
944
+ * the live `snapshot` above cannot round-trip active children.
945
+ */
946
+ persistedSnapshot?: Snapshot<unknown>;
947
+ } | {
948
+ status: "error";
949
+ cause: RunAgentErrorCause;
950
+ error: unknown;
951
+ snapshot: SnapshotFrom<TMachine>;
329
952
  };
330
- type TextResultMeta = {
331
- correlationId: string;
332
- parentCorrelationId?: string;
953
+ /**
954
+ * Discriminates a {@link RunAgentResult} `error`:
955
+ * - `'aborted'` — the run's `signal` fired.
956
+ * - `'max-model-calls'` — the `maxModelCalls` budget was exceeded.
957
+ * - `'decision-exhausted'` — the machine reached an error state whose error is
958
+ * (or wraps) a {@link DecisionExhaustedError} that no `onError` handled.
959
+ * - `'machine'` — any other machine error state.
960
+ * - `'stopped'` — the actor was stopped externally (`status === 'stopped'`).
961
+ */
962
+ type RunAgentErrorCause = "aborted" | "max-model-calls" | "decision-exhausted" | "machine" | "stopped";
963
+ /**
964
+ * Runs an agent machine to completion or idle: a `createActor` host that
965
+ * binds `options`' host executors onto the machine's `agent.*`/`TextLogic`/
966
+ * `DecisionLogic` actor sources, starts (or resumes) the actor, and drives
967
+ * it until it settles — {@link RunAgentResult} `done | idle | error`. Unlike
968
+ * the step helpers ({@link initialAgentStep} etc — a pure
969
+ * transition-at-a-time path for durable hosts), `runAgent` owns a live actor
970
+ * internally; there is no continuation callback, so **idle always settles**
971
+ * and the caller resumes explicitly by passing the settled `{ snapshot,
972
+ * event }` back in. The actor is stopped on every settle path (`done`,
973
+ * `idle`, and `error` alike) — resume is always by snapshot, never by
974
+ * holding a reference to a live actor.
975
+ *
976
+ * Binding happens **before** the actor starts: every invoke the machine
977
+ * could reach is walked and checked against the effective actor sources
978
+ * (`options.actorSources` merged onto the machine), so a missing
979
+ * `streamText`/`decide` executor or any other unbound actor source throws
980
+ * immediately — a bind-time error, not a mid-run failure. The one exception
981
+ * is `agent.userInput`: unhandled, it binds as a pending placeholder that
982
+ * settles the run idle (with `pendingUserInputs`) instead of erroring.
983
+ *
984
+ * @example
985
+ * ```ts
986
+ * const executors = createAiSdkExecutors({ models });
987
+ * let r = await runAgent(machine, { input, executors });
988
+ * while (r.status === 'idle') {
989
+ * const event = await promptUser(getAcceptedEvents(r.snapshot));
990
+ * r = await runAgent(machine, { snapshot: r.snapshot, event, executors });
991
+ * }
992
+ * if (r.status !== 'done') throw new Error(`Run did not complete: ${r.status}`);
993
+ * console.log(r.output);
994
+ * ```
995
+ *
996
+ * The `executors`' `generateText`/`streamText` accept the raw Vercel AI SDK
997
+ * functions directly (`executors: { generateText, streamText }` with them
998
+ * imported from `ai`) — their `{ text }`/`{ textStream }` results are unwrapped
999
+ * natively. `decide` cannot be a raw AI SDK function: the tool-per-event mapping
1000
+ * lives in an adapter — use `createAiSdkExecutors` from '@statelyai/agent/ai-sdk'.
1001
+ */
1002
+ declare function runAgent<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentOptions<TMachine>): Promise<RunAgentResult<TMachine>>;
1003
+ /**
1004
+ * Runs an agent machine to a **final state** and returns its output, for
1005
+ * run-to-done flows where an idle pause is unexpected. Wraps {@link runAgent}:
1006
+ *
1007
+ * - `done` → resolves with `result.output` (the machine's `OutputFrom`).
1008
+ * - `idle` → throws {@link AgentIdleError} carrying the idle snapshot and the
1009
+ * event types that could resume it.
1010
+ * - `error` → throws `result.error` when it is an `Error`; otherwise wraps it
1011
+ * in an `Error` whose `.cause` is the {@link RunAgentErrorCause} and whose
1012
+ * `.error` is the raw thrown value.
1013
+ *
1014
+ * Use {@link runAgent} directly when idle is an expected outcome you handle
1015
+ * (human-in-the-loop, resumable flows); use `runAgentToCompletion` when the
1016
+ * machine is meant to run straight through to a final state.
1017
+ */
1018
+ declare function runAgentToCompletion<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentOptions<TMachine>): Promise<OutputFrom<TMachine>>;
1019
+ /**
1020
+ * The actor handed to an {@link inspectTransitions} handler: an
1021
+ * {@link AnyActorRef} widened with the runtime `id`/`src` used to attribute a
1022
+ * transition to the root machine or a specific invoked child (xstate's static
1023
+ * `ActorRef` type omits them, but they are always present at runtime).
1024
+ */
1025
+ type InspectedActorRef = AnyActorRef & {
1026
+ id: string;
1027
+ src?: string | AnyActorLogic;
333
1028
  };
334
- type AgentGenerateTextOptions = Omit<GenerateTextOptions, 'model' | 'prompt' | 'messages'> & CommonTextOptions;
335
- type AgentGenerateTextResult = GenerateTextResult<any> & TextResultMeta;
336
- type AgentStreamTextOptions = Omit<StreamTextOptions, 'model' | 'prompt' | 'messages'> & CommonTextOptions;
337
- type AgentStreamTextResult = StreamTextResult<any> & TextResultMeta;
338
- interface ObservedState {
339
- /**
340
- * The current state value of the state machine, e.g.
341
- * `"loading"` or `"processing"` or `"ready"`
342
- */
343
- value: StateValue;
344
- /**
345
- * Additional contextual data related to the current state
346
- */
347
- context: Record<string, unknown>;
1029
+ /**
1030
+ * Wraps a `(snapshot, actorRef) => void` handler into a function usable as
1031
+ * {@link RunAgentOptions.inspect}: it filters the raw inspection stream to
1032
+ * `@xstate.transition` events and hands the handler the typed
1033
+ * {@link AnyMachineSnapshot} and the {@link InspectedActorRef} that
1034
+ * transitioned. Attribute a child actor via `actorRef.id`/`actorRef.src`. Saves
1035
+ * the manual `event.type === '@xstate.transition'` filtering and the snapshot/
1036
+ * actorRef casts.
1037
+ */
1038
+ declare function inspectTransitions(handler: (snapshot: AnyMachineSnapshot, actorRef: InspectedActorRef) => void): (inspectionEvent: InspectionEvent) => void;
1039
+ //#endregion
1040
+ //#region src/verify.d.ts
1041
+ /** Severity of an {@link AgentLintDiagnostic}. `error` findings fail CI/the CLI; `warning`s are advisory. */
1042
+ type AgentLintSeverity = "error" | "warning";
1043
+ /**
1044
+ * One static-analysis finding from {@link lintAgentMachine}. `code` names the
1045
+ * check (stable, machine-readable), `path` points at the offending state path
1046
+ * or config location, and `message` explains the problem and its remedy.
1047
+ */
1048
+ interface AgentLintDiagnostic {
1049
+ code: "unreachable-state" | "decide-without-events" | "unserializable-context" | "direct-object-src" | "final-without-output" | "final-output-reads-event" | "missing-final";
1050
+ severity: AgentLintSeverity;
1051
+ /** State path (`parent.child`) or config pointer (e.g. `(root)`, `context`) the finding is about. */
1052
+ path: string;
1053
+ message: string;
348
1054
  }
349
- type ObservedStateFrom<TActor extends AnyActorRef> = Pick<SnapshotFrom<TActor>, 'value' | 'context'>;
350
- type AgentMemoryContext = {
351
- observations: AgentObservation<any>[];
352
- messages: AgentMessage[];
353
- plans: AgentPlan<any>[];
354
- feedback: AgentFeedback[];
355
- };
356
- type AgentMemory = AppendOnlyStorage<AgentMemoryContext>;
357
- interface AppendOnlyStorage<T extends Record<string, any[]>> {
358
- append<K extends keyof T>(sessionId: string, key: K, item: T[K][0]): Promise<void>;
359
- getAll<K extends keyof T>(sessionId: string, key: K): Promise<T[K] | undefined>;
1055
+ /** Options for {@link lintAgentMachine}. Reserved for future check selection. */
1056
+ interface LintAgentMachineOptions {
1057
+ /** Skip these check codes entirely. */
1058
+ disable?: AgentLintDiagnostic["code"][];
360
1059
  }
361
- interface AgentLongTermMemory {
362
- get<K extends keyof AgentMemoryContext>(key: K): Promise<AgentMemoryContext[K]>;
363
- append<K extends keyof AgentMemoryContext>(key: K, item: AgentMemoryContext[K][0]): Promise<void>;
364
- set<K extends keyof AgentMemoryContext>(key: K, items: AgentMemoryContext[K]): Promise<void>;
1060
+ /**
1061
+ * Runs static structural checks over a built agent machine and returns the
1062
+ * findings ({@link AgentLintDiagnostic}[], empty when clean). Works for
1063
+ * TS-authored (`setupAgent(...).createMachine(...)`) and
1064
+ * `setupAgent.fromConfig(...)`-compiled machines alike, reading `machine.config`
1065
+ * plus the schemas/actor sources the library already retains per machine.
1066
+ *
1067
+ * No model calls, no API keys — a coding agent that emits an agent machine can
1068
+ * call this to catch dead states, undeliverable decisions, un-rebindable
1069
+ * invoke srcs, and output-contract gaps before ever running it.
1070
+ *
1071
+ * @example
1072
+ * ```ts
1073
+ * const errors = lintAgentMachine(machine).filter((d) => d.severity === 'error');
1074
+ * if (errors.length) throw new Error(errors.map((e) => `${e.path}: ${e.message}`).join('\n'));
1075
+ * ```
1076
+ */
1077
+ declare function lintAgentMachine(machine: AnyStateMachine, options?: LintAgentMachineOptions): AgentLintDiagnostic[];
1078
+ /**
1079
+ * Scripted responses for a {@link simulateAgent} playthrough. Each channel is a
1080
+ * by-`src` map of FIFO queues, consumed in the order the machine reaches the
1081
+ * requests:
1082
+ * - `text` — output values for text requests, keyed by request src (the
1083
+ * `setupAgent({ requests })` key, or `agent.generateText`/`agent.streamText`).
1084
+ * - `decisions` — the {@link ChosenEvent} to apply for a decision request,
1085
+ * keyed by decision src (usually `agent.decide`).
1086
+ * - `userInput` — output values for `agent.userInput` invokes, keyed by src
1087
+ * (usually `agent.userInput`).
1088
+ */
1089
+ interface SimulationScript {
1090
+ text?: Record<string, unknown[]>;
1091
+ decisions?: Record<string, ChosenEvent[]>;
1092
+ userInput?: Record<string, unknown[]>;
365
1093
  }
366
- interface AIAdapter {
367
- generateText: typeof generateText;
368
- streamText: typeof streamText;
1094
+ /** One entry in a {@link SimulateAgentResult.trail}: the state after this step, plus what drove the step. */
1095
+ interface SimulationTrailEntry {
1096
+ /** The machine state value after applying this step. */
1097
+ state: unknown;
1098
+ /** The chosen event applied (for a decision request). */
1099
+ appliedEvent?: ChosenEvent;
1100
+ /** The resolved request (for a text/userInput invoke): its kind and src. */
1101
+ resolvedRequest?: {
1102
+ kind: "text" | "userInput";
1103
+ src: string;
1104
+ id: string;
1105
+ };
369
1106
  }
370
- type Compute<A extends any> = {
371
- [K in keyof A]: A[K];
372
- } & unknown;
373
-
374
- declare function createAgent<const TContextSchema extends ZodContextMapping, const TEventSchemas extends ZodEventMapping, TEvents extends EventObject = EventsFromZodEventMapping<TEventSchemas>, TContext = ContextFromZodContextMapping<TContextSchema>>({ name, description, model, events, context, planner, stringify, getMemory, logic, adapter, ...generateTextOptions }: {
375
- /**
376
- * The unique identifier for the agent.
377
- *
378
- * This should be the same across all sessions of a specific agent, as it can be
379
- * used to retrieve memory for this agent.
380
- *
381
- * @example
382
- * ```ts
383
- * const agent = createAgent({
384
- * id: 'recipe-assistant',
385
- * // ...
386
- * });
387
- * ```
388
- */
389
- id?: string;
390
- /**
391
- * The name of the agent
392
- */
393
- name?: string;
394
- /**
395
- * A description of the role of the agent
396
- */
397
- description?: string;
398
- /**
399
- * Events that the agent can cause (send) in an environment
400
- * that the agent knows about.
401
- */
402
- events: TEventSchemas;
403
- context?: TContextSchema;
404
- planner?: AgentPlanner<Agent<TContext, TEvents>>;
405
- stringify?: typeof JSON.stringify;
406
- /**
407
- * A function that retrieves the agent's long term memory
408
- */
409
- getMemory?: (agent: Agent<TContext, TEvents>) => AgentLongTermMemory;
410
- /**
411
- * Agent logic
412
- */
413
- logic?: AgentLogic<TEvents>;
414
- adapter?: AIAdapter;
415
- } & GenerateTextOptions): Agent<TContext, TEvents>;
416
-
417
- declare function fromTextStream<T extends AnyAgent>(agent: T, defaultOptions?: AgentStreamTextOptions): ObservableActorLogic<{
418
- textDelta: string;
419
- }, Omit<AgentStreamTextOptions, 'context'> & {
420
- context?: AgentStreamTextOptions['context'];
421
- }>;
422
- declare function fromText<T extends AnyAgent>(agent: T, defaultOptions?: AgentGenerateTextOptions): PromiseActorLogic<GenerateTextResult<Record<string, CoreTool<any, any>>>, Omit<AgentGenerateTextOptions, 'context'> & {
423
- context?: AgentGenerateTextOptions['context'];
424
- }>;
425
-
426
- declare function fromDecision(agent: AnyAgent, defaultInput?: AgentDecisionInput): AgentDecisionLogic<any>;
427
-
428
- export { type AIAdapter, type Agent, type AgentDecideOptions, type AgentDecisionInput, type AgentDecisionLogic, type AgentEmitted, type AgentFeedback, type AgentFeedbackInput, type AgentGenerateTextOptions, type AgentGenerateTextResult, type AgentLogic, type AgentLongTermMemory, type AgentMemory, type AgentMemoryContext, type AgentMessage, type AgentMessageInput, type AgentObservation, type AgentObservationInput, type AgentPlan, type AgentPlanInput, type AgentPlanner, type AgentStreamTextOptions, type AgentStreamTextResult, type AnyAgent, type AppendOnlyStorage, type CommonTextOptions, type Compute, type ContextFromZodContextMapping, type EventsFromZodEventMapping, type FromAgent, type GenerateTextOptions, type ObservedState, type ObservedStateFrom, type PromptTemplate, type StreamTextOptions, type TextResultMeta, type TransitionData, createAgent, fromDecision, fromText, fromTextStream };
1107
+ /** Options for {@link simulateAgent}. */
1108
+ interface SimulateAgentOptions {
1109
+ input?: unknown;
1110
+ script: SimulationScript;
1111
+ /** Max steps before returning `'exhausted'`. Default 100. */
1112
+ maxSteps?: number;
1113
+ }
1114
+ /** The outcome of a {@link simulateAgent} playthrough. */
1115
+ interface SimulateAgentResult {
1116
+ /** `'done'` = reached a final state; `'idle'` = paused with no pending work; `'exhausted'` = hit `maxSteps`. */
1117
+ status: "done" | "idle" | "exhausted";
1118
+ snapshot: AnyMachineSnapshot;
1119
+ trail: SimulationTrailEntry[];
1120
+ }
1121
+ /**
1122
+ * Deterministically plays a machine through, resolving each request from a
1123
+ * {@link SimulationScript} instead of a model — no API keys, no model calls.
1124
+ * Runs on the pure step path ({@link initialAgentStep} etc.), so it exercises
1125
+ * the real transition logic. Returns the terminal `status`, final `snapshot`,
1126
+ * and a `trail` of every step taken.
1127
+ *
1128
+ * Throws a descriptive error when the script runs dry mid-request, naming the
1129
+ * pending request's kind, src, and id so the missing scripted response is
1130
+ * obvious.
1131
+ *
1132
+ * @example
1133
+ * ```ts
1134
+ * const { status, snapshot } = simulateAgent(machine, {
1135
+ * input: { topic: 'state machines' },
1136
+ * script: { decisions: { 'agent.decide': [{ type: 'END' }] } },
1137
+ * });
1138
+ * ```
1139
+ */
1140
+ declare function simulateAgent(machine: AnyStateMachine, options: SimulateAgentOptions): Promise<SimulateAgentResult>;
1141
+ /** Options for {@link explorePaths}. */
1142
+ interface ExplorePathsOptions {
1143
+ input?: unknown;
1144
+ /** Max branch points (decisions + external-event forks) along any path. Default 8. */
1145
+ maxDepth?: number;
1146
+ /** Total path cap before exploration stops (reported via `hitPathCap`). Default 200. */
1147
+ maxPaths?: number;
1148
+ /** Canned outputs for text/userInput invokes, keyed by src. A missing src halts that branch with a `needs-output` note. */
1149
+ textOutputs?: Record<string, unknown>;
1150
+ }
1151
+ /** A single explored path's terminal outcome. */
1152
+ interface AgentPathTerminal {
1153
+ status: "done" | "idle" | "needs-output" | "max-depth";
1154
+ /** The chosen/applied events, in order, that produced this terminal. */
1155
+ path: ChosenEvent[];
1156
+ /** The final state value on this path. */
1157
+ state: unknown;
1158
+ /** For `needs-output`: the src whose canned output was missing. */
1159
+ missingSrc?: string;
1160
+ }
1161
+ /** The report returned by {@link explorePaths}. */
1162
+ interface AgentPathReport {
1163
+ /** Every distinct state value (JSON) encountered across all explored paths. */
1164
+ reachedStates: unknown[];
1165
+ /** One entry per explored path. */
1166
+ terminals: AgentPathTerminal[];
1167
+ /** How many candidate events were pruned because a guard rejected them. */
1168
+ prunedByGuard: number;
1169
+ /** Notes about coverage the exploration could not complete (missing outputs, depth/path caps). */
1170
+ unexplored: string[];
1171
+ /** Total paths explored. */
1172
+ pathsExplored: number;
1173
+ /** True when the total-paths cap was hit (report is partial). */
1174
+ hitPathCap: boolean;
1175
+ }
1176
+ /**
1177
+ * Enumerates a machine's decision and external-event branches to a bounded
1178
+ * depth, model-free, and reports which states are reached and how each path
1179
+ * terminates. At each decision request it forks one branch per candidate event
1180
+ * (guard-rejected candidates are counted in `prunedByGuard`, not explored); at
1181
+ * an idle wait it forks per externally-accepted event. A `agent.plan` request
1182
+ * forks the same way — one branch per candidate, including the reserved
1183
+ * `agent.plan.done` move — advancing each branch through the real plan protocol
1184
+ * (`resolveAgentRequests`), so a plan can consume several depth units. Text/`userInput` invokes
1185
+ * are resolved from `textOutputs` (a by-src canned-output map) — a missing src
1186
+ * halts that branch with a `needs-output` terminal rather than throwing.
1187
+ *
1188
+ * Combinatorics are bounded by `maxDepth` (default 8) and `maxPaths` (default
1189
+ * 200, reported via `hitPathCap`).
1190
+ *
1191
+ * @example
1192
+ * ```ts
1193
+ * const report = await explorePaths(refundMachine, { input: { request: 'x', amount: 5000 } });
1194
+ * // report.terminals → both 'refunded' and 'denied'; report.prunedByGuard → 1
1195
+ * ```
1196
+ */
1197
+ declare function explorePaths(machine: AnyStateMachine, options?: ExplorePathsOptions): Promise<AgentPathReport>;
1198
+ /** The result of a {@link canReach} query. */
1199
+ interface CanReachResult {
1200
+ canReach: boolean;
1201
+ /** When reachable, the sequence of chosen/applied events that gets there. */
1202
+ witness?: ChosenEvent[];
1203
+ }
1204
+ /**
1205
+ * Answers "can the machine reach `statePath`?" by exploring its branches (a
1206
+ * thin wrapper over {@link explorePaths}). Returns `{ canReach: true, witness }`
1207
+ * with the event sequence that reaches it, or `{ canReach: false }`.
1208
+ *
1209
+ * @example
1210
+ * ```ts
1211
+ * const { canReach, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
1212
+ * // canReach → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
1213
+ * ```
1214
+ */
1215
+ declare function canReach(machine: AnyStateMachine, statePath: string, options?: ExplorePathsOptions): Promise<CanReachResult>;
1216
+ //#endregion
1217
+ export { type AgentDecisionExecutor, type AgentDecisionInput, type AgentDecisionRequest, type AgentEventDescriptor, type AgentEventToolNameResolver, AgentIdleError, type AgentLintDiagnostic, type AgentLintSeverity, type AgentMessage, type AgentModelMap, type AgentModelRef, type AgentOutputMode, type AgentPathReport, type AgentPathTerminal, type AgentPlanInput, type AgentPlanOutput, type AgentPlanRequest, type AgentRequest, type AgentRequestConfig, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestMode, type AgentRequestOptions, type AgentRequestSource, type AgentSchemaPack, type AgentSnapshotStore, type AgentStateRequest, type AgentStep, type AgentStepRequest, type AgentTextRequest, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentToolSchema, type AgentTools, type AgentTraceEvent, type AgentUserInput, type AgentUserInputExecutor, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AiSdkShapedStreamResult, type AiSdkShapedTextResult, type AllowedEventPattern, type AllowedEvents, type AssistantMessage, type CanReachResult, type ChosenEvent, type DataContent, type DecisionAttempt, DecisionExhaustedError, type DecisionLogic, type DecisionLogicConfig, EVENT_TOOL_PREFIX, type EventPayload, type EventUnion, type ExplorePathsOptions, type FilePart, type FromConfigOptions, IllegalResumeEventError, type ImagePart, type InferOutput, type InspectedActorRef, type LintAgentMachineOptions, PLAN_DONE_EVENT_TYPE, type PendingUserInput, type ProviderOptions, type ResolveAgentRequestsOptions, type ResolveDecisionOptions, type RunAgentOptions, type RunAgentResult, type SchemaCompiler, type SimulateAgentOptions, type SimulateAgentResult, type SimulationScript, type SimulationTrailEntry, SnapshotVersionMismatchError, type StandardSchemaV1, type StructuredOutputEnvelope, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextLogicInput, type TextLogicOutput, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultOutput, type ToolResultPart, type UserMessage, appendMessages, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentSchemas, createTextLogic, executeAgentRequest, explorePaths, getAcceptedEvents, getAgentMessages, getAgentOutputMode, getAgentRequests, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getStateMeta, initialAgentStep, inspectTransitions, isStandardSchema, isStructuredOutputSchema, lintAgentMachine, matchesEventPattern, messagesSchema, parseAgentEvent, parseOutput, persistSnapshot, renderDecisionAttempts, resolveAgentRequests, resolveAgentStep, resolveDecision, runAgent, runAgentToCompletion, setupAgent, simulateAgent, systemMessage, toolMessage, transitionAgentStep, userMessage, validateSchemaSync };