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

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,1103 @@
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-qm00QF91.mjs";
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-C7WJpCIc.mjs";
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
+ /**
704
+ * The run's machine identity, stamped onto every settled snapshot's `agentMeta`.
705
+ * `machineId` is the machine's `id`; `version` is
706
+ * {@link RunAgentOptions.machineVersion} or the
707
+ * {@link getMachineStructuralHash} of the machine. Trace events and the
708
+ * `onMessage` info arg carry the same identity flattened, as
709
+ * `machineId`/`machineVersion`.
710
+ */
711
+ interface AgentRunMeta {
712
+ machineId: string;
713
+ version: string;
714
+ }
715
+ /**
716
+ * Second argument passed to {@link RunAgentOptions.onMessage}: the run's
717
+ * identity, carried alongside each live message. Not stamped onto the message
718
+ * itself (messages stay clean model input).
719
+ */
720
+ interface AgentMessageInfo {
721
+ runId: string;
722
+ machineId: string;
723
+ /** {@link RunAgentOptions.machineVersion} or the machine's structural hash. */
724
+ machineVersion: string;
725
+ }
726
+ type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
727
+ runId: string;
728
+ seq: number;
729
+ timestamp: string;
730
+ machineId: string; /** {@link RunAgentOptions.machineVersion} or the machine's structural hash. */
731
+ machineVersion: string;
732
+ } & ({
733
+ type: "run.start";
734
+ input?: InputFrom<TMachine>;
735
+ snapshot?: Snapshot<unknown>;
736
+ event?: EventFromLogic<TMachine>;
737
+ } | {
738
+ type: "request.start";
739
+ request: AgentStepRequest;
740
+ } | {
741
+ type: "request.end";
742
+ request: AgentStepRequest;
743
+ output: unknown;
744
+ raw: unknown;
745
+ /** The model's reasoning, lifted off the raw executor result when the
746
+ * request opted into the structured-output envelope's `reasoning` field.
747
+ * Present only when the executor surfaced a string `reasoning`. */
748
+ reasoning?: string;
749
+ } | {
750
+ type: "request.error";
751
+ request: AgentStepRequest;
752
+ error: unknown;
753
+ } | {
754
+ type: "stream.chunk";
755
+ request: AgentRequest;
756
+ chunk: string;
757
+ } | {
758
+ type: "machine.transition";
759
+ snapshot: SnapshotFrom<TMachine>;
760
+ event: EventFromLogic<TMachine>;
761
+ } | {
762
+ type: "emit";
763
+ event: EmittedFrom<TMachine>;
764
+ } | ({
765
+ type: "run.end";
766
+ status: "done";
767
+ output: OutputFrom<TMachine>;
768
+ snapshot: SnapshotFrom<TMachine>;
769
+ } | {
770
+ type: "run.end";
771
+ status: "idle";
772
+ snapshot: SnapshotFrom<TMachine>;
773
+ pendingUserInputs?: PendingUserInput[];
774
+ persistedSnapshot?: Snapshot<unknown>;
775
+ } | {
776
+ type: "run.end";
777
+ status: "error";
778
+ cause: RunAgentErrorCause;
779
+ error: unknown;
780
+ snapshot: SnapshotFrom<TMachine>;
781
+ }));
782
+ /**
783
+ * Options for {@link runAgent}.
784
+ *
785
+ * Host executors are passed as a single {@link AgentRequestExecutors}-shaped
786
+ * set under `executors` (the same shape the step path takes). Each executor
787
+ * kind is required only if the machine actually reaches a request of that kind
788
+ * — checked at bind time, before any actor runs. The whole `executors` field is
789
+ * optional: a machine whose agent sources all carry their own executor
790
+ * (`.withExecutor(...)`) needs none.
791
+ */
792
+ interface RunAgentOptions<TMachine extends AnyStateMachine> {
793
+ /**
794
+ * The host executor set backing the machine's agent actors — build it with
795
+ * `createAiSdkExecutors({ models })` from '@statelyai/agent/ai-sdk', or supply
796
+ * `{ generateText?, streamText?, decide? }` by hand. Every slot is optional
797
+ * here (unlike the step path's {@link AgentRequestExecutors}): each kind is
798
+ * bind-time-checked only when the machine actually reaches a request of that
799
+ * kind, so e.g. a stream-only machine may pass `{ streamText }` alone.
800
+ */
801
+ executors?: Partial<AgentRequestExecutors>;
802
+ /** Machine input, passed straight to `createActor(machine, { input })`. Omit when resuming via `snapshot`. */
803
+ input?: InputFrom<TMachine>;
804
+ /** 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. */
805
+ snapshot?: Snapshot<unknown>;
806
+ /** An event to send immediately after starting/resuming the actor (e.g. the human's answer to an idle-state prompt). */
807
+ event?: EventFromLogic<TMachine>;
808
+ /**
809
+ * How to handle a resume `event` the restored state cannot accept (a
810
+ * type-level check via {@link getAcceptedEvents}, only applied when resuming
811
+ * from a `snapshot`). `'throw'` (default) throws {@link IllegalResumeEventError}
812
+ * before delivering the event; `'ignore'` restores the older silent behavior
813
+ * (the event is sent and the machine drops it). A type-legal event a guard
814
+ * rejects is never an illegal resume event.
815
+ */
816
+ onIllegalResumeEvent?: "throw" | "ignore";
817
+ /**
818
+ * The version stamped onto every settled snapshot's `agentMeta` and compared
819
+ * against an incoming snapshot's stamp on resume. Defaults to
820
+ * {@link getMachineStructuralHash} of the machine (a structural fingerprint).
821
+ * Set an explicit value (e.g. a semver or build id) to control migration
822
+ * boundaries yourself.
823
+ */
824
+ machineVersion?: string;
825
+ /**
826
+ * How to handle a resume `snapshot` whose stamped `agentMeta.version` differs
827
+ * from the current machine's version. `'throw'` (default) throws
828
+ * {@link SnapshotVersionMismatchError} with `from`/`to`; `'warn'`
829
+ * `console.warn`s once and proceeds; `'ignore'` proceeds silently. Ignored
830
+ * when {@link migrateSnapshot} is provided (that runs instead), and never
831
+ * triggers for an unstamped snapshot (no `agentMeta`).
832
+ */
833
+ onVersionMismatch?: "throw" | "warn" | "ignore";
834
+ /**
835
+ * Called instead of {@link onVersionMismatch} when a resume snapshot's
836
+ * version mismatches the current machine's: receives the incoming snapshot
837
+ * and `{ from, to }`, and its return value is used as the snapshot to resume
838
+ * from. A throw propagates.
839
+ */
840
+ migrateSnapshot?: (snapshot: Snapshot<unknown>, info: {
841
+ from: string;
842
+ to: string;
843
+ }) => Snapshot<unknown>;
844
+ /** Actor source implementations, merged onto the machine before binding — sugar for `machine.provide({ actorSources })` ahead of the run. */
845
+ actorSources?: Record<string, AnyActorLogic>;
846
+ /**
847
+ * Optional human-input handler for `agent.userInput` invokes (CLI prompt,
848
+ * web form, Slack, …). With a handler, input is gathered inline without
849
+ * settling. Without one, an `agent.userInput` invoke becomes a *pending
850
+ * placeholder*: it waits indefinitely, does not block idle detection, and
851
+ * the run settles `{ status: 'idle', pendingUserInputs, persistedSnapshot }`
852
+ * once no other work is in flight — resume by passing `persistedSnapshot`
853
+ * back as `snapshot` together with a `userInput` handler that answers it.
854
+ */
855
+ userInput?: AgentUserInputExecutor;
856
+ /**
857
+ * Host override for detecting a snapshot that is an INTENTIONAL wait for an
858
+ * external event — the deterministic replacement for the timing heuristic
859
+ * runAgent uses to settle idle. Resolution order: this option (host override)
860
+ * → the machine-carried predicate declared via `setupAgent({ isSuspended })`
861
+ * → the timing heuristic (when neither is present). When the resolved
862
+ * predicate returns true and nothing is in flight (no live requests/plans/
863
+ * invokes; the `agent.userInput` placeholder exemption still applies), runAgent
864
+ * settles idle immediately, without the `setTimeout` heuristic. It does NOT
865
+ * force-settle while agent work is in flight, and whole-machine idle semantics
866
+ * are unchanged; a machine with no predicate falls back to the heuristic
867
+ * exactly as before. Declare your own signal, e.g.
868
+ * `(s) => s.hasTag('awaiting-review')`.
869
+ *
870
+ * Provisional name — may change before 2.0.
871
+ */
872
+ isSuspended?: (snapshot: AnyMachineSnapshot) => boolean;
873
+ /**
874
+ * The override to runAgent's DEFAULT contract. By default agent work is
875
+ * whatever the machine *invokes* (`agent.generateText`, TextLogic,
876
+ * `agent.decide`, …). With `getRequests`, whenever the machine would
877
+ * otherwise settle idle, this hook reads the snapshot and returns the model
878
+ * request(s) to run instead — prompts from state `description`s, `meta`,
879
+ * tags, a lookup table keyed by state value, wherever you keep them. Return
880
+ * nothing to settle idle (human-wait states).
881
+ *
882
+ * There is no blessed source for the prompts — this is a recipe seam.
883
+ * Prompts-in-descriptions, copy-paste and adapt:
884
+ *
885
+ * ```ts
886
+ * getRequests: (snapshot) =>
887
+ * snapshot._nodes
888
+ * .filter((node) => node.description && !node.tags.includes('waiting'))
889
+ * .map((node) => ({
890
+ * model: 'writer',
891
+ * prompt: node.description!,
892
+ * kind: node.tags.includes('decision') ? 'decision' : 'text',
893
+ * // single-outcome states advance deterministically; else `decide`
894
+ * onDone: node.ownEvents.length === 1 ? { type: node.ownEvents[0] } : undefined,
895
+ * allowedEvents: node.ownEvents,
896
+ * })),
897
+ * ```
898
+ *
899
+ * Each request runs per {@link AgentStateRequest.kind}, appends to the
900
+ * run's message log (see {@link RunAgentOptions.messages}), and advances
901
+ * the machine per {@link AgentStateRequest.onDone} — explicitly named/
902
+ * computed event, or a `decide` call when omitted — always gated by
903
+ * `snapshot.can`. Multiple requests run concurrently (parallel regions —
904
+ * scope each with `allowedEvents`, e.g. the node's `ownEvents`). A pass
905
+ * that sends no event settles idle. Every model call counts against
906
+ * `maxModelCalls`.
907
+ */
908
+ getRequests?: (snapshot: SnapshotFrom<TMachine>, agentContext: {
909
+ messages: readonly AgentMessage[];
910
+ }) => AgentStateRequest | readonly AgentStateRequest[] | undefined;
911
+ /**
912
+ * Adds to the run's aggregated message log (the working memory
913
+ * `getRequests` requests read and append to). The log starts as the resume
914
+ * `snapshot`'s stamped `messages` (else `[]`); an ARRAY here is APPENDED to
915
+ * that history — the safe default for folding in a user reply on resume,
916
+ * never silently erasing prior conversation. Pass a FUNCTION
917
+ * `(prior) => AgentMessage[]` to take full control (replace, filter,
918
+ * compact). The final log is stamped onto every settled result's
919
+ * `snapshot.messages` (like `agentMeta`), so persist/resume round-trips it
920
+ * with no extra wiring — read it with `getAgentMessages(snapshot)`.
921
+ */
922
+ messages?: AgentMessage[] | ((prior: AgentMessage[]) => AgentMessage[]);
923
+ /** 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. */
924
+ onChunk?: (chunk: string, info: {
925
+ request: AgentRequest;
926
+ }) => void;
927
+ /** 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. */
928
+ onResult?: (request: AgentStepRequest, result: {
929
+ output: unknown;
930
+ raw: unknown;
931
+ }) => void;
932
+ /** Fires a single ordered stream of run/request/chunk/transition/emit/end events. Intended for eval traces, JSONL logs, and adapter-owned telemetry/exporters. */
933
+ onTrace?: (event: AgentTraceEvent<TMachine>) => void;
934
+ /**
935
+ * Fires on every machine transition (snapshot + causing event). Pure
936
+ * observation — progress UIs, logging, tracing. Cannot send events.
937
+ */
938
+ onTransition?: (snapshot: SnapshotFrom<TMachine>, event: EventFromLogic<TMachine>) => void;
939
+ /**
940
+ * Fires for each message appended to the run's aggregated log (see
941
+ * {@link RunAgentOptions.messages}) the moment a `getRequests` request
942
+ * appends it — the live view of the log a caller otherwise only reads off
943
+ * the settled snapshot via `getAgentMessages`. Purely observational, like
944
+ * {@link onTransition}. Never fires for the seeded history, and never fires
945
+ * on a default invoke-driven run (nothing appends there).
946
+ */
947
+ onMessage?: (message: AgentMessage, info: AgentMessageInfo) => void;
948
+ /**
949
+ * Handlers for events the machine emits (`enq.emit(...)`), keyed by emitted
950
+ * event type — `'*'` catches all. Typed from the machine's `emitted`
951
+ * schemas (`setupAgent({ emitted: { ... } })`). Purely observational, like
952
+ * {@link onTransition}: the machine narrates progress on its own vocabulary
953
+ * (not xstate internals) and the host renders it — a progress UI, an SSE
954
+ * stream, a log line.
955
+ */
956
+ on?: { [TType in EmittedFrom<TMachine>["type"] | "*"]?: (emitted: EmittedFrom<TMachine> & (TType extends "*" ? unknown : {
957
+ type: TType;
958
+ })) => void };
959
+ /**
960
+ * Raw xstate inspection passthrough: fires for every inspection event in
961
+ * the whole actor system — root machine, invoked child machines, spawned
962
+ * actors — each carrying its `actorRef` (`event.actorRef.id`/`.src`). This
963
+ * is the system-wide seam {@link onTransition} (root transitions only)
964
+ * cannot give you: filter `event.type === '@xstate.transition'` and read
965
+ * `event.actorRef` to attribute a child machine's states to the child.
966
+ * Purely observational, like the other callbacks. Unlike them it also
967
+ * fires during the final settle (a child's last transition and stop events
968
+ * arrive while the run is tearing down).
969
+ */
970
+ inspect?: (inspectionEvent: InspectionEvent) => void;
971
+ /** 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. */
972
+ maxModelCalls?: number;
973
+ /** Aborts the run; settles `{ status: 'error', cause: 'aborted' }` with `signal.reason` as the error. */
974
+ signal?: AbortSignal;
975
+ }
976
+ /**
977
+ * The outcome of a {@link runAgent} call — always exactly one of three
978
+ * variants, never a throw for a waiting or failed machine (programmer
979
+ * errors like a missing executor still throw, at bind time before any actor
980
+ * runs). `done`: a final state was reached (`output` is the machine's
981
+ * `OutputFrom`). `idle`: the run settled with no in-flight work — resume by
982
+ * calling `runAgent` again with `{ snapshot, event }`. `error`: a run-level
983
+ * failure, discriminated by `cause` (`'aborted'`, `'max-model-calls'`,
984
+ * `'decision-exhausted'`, `'machine'` for any other machine error state, or
985
+ * `'stopped'` for an external stop — see {@link RunAgentErrorCause}). Every
986
+ * variant carries the final `snapshot`, and the underlying
987
+ * actor is stopped on every settle path — there is no live actor to resume;
988
+ * resume is always by snapshot.
989
+ */
990
+ /** 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. */
991
+ interface PendingUserInput {
992
+ id: string;
993
+ input: AgentUserInput | undefined;
994
+ }
995
+ type RunAgentResult<TMachine extends AnyStateMachine> = {
996
+ status: "done";
997
+ output: OutputFrom<TMachine>;
998
+ snapshot: SnapshotFrom<TMachine>;
999
+ } | {
1000
+ status: "idle";
1001
+ snapshot: SnapshotFrom<TMachine>; /** Present when the machine is waiting on unhandled `agent.userInput` invokes: one entry per pending invoke. */
1002
+ pendingUserInputs?: PendingUserInput[];
1003
+ /**
1004
+ * Present alongside `pendingUserInputs`: the JSON-serializable persisted
1005
+ * snapshot (in-flight children included). Persist THIS one and resume
1006
+ * with `runAgent(machine, { snapshot: persistedSnapshot, userInput })` —
1007
+ * the live `snapshot` above cannot round-trip active children.
1008
+ */
1009
+ persistedSnapshot?: Snapshot<unknown>;
1010
+ } | {
1011
+ status: "error";
1012
+ cause: RunAgentErrorCause;
1013
+ error: unknown;
1014
+ snapshot: SnapshotFrom<TMachine>;
1015
+ };
1016
+ /**
1017
+ * Discriminates a {@link RunAgentResult} `error`:
1018
+ * - `'aborted'` — the run's `signal` fired.
1019
+ * - `'max-model-calls'` — the `maxModelCalls` budget was exceeded.
1020
+ * - `'decision-exhausted'` — the machine reached an error state whose error is
1021
+ * (or wraps) a {@link DecisionExhaustedError} that no `onError` handled.
1022
+ * - `'machine'` — any other machine error state.
1023
+ * - `'stopped'` — the actor was stopped externally (`status === 'stopped'`).
1024
+ */
1025
+ type RunAgentErrorCause = "aborted" | "max-model-calls" | "decision-exhausted" | "machine" | "stopped";
1026
+ /**
1027
+ * Runs an agent machine to completion or idle: a `createActor` host that
1028
+ * binds `options`' host executors onto the machine's `agent.*`/`TextLogic`/
1029
+ * `DecisionLogic` actor sources, starts (or resumes) the actor, and drives
1030
+ * it until it settles — {@link RunAgentResult} `done | idle | error`. Unlike
1031
+ * the step helpers ({@link initialAgentStep} etc — a pure
1032
+ * transition-at-a-time path for durable hosts), `runAgent` owns a live actor
1033
+ * internally; there is no continuation callback, so **idle always settles**
1034
+ * and the caller resumes explicitly by passing the settled `{ snapshot,
1035
+ * event }` back in. The actor is stopped on every settle path (`done`,
1036
+ * `idle`, and `error` alike) — resume is always by snapshot, never by
1037
+ * holding a reference to a live actor.
1038
+ *
1039
+ * Binding happens **before** the actor starts: every invoke the machine
1040
+ * could reach is walked and checked against the effective actor sources
1041
+ * (`options.actorSources` merged onto the machine), so a missing
1042
+ * `streamText`/`decide` executor or any other unbound actor source throws
1043
+ * immediately — a bind-time error, not a mid-run failure. The one exception
1044
+ * is `agent.userInput`: unhandled, it binds as a pending placeholder that
1045
+ * settles the run idle (with `pendingUserInputs`) instead of erroring.
1046
+ *
1047
+ * @example
1048
+ * ```ts
1049
+ * const executors = createAiSdkExecutors({ models });
1050
+ * let r = await runAgent(machine, { input, executors });
1051
+ * while (r.status === 'idle') {
1052
+ * const event = await promptUser(getAcceptedEvents(r.snapshot));
1053
+ * r = await runAgent(machine, { snapshot: r.snapshot, event, executors });
1054
+ * }
1055
+ * if (r.status !== 'done') throw new Error(`Run did not complete: ${r.status}`);
1056
+ * console.log(r.output);
1057
+ * ```
1058
+ *
1059
+ * The `executors`' `generateText`/`streamText` accept the raw Vercel AI SDK
1060
+ * functions directly (`executors: { generateText, streamText }` with them
1061
+ * imported from `ai`) — their `{ text }`/`{ textStream }` results are unwrapped
1062
+ * natively. `decide` cannot be a raw AI SDK function: the tool-per-event mapping
1063
+ * lives in an adapter — use `createAiSdkExecutors` from '@statelyai/agent/ai-sdk'.
1064
+ */
1065
+ declare function runAgent<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentOptions<TMachine>): Promise<RunAgentResult<TMachine>>;
1066
+ /**
1067
+ * Runs an agent machine to a **final state** and returns its output, for
1068
+ * run-to-done flows where an idle pause is unexpected. Wraps {@link runAgent}:
1069
+ *
1070
+ * - `done` → resolves with `result.output` (the machine's `OutputFrom`).
1071
+ * - `idle` → throws {@link AgentIdleError} carrying the idle snapshot and the
1072
+ * event types that could resume it.
1073
+ * - `error` → throws `result.error` when it is an `Error`; otherwise wraps it
1074
+ * in an `Error` whose `.cause` is the {@link RunAgentErrorCause} and whose
1075
+ * `.error` is the raw thrown value.
1076
+ *
1077
+ * Use {@link runAgent} directly when idle is an expected outcome you handle
1078
+ * (human-in-the-loop, resumable flows); use `runAgentToCompletion` when the
1079
+ * machine is meant to run straight through to a final state.
1080
+ */
1081
+ declare function runAgentToCompletion<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentOptions<TMachine>): Promise<OutputFrom<TMachine>>;
1082
+ /**
1083
+ * The actor handed to an {@link inspectTransitions} handler: an
1084
+ * {@link AnyActorRef} widened with the runtime `id`/`src` used to attribute a
1085
+ * transition to the root machine or a specific invoked child (xstate's static
1086
+ * `ActorRef` type omits them, but they are always present at runtime).
1087
+ */
1088
+ type InspectedActorRef = AnyActorRef & {
1089
+ id: string;
1090
+ src?: string | AnyActorLogic;
1091
+ };
1092
+ /**
1093
+ * Wraps a `(snapshot, actorRef) => void` handler into a function usable as
1094
+ * {@link RunAgentOptions.inspect}: it filters the raw inspection stream to
1095
+ * `@xstate.transition` events and hands the handler the typed
1096
+ * {@link AnyMachineSnapshot} and the {@link InspectedActorRef} that
1097
+ * transitioned. Attribute a child actor via `actorRef.id`/`actorRef.src`. Saves
1098
+ * the manual `event.type === '@xstate.transition'` filtering and the snapshot/
1099
+ * actorRef casts.
1100
+ */
1101
+ declare function inspectTransitions(handler: (snapshot: AnyMachineSnapshot, actorRef: InspectedActorRef) => void): (inspectionEvent: InspectionEvent) => void;
1102
+ //#endregion
1103
+ export { AgentSchemaPack as A, AgentWorkflowStateConfig as B, initialAgentStep as C, AgentMachine as D, transitionAgentStep as E, AgentWorkflowActionConfig as F, messagesSchema as G, FromConfigOptions as H, AgentWorkflowActorConfig as I, AgentWorkflowConfig as L, AgentStateNarrowing as M, createAgentSchemas as N, AgentMachineConfig as O, setupAgent as P, AgentWorkflowInvokeConfig as R, getAgentRequests as S, resolveAgentStep as T, SchemaCompiler as U, AgentWorkflowTransitionConfig as V, appendMessages as W, AgentRequest as _, AgentUserInputExecutor as a, ResolveAgentRequestsOptions as b, PendingUserInput as c, SnapshotVersionMismatchError as d, inspectTransitions as f, AgentPlanRequest as g, AgentStateRequest as h, AgentTraceEvent as i, AgentSetupStateSchema as j, AgentRequestConfig as k, RunAgentOptions as l, runAgentToCompletion as m, AgentMessageInfo as n, IllegalResumeEventError as o, runAgent as p, AgentRunMeta as r, InspectedActorRef as s, AgentIdleError as t, RunAgentResult as u, AgentStep as v, resolveAgentRequests as w, executeAgentRequest as x, AgentStepRequest as y, AgentWorkflowRequestConfig as z };