@statelyai/agent 1.1.6 → 2.0.0-alpha.11

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