@statelyai/agent 2.0.0-alpha.7 → 2.0.0-alpha.8

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.
@@ -0,0 +1,1078 @@
1
+ import { C as StandardSchemaV1, _ as EventUnion, b as InferOutput, m as ChosenEvent, n as AgentEventSchemaInputMap, o as AgentToolChoice, r as AgentMessage, u as AgentTools, x as NormalizedEventSchemas } from "./types-C9QiMjre.cjs";
2
+ import { G as AgentRequestSource, H as AgentEventDescriptor, M as AgentPlanInput, W as AgentRequestOptions, c as AgentRequestMode, g as TextLogicConfig, h as TextLogic, j as AgentDecisionRequest, l as AgentTextRequest, n as AgentModelRef, p as BuiltinAgentActors, s as AgentRequestExecutors, t as AgentModelMap, u as AgentUserInput } from "./text-logic-CZjyACzQ.cjs";
3
+ import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, InputFrom, InspectionEvent, MachineContext, MetaObject, NonReducibleUnknown, OutputFrom, SetupReturnFromConfig, SetupStateSchema, Snapshot, SnapshotFrom } from "xstate";
4
+
5
+ //#region src/messages.d.ts
6
+ /**
7
+ * Builds a transition-function result that appends one or more
8
+ * {@link AgentMessage}s to a context's `messages` array. `resolve` is either
9
+ * a message (or array of messages) or a function of `{ context, event }`
10
+ * returning them; the returned function is meant to be used directly as (or
11
+ * composed into) a transition's result, e.g. `on: { USER_REPLIED:
12
+ * agent.appendMessages(({ event }) => userMessage(event.text)) }`. Requires
13
+ * `messages: AgentMessage[]` on context — see {@link messagesSchema} for a
14
+ * ready-made schema for that field.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * on: {
19
+ * USER_REPLIED: appendMessages(({ event }) => userMessage(event.text)),
20
+ * }
21
+ * ```
22
+ */
23
+ declare function appendMessages<TContext extends {
24
+ messages: AgentMessage[];
25
+ }, TEvent extends EventObject>(resolve: AgentMessage | AgentMessage[] | ((args: {
26
+ context: TContext;
27
+ event: TEvent;
28
+ }) => AgentMessage | AgentMessage[])): (args: {
29
+ context: TContext;
30
+ event: TEvent;
31
+ }) => {
32
+ context: {
33
+ messages: AgentMessage[];
34
+ };
35
+ };
36
+ /**
37
+ * A {@link StandardSchemaV1} validating an `AgentMessage[]` context field —
38
+ * checks that every message has a known `role` (`system`/`user`/`assistant`/
39
+ * `tool`) and that `content` is either a string (where the role allows it) or
40
+ * an array of parts with a known `type`. Use it directly as a context
41
+ * schema's `messages` field when authoring with `createAgentSchemas`.
42
+ */
43
+ declare const messagesSchema: StandardSchemaV1<AgentMessage[]>;
44
+ //#endregion
45
+ //#region src/workflow-config.d.ts
46
+ type JsonSchemaObject = {
47
+ type?: string | string[];
48
+ properties?: Record<string, JsonSchemaObject>;
49
+ required?: string[];
50
+ items?: JsonSchemaObject;
51
+ enum?: unknown[];
52
+ const?: unknown;
53
+ additionalProperties?: unknown;
54
+ [key: string]: unknown;
55
+ };
56
+ /**
57
+ * Compiles a JSON Schema object (from an `AgentWorkflowConfig`) into a
58
+ * runtime `StandardSchemaV1` validator. `setupAgent.fromConfig(...)` calls
59
+ * this once per schema in the config (context/events/input/output/meta,
60
+ * request input/output) — bring your own engine (Ajv, @cfworker/json-schema,
61
+ * a compiled-Zod-from-JSON-Schema pipeline, ...). Core intentionally ships no
62
+ * JSON Schema engine.
63
+ */
64
+ type SchemaCompiler = (jsonSchema: Record<string, unknown>, name: string) => StandardSchemaV1;
65
+ /**
66
+ * Serializable JSON/YAML machine definition — the config a database, visual
67
+ * editor, or LLM could produce and hand to `setupAgent.fromConfig(config, {
68
+ * compileSchema })` to get back the same kind of `AnyStateMachine`
69
+ * TypeScript `setupAgent(...)` authoring would build. JS/TS authoring should
70
+ * use `setupAgent(...)` directly instead of this JSON form. Any `unknown`-
71
+ * typed field here (`model`, `guard`, action `params`, …) accepts either a
72
+ * literal JSON value or a `"{{ path.to.value }}"` template-expression string
73
+ * resolved against `{ context, event, input, output }` at machine-build/
74
+ * transition time — see the sibling `evaluateWorkflowConfigValue` lowering.
75
+ */
76
+ interface AgentWorkflowConfig {
77
+ key?: string;
78
+ id?: string;
79
+ version?: string;
80
+ description?: string;
81
+ schemas?: {
82
+ input?: JsonSchemaObject;
83
+ context?: JsonSchemaObject;
84
+ events?: Record<string, JsonSchemaObject>;
85
+ emitted?: Record<string, JsonSchemaObject>;
86
+ output?: JsonSchemaObject;
87
+ meta?: JsonSchemaObject;
88
+ };
89
+ context?: Record<string, unknown>;
90
+ requests?: Record<string, AgentWorkflowRequestConfig>;
91
+ actors?: Record<string, AgentWorkflowActorConfig>;
92
+ initial: string;
93
+ states: Record<string, AgentWorkflowStateConfig>;
94
+ meta?: Record<string, unknown>;
95
+ }
96
+ /** 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}). */
97
+ interface AgentWorkflowRequestConfig {
98
+ mode?: AgentRequestMode;
99
+ description?: string;
100
+ model: unknown;
101
+ system?: unknown;
102
+ prompt?: unknown;
103
+ messages?: unknown;
104
+ input: JsonSchemaObject;
105
+ output: JsonSchemaObject;
106
+ tools?: AgentTools;
107
+ toolChoice?: AgentToolChoice | unknown;
108
+ /** Opt into the structured-output envelope's `reasoning` field (see `AgentTextRequest.reasoning`). */
109
+ reasoning?: boolean;
110
+ temperature?: unknown;
111
+ maxOutputTokens?: unknown;
112
+ topP?: unknown;
113
+ topK?: unknown;
114
+ seed?: unknown;
115
+ stopSequences?: unknown;
116
+ metadata?: unknown;
117
+ }
118
+ /** 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(...)`. */
119
+ interface AgentWorkflowActorConfig {
120
+ input?: JsonSchemaObject;
121
+ output?: JsonSchemaObject;
122
+ description?: string;
123
+ }
124
+ /** A `states` entry in {@link AgentWorkflowConfig} — the JSON equivalent of an XState state node config. */
125
+ interface AgentWorkflowStateConfig {
126
+ description?: string;
127
+ type?: "parallel" | "history" | "final" | "choice";
128
+ initial?: string;
129
+ states?: Record<string, AgentWorkflowStateConfig>;
130
+ choice?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
131
+ invoke?: AgentWorkflowInvokeConfig | AgentWorkflowInvokeConfig[];
132
+ on?: Record<string, AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[]>;
133
+ always?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
134
+ onDone?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
135
+ after?: Record<string, AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[]>;
136
+ entry?: AgentWorkflowActionConfig | AgentWorkflowActionConfig[];
137
+ exit?: AgentWorkflowActionConfig | AgentWorkflowActionConfig[];
138
+ tags?: string[];
139
+ output?: unknown;
140
+ meta?: Record<string, unknown>;
141
+ }
142
+ /**
143
+ * An `invoke` entry in {@link AgentWorkflowStateConfig}. For `src:
144
+ * 'agent.decide'`, the chosen event is delivered automatically — its
145
+ * transition usually exits the state and ends the invoke, so an `onDone` is
146
+ * rarely needed; declare one only to observe a chosen event whose transition
147
+ * stays in-state. `onError` handles retries-exhausted.
148
+ */
149
+ interface AgentWorkflowInvokeConfig {
150
+ id?: string;
151
+ src: string;
152
+ input?: unknown;
153
+ onDone?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
154
+ onError?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
155
+ meta?: Record<string, unknown>;
156
+ }
157
+ /** 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. */
158
+ interface AgentWorkflowTransitionConfig {
159
+ target?: string | string[];
160
+ guard?: unknown;
161
+ assign?: Record<string, unknown>;
162
+ actions?: AgentWorkflowActionConfig | AgentWorkflowActionConfig[];
163
+ description?: string;
164
+ reenter?: boolean;
165
+ meta?: Record<string, unknown>;
166
+ }
167
+ /** An `entry`/`exit`/transition `actions` entry in {@link AgentWorkflowConfig} — either a named action `type` (with template-expression `params`) or a bare context `assign`. */
168
+ interface AgentWorkflowActionConfig {
169
+ type?: string;
170
+ params?: unknown;
171
+ assign?: Record<string, unknown>;
172
+ emit?: unknown;
173
+ [key: string]: unknown;
174
+ }
175
+ /** Options for `setupAgent.fromConfig(...)`. */
176
+ interface FromConfigOptions {
177
+ /**
178
+ * Compile a JSON Schema from the config into a runtime validator. Bring
179
+ * your own engine (Ajv, @cfworker/json-schema, a compiled-Zod-from-JSON-Schema
180
+ * pipeline, ...). Core intentionally ships no JSON Schema engine.
181
+ */
182
+ compileSchema: SchemaCompiler;
183
+ }
184
+ //#endregion
185
+ //#region src/setup-agent.d.ts
186
+ type Constrain<T, TConstraint> = T extends TConstraint ? T : TConstraint;
187
+ type ContextOf<TContextSchema extends StandardSchemaV1> = Constrain<InferOutput<TContextSchema>, MachineContext>;
188
+ type EventsOf<TEventSchemas extends AgentEventSchemaInputMap> = Constrain<EventUnion<TEventSchemas>, EventObject>;
189
+ 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] };
190
+ type AgentSetupActors<TActors extends { [K in keyof TActors]: AnyActorLogic }, TEvent extends string = string, TModel extends string = string> = TActors & BuiltinAgentActors<TEvent, TModel>;
191
+ /**
192
+ * A machine's full schema set — context, event payloads, machine input/
193
+ * output, and state/transition meta — as returned by {@link createAgentSchemas}
194
+ * and retained on `setupAgent(...)`'s `result.schemas` for runtime
195
+ * validation (e.g. by the step path to validate `initialAgentStep` input, or
196
+ * by `getAcceptedEvents` to attach event payload schemas). Unlike
197
+ * `AgentSchemaConfig` (the input to `createAgentSchemas`), every field here
198
+ * is required — `events`/`input`/`output`/`meta` default to empty/unknown
199
+ * schemas when not supplied.
200
+ */
201
+ 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>> {
202
+ context: TContextSchema;
203
+ events: NormalizedEventSchemas<TEventSchemas>;
204
+ input: TInputSchema;
205
+ output: TOutputSchema;
206
+ meta: TMetaSchema;
207
+ /** 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. */
208
+ emitted?: TEmittedSchemas;
209
+ }
210
+ 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>> = {
211
+ context: TContextSchema;
212
+ events?: TEventSchemas;
213
+ input?: TInputSchema;
214
+ output?: TOutputSchema;
215
+ meta?: TMetaSchema;
216
+ emitted?: TEmittedSchemas;
217
+ };
218
+ /**
219
+ * Builds a machine's {@link AgentSchemaPack} from a partial schema
220
+ * declaration — only `context` is required; `events`/`input`/`output`/`meta`
221
+ * default to empty/unknown schemas when omitted. Pass the result as
222
+ * `setupAgent({ schemas })`'s `schemas` (or spread the individual fields
223
+ * directly into `setupAgent({ context, events, ... })` — both forms are
224
+ * accepted).
225
+ */
226
+ 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>;
227
+ type AgentRequestConfig<TInputSchema extends StandardSchemaV1 = StandardSchemaV1, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1, TMetadata = Record<string, unknown>, TModel extends string = string> = TextLogicConfig<TInputSchema, TOutputSchema, TMetadata, TModel> & {
228
+ mode?: AgentRequestMode;
229
+ };
230
+ type AgentRequestSchemaMap = Record<string, {
231
+ input: StandardSchemaV1;
232
+ output: StandardSchemaV1;
233
+ }>;
234
+ type AgentRequestInput<TRequestSchemas extends AgentRequestSchemaMap, TModel extends string = string> = { [K in keyof TRequestSchemas]: AgentRequestConfig<TRequestSchemas[K]["input"], TRequestSchemas[K]["output"], Record<string, unknown>, TModel> & {
235
+ schemas: TRequestSchemas[K];
236
+ } };
237
+ type RequestActors<TRequestSchemas extends AgentRequestSchemaMap> = { [K in keyof TRequestSchemas]: TextLogic<TRequestSchemas[K]["input"], TRequestSchemas[K]["output"]> };
238
+ type AgentAllActors<TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap> = TActors & RequestActors<TRequestSchemas>;
239
+ type AgentSetupEventsSchema<TEventSchemas extends AgentEventSchemaInputMap> = [keyof TEventSchemas] extends [never] ? {} : {
240
+ events: NormalizedEventSchemas<TEventSchemas>;
241
+ };
242
+ type AgentSetupEmittedSchema<TEmittedSchemas extends Record<string, StandardSchemaV1>> = [keyof TEmittedSchemas] extends [never] ? {} : {
243
+ emitted: TEmittedSchemas;
244
+ };
245
+ 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>> = {
246
+ schemas: {
247
+ context: TContextSchema;
248
+ input: TInputSchema;
249
+ output: TOutputSchema;
250
+ meta: TMetaSchema;
251
+ } & AgentSetupEventsSchema<TEventSchemas> & AgentSetupEmittedSchema<TEmittedSchemas>;
252
+ states?: TStateSchemas;
253
+ actorSources: SetupActors<AgentSetupActors<AgentAllActors<TActors, TRequestSchemas>, keyof TEventSchemas & string, AgentModelRef<TModels>>>;
254
+ actions?: NonNullable<AnySetupConfig["actions"]>;
255
+ guards?: NonNullable<AnySetupConfig["guards"]>;
256
+ delays?: NonNullable<AnySetupConfig["delays"]>;
257
+ };
258
+ /**
259
+ * Field-level context-narrowing sugar for one `setupAgent({ states })` entry:
260
+ * each `context` entry overrides that field's schema inside the state; every
261
+ * other field keeps the base context schema. Sugar for the full xstate form —
262
+ * `{ context: { draft: z.string() } }` resolves to
263
+ * `{ schemas: { context: <base with draft: string> } }` — so only the fields
264
+ * that change are declared, not the whole context schema.
265
+ */
266
+ interface AgentStateNarrowing {
267
+ context: Record<string, StandardSchemaV1>;
268
+ states?: Record<string, AgentSetupStateSchema>;
269
+ }
270
+ /** One `setupAgent({ states })` entry: xstate's {@link SetupStateSchema} full form, or the {@link AgentStateNarrowing} field-level sugar. */
271
+ type AgentSetupStateSchema = SetupStateSchema | AgentStateNarrowing;
272
+ type NarrowedContext<TContextSchema extends StandardSchemaV1, TFields extends Record<string, StandardSchemaV1>> = Omit<InferOutput<TContextSchema>, keyof TFields> & { [K in keyof TFields]: InferOutput<TFields[K]> };
273
+ type ResolveAgentStateSchema<TContextSchema extends StandardSchemaV1, T> = T extends {
274
+ context: infer TFields extends Record<string, StandardSchemaV1>;
275
+ } ? {
276
+ schemas: {
277
+ context: StandardSchemaV1<NarrowedContext<TContextSchema, TFields>>;
278
+ };
279
+ } & (T extends {
280
+ states: infer TChildren extends Record<string, AgentSetupStateSchema>;
281
+ } ? {
282
+ states: ResolveAgentStateSchemas<TContextSchema, TChildren>;
283
+ } : {}) : T extends {
284
+ states: infer TChildren extends Record<string, AgentSetupStateSchema>;
285
+ } ? Omit<T, "states"> & {
286
+ states: ResolveAgentStateSchemas<TContextSchema, TChildren>;
287
+ } : T;
288
+ type ResolveAgentStateSchemas<TContextSchema extends StandardSchemaV1, TStates extends Record<string, AgentSetupStateSchema>> = Constrain<{ [K in keyof TStates]: ResolveAgentStateSchema<TContextSchema, TStates[K]> }, Record<string, SetupStateSchema>>;
289
+ 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>> = ({
290
+ schemas: AgentSchemaPack<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>;
291
+ } | AgentSchemaConfig<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>) & {
292
+ models?: TModels;
293
+ actorSources?: TActors;
294
+ /**
295
+ * Per-state schemas, mirroring xstate's `setup({ states })`: narrow
296
+ * `context` inside a state (invoke `input`, transition fns, final `output`)
297
+ * — e.g. mark a field non-null in states only reachable after it is set.
298
+ * Two forms per state: the {@link AgentStateNarrowing} sugar
299
+ * (`{ context: { draft: z.string() } }` — only the fields that change) or
300
+ * xstate's full `{ schemas: { context } }` with a complete context schema.
301
+ */
302
+ states?: TStateSchemas;
303
+ requests?: AgentRequestInput<TRequestSchemas, AgentModelRef<TModels>>;
304
+ actions?: NonNullable<AnySetupConfig["actions"]>;
305
+ guards?: NonNullable<AnySetupConfig["guards"]>;
306
+ delays?: NonNullable<AnySetupConfig["delays"]>;
307
+ /**
308
+ * Detects a snapshot that is an INTENTIONAL wait for an external event (a
309
+ * human approval, an inbound webhook, …) — the machine's own declaration of
310
+ * what "suspended" means for it, so `runAgent` settles those snapshots idle
311
+ * deterministically instead of using its timing heuristic. Travels with the
312
+ * machine through `machine.provide(...)`. A `runAgent({ isSuspended })` host
313
+ * override takes precedence; with neither, `runAgent` falls back to the timing
314
+ * heuristic. Declare your own signal — e.g. `(s) => s.hasTag('awaiting-review')`
315
+ * or `(s) => getStateMeta(s).interaction !== undefined`.
316
+ */
317
+ isSuspended?: (snapshot: AnyMachineSnapshot) => boolean;
318
+ };
319
+ 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>>>;
320
+ /**
321
+ * The object returned by {@link setupAgent}: an xstate `setup(...)` result
322
+ * (`createMachine`, `assign`, …) extended with `schemas` (the resolved
323
+ * {@link AgentSchemaPack}), `models`, `requests` (the built request actors),
324
+ * and {@link appendMessages}. Machines created here are registered so
325
+ * `runAgent` and the free step helpers can resolve their schemas/actors
326
+ * without re-passing them each call.
327
+ */
328
+ 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"> & {
329
+ /**
330
+ * Creates the agent machine — XState's own `createMachine`, plus: the
331
+ * machine is registered so step helpers and {@link runAgent} can resolve
332
+ * its schemas/actors without re-passing them, and a single final state's
333
+ * `output` is copied to the machine root when the root declares none.
334
+ */
335
+ 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. */
336
+ schemas: AgentSchemaPack<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>; /** The `models` registry passed to `setupAgent(...)`, if any (used to type-narrow `AgentModelRef`). */
337
+ readonly models: TModels; /** The {@link TextLogic} actors built from `setupAgent({ requests })`, keyed the same way. */
338
+ readonly requests: RequestActors<TRequestSchemas>; /** {@link appendMessages}, typed against this agent's context/event schemas. */
339
+ appendMessages(resolve: AgentMessage | AgentMessage[] | ((args: {
340
+ context: ContextOf<TContextSchema> & {
341
+ messages: AgentMessage[];
342
+ };
343
+ event: any;
344
+ }) => AgentMessage | AgentMessage[])): ReturnType<typeof appendMessages<ContextOf<TContextSchema> & {
345
+ messages: AgentMessage[];
346
+ }, EventsOf<TEventSchemas>>>;
347
+ };
348
+ /** Typed machine config used by convenience authoring layers built on `setupAgent`. */
349
+ 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];
350
+ /** Machine produced from {@link AgentMachineConfig}. */
351
+ 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"]>;
352
+ /**
353
+ * Schema-first `setup(...)` for agent machines — the standard entry point
354
+ * for authoring a machine (the blueprint) that this library then runs (via
355
+ * {@link runAgent} or the step helpers) against host-supplied model/decision
356
+ * executors. Context, events, machine input, machine output, and
357
+ * state/transition meta are all standard schemas — no `{} as Type` casts —
358
+ * and are retained on `result.schemas` for runtime validation. Also
359
+ * registers the `agent.generateText`/`agent.streamText`/`agent.userInput`/
360
+ * `agent.decide` builtin actors and lowers `requests`/`actorSources` into the
361
+ * machine's actor sources. The result is the xstate `setup(...)` object with
362
+ * a wrapped `result.createMachine(...)` plus `result.schemas`/`models`/
363
+ * `requests`/`appendMessages` attached. Also has a
364
+ * `setupAgent.fromConfig(...)` namespace member for building a machine from
365
+ * a serializable {@link AgentWorkflowConfig} instead of this TS API.
366
+ *
367
+ * @example
368
+ * ```ts
369
+ * const schemas = createAgentSchemas({
370
+ * context: z.object({ topic: z.string(), joke: z.string().nullable() }),
371
+ * input: z.object({ topic: z.string() }),
372
+ * output: z.object({ joke: z.string() }),
373
+ * });
374
+ *
375
+ * const agent = setupAgent({
376
+ * schemas,
377
+ * actorSources: { tellJoke },
378
+ * });
379
+ *
380
+ * const jokeMachine = agent.createMachine({
381
+ * context: ({ input }) => ({ topic: input.topic, joke: null }),
382
+ * initial: 'telling',
383
+ * states: {
384
+ * telling: {
385
+ * invoke: {
386
+ * id: 'joke',
387
+ * src: 'tellJoke',
388
+ * input: ({ context }) => ({ topic: context.topic }),
389
+ * onDone: ({ output }) => ({ target: 'done', context: { joke: output } }),
390
+ * },
391
+ * },
392
+ * done: { type: 'final', output: ({ context }) => ({ joke: context.joke ?? '' }) },
393
+ * },
394
+ * });
395
+ * ```
396
+ */
397
+ 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>;
398
+ declare namespace setupAgent {
399
+ /**
400
+ * Builds a state machine from a serializable {@link AgentWorkflowConfig}
401
+ * (JSON/YAML) instead of the TypeScript `setupAgent(...)` API — the same
402
+ * kind of machine a database, visual editor, or LLM could produce and hand
403
+ * back. Requires a `compileSchema` (see {@link FromConfigOptions}) since
404
+ * the library bundles no JSON Schema engine itself; bring Ajv,
405
+ * @cfworker/json-schema, or another compiler that returns Standard Schema.
406
+ *
407
+ * @example
408
+ * ```ts
409
+ * const machine = setupAgent.fromConfig(workflowConfig, {
410
+ * compileSchema,
411
+ * });
412
+ * const result = await runAgent(machine, { input: { ticket }, executors: { generateText, decide } });
413
+ * ```
414
+ */
415
+ function fromConfig(config: AgentWorkflowConfig, options: FromConfigOptions): AnyStateMachine;
416
+ }
417
+ //#endregion
418
+ //#region src/internal/registry.d.ts
419
+ type AgentExecutionOptions = Pick<AgentRequestOptions, "schemas" | "actorSources"> & {
420
+ models?: object;
421
+ };
422
+ //#endregion
423
+ //#region src/steps.d.ts
424
+ /**
425
+ * A pending text request surfaced by step discovery ({@link getAgentRequests}
426
+ * / {@link AgentStep.requests}): the machine has spawned a
427
+ * `TextLogic`-backed invoke and is waiting on its result. Resolve it with
428
+ * {@link executeAgentRequest} (or by hand, then feed the output into
429
+ * {@link resolveAgentStep} via `xstate.done.actor.<id>`).
430
+ */
431
+ interface AgentRequest<TInput extends AgentTextRequest = AgentTextRequest> {
432
+ kind: "text";
433
+ id: string;
434
+ src: AgentRequestSource;
435
+ mode?: AgentRequestMode;
436
+ input: TInput;
437
+ tools: AgentTools;
438
+ events: AgentEventDescriptor[];
439
+ }
440
+ /**
441
+ * A pending **plan** request re-surfaced by step discovery: the machine
442
+ * invoked `agent.plan`, which applies an ordered sequence of legal events
443
+ * (each one a decision) rather than a single one. Unlike text/decision
444
+ * requests — surfaced once and resolved once — a plan request **re-surfaces on
445
+ * every step** while the plan is in flight, its `events`/`applied`/
446
+ * `stepsRemaining` updated each time, until it terminates.
447
+ *
448
+ * All fields are plain serializable data. Resolve ONE decision per step from
449
+ * `events` (via {@link resolveDecision}, wiring `canTake` to
450
+ * `snapshot.can` exactly like a single decision) then apply it: a real machine
451
+ * event advances the plan (the next step re-surfaces this request); the
452
+ * reserved `agent.plan.done` move, a `stopOn` event, an exhausted budget, or no
453
+ * legal events completes it (its invoke resolves with `{ steps, stopped }`).
454
+ * {@link resolveAgentRequests} does all of this natively — one decision (or one
455
+ * completion) per call.
456
+ *
457
+ * The in-progress plan state (`applied` trail + remaining budget) lives in the
458
+ * plan invoke child's own `createLogic` snapshot `context`
459
+ * (`children.<id>.snapshot.context`), so it survives a full JSON
460
+ * `getPersistedSnapshot` → restore round-trip: a host that persists the step
461
+ * after every event and reloads resumes the plan identically.
462
+ */
463
+ interface AgentPlanRequest {
464
+ kind: "plan";
465
+ /** Durable invoke id of the `agent.plan` invoke. */
466
+ id: string;
467
+ /** Invoke src (`'agent.plan'` or a registered plan-logic source name). */
468
+ src: AgentRequestSource;
469
+ /** The resolved plan input (`model`/`system`/`prompt`/`allowedEvents`/`stopOn`/`maxSteps`/…). */
470
+ input: AgentPlanInput;
471
+ /**
472
+ * The legal candidates for the NEXT plan step: the currently
473
+ * snapshot-legal machine events (∩ declared `allowedEvents`) plus the
474
+ * reserved `agent.plan.done` move.
475
+ */
476
+ events: AgentEventDescriptor[];
477
+ /** The events applied so far in this plan, in order (the trail). */
478
+ applied: ChosenEvent[];
479
+ /** How many more events the plan may apply (`maxSteps - applied.length`). */
480
+ stepsRemaining: number;
481
+ }
482
+ /** `AgentStep.requests` element: a text, decision, or plan request. */
483
+ type AgentStepRequest = AgentRequest | AgentDecisionRequest | AgentPlanRequest;
484
+ /**
485
+ * One durable checkpoint on the step path: the machine's current snapshot,
486
+ * the executable actions that produced it, the pending
487
+ * {@link AgentStepRequest}s (text/decision work still to resolve), and
488
+ * whether the machine has reached a final state. This is the
489
+ * per-model-call-checkpoint path for durable hosts (Workflows, Temporal,
490
+ * queues, …) — a peer of `runAgent`, not a lesser version of it. Produced by
491
+ * {@link initialAgentStep}/{@link transitionAgentStep}/{@link resolveAgentStep}.
492
+ */
493
+ interface AgentStep<TSnapshot extends AnyMachineSnapshot = AnyMachineSnapshot> {
494
+ snapshot: TSnapshot;
495
+ actions: readonly {
496
+ type?: string;
497
+ params?: unknown;
498
+ }[];
499
+ requests: AgentStepRequest[];
500
+ done: boolean;
501
+ }
502
+ /**
503
+ * Starts a machine and returns its first {@link AgentStep} — the step-path
504
+ * equivalent of `initialTransition` plus request discovery. Begins the
505
+ * durable/per-model-call-checkpoint loop: resolve each `step.requests` entry
506
+ * (via {@link executeAgentRequest} for `kind: 'text'`, or
507
+ * {@link resolveDecision} for `kind: 'decision'`), then advance with
508
+ * {@link resolveAgentStep} or {@link transitionAgentStep}.
509
+ */
510
+ declare function initialAgentStep<TMachine extends AnyActorLogic>(machine: TMachine, input?: unknown, options?: Partial<AgentExecutionOptions>): AgentStep<SnapshotFrom<TMachine>>;
511
+ /**
512
+ * Applies an externally-sent event (e.g. a decision's chosen event, or a
513
+ * human's reply) and returns the next {@link AgentStep}. Accepts **either**
514
+ * a raw snapshot **or** a prior `AgentStep` as the second argument —
515
+ * `.snapshot` is unwrapped automatically, so callers can thread the whole
516
+ * step object through without manually plucking the snapshot out.
517
+ */
518
+ declare function transitionAgentStep<TMachine extends AnyActorLogic>(machine: TMachine, snapshotOrStep: SnapshotFrom<TMachine> | AgentStep<SnapshotFrom<TMachine>>, event: EventFromLogic<TMachine>, options?: Partial<AgentExecutionOptions>): AgentStep<SnapshotFrom<TMachine>>;
519
+ /**
520
+ * Applies a resolved text request's output (a `kind: 'text'`
521
+ * {@link AgentRequest} — not a decision) as a done event and returns the
522
+ * next {@link AgentStep}. For decisions, resolve with `resolveDecision`
523
+ * (which returns a {@link ChosenEvent}) and apply it with
524
+ * {@link transitionAgentStep} instead — a decision has no output value of
525
+ * its own to feed here.
526
+ */
527
+ declare function resolveAgentStep<TMachine extends AnyActorLogic>(machine: TMachine, step: AgentStep<SnapshotFrom<TMachine>>, request: Pick<AgentRequest, "id"> | string, output: unknown, options?: Partial<AgentExecutionOptions>): AgentStep<SnapshotFrom<TMachine>>;
528
+ /**
529
+ * Snapshot in, requests out: scans executable actions for spawned agent
530
+ * invokes and lowers each into an {@link AgentStepRequest}, pre-filled with
531
+ * the machine's registered `setupAgent` schemas/actorSources (so callers
532
+ * don't pass them by hand each call) — merged with any `options` passed here,
533
+ * which take precedence. The step path's public discovery primitive;
534
+ * `initialAgentStep`/`transitionAgentStep`/`resolveAgentStep` call it
535
+ * internally to populate `AgentStep.requests`.
536
+ */
537
+ declare function getAgentRequests(machine: AnyActorLogic, actions: readonly {
538
+ type?: string;
539
+ params?: unknown;
540
+ }[], snapshot?: AnyMachineSnapshot, options?: Pick<AgentRequestOptions, "eventToolName"> & Partial<AgentExecutionOptions>): AgentStepRequest[];
541
+ /**
542
+ * Resolves one **text** {@link AgentRequest} against a host's
543
+ * {@link AgentRequestExecutors} — merges the request's tools, dispatches to
544
+ * `generateText`/`streamText` per `request.mode`, and validates the result
545
+ * against `request.input.outputSchema` if present. **Text-only**: passing a
546
+ * `kind: 'decision'` request throws, directing the caller to
547
+ * `resolveDecision(request, executors.decide, ...)` instead. By default
548
+ * returns the normalized output; pass `{ verbose: true }` to also get the
549
+ * raw executor result (tool calls, usage, finish reason — needed for
550
+ * observability and event-sourced replay).
551
+ */
552
+ declare function executeAgentRequest(request: AgentRequest, executors: Partial<AgentRequestExecutors>): Promise<unknown>;
553
+ declare function executeAgentRequest(request: AgentRequest, executors: Partial<AgentRequestExecutors>, options: {
554
+ verbose: true;
555
+ }): Promise<{
556
+ output: unknown;
557
+ raw: unknown;
558
+ }>;
559
+ /**
560
+ * Options for {@link resolveAgentRequests}.
561
+ */
562
+ interface ResolveAgentRequestsOptions extends Partial<AgentExecutionOptions> {
563
+ /** Retries per decision, passed to `resolveDecision`. Default `2`. */
564
+ maxRetries?: number;
565
+ }
566
+ /**
567
+ * Resolves the current step's pending requests and returns the next
568
+ * {@link AgentStep} — one iteration of the durable step loop, collapsing the
569
+ * manual `request.kind` dispatch a host would otherwise write by hand.
570
+ *
571
+ * For each pending request, in order: a `kind: 'text'` request is run with
572
+ * {@link executeAgentRequest} then fed back via {@link resolveAgentStep}; a
573
+ * `kind: 'decision'` request is resolved with `resolveDecision` (wiring
574
+ * `canTake` to `step.snapshot.can` so guard-rejected choices retry) then
575
+ * applied with {@link transitionAgentStep}. The **current** step is re-read
576
+ * after each application — the machine may advance and its `requests` change —
577
+ * so this always resolves against the live step, never a stale list.
578
+ *
579
+ * A `kind: 'plan'` request (`agent.plan`) is resolved natively too: one plan
580
+ * step per call. It resolves a single decision from `request.events` (wiring
581
+ * `canTake` to `step.snapshot.can`, exempting the reserved `agent.plan.done`
582
+ * move and `stopOn` events), then either applies the chosen machine event and
583
+ * lets the next step re-surface the plan, or completes the plan (feeding its
584
+ * `{ steps, stopped }` output back) on the done move / a `stopOn` event / an
585
+ * exhausted budget / no legal events. The plan's applied trail is carried in
586
+ * the invoke child's snapshot, so persisting the step between calls resumes the
587
+ * plan identically.
588
+ *
589
+ * Missing the executor a request needs throws a clear error
590
+ * (`generateText`/`streamText` for text, `decide` for decisions and plans).
591
+ *
592
+ * A complete durable host is two lines:
593
+ *
594
+ * ```ts
595
+ * let step = initialAgentStep(machine, input);
596
+ * while (!step.done) step = await resolveAgentRequests(machine, step, executors);
597
+ * ```
598
+ *
599
+ * All pending **text** requests of a step are resolved in parallel
600
+ * (`Promise.all`) — parallel statechart regions are genuinely concurrent, so
601
+ * their model calls run concurrently — then their outputs apply in
602
+ * **request-array order** (deterministic for durable replay regardless of which
603
+ * call finishes first). Decisions and plans stay **one at a time**: applying
604
+ * either changes the set of legal candidates for what follows, so they cannot be
605
+ * resolved against a stale snapshot. A host that instead wants strictly
606
+ * sequential text resolution loops the manual per-request helpers
607
+ * ({@link executeAgentRequest} + {@link resolveAgentStep}) one at a time.
608
+ */
609
+ declare function resolveAgentRequests<TMachine extends AnyActorLogic>(machine: TMachine, step: AgentStep<SnapshotFrom<TMachine>>, executors: Partial<AgentRequestExecutors>, options?: ResolveAgentRequestsOptions): Promise<AgentStep<SnapshotFrom<TMachine>>>;
610
+ //#endregion
611
+ //#region src/internal/state-request-pass.d.ts
612
+ /**
613
+ * One model request read off the machine's CURRENT snapshot by a
614
+ * `RunAgentOptions.getRequests` hook. `model` is an executor model NAME — the
615
+ * same string every {@link AgentTextRequest.model} carries, resolved by the
616
+ * run's executors (e.g. a `defineModels` key when using
617
+ * `createAiSdkExecutors`) — never a model instance.
618
+ */
619
+ interface AgentStateRequest {
620
+ /** Instruction for this request's model call, appended to the run's message log as a user message. */
621
+ prompt: string;
622
+ /** System prompt for this request's model call(s). */
623
+ system?: string;
624
+ /** Executor model name (resolved by the run's executors). */
625
+ model: string;
626
+ /**
627
+ * `'text'` (default): a `generateText` call with the message log +
628
+ * `prompt`; the reply is appended to the log, then the machine is advanced
629
+ * per {@link AgentStateRequest.onDone}. `'decision'`: no text call — a
630
+ * single `decide` call (log + `prompt`) chooses the event. Use for pure
631
+ * routing states.
632
+ */
633
+ kind?: "text" | "decision";
634
+ /**
635
+ * What to send when this request's text call resolves — the EXPLICIT
636
+ * advancement contract, always an event OBJECT (the same shape
637
+ * `actor.send` takes; no string shorthand). A literal event sends exactly
638
+ * that; a function receives the text output (plus the live snapshot and
639
+ * message log) and returns the event to send — payload included — or
640
+ * `undefined` to send nothing. Omitted: a `decide` call chooses among the
641
+ * candidate events (requires a `decide` executor) — there is no implicit
642
+ * auto-send. A resolved event whose type the state does not accept throws
643
+ * (programmer error); one a guard rejects is simply not sent. Ignored for
644
+ * `kind: 'decision'` (the decide call IS the advancement).
645
+ */
646
+ onDone?: ChosenEvent | ((args: {
647
+ output: unknown;
648
+ snapshot: AnyMachineSnapshot;
649
+ messages: readonly AgentMessage[];
650
+ }) => ChosenEvent | undefined);
651
+ /** Restricts this request's candidate outcome events for the `decide` fallback (default: every currently-accepted event). */
652
+ allowedEvents?: readonly string[];
653
+ /** Trace/request id; defaults to `interpret_<n>`. */
654
+ id?: string;
655
+ }
656
+ //#endregion
657
+ //#region src/run-agent.d.ts
658
+ /**
659
+ * Thrown by {@link runAgent} when resuming with a `snapshot` + `event` whose
660
+ * `type` the restored state cannot accept (a type-level check via
661
+ * {@link getAcceptedEvents}). A programmer/integration error, in the same
662
+ * class as runAgent's bind-time throws — it throws rather than settling an
663
+ * `error` result. A type-legal event a guard rejects is NOT this error (the
664
+ * machine simply takes no transition). Opt out with
665
+ * {@link RunAgentOptions.onIllegalResumeEvent} `'ignore'`.
666
+ */
667
+ declare class IllegalResumeEventError extends Error {
668
+ readonly eventType: string;
669
+ readonly acceptedTypes: string[];
670
+ constructor(eventType: string, acceptedTypes: string[]);
671
+ }
672
+ /**
673
+ * Thrown by {@link runAgent} when resuming from a `snapshot` whose stamped
674
+ * `agentMeta.version` differs from the current machine's version, under the
675
+ * default `onVersionMismatch: 'throw'` and with no `migrateSnapshot` hook. The
676
+ * structural fingerprint of the machine changed since the snapshot was
677
+ * persisted (a state/transition/invoke was added, removed, or retargeted), so
678
+ * the snapshot may no longer resume cleanly. `from` is the snapshot's version,
679
+ * `to` the current machine's.
680
+ */
681
+ declare class SnapshotVersionMismatchError extends Error {
682
+ readonly from: string;
683
+ readonly to: string;
684
+ readonly machineId: string;
685
+ constructor(from: string, to: string, machineId: string);
686
+ }
687
+ /**
688
+ * Thrown by {@link runAgentToCompletion} when the run settles `idle` instead of
689
+ * `done`: the machine paused for external input. Carries the idle `snapshot`
690
+ * and `acceptedTypes` (the event types that could resume it, via
691
+ * {@link getAcceptedEvents}). Use {@link runAgent} directly when idle is an
692
+ * expected outcome you handle.
693
+ */
694
+ declare class AgentIdleError extends Error {
695
+ readonly snapshot: AnyMachineSnapshot;
696
+ readonly acceptedTypes: string[];
697
+ constructor(snapshot: AnyMachineSnapshot, acceptedTypes: string[]);
698
+ }
699
+ /** Handler for `agent.userInput` invokes passed as {@link RunAgentOptions.userInput}. Resolves to what the human typed. */
700
+ interface AgentUserInputExecutor {
701
+ (input: AgentUserInput): PromiseLike<string>;
702
+ }
703
+ type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
704
+ runId: string;
705
+ seq: number;
706
+ timestamp: string;
707
+ } & ({
708
+ type: "run.start";
709
+ input?: InputFrom<TMachine>;
710
+ snapshot?: Snapshot<unknown>;
711
+ event?: EventFromLogic<TMachine>;
712
+ } | {
713
+ type: "request.start";
714
+ request: AgentStepRequest;
715
+ } | {
716
+ type: "request.end";
717
+ request: AgentStepRequest;
718
+ output: unknown;
719
+ raw: unknown;
720
+ /** The model's reasoning, lifted off the raw executor result when the
721
+ * request opted into the structured-output envelope's `reasoning` field.
722
+ * Present only when the executor surfaced a string `reasoning`. */
723
+ reasoning?: string;
724
+ } | {
725
+ type: "request.error";
726
+ request: AgentStepRequest;
727
+ error: unknown;
728
+ } | {
729
+ type: "stream.chunk";
730
+ request: AgentRequest;
731
+ chunk: string;
732
+ } | {
733
+ type: "machine.transition";
734
+ snapshot: SnapshotFrom<TMachine>;
735
+ event: EventFromLogic<TMachine>;
736
+ } | {
737
+ type: "emit";
738
+ event: EmittedFrom<TMachine>;
739
+ } | ({
740
+ type: "run.end";
741
+ status: "done";
742
+ output: OutputFrom<TMachine>;
743
+ snapshot: SnapshotFrom<TMachine>;
744
+ } | {
745
+ type: "run.end";
746
+ status: "idle";
747
+ snapshot: SnapshotFrom<TMachine>;
748
+ pendingUserInputs?: PendingUserInput[];
749
+ persistedSnapshot?: Snapshot<unknown>;
750
+ } | {
751
+ type: "run.end";
752
+ status: "error";
753
+ cause: RunAgentErrorCause;
754
+ error: unknown;
755
+ snapshot: SnapshotFrom<TMachine>;
756
+ }));
757
+ /**
758
+ * Options for {@link runAgent}.
759
+ *
760
+ * Host executors are passed as a single {@link AgentRequestExecutors}-shaped
761
+ * set under `executors` (the same shape the step path takes). Each executor
762
+ * kind is required only if the machine actually reaches a request of that kind
763
+ * — checked at bind time, before any actor runs. The whole `executors` field is
764
+ * optional: a machine whose agent sources all carry their own executor
765
+ * (`.withExecutor(...)`) needs none.
766
+ */
767
+ interface RunAgentOptions<TMachine extends AnyStateMachine> {
768
+ /**
769
+ * The host executor set backing the machine's agent actors — build it with
770
+ * `createAiSdkExecutors({ models })` from '@statelyai/agent/ai-sdk', or supply
771
+ * `{ generateText?, streamText?, decide? }` by hand. Every slot is optional
772
+ * here (unlike the step path's {@link AgentRequestExecutors}): each kind is
773
+ * bind-time-checked only when the machine actually reaches a request of that
774
+ * kind, so e.g. a stream-only machine may pass `{ streamText }` alone.
775
+ */
776
+ executors?: Partial<AgentRequestExecutors>;
777
+ /** Machine input, passed straight to `createActor(machine, { input })`. Omit when resuming via `snapshot`. */
778
+ input?: InputFrom<TMachine>;
779
+ /** 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. */
780
+ snapshot?: Snapshot<unknown>;
781
+ /** An event to send immediately after starting/resuming the actor (e.g. the human's answer to an idle-state prompt). */
782
+ event?: EventFromLogic<TMachine>;
783
+ /**
784
+ * How to handle a resume `event` the restored state cannot accept (a
785
+ * type-level check via {@link getAcceptedEvents}, only applied when resuming
786
+ * from a `snapshot`). `'throw'` (default) throws {@link IllegalResumeEventError}
787
+ * before delivering the event; `'ignore'` restores the older silent behavior
788
+ * (the event is sent and the machine drops it). A type-legal event a guard
789
+ * rejects is never an illegal resume event.
790
+ */
791
+ onIllegalResumeEvent?: "throw" | "ignore";
792
+ /**
793
+ * The version stamped onto every settled snapshot's `agentMeta` and compared
794
+ * against an incoming snapshot's stamp on resume. Defaults to
795
+ * {@link getMachineStructuralHash} of the machine (a structural fingerprint).
796
+ * Set an explicit value (e.g. a semver or build id) to control migration
797
+ * boundaries yourself.
798
+ */
799
+ machineVersion?: string;
800
+ /**
801
+ * How to handle a resume `snapshot` whose stamped `agentMeta.version` differs
802
+ * from the current machine's version. `'throw'` (default) throws
803
+ * {@link SnapshotVersionMismatchError} with `from`/`to`; `'warn'`
804
+ * `console.warn`s once and proceeds; `'ignore'` proceeds silently. Ignored
805
+ * when {@link migrateSnapshot} is provided (that runs instead), and never
806
+ * triggers for an unstamped snapshot (no `agentMeta`).
807
+ */
808
+ onVersionMismatch?: "throw" | "warn" | "ignore";
809
+ /**
810
+ * Called instead of {@link onVersionMismatch} when a resume snapshot's
811
+ * version mismatches the current machine's: receives the incoming snapshot
812
+ * and `{ from, to }`, and its return value is used as the snapshot to resume
813
+ * from. A throw propagates.
814
+ */
815
+ migrateSnapshot?: (snapshot: Snapshot<unknown>, info: {
816
+ from: string;
817
+ to: string;
818
+ }) => Snapshot<unknown>;
819
+ /** Actor source implementations, merged onto the machine before binding — sugar for `machine.provide({ actorSources })` ahead of the run. */
820
+ actorSources?: Record<string, AnyActorLogic>;
821
+ /**
822
+ * Optional human-input handler for `agent.userInput` invokes (CLI prompt,
823
+ * web form, Slack, …). With a handler, input is gathered inline without
824
+ * settling. Without one, an `agent.userInput` invoke becomes a *pending
825
+ * placeholder*: it waits indefinitely, does not block idle detection, and
826
+ * the run settles `{ status: 'idle', pendingUserInputs, persistedSnapshot }`
827
+ * once no other work is in flight — resume by passing `persistedSnapshot`
828
+ * back as `snapshot` together with a `userInput` handler that answers it.
829
+ */
830
+ userInput?: AgentUserInputExecutor;
831
+ /**
832
+ * Host override for detecting a snapshot that is an INTENTIONAL wait for an
833
+ * external event — the deterministic replacement for the timing heuristic
834
+ * runAgent uses to settle idle. Resolution order: this option (host override)
835
+ * → the machine-carried predicate declared via `setupAgent({ isSuspended })`
836
+ * → the timing heuristic (when neither is present). When the resolved
837
+ * predicate returns true and nothing is in flight (no live requests/plans/
838
+ * invokes; the `agent.userInput` placeholder exemption still applies), runAgent
839
+ * settles idle immediately, without the `setTimeout` heuristic. It does NOT
840
+ * force-settle while agent work is in flight, and whole-machine idle semantics
841
+ * are unchanged; a machine with no predicate falls back to the heuristic
842
+ * exactly as before. Declare your own signal, e.g.
843
+ * `(s) => s.hasTag('awaiting-review')`.
844
+ *
845
+ * Provisional name — may change before 2.0.
846
+ */
847
+ isSuspended?: (snapshot: AnyMachineSnapshot) => boolean;
848
+ /**
849
+ * The override to runAgent's DEFAULT contract. By default agent work is
850
+ * whatever the machine *invokes* (`agent.generateText`, TextLogic,
851
+ * `agent.decide`, …). With `getRequests`, whenever the machine would
852
+ * otherwise settle idle, this hook reads the snapshot and returns the model
853
+ * request(s) to run instead — prompts from state `description`s, `meta`,
854
+ * tags, a lookup table keyed by state value, wherever you keep them. Return
855
+ * nothing to settle idle (human-wait states).
856
+ *
857
+ * There is no blessed source for the prompts — this is a recipe seam.
858
+ * Prompts-in-descriptions, copy-paste and adapt:
859
+ *
860
+ * ```ts
861
+ * getRequests: (snapshot) =>
862
+ * snapshot._nodes
863
+ * .filter((node) => node.description && !node.tags.includes('waiting'))
864
+ * .map((node) => ({
865
+ * model: 'writer',
866
+ * prompt: node.description!,
867
+ * kind: node.tags.includes('decision') ? 'decision' : 'text',
868
+ * // single-outcome states advance deterministically; else `decide`
869
+ * onDone: node.ownEvents.length === 1 ? { type: node.ownEvents[0] } : undefined,
870
+ * allowedEvents: node.ownEvents,
871
+ * })),
872
+ * ```
873
+ *
874
+ * Each request runs per {@link AgentStateRequest.kind}, appends to the
875
+ * run's message log (see {@link RunAgentOptions.messages}), and advances
876
+ * the machine per {@link AgentStateRequest.onDone} — explicitly named/
877
+ * computed event, or a `decide` call when omitted — always gated by
878
+ * `snapshot.can`. Multiple requests run concurrently (parallel regions —
879
+ * scope each with `allowedEvents`, e.g. the node's `ownEvents`). A pass
880
+ * that sends no event settles idle. Every model call counts against
881
+ * `maxModelCalls`.
882
+ */
883
+ getRequests?: (snapshot: SnapshotFrom<TMachine>, agentContext: {
884
+ messages: readonly AgentMessage[];
885
+ }) => AgentStateRequest | readonly AgentStateRequest[] | undefined;
886
+ /**
887
+ * Adds to the run's aggregated message log (the working memory
888
+ * `getRequests` requests read and append to). The log starts as the resume
889
+ * `snapshot`'s stamped `messages` (else `[]`); an ARRAY here is APPENDED to
890
+ * that history — the safe default for folding in a user reply on resume,
891
+ * never silently erasing prior conversation. Pass a FUNCTION
892
+ * `(prior) => AgentMessage[]` to take full control (replace, filter,
893
+ * compact). The final log is stamped onto every settled result's
894
+ * `snapshot.messages` (like `agentMeta`), so persist/resume round-trips it
895
+ * with no extra wiring — read it with `getAgentMessages(snapshot)`.
896
+ */
897
+ messages?: AgentMessage[] | ((prior: AgentMessage[]) => AgentMessage[]);
898
+ /** 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. */
899
+ onChunk?: (chunk: string, info: {
900
+ request: AgentRequest;
901
+ }) => void;
902
+ /** 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. */
903
+ onResult?: (request: AgentStepRequest, result: {
904
+ output: unknown;
905
+ raw: unknown;
906
+ }) => void;
907
+ /** Fires a single ordered stream of run/request/chunk/transition/emit/end events. Intended for eval traces, JSONL logs, and adapter-owned telemetry/exporters. */
908
+ onTrace?: (event: AgentTraceEvent<TMachine>) => void;
909
+ /**
910
+ * Fires on every machine transition (snapshot + causing event). Pure
911
+ * observation — progress UIs, logging, tracing. Cannot send events.
912
+ */
913
+ onTransition?: (snapshot: SnapshotFrom<TMachine>, event: EventFromLogic<TMachine>) => void;
914
+ /**
915
+ * Fires for each message appended to the run's aggregated log (see
916
+ * {@link RunAgentOptions.messages}) the moment a `getRequests` request
917
+ * appends it — the live view of the log a caller otherwise only reads off
918
+ * the settled snapshot via `getAgentMessages`. Purely observational, like
919
+ * {@link onTransition}. Never fires for the seeded history, and never fires
920
+ * on a default invoke-driven run (nothing appends there).
921
+ */
922
+ onMessage?: (message: AgentMessage) => void;
923
+ /**
924
+ * Handlers for events the machine emits (`enq.emit(...)`), keyed by emitted
925
+ * event type — `'*'` catches all. Typed from the machine's `emitted`
926
+ * schemas (`setupAgent({ emitted: { ... } })`). Purely observational, like
927
+ * {@link onTransition}: the machine narrates progress on its own vocabulary
928
+ * (not xstate internals) and the host renders it — a progress UI, an SSE
929
+ * stream, a log line.
930
+ */
931
+ on?: { [TType in EmittedFrom<TMachine>["type"] | "*"]?: (emitted: EmittedFrom<TMachine> & (TType extends "*" ? unknown : {
932
+ type: TType;
933
+ })) => void };
934
+ /**
935
+ * Raw xstate inspection passthrough: fires for every inspection event in
936
+ * the whole actor system — root machine, invoked child machines, spawned
937
+ * actors — each carrying its `actorRef` (`event.actorRef.id`/`.src`). This
938
+ * is the system-wide seam {@link onTransition} (root transitions only)
939
+ * cannot give you: filter `event.type === '@xstate.transition'` and read
940
+ * `event.actorRef` to attribute a child machine's states to the child.
941
+ * Purely observational, like the other callbacks. Unlike them it also
942
+ * fires during the final settle (a child's last transition and stop events
943
+ * arrive while the run is tearing down).
944
+ */
945
+ inspect?: (inspectionEvent: InspectionEvent) => void;
946
+ /** 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. */
947
+ maxModelCalls?: number;
948
+ /** Aborts the run; settles `{ status: 'error', cause: 'aborted' }` with `signal.reason` as the error. */
949
+ signal?: AbortSignal;
950
+ }
951
+ /**
952
+ * The outcome of a {@link runAgent} call — always exactly one of three
953
+ * variants, never a throw for a waiting or failed machine (programmer
954
+ * errors like a missing executor still throw, at bind time before any actor
955
+ * runs). `done`: a final state was reached (`output` is the machine's
956
+ * `OutputFrom`). `idle`: the run settled with no in-flight work — resume by
957
+ * calling `runAgent` again with `{ snapshot, event }`. `error`: a run-level
958
+ * failure, discriminated by `cause` (`'aborted'`, `'max-model-calls'`,
959
+ * `'decision-exhausted'`, `'machine'` for any other machine error state, or
960
+ * `'stopped'` for an external stop — see {@link RunAgentErrorCause}). Every
961
+ * variant carries the final `snapshot`, and the underlying
962
+ * actor is stopped on every settle path — there is no live actor to resume;
963
+ * resume is always by snapshot.
964
+ */
965
+ /** 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. */
966
+ interface PendingUserInput {
967
+ id: string;
968
+ input: AgentUserInput | undefined;
969
+ }
970
+ type RunAgentResult<TMachine extends AnyStateMachine> = {
971
+ status: "done";
972
+ output: OutputFrom<TMachine>;
973
+ snapshot: SnapshotFrom<TMachine>;
974
+ } | {
975
+ status: "idle";
976
+ snapshot: SnapshotFrom<TMachine>; /** Present when the machine is waiting on unhandled `agent.userInput` invokes: one entry per pending invoke. */
977
+ pendingUserInputs?: PendingUserInput[];
978
+ /**
979
+ * Present alongside `pendingUserInputs`: the JSON-serializable persisted
980
+ * snapshot (in-flight children included). Persist THIS one and resume
981
+ * with `runAgent(machine, { snapshot: persistedSnapshot, userInput })` —
982
+ * the live `snapshot` above cannot round-trip active children.
983
+ */
984
+ persistedSnapshot?: Snapshot<unknown>;
985
+ } | {
986
+ status: "error";
987
+ cause: RunAgentErrorCause;
988
+ error: unknown;
989
+ snapshot: SnapshotFrom<TMachine>;
990
+ };
991
+ /**
992
+ * Discriminates a {@link RunAgentResult} `error`:
993
+ * - `'aborted'` — the run's `signal` fired.
994
+ * - `'max-model-calls'` — the `maxModelCalls` budget was exceeded.
995
+ * - `'decision-exhausted'` — the machine reached an error state whose error is
996
+ * (or wraps) a {@link DecisionExhaustedError} that no `onError` handled.
997
+ * - `'machine'` — any other machine error state.
998
+ * - `'stopped'` — the actor was stopped externally (`status === 'stopped'`).
999
+ */
1000
+ type RunAgentErrorCause = "aborted" | "max-model-calls" | "decision-exhausted" | "machine" | "stopped";
1001
+ /**
1002
+ * Runs an agent machine to completion or idle: a `createActor` host that
1003
+ * binds `options`' host executors onto the machine's `agent.*`/`TextLogic`/
1004
+ * `DecisionLogic` actor sources, starts (or resumes) the actor, and drives
1005
+ * it until it settles — {@link RunAgentResult} `done | idle | error`. Unlike
1006
+ * the step helpers ({@link initialAgentStep} etc — a pure
1007
+ * transition-at-a-time path for durable hosts), `runAgent` owns a live actor
1008
+ * internally; there is no continuation callback, so **idle always settles**
1009
+ * and the caller resumes explicitly by passing the settled `{ snapshot,
1010
+ * event }` back in. The actor is stopped on every settle path (`done`,
1011
+ * `idle`, and `error` alike) — resume is always by snapshot, never by
1012
+ * holding a reference to a live actor.
1013
+ *
1014
+ * Binding happens **before** the actor starts: every invoke the machine
1015
+ * could reach is walked and checked against the effective actor sources
1016
+ * (`options.actorSources` merged onto the machine), so a missing
1017
+ * `streamText`/`decide` executor or any other unbound actor source throws
1018
+ * immediately — a bind-time error, not a mid-run failure. The one exception
1019
+ * is `agent.userInput`: unhandled, it binds as a pending placeholder that
1020
+ * settles the run idle (with `pendingUserInputs`) instead of erroring.
1021
+ *
1022
+ * @example
1023
+ * ```ts
1024
+ * const executors = createAiSdkExecutors({ models });
1025
+ * let r = await runAgent(machine, { input, executors });
1026
+ * while (r.status === 'idle') {
1027
+ * const event = await promptUser(getAcceptedEvents(r.snapshot));
1028
+ * r = await runAgent(machine, { snapshot: r.snapshot, event, executors });
1029
+ * }
1030
+ * if (r.status !== 'done') throw new Error(`Run did not complete: ${r.status}`);
1031
+ * console.log(r.output);
1032
+ * ```
1033
+ *
1034
+ * The `executors`' `generateText`/`streamText` accept the raw Vercel AI SDK
1035
+ * functions directly (`executors: { generateText, streamText }` with them
1036
+ * imported from `ai`) — their `{ text }`/`{ textStream }` results are unwrapped
1037
+ * natively. `decide` cannot be a raw AI SDK function: the tool-per-event mapping
1038
+ * lives in an adapter — use `createAiSdkExecutors` from '@statelyai/agent/ai-sdk'.
1039
+ */
1040
+ declare function runAgent<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentOptions<TMachine>): Promise<RunAgentResult<TMachine>>;
1041
+ /**
1042
+ * Runs an agent machine to a **final state** and returns its output, for
1043
+ * run-to-done flows where an idle pause is unexpected. Wraps {@link runAgent}:
1044
+ *
1045
+ * - `done` → resolves with `result.output` (the machine's `OutputFrom`).
1046
+ * - `idle` → throws {@link AgentIdleError} carrying the idle snapshot and the
1047
+ * event types that could resume it.
1048
+ * - `error` → throws `result.error` when it is an `Error`; otherwise wraps it
1049
+ * in an `Error` whose `.cause` is the {@link RunAgentErrorCause} and whose
1050
+ * `.error` is the raw thrown value.
1051
+ *
1052
+ * Use {@link runAgent} directly when idle is an expected outcome you handle
1053
+ * (human-in-the-loop, resumable flows); use `runAgentToCompletion` when the
1054
+ * machine is meant to run straight through to a final state.
1055
+ */
1056
+ declare function runAgentToCompletion<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentOptions<TMachine>): Promise<OutputFrom<TMachine>>;
1057
+ /**
1058
+ * The actor handed to an {@link inspectTransitions} handler: an
1059
+ * {@link AnyActorRef} widened with the runtime `id`/`src` used to attribute a
1060
+ * transition to the root machine or a specific invoked child (xstate's static
1061
+ * `ActorRef` type omits them, but they are always present at runtime).
1062
+ */
1063
+ type InspectedActorRef = AnyActorRef & {
1064
+ id: string;
1065
+ src?: string | AnyActorLogic;
1066
+ };
1067
+ /**
1068
+ * Wraps a `(snapshot, actorRef) => void` handler into a function usable as
1069
+ * {@link RunAgentOptions.inspect}: it filters the raw inspection stream to
1070
+ * `@xstate.transition` events and hands the handler the typed
1071
+ * {@link AnyMachineSnapshot} and the {@link InspectedActorRef} that
1072
+ * transitioned. Attribute a child actor via `actorRef.id`/`actorRef.src`. Saves
1073
+ * the manual `event.type === '@xstate.transition'` filtering and the snapshot/
1074
+ * actorRef casts.
1075
+ */
1076
+ declare function inspectTransitions(handler: (snapshot: AnyMachineSnapshot, actorRef: InspectedActorRef) => void): (inspectionEvent: InspectionEvent) => void;
1077
+ //#endregion
1078
+ export { AgentStateNarrowing as A, FromConfigOptions as B, resolveAgentStep as C, AgentRequestConfig as D, AgentMachineConfig as E, AgentWorkflowConfig as F, appendMessages as H, AgentWorkflowInvokeConfig as I, AgentWorkflowRequestConfig as L, setupAgent as M, AgentWorkflowActionConfig as N, AgentSchemaPack as O, AgentWorkflowActorConfig as P, AgentWorkflowStateConfig as R, resolveAgentRequests as S, AgentMachine as T, messagesSchema as U, SchemaCompiler as V, AgentStepRequest as _, InspectedActorRef as a, getAgentRequests as b, RunAgentResult as c, runAgent as d, runAgentToCompletion as f, AgentStep as g, AgentRequest as h, IllegalResumeEventError as i, createAgentSchemas as j, AgentSetupStateSchema as k, SnapshotVersionMismatchError as l, AgentPlanRequest as m, AgentTraceEvent as n, PendingUserInput as o, AgentStateRequest as p, AgentUserInputExecutor as r, RunAgentOptions as s, AgentIdleError as t, inspectTransitions as u, ResolveAgentRequestsOptions as v, transitionAgentStep as w, initialAgentStep as x, executeAgentRequest as y, AgentWorkflowTransitionConfig as z };