@statelyai/agent 2.0.0-alpha.11 → 2.0.0-alpha.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/ai-sdk.cjs +4 -5
  2. package/dist/ai-sdk.d.cts +7 -4
  3. package/dist/ai-sdk.d.mts +7 -4
  4. package/dist/ai-sdk.mjs +1 -2
  5. package/dist/{events-JiVPYrct.mjs → decision-BezSD_YC.mjs} +327 -20
  6. package/dist/{events-CRQj3VtP.cjs → decision-dWGhBh0P.cjs} +401 -28
  7. package/dist/errors-BQRk9eiZ.d.cts +19 -0
  8. package/dist/errors-C9rxnWbX.d.mts +19 -0
  9. package/dist/errors-CeSXQx0v.mjs +23 -0
  10. package/dist/errors-DUBBzRLP.cjs +28 -0
  11. package/dist/event-log-store-CNT_7F0V.cjs +452 -0
  12. package/dist/event-log-store-CriMgX1D.d.mts +144 -0
  13. package/dist/event-log-store-D7pWtIhb.mjs +411 -0
  14. package/dist/event-log-store-Ruq18mGp.d.cts +144 -0
  15. package/dist/index.cjs +1050 -705
  16. package/dist/index.d.cts +538 -565
  17. package/dist/index.d.mts +538 -565
  18. package/dist/index.mjs +950 -644
  19. package/dist/machines.cjs +752 -0
  20. package/dist/machines.d.cts +372 -0
  21. package/dist/machines.d.mts +372 -0
  22. package/dist/machines.mjs +741 -0
  23. package/dist/otel.cjs +268 -0
  24. package/dist/otel.d.cts +67 -0
  25. package/dist/otel.d.mts +67 -0
  26. package/dist/otel.mjs +267 -0
  27. package/dist/run-agent-C3mFDGTf.d.mts +1111 -0
  28. package/dist/run-agent-DnvtcnTZ.d.cts +1111 -0
  29. package/dist/setup-agent-DAZZSjDS.mjs +1711 -0
  30. package/dist/setup-agent-DP95MFrI.cjs +1836 -0
  31. package/dist/sqlite.cjs +135 -0
  32. package/dist/sqlite.d.cts +57 -0
  33. package/dist/sqlite.d.mts +57 -0
  34. package/dist/sqlite.mjs +133 -0
  35. package/dist/{text-logic-CaKqgX4Y.d.mts → text-logic-BDxwQNsD.d.cts} +155 -72
  36. package/dist/{text-logic-Ckhr2kKC.d.cts → text-logic-TkKPw8Aq.d.mts} +155 -72
  37. package/dist/{types-qm00QF91.d.mts → types-QbEfCVny.d.cts} +1 -1
  38. package/dist/{types-C9QiMjre.d.cts → types-_FXoFBGO.d.mts} +1 -1
  39. package/package.json +47 -39
  40. package/readme.md +49 -12
  41. package/schemas/agent-workflow.json +40 -21
  42. package/skills/generate-machine/SKILL.md +267 -0
  43. package/dist/adapter.cjs +0 -15
  44. package/dist/adapter.d.cts +0 -4
  45. package/dist/adapter.d.mts +0 -4
  46. package/dist/adapter.mjs +0 -2
  47. package/dist/decision-C3k4ve51.mjs +0 -227
  48. package/dist/decision-D8wJrM8W.cjs +0 -286
  49. package/dist/openai-compat.cjs +0 -309
  50. package/dist/openai-compat.d.cts +0 -59
  51. package/dist/openai-compat.d.mts +0 -59
  52. package/dist/openai-compat.mjs +0 -308
  53. package/dist/steps-BALp1eZo.d.mts +0 -198
  54. package/dist/steps-CVe54GPP.cjs +0 -420
  55. package/dist/steps-CkyyyuHd.mjs +0 -379
  56. package/dist/steps-MjnQI4aB.d.cts +0 -198
  57. package/dist/steps.cjs +0 -12
  58. package/dist/steps.d.cts +0 -3
  59. package/dist/steps.d.mts +0 -3
  60. package/dist/steps.mjs +0 -3
  61. package/dist/utils-BYqT_Dyv.d.cts +0 -108
  62. package/dist/utils-Do5wIJrh.d.mts +0 -108
  63. package/dist/zod.cjs +0 -31
  64. package/dist/zod.d.cts +0 -30
  65. package/dist/zod.d.mts +0 -30
  66. package/dist/zod.mjs +0 -30
package/dist/index.d.mts CHANGED
@@ -1,8 +1,9 @@
1
- import { A as UserMessage, C as StandardSchemaV1, D as ToolMessage, E as ToolCallPart, O as ToolResultOutput, S as ProviderOptions, T as TextPart, _ as EventUnion, a as AgentTool, b as InferOutput, c as AgentToolExecute, d as AllowedEventPattern, f as AllowedEvents, g as EventPayload, h as DataContent, i as AgentSnapshotStore, k as ToolResultPart, l as AgentToolSchema, m as ChosenEvent, n as AgentEventSchemaInputMap, o as AgentToolChoice, p as AssistantMessage, r as AgentMessage, s as AgentToolDescriptor, t as AgentEventSchemaInput, u as AgentTools, v as FilePart, w as SystemMessage, x as NormalizedEventSchemas, y as ImagePart } from "./types-qm00QF91.mjs";
2
- import { A as AgentDecisionInput, C as createTextLogic, F as DecisionExhaustedError, G as AgentRequestOptions, I as DecisionLogic, K as AgentRequestSource, M as AgentPlanInput, N as AgentPlanOutput, P as DecisionAttempt, U as AgentEventDescriptor, W as AgentEventToolNameResolver, Y as parseAgentEvent, _ as TextLogicExecuteArgs, a as AgentRequestExecutorInfo, b as TextLogicOutput, c as AgentRequestMode, d as AiSdkShapedStreamResult, f as AiSdkShapedTextResult, g as TextLogicConfig, h as TextLogic, i as AgentRequestExecutor, j as AgentDecisionRequest, k as AgentDecisionExecutor, l as AgentTextRequest, n as AgentModelRef, o as AgentRequestExecutorResult, p as BuiltinAgentActors, q as getAcceptedEvents, s as AgentRequestExecutors, t as AgentModelMap, u as AgentUserInput, v as TextLogicExecutor, y as TextLogicInput, z as PlanLogic } from "./text-logic-CaKqgX4Y.mjs";
3
- import { c as persistSnapshot, d as userMessage, l as systemMessage, n as getAgentMessages, o as getStateMeta, t as assistantMessage, u as toolMessage } from "./utils-Do5wIJrh.mjs";
4
- import { i as AgentStepRequest, n as AgentRequest } from "./steps-BALp1eZo.mjs";
5
- import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, InputFrom, InspectionEvent, MachineContext, MetaObject, NonReducibleUnknown, OutputFrom, SetupReturnFromConfig, SetupStateSchema, Snapshot, SnapshotFrom } from "xstate";
1
+ import { C as UserMessage, S as ToolResultPart, _ as StandardSchemaV1, a as AgentToolChoice, b as ToolCallPart, c as AgentTools, d as ChosenEvent, f as EventUnion, g as NormalizedEventSchemas, h as InferOutput, i as AgentTool, l as AllowedEvents, m as ImagePart, n as AgentMessage, o as AgentToolDescriptor, p as FilePart, r as AgentSnapshotStore, s as AgentToolExecute, t as AgentEventSchemaInputMap, u as AssistantMessage, v as SystemMessage, x as ToolMessage, y as TextPart } from "./types-_FXoFBGO.mjs";
2
+ import { t as AgentError } from "./errors-C9rxnWbX.mjs";
3
+ import { A as AgentDecisionExhaustedError, B as renderDecisionAttempts, C as buildEnvelopeSchema, D as parseOutput, E as parseModelRef, F as DecisionAttempt, G as AgentRequestSource, H as AgentEventDescriptor, I as DecisionLogicConfig, K as getAcceptedEvents, L as PLAN_DONE_EVENT_TYPE, M as AgentDecisionRequest, N as AgentPlanInput, O as parseStructuredEnvelope, P as AgentPlanOutput, R as PlanLogic, S as bindRequestExecutor, T as getAgentOutputMode, U as AgentEventToolNameResolver, V as resolveDecision, W as AgentRequestOptions, _ as StructuredOutputEnvelope, a as AgentOutputMode, b as TextLogicExecuteArgs, c as AgentRequestExecutorResult, d as AgentTextRequest, f as AgentUsage, g as BuiltinAgentActors, h as AiSdkShapedTextResult, i as AgentModelRef, j as AgentDecisionInput, k as AgentDecisionExecutor, l as AgentRequestExecutors, m as AiSdkShapedStreamResult, n as AgentExecutorTextRequest, o as AgentRequestExecutor, p as AgentUserInput, q as parseAgentEvent, r as AgentModelMap, s as AgentRequestExecutorInfo, t as AgentCallUsage, u as AgentRequestMode, v as TextLogic, w as createTextLogic, x as TextLogicExecutor, y as TextLogicConfig, z as ResolveDecisionOptions } from "./text-logic-TkKPw8Aq.mjs";
4
+ import { A as AgentReplayDivergenceError, B as getCallUsage, C as AgentStateRequest, D as AgentEffectDiff, E as AgentEffect, F as ReplayOptions, G as AgentRequest, H as replay, I as ReplayResult, K as AgentStepRequest, L as createReplayEntry, M as AgentUsageEvent, N as CreateReplayEntryOptions, O as AgentEventLogDiff, P as GetAgentEffectsOptions, R as diffEventLogs, S as traceTransitions, T as AGENT_USAGE_EVENT_TYPE, U as verifyReplay, V as initEntry, W as AgentPlanRequest, _ as createAgentActor, a as AgentMessageInfo, b as runAgent, c as AgentTraceEvent, d as InspectedActorRef, f as JsonSerializableTraceEvent, g as RunAgentResult, h as RunAgentOptions, i as AgentIllegalResumeEventError, j as AgentReplayMachineMismatchError, k as AgentLogPatchOperation, l as AgentUserInputExecutor, m as RunAgentErrorCause, n as AgentActorSession, o as AgentRunMeta, p as PendingUserInput, q as executeAgentRequest, r as AgentIdleError, s as AgentSnapshotVersionMismatchError, t as AGENT_TRACE_SCHEMA_VERSION, u as GenerateResult, v as generateResult, w as AGENT_INIT_EVENT_TYPE, x as serializeTraceEvent, y as inspectTransitions, z as getAgentEffects } from "./run-agent-C3mFDGTf.mjs";
5
+ import { a as AgentLogVerification, c as assertAgentLogEntry, d as createInMemoryEventLogStore, i as AgentLogEntry, l as assertEventLogStoreConformance, n as AgentEventLogConflictError, o as JsonValue, r as AgentEventLogStore, s as NonSerializableAgentEventError, t as AGENT_EVENT_SCHEMA_VERSION, u as assertJsonSerializable } from "./event-log-store-CriMgX1D.mjs";
6
+ import { AnyActorLogic, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, EventFromLogic, EventObject, InputFrom, MachineContext, MetaObject, NonReducibleUnknown, SetupReturnFromConfig, SetupStateSchema, SnapshotFrom, StateValue } from "xstate";
6
7
 
7
8
  //#region src/messages.d.ts
8
9
  /**
@@ -119,7 +120,7 @@ interface AgentWorkflowRequestConfig {
119
120
  stopSequences?: unknown;
120
121
  metadata?: unknown;
121
122
  }
122
- /** An `actors` entry in {@link AgentWorkflowConfig} — declares a placeholder actor source (by key) with no host execution wired from JSON; provide it via `machine.provide({ actorSources })` after `setupAgent.fromConfig(...)`. */
123
+ /** 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({ actors })` after `setupAgent.fromConfig(...)`. */
123
124
  interface AgentWorkflowActorConfig {
124
125
  input?: JsonSchemaObject;
125
126
  output?: JsonSchemaObject;
@@ -158,7 +159,15 @@ interface AgentWorkflowInvokeConfig {
158
159
  onError?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
159
160
  meta?: Record<string, unknown>;
160
161
  }
161
- /** A transition target in {@link AgentWorkflowConfig} (`on`/`always`/`onDone`/`after`/invoke `onDone`/`onError`) — the JSON equivalent of an XState transition config. `guard`, when a string, is a template expression evaluated as truthy/falsy. */
162
+ /**
163
+ * A transition target in {@link AgentWorkflowConfig}
164
+ * (`on`/`always`/`onDone`/`after`/invoke `onDone`/`onError`) — the JSON
165
+ * equivalent of an XState transition config. A string `guard` containing
166
+ * `{{ ... }}` is a template expression evaluated as truthy/falsy; any other
167
+ * string is a named guard reference resolved against the `guards` passed to
168
+ * `setupAgent.fromConfig(config, { guards })` (unresolvable references throw
169
+ * at build time).
170
+ */
162
171
  interface AgentWorkflowTransitionConfig {
163
172
  target?: string | string[];
164
173
  guard?: unknown;
@@ -168,7 +177,7 @@ interface AgentWorkflowTransitionConfig {
168
177
  reenter?: boolean;
169
178
  meta?: Record<string, unknown>;
170
179
  }
171
- /** An `entry`/`exit`/transition `actions` entry in {@link AgentWorkflowConfig} — either a named action `type` (with template-expression `params`) or a bare context `assign`. */
180
+ /** An `entry`/`exit`/transition `actions` entry in {@link AgentWorkflowConfig} — a bare context `assign`, an `emit`, or a named action `type` (with template-expression `params`) resolved against the `actions` passed to `setupAgent.fromConfig(config, { actions })`. */
172
181
  interface AgentWorkflowActionConfig {
173
182
  type?: string;
174
183
  params?: unknown;
@@ -176,6 +185,23 @@ interface AgentWorkflowActionConfig {
176
185
  emit?: unknown;
177
186
  [key: string]: unknown;
178
187
  }
188
+ /**
189
+ * What `setupAgent.fromConfig(...)` returns: the built machine plus the
190
+ * schema pack compiled from the config's `schemas` (with `compileSchema`).
191
+ * The pack is what hosts need for the runtime work the machine's types can't
192
+ * do for a JSON-authored agent — e.g. validating an inbound raw event:
193
+ *
194
+ * @example
195
+ * ```ts
196
+ * const { machine, schemas } = setupAgent.fromConfig(config, { compileSchema });
197
+ * const event = parseAgentEvent(snapshot, raw, { events: schemas.events });
198
+ * ```
199
+ */
200
+ interface FromConfigResult {
201
+ machine: AnyStateMachine;
202
+ /** Compiled `context`/`events`/`input`/`output`/`meta`/`emitted` schemas — the same pack `runAgent` executes this machine with. */
203
+ schemas: AgentSchemaPack<StandardSchemaV1<Record<string, unknown>>, Record<string, StandardSchemaV1>, StandardSchemaV1, StandardSchemaV1, StandardSchemaV1<MetaObject>>;
204
+ }
179
205
  /** Options for `setupAgent.fromConfig(...)`. */
180
206
  interface FromConfigOptions {
181
207
  /**
@@ -184,6 +210,24 @@ interface FromConfigOptions {
184
210
  * pipeline, ...). Core intentionally ships no JSON Schema engine.
185
211
  */
186
212
  compileSchema: SchemaCompiler;
213
+ /**
214
+ * Host guard implementations for named guard references in the config
215
+ * (`guard: "isFromHuman"`). Each is called with `{ context, event }` and
216
+ * returns a boolean. A named guard reference with no implementation here is
217
+ * a build-time error — a guard is never silently dropped.
218
+ */
219
+ guards?: Record<string, (args: {
220
+ context: any;
221
+ event: any;
222
+ }) => boolean>;
223
+ /**
224
+ * Host action implementations for named action types in the config
225
+ * (`{ type: "notify", params: ... }`). Each is called with the
226
+ * template-resolved `params` as its only argument — pull context/event data
227
+ * into `params` via `{{ ... }}` templates. A named action type with no
228
+ * implementation here is a build-time error.
229
+ */
230
+ actions?: Record<string, (params: any) => unknown>;
187
231
  }
188
232
  //#endregion
189
233
  //#region src/setup-agent.d.ts
@@ -219,6 +263,21 @@ type AgentSchemaConfig<TContextSchema extends StandardSchemaV1<Record<string, un
219
263
  meta?: TMetaSchema;
220
264
  emitted?: TEmittedSchemas;
221
265
  };
266
+ /**
267
+ * The payload of the reserved `'@agent.usage'` event — {@link AgentUsageEvent}
268
+ * without its `type`. It is what a machine's `'@agent.usage'` handler receives
269
+ * alongside `type`, since event schemas describe payloads only.
270
+ */
271
+ type AgentUsageEventPayload = Omit<AgentUsageEvent, "type">;
272
+ /**
273
+ * An authored event schema map with the reserved `'@agent.usage'` entry added —
274
+ * every agent machine's event union includes it, so `on: { '@agent.usage': … }`
275
+ * is typed (and autocompletes) without the machine declaring anything.
276
+ * Idempotent: re-applying it to an already-registered map is a no-op.
277
+ */
278
+ type WithAgentUsageEvent<T extends AgentEventSchemaInputMap> = Omit<T, typeof AGENT_USAGE_EVENT_TYPE> & {
279
+ [AGENT_USAGE_EVENT_TYPE]: StandardSchemaV1<AgentUsageEventPayload>;
280
+ };
222
281
  /**
223
282
  * Builds a machine's {@link AgentSchemaPack} from a partial schema
224
283
  * declaration — only `context` is required; `events`/`input`/`output`/`meta`
@@ -227,21 +286,25 @@ type AgentSchemaConfig<TContextSchema extends StandardSchemaV1<Record<string, un
227
286
  * directly into `setupAgent({ context, events, ... })` — both forms are
228
287
  * accepted).
229
288
  */
230
- declare function createAgentSchemas<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap = {}, TInputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TMetaSchema extends StandardSchemaV1 = StandardSchemaV1<MetaObject>, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}>(schemas: AgentSchemaConfig<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>): AgentSchemaPack<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>;
231
- type AgentRequestConfig<TInputSchema extends StandardSchemaV1 = StandardSchemaV1, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1, TMetadata = Record<string, unknown>, TModel extends string = string> = TextLogicConfig<TInputSchema, TOutputSchema, TMetadata, TModel> & {
232
- mode?: AgentRequestMode;
233
- };
289
+ 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, WithAgentUsageEvent<TEventSchemas>, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>;
234
290
  type AgentRequestSchemaMap = Record<string, {
235
- input: StandardSchemaV1;
236
- output: StandardSchemaV1;
291
+ input?: StandardSchemaV1;
292
+ output?: StandardSchemaV1;
237
293
  }>;
238
- type AgentRequestInput<TRequestSchemas extends AgentRequestSchemaMap, TModel extends string = string> = { [K in keyof TRequestSchemas]: AgentRequestConfig<TRequestSchemas[K]["input"], TRequestSchemas[K]["output"], Record<string, unknown>, TModel> & {
294
+ type ResolvedRequestSchema<TSchema, TFallback> = [NonNullable<TSchema>] extends [never] ? TFallback : [NonNullable<TSchema>] extends [StandardSchemaV1] ? NonNullable<TSchema> : TFallback;
295
+ type RequestInputSchema<TSchemas extends {
296
+ input?: StandardSchemaV1;
297
+ }> = ResolvedRequestSchema<TSchemas["input"], StandardSchemaV1<undefined>>;
298
+ type RequestOutputSchema<TSchemas extends {
299
+ output?: StandardSchemaV1;
300
+ }> = ResolvedRequestSchema<TSchemas["output"], StandardSchemaV1<string>>;
301
+ type AgentRequestInput<TRequestSchemas extends AgentRequestSchemaMap, TModel extends string = string> = { [K in keyof TRequestSchemas]: Omit<TextLogicConfig<RequestInputSchema<TRequestSchemas[K]>, RequestOutputSchema<TRequestSchemas[K]>, Record<string, unknown>, TModel>, "schemas"> & {
239
302
  schemas: TRequestSchemas[K];
240
303
  } };
241
- type RequestActors<TRequestSchemas extends AgentRequestSchemaMap> = { [K in keyof TRequestSchemas]: TextLogic<TRequestSchemas[K]["input"], TRequestSchemas[K]["output"]> };
304
+ type RequestActors<TRequestSchemas extends AgentRequestSchemaMap> = { [K in keyof TRequestSchemas]: TextLogic<RequestInputSchema<TRequestSchemas[K]>, RequestOutputSchema<TRequestSchemas[K]>> };
242
305
  type AgentAllActors<TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap> = TActors & RequestActors<TRequestSchemas>;
243
- type AgentSetupEventsSchema<TEventSchemas extends AgentEventSchemaInputMap> = [keyof TEventSchemas] extends [never] ? {} : {
244
- events: NormalizedEventSchemas<TEventSchemas>;
306
+ type AgentSetupEventsSchema<TEventSchemas extends AgentEventSchemaInputMap> = {
307
+ events: NormalizedEventSchemas<WithAgentUsageEvent<TEventSchemas>>;
245
308
  };
246
309
  type AgentSetupEmittedSchema<TEmittedSchemas extends Record<string, StandardSchemaV1>> = [keyof TEmittedSchemas] extends [never] ? {} : {
247
310
  emitted: TEmittedSchemas;
@@ -254,7 +317,7 @@ type AgentSetupXStateConfig<TContextSchema extends StandardSchemaV1<Record<strin
254
317
  meta: TMetaSchema;
255
318
  } & AgentSetupEventsSchema<TEventSchemas> & AgentSetupEmittedSchema<TEmittedSchemas>;
256
319
  states?: TStateSchemas;
257
- actorSources: SetupActors<AgentSetupActors<AgentAllActors<TActors, TRequestSchemas>, keyof TEventSchemas & string, AgentModelRef<TModels>>>;
320
+ actors: SetupActors<AgentSetupActors<AgentAllActors<TActors, TRequestSchemas>, Exclude<keyof TEventSchemas & string, typeof AGENT_USAGE_EVENT_TYPE>, AgentModelRef<TModels>>>;
258
321
  actions?: NonNullable<AnySetupConfig["actions"]>;
259
322
  guards?: NonNullable<AnySetupConfig["guards"]>;
260
323
  delays?: NonNullable<AnySetupConfig["delays"]>;
@@ -294,7 +357,7 @@ type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string,
294
357
  schemas: AgentSchemaPack<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>;
295
358
  } | AgentSchemaConfig<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>) & {
296
359
  models?: TModels;
297
- actorSources?: TActors;
360
+ actors?: TActors;
298
361
  /**
299
362
  * Per-state schemas, mirroring xstate's `setup({ states })`: narrow
300
363
  * `context` inside a state (invoke `input`, transition fns, final `output`)
@@ -336,8 +399,8 @@ type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unk
336
399
  * its schemas/actors without re-passing them, and a single final state's
337
400
  * `output` is copied to the machine root when the root declares none.
338
401
  */
339
- createMachine: SetupAgentXStateResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>["createMachine"]; /** The retained schema pack ({@link AgentSchemaPack}) for host-side validation and tooling. */
340
- schemas: AgentSchemaPack<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>; /** The `models` registry passed to `setupAgent(...)`, if any (used to type-narrow `AgentModelRef`). */
402
+ 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. Its `events` include the reserved `'@agent.usage'` entry setupAgent registers by default. */
403
+ schemas: AgentSchemaPack<TContextSchema, WithAgentUsageEvent<TEventSchemas>, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>; /** The `models` registry passed to `setupAgent(...)`, if any (used to type-narrow `AgentModelRef`). */
341
404
  readonly models: TModels; /** The {@link TextLogic} actors built from `setupAgent({ requests })`, keyed the same way. */
342
405
  readonly requests: RequestActors<TRequestSchemas>; /** {@link appendMessages}, typed against this agent's context/event schemas. */
343
406
  appendMessages(resolve: AgentMessage | AgentMessage[] | ((args: {
@@ -347,12 +410,8 @@ type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unk
347
410
  event: any;
348
411
  }) => AgentMessage | AgentMessage[])): ReturnType<typeof appendMessages<ContextOf<TContextSchema> & {
349
412
  messages: AgentMessage[];
350
- }, EventsOf<TEventSchemas>>>;
413
+ }, EventsOf<WithAgentUsageEvent<TEventSchemas>>>>;
351
414
  };
352
- /** Typed machine config used by convenience authoring layers built on `setupAgent`. */
353
- type AgentMachineConfig<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TInputSchema extends StandardSchemaV1, TEventSchemas extends AgentEventSchemaInputMap = {}, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TModels extends AgentModelMap = {}> = Parameters<SetupAgentResult<TContextSchema, TEventSchemas, {}, {}, TInputSchema, TOutputSchema, StandardSchemaV1<MetaObject>, TModels>["createMachine"]>[0];
354
- /** Machine produced from {@link AgentMachineConfig}. */
355
- type AgentMachine<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TInputSchema extends StandardSchemaV1, TEventSchemas extends AgentEventSchemaInputMap = {}, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TModels extends AgentModelMap = {}> = ReturnType<SetupAgentResult<TContextSchema, TEventSchemas, {}, {}, TInputSchema, TOutputSchema, StandardSchemaV1<MetaObject>, TModels>["createMachine"]>;
356
415
  /**
357
416
  * Schema-first `setup(...)` for agent machines — the standard entry point
358
417
  * for authoring a machine (the blueprint) that this library then runs (via
@@ -361,7 +420,7 @@ type AgentMachine<TContextSchema extends StandardSchemaV1<Record<string, unknown
361
420
  * state/transition meta are all standard schemas — no `{} as Type` casts —
362
421
  * and are retained on `result.schemas` for runtime validation. Also
363
422
  * registers the `agent.generateText`/`agent.streamText`/`agent.userInput`/
364
- * `agent.decide`/`agent.plan` builtin actors and lowers `requests`/`actorSources` into the
423
+ * `agent.decide`/`agent.plan` builtin actors and lowers `requests`/`actors` into the
365
424
  * machine's actor sources. The result is the xstate `setup(...)` object with
366
425
  * a wrapped `result.createMachine(...)` plus `result.schemas`/`models`/
367
426
  * `requests`/`appendMessages` attached. Also has a
@@ -378,7 +437,7 @@ type AgentMachine<TContextSchema extends StandardSchemaV1<Record<string, unknown
378
437
  *
379
438
  * const agent = setupAgent({
380
439
  * schemas,
381
- * actorSources: { tellJoke },
440
+ * actors: { tellJoke },
382
441
  * });
383
442
  *
384
443
  * const jokeMachine = agent.createMachine({
@@ -408,567 +467,97 @@ declare namespace setupAgent {
408
467
  * the library bundles no JSON Schema engine itself; bring Ajv,
409
468
  * @cfworker/json-schema, or another compiler that returns Standard Schema.
410
469
  *
470
+ * Returns the built `machine` plus the compiled `schemas` pack (context,
471
+ * events, input, output, meta, emitted) — a JSON-authored agent has no
472
+ * TypeScript types, so hosts need the runtime schemas for things like
473
+ * validating an inbound raw event with `parseAgentEvent`.
474
+ *
411
475
  * @example
412
476
  * ```ts
413
- * const machine = setupAgent.fromConfig(workflowConfig, {
477
+ * const { machine, schemas } = setupAgent.fromConfig(workflowConfig, {
414
478
  * compileSchema,
415
479
  * });
416
480
  * const result = await runAgent(machine, { input: { ticket }, executors: { generateText, decide } });
481
+ * const event = parseAgentEvent(result.snapshot, raw, { events: schemas.events });
417
482
  * ```
418
483
  */
419
- function fromConfig(config: AgentWorkflowConfig, options: FromConfigOptions): AnyStateMachine;
484
+ function fromConfig(config: AgentWorkflowConfig, options: FromConfigOptions): FromConfigResult;
420
485
  }
421
486
  //#endregion
422
- //#region src/internal/state-request-pass.d.ts
487
+ //#region src/agent-run.d.ts
423
488
  /**
424
- * One model request read off the machine's CURRENT snapshot by a
425
- * `RunAgentOptions.getRequests` hook. `model` is an executor model NAME — the
426
- * same string every {@link AgentTextRequest.model} carries, resolved by the
427
- * run's executors (e.g. a `defineModels` key when using
428
- * `createAiSdkExecutors`) — never a model instance.
429
- */
430
- interface AgentStateRequest {
431
- /** Instruction for this request's model call, appended to the run's message log as a user message. */
432
- prompt: string;
433
- /** System prompt for this request's model call(s). */
434
- system?: string;
435
- /** Executor model name (resolved by the run's executors). */
436
- model: string;
437
- /**
438
- * `'text'` (default): a `generateText` call with the message log +
439
- * `prompt`; the reply is appended to the log, then the machine is advanced
440
- * per {@link AgentStateRequest.onDone}. `'decision'`: no text call — a
441
- * single `decide` call (log + `prompt`) chooses the event. Use for pure
442
- * routing states.
443
- */
444
- kind?: "text" | "decision";
445
- /**
446
- * What to send when this request's text call resolves — the EXPLICIT
447
- * advancement contract, always an event OBJECT (the same shape
448
- * `actor.send` takes; no string shorthand). A literal event sends exactly
449
- * that; a function receives the text output (plus the live snapshot and
450
- * message log) and returns the event to send — payload included — or
451
- * `undefined` to send nothing. Omitted: a `decide` call chooses among the
452
- * candidate events (requires a `decide` executor) — there is no implicit
453
- * auto-send. A resolved event whose type the state does not accept throws
454
- * (programmer error); one a guard rejects is simply not sent. Ignored for
455
- * `kind: 'decision'` (the decide call IS the advancement).
456
- */
457
- onDone?: ChosenEvent | ((args: {
458
- output: unknown;
459
- snapshot: AnyMachineSnapshot;
460
- messages: readonly AgentMessage[];
461
- }) => ChosenEvent | undefined);
462
- /** Restricts this request's candidate outcome events for the `decide` fallback (default: every currently-accepted event). */
463
- allowedEvents?: readonly string[];
464
- /** Trace/request id; defaults to `interpret_<n>`. */
465
- id?: string;
466
- }
467
- //#endregion
468
- //#region src/run-agent.d.ts
469
- /**
470
- * Thrown by {@link runAgent} when resuming with a `snapshot` + `event` whose
471
- * `type` the restored state cannot accept (a type-level check via
472
- * {@link getAcceptedEvents}). A programmer/integration error, in the same
473
- * class as runAgent's bind-time throws — it throws rather than settling an
474
- * `error` result. A type-legal event a guard rejects is NOT this error (the
475
- * machine simply takes no transition). Opt out with
476
- * {@link RunAgentOptions.onIllegalResumeEvent} `'ignore'`.
477
- */
478
- declare class IllegalResumeEventError extends Error {
479
- readonly eventType: string;
480
- readonly acceptedTypes: string[];
481
- constructor(eventType: string, acceptedTypes: string[]);
482
- }
483
- /**
484
- * Thrown by {@link runAgent} when resuming from a `snapshot` whose stamped
485
- * `agentMeta.version` differs from the current machine's version, under the
486
- * default `onVersionMismatch: 'throw'` and with no `migrateSnapshot` hook. The
487
- * structural fingerprint of the machine changed since the snapshot was
488
- * persisted (a state/transition/invoke was added, removed, or retargeted), so
489
- * the snapshot may no longer resume cleanly. `from` is the snapshot's version,
490
- * `to` the current machine's.
491
- */
492
- declare class SnapshotVersionMismatchError extends Error {
493
- readonly from: string;
494
- readonly to: string;
495
- readonly machineId: string;
496
- constructor(from: string, to: string, machineId: string);
497
- }
498
- /**
499
- * Thrown by {@link runAgentToCompletion} when the run settles `idle` instead of
500
- * `done`: the machine paused for external input. Carries the idle `snapshot`
501
- * and `acceptedTypes` (the event types that could resume it, via
502
- * {@link getAcceptedEvents}). Use {@link runAgent} directly when idle is an
503
- * expected outcome you handle.
504
- */
505
- declare class AgentIdleError extends Error {
506
- readonly snapshot: AnyMachineSnapshot;
507
- readonly acceptedTypes: string[];
508
- constructor(snapshot: AnyMachineSnapshot, acceptedTypes: string[]);
509
- }
510
- /** Handler for `agent.userInput` invokes passed as {@link RunAgentOptions.userInput}. Resolves to what the human typed. */
511
- interface AgentUserInputExecutor {
512
- (input: AgentUserInput): PromiseLike<string>;
513
- }
514
- /**
515
- * The run's machine identity, stamped onto every settled snapshot's `agentMeta`.
516
- * `machineId` is the machine's `id`; `version` is
517
- * {@link RunAgentOptions.machineVersion} or the
518
- * {@link getMachineStructuralHash} of the machine. Trace events and the
519
- * `onMessage` info arg carry the same identity flattened, as
520
- * `machineId`/`machineVersion`.
521
- */
522
- interface AgentRunMeta {
523
- machineId: string;
524
- version: string;
525
- }
526
- /**
527
- * Second argument passed to {@link RunAgentOptions.onMessage}: the run's
528
- * identity, carried alongside each live message. Not stamped onto the message
529
- * itself (messages stay clean model input).
530
- */
531
- interface AgentMessageInfo {
532
- runId: string;
533
- machineId: string;
534
- /** {@link RunAgentOptions.machineVersion} or the machine's structural hash. */
535
- machineVersion: string;
536
- }
537
- /**
538
- * The version of the {@link AgentTraceEvent} envelope every trace event carries
539
- * as `schemaVersion`. Bumped only on a breaking change to the envelope or any
540
- * payload shape, so a consumer can gate on it. Emitted identically by
541
- * {@link runAgent}, {@link provideExecutors}' `onTrace`, and
542
- * {@link traceTransitions}.
543
- */
544
- declare const AGENT_TRACE_SCHEMA_VERSION = 1;
545
- type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
546
- /** The {@link AGENT_TRACE_SCHEMA_VERSION} the event was produced with. */schemaVersion: typeof AGENT_TRACE_SCHEMA_VERSION;
547
- runId: string;
548
- seq: number;
549
- timestamp: string;
550
- machineId: string; /** {@link RunAgentOptions.machineVersion} or the machine's structural hash. */
551
- machineVersion: string;
552
- } & ({
553
- type: "run.start";
554
- input?: InputFrom<TMachine>;
555
- snapshot?: Snapshot<unknown>;
556
- event?: EventFromLogic<TMachine>;
557
- } | {
558
- type: "request.start";
559
- request: AgentStepRequest;
560
- } | {
561
- type: "request.end";
562
- request: AgentStepRequest;
563
- output: unknown;
564
- raw: unknown;
565
- /** The model's reasoning, lifted off the raw executor result when the
566
- * request opted into the structured-output envelope's `reasoning` field.
567
- * Present only when the executor surfaced a string `reasoning`. */
568
- reasoning?: string;
569
- } | {
570
- type: "request.error";
571
- request: AgentStepRequest;
572
- error: unknown;
573
- } | {
574
- type: "stream.chunk";
575
- request: AgentRequest;
576
- chunk: string;
577
- } | {
578
- type: "machine.transition";
579
- snapshot: SnapshotFrom<TMachine>;
580
- event: EventFromLogic<TMachine>;
581
- } | {
582
- type: "emit";
583
- event: EmittedFrom<TMachine>;
584
- } | ({
585
- type: "run.end";
586
- status: "done";
587
- output: OutputFrom<TMachine>;
588
- snapshot: SnapshotFrom<TMachine>;
589
- } | {
590
- type: "run.end";
591
- status: "idle";
592
- snapshot: SnapshotFrom<TMachine>;
593
- pendingUserInputs?: PendingUserInput[];
594
- persistedSnapshot?: Snapshot<unknown>;
595
- } | {
596
- type: "run.end";
597
- status: "error";
598
- cause: RunAgentErrorCause;
599
- error: unknown;
600
- snapshot: SnapshotFrom<TMachine>;
601
- }));
602
- /**
603
- * Options for {@link runAgent}.
489
+ * A live handle over a single {@link runAgent} call: its trace events as an
490
+ * async stream, plus the same result promise `runAgent` returns.
604
491
  *
605
- * Host executors are passed as a single {@link AgentRequestExecutors}-shaped
606
- * set under `executors` (the same shape the step path takes). Each executor
607
- * kind is required only if the machine actually reaches a request of that kind
608
- * checked at bind time, before any actor runs. The whole `executors` field is
609
- * optional: a machine whose agent sources all carry their own executor
610
- * (`.withExecutor(...)`) needs none.
492
+ * Build it with {@link createAgentRun}. Use `events` for a pull-based feed
493
+ * (SSE, a JSONL logger, a progress UI) and `result` for the final outcome —
494
+ * either, both, or neither; nothing about consuming one is required to consume
495
+ * the other.
611
496
  */
612
- interface RunAgentOptions<TMachine extends AnyStateMachine> {
613
- /**
614
- * The host executor set backing the machine's agent actors — build it with
615
- * `createAiSdkExecutors({ models })` from '@statelyai/agent/ai-sdk', or supply
616
- * `{ generateText?, streamText?, decide? }` by hand. Every slot is optional
617
- * here (unlike the step path's {@link AgentRequestExecutors}): each kind is
618
- * bind-time-checked only when the machine actually reaches a request of that
619
- * kind, so e.g. a stream-only machine may pass `{ streamText }` alone.
620
- */
621
- executors?: Partial<AgentRequestExecutors>;
622
- /** Machine input, passed straight to `createActor(machine, { input })`. Omit when resuming via `snapshot`. */
623
- input?: InputFrom<TMachine>;
624
- /** A previously-settled run's `result.snapshot`, to resume from instead of starting fresh. Pair with `event` to deliver the event that unblocks the resumed idle state. */
625
- snapshot?: Snapshot<unknown>;
626
- /** An event to send immediately after starting/resuming the actor (e.g. the human's answer to an idle-state prompt). */
627
- event?: EventFromLogic<TMachine>;
628
- /**
629
- * How to handle a resume `event` the restored state cannot accept (a
630
- * type-level check via {@link getAcceptedEvents}, only applied when resuming
631
- * from a `snapshot`). `'throw'` (default) throws {@link IllegalResumeEventError}
632
- * before delivering the event; `'ignore'` restores the older silent behavior
633
- * (the event is sent and the machine drops it). A type-legal event a guard
634
- * rejects is never an illegal resume event.
635
- */
636
- onIllegalResumeEvent?: "throw" | "ignore";
637
- /**
638
- * The version stamped onto every settled snapshot's `agentMeta` and compared
639
- * against an incoming snapshot's stamp on resume. Defaults to
640
- * {@link getMachineStructuralHash} of the machine (a structural fingerprint).
641
- * Set an explicit value (e.g. a semver or build id) to control migration
642
- * boundaries yourself.
643
- */
644
- machineVersion?: string;
645
- /**
646
- * How to handle a resume `snapshot` whose stamped `agentMeta.version` differs
647
- * from the current machine's version. `'throw'` (default) throws
648
- * {@link SnapshotVersionMismatchError} with `from`/`to`; `'warn'`
649
- * `console.warn`s once and proceeds; `'ignore'` proceeds silently. Ignored
650
- * when {@link migrateSnapshot} is provided (that runs instead), and never
651
- * triggers for an unstamped snapshot (no `agentMeta`).
652
- */
653
- onVersionMismatch?: "throw" | "warn" | "ignore";
654
- /**
655
- * Called instead of {@link onVersionMismatch} when a resume snapshot's
656
- * version mismatches the current machine's: receives the incoming snapshot
657
- * and `{ from, to }`, and its return value is used as the snapshot to resume
658
- * from. A throw propagates.
659
- */
660
- migrateSnapshot?: (snapshot: Snapshot<unknown>, info: {
661
- from: string;
662
- to: string;
663
- }) => Snapshot<unknown>;
664
- /** Actor source implementations, merged onto the machine before binding — sugar for `machine.provide({ actorSources })` ahead of the run. */
665
- actorSources?: Record<string, AnyActorLogic>;
666
- /**
667
- * Optional human-input handler for `agent.userInput` invokes (CLI prompt,
668
- * web form, Slack, …). With a handler, input is gathered inline without
669
- * settling. Without one, an `agent.userInput` invoke becomes a *pending
670
- * placeholder*: it waits indefinitely, does not block idle detection, and
671
- * the run settles `{ status: 'idle', pendingUserInputs, persistedSnapshot }`
672
- * once no other work is in flight — resume by passing `persistedSnapshot`
673
- * back as `snapshot` together with a `userInput` handler that answers it.
674
- */
675
- userInput?: AgentUserInputExecutor;
676
- /**
677
- * Host override for detecting a snapshot that is an INTENTIONAL wait for an
678
- * external event — the deterministic replacement for the timing heuristic
679
- * runAgent uses to settle idle. Resolution order: this option (host override)
680
- * → the machine-carried predicate declared via `setupAgent({ isSuspended })`
681
- * → the timing heuristic (when neither is present). When the resolved
682
- * predicate returns true and nothing is in flight (no live requests/plans/
683
- * invokes; the `agent.userInput` placeholder exemption still applies), runAgent
684
- * settles idle immediately, without the `setTimeout` heuristic. It does NOT
685
- * force-settle while agent work is in flight, and whole-machine idle semantics
686
- * are unchanged; a machine with no predicate falls back to the heuristic
687
- * exactly as before. Declare your own signal, e.g.
688
- * `(s) => s.hasTag('awaiting-review')`.
689
- *
690
- * Provisional name — may change before 2.0.
691
- */
692
- isSuspended?: (snapshot: AnyMachineSnapshot) => boolean;
693
- /**
694
- * The override to runAgent's DEFAULT contract. By default agent work is
695
- * whatever the machine *invokes* (`agent.generateText`, TextLogic,
696
- * `agent.decide`, …). With `getRequests`, whenever the machine would
697
- * otherwise settle idle, this hook reads the snapshot and returns the model
698
- * request(s) to run instead — prompts from state `description`s, `meta`,
699
- * tags, a lookup table keyed by state value, wherever you keep them. Return
700
- * nothing to settle idle (human-wait states).
701
- *
702
- * There is no blessed source for the prompts — this is a recipe seam.
703
- * Prompts-in-descriptions, copy-paste and adapt:
704
- *
705
- * ```ts
706
- * getRequests: (snapshot) =>
707
- * snapshot._nodes
708
- * .filter((node) => node.description && !node.tags.includes('waiting'))
709
- * .map((node) => ({
710
- * model: 'writer',
711
- * prompt: node.description!,
712
- * kind: node.tags.includes('decision') ? 'decision' : 'text',
713
- * // single-outcome states advance deterministically; else `decide`
714
- * onDone: node.ownEvents.length === 1 ? { type: node.ownEvents[0] } : undefined,
715
- * allowedEvents: node.ownEvents,
716
- * })),
717
- * ```
718
- *
719
- * Each request runs per {@link AgentStateRequest.kind}, appends to the
720
- * run's message log (see {@link RunAgentOptions.messages}), and advances
721
- * the machine per {@link AgentStateRequest.onDone} — explicitly named/
722
- * computed event, or a `decide` call when omitted — always gated by
723
- * `snapshot.can`. Multiple requests run concurrently (parallel regions —
724
- * scope each with `allowedEvents`, e.g. the node's `ownEvents`). A pass
725
- * that sends no event settles idle. Every model call counts against
726
- * `maxModelCalls`.
727
- */
728
- getRequests?: (snapshot: SnapshotFrom<TMachine>, agentContext: {
729
- messages: readonly AgentMessage[];
730
- }) => AgentStateRequest | readonly AgentStateRequest[] | undefined;
731
- /**
732
- * Adds to the run's aggregated message log (the working memory
733
- * `getRequests` requests read and append to). The log starts as the resume
734
- * `snapshot`'s stamped `messages` (else `[]`); an ARRAY here is APPENDED to
735
- * that history — the safe default for folding in a user reply on resume,
736
- * never silently erasing prior conversation. Pass a FUNCTION
737
- * `(prior) => AgentMessage[]` to take full control (replace, filter,
738
- * compact). The final log is stamped onto every settled result's
739
- * `snapshot.messages` (like `agentMeta`), so persist/resume round-trips it
740
- * with no extra wiring — read it with `getAgentMessages(snapshot)`.
741
- */
742
- messages?: AgentMessage[] | ((prior: AgentMessage[]) => AgentMessage[]);
743
- /** Fires for each streamed chunk of a `mode: 'stream'` text request, alongside the {@link AgentRequest} that produced it (parallel states can interleave multiple streams). Purely observational. */
744
- onChunk?: (chunk: string, info: {
745
- request: AgentRequest;
746
- }) => void;
747
- /** Fires once per resolved text/decision request with its normalized output and the raw executor result (tool calls, usage, …) — the seam for tracing/observability and event-sourced replay logging. */
748
- onResult?: (request: AgentStepRequest, result: {
749
- output: unknown;
750
- raw: unknown;
751
- }) => void;
752
- /** Fires a single ordered stream of run/request/chunk/transition/emit/end events. Intended for eval traces, JSONL logs, and adapter-owned telemetry/exporters. */
753
- onTrace?: (event: AgentTraceEvent<TMachine>) => void;
497
+ interface AgentRun<TMachine extends AnyStateMachine = AnyStateMachine> {
754
498
  /**
755
- * Fires on every machine transition (snapshot + causing event). Pure
756
- * observation progress UIs, logging, tracing. Cannot send events.
499
+ * Single-consumer async stream of the run's trace events, in `runAgent`'s
500
+ * emission order (`run.start` request/chunk/transition/emit events
501
+ * `run.end`). Completes right after `run.end` is delivered. Events are
502
+ * buffered unboundedly, so a slow or absent consumer never blocks the run
503
+ * (see {@link createAgentRun}). Single-consumer: a second `for await` over the
504
+ * same iterator picks up only the events not yet pulled — it is one shared
505
+ * cursor, not a fresh replay.
757
506
  */
758
- onTransition?: (snapshot: SnapshotFrom<TMachine>, event: EventFromLogic<TMachine>) => void;
507
+ events: AsyncIterableIterator<AgentTraceEvent<TMachine>>;
759
508
  /**
760
- * Fires for each message appended to the run's aggregated log (see
761
- * {@link RunAgentOptions.messages}) the moment a `getRequests` request
762
- * appends it the live view of the log a caller otherwise only reads off
763
- * the settled snapshot via `getAgentMessages`. Purely observational, like
764
- * {@link onTransition}. Never fires for the seeded history, and never fires
765
- * on a default invoke-driven run (nothing appends there).
509
+ * Settles exactly like {@link runAgent}'s return value: resolves with the
510
+ * `done | idle | error` {@link RunAgentResult}, and rejects only where
511
+ * `runAgent` itself rejects (bind-time programmer errors a missing
512
+ * executor, an illegal resume event, a version mismatch). A run-level failure
513
+ * still resolves with `{ status: 'error' }`, never rejects.
766
514
  */
767
- onMessage?: (message: AgentMessage, info: AgentMessageInfo) => void;
768
- /**
769
- * Handlers for events the machine emits (`enq.emit(...)`), keyed by emitted
770
- * event type — `'*'` catches all. Typed from the machine's `emitted`
771
- * schemas (`setupAgent({ emitted: { ... } })`). Purely observational, like
772
- * {@link onTransition}: the machine narrates progress on its own vocabulary
773
- * (not xstate internals) and the host renders it — a progress UI, an SSE
774
- * stream, a log line.
775
- */
776
- on?: { [TType in EmittedFrom<TMachine>["type"] | "*"]?: (emitted: EmittedFrom<TMachine> & (TType extends "*" ? unknown : {
777
- type: TType;
778
- })) => void };
779
- /**
780
- * Raw xstate inspection passthrough: fires for every inspection event in
781
- * the whole actor system — root machine, invoked child machines, spawned
782
- * actors — each carrying its `actorRef` (`event.actorRef.id`/`.src`). This
783
- * is the system-wide seam {@link onTransition} (root transitions only)
784
- * cannot give you: filter `event.type === '@xstate.transition'` and read
785
- * `event.actorRef` to attribute a child machine's states to the child.
786
- * Purely observational, like the other callbacks. Unlike them it also
787
- * fires during the final settle (a child's last transition and stop events
788
- * arrive while the run is tearing down).
789
- *
790
- * Accepts a function or an observer (`{ next }`), matching `createActor`'s
791
- * `inspect` option, so `@statelyai/inspect`'s `inspector.inspect` plugs in
792
- * directly.
793
- */
794
- inspect?: ((inspectionEvent: InspectionEvent) => void) | {
795
- next?: (inspectionEvent: InspectionEvent) => void;
796
- };
797
- /** Caps the number of model/decision calls this run may make (each retry of a decision counts separately); exceeding it settles `{ status: 'error', cause: 'max-model-calls' }`. Default 100. */
798
- maxModelCalls?: number;
799
- /** Aborts the run; settles `{ status: 'error', cause: 'aborted' }` with `signal.reason` as the error. */
800
- signal?: AbortSignal;
515
+ result: Promise<RunAgentResult<TMachine>>;
801
516
  }
802
517
  /**
803
- * The outcome of a {@link runAgent} call always exactly one of three
804
- * variants, never a throw for a waiting or failed machine (programmer
805
- * errors like a missing executor still throw, at bind time before any actor
806
- * runs). `done`: a final state was reached (`output` is the machine's
807
- * `OutputFrom`). `idle`: the run settled with no in-flight work — resume by
808
- * calling `runAgent` again with `{ snapshot, event }`. `error`: a run-level
809
- * failure, discriminated by `cause` (`'aborted'`, `'max-model-calls'`,
810
- * `'decision-exhausted'`, `'machine'` for any other machine error state, or
811
- * `'stopped'` for an external stop — see {@link RunAgentErrorCause}). Every
812
- * variant carries the final `snapshot`, and the underlying
813
- * actor is stopped on every settle path — there is no live actor to resume;
814
- * resume is always by snapshot.
815
- */
816
- /** A pending unhandled `agent.userInput` invoke surfaced on an idle settle — `id` is the invoke's id, `input` its resolved invoke input (prompt, metadata). Answer it by resuming with a `userInput` handler. */
817
- interface PendingUserInput {
818
- id: string;
819
- input: AgentUserInput | undefined;
820
- }
821
- type RunAgentResult<TMachine extends AnyStateMachine> = {
822
- status: "done";
823
- output: OutputFrom<TMachine>;
824
- snapshot: SnapshotFrom<TMachine>;
825
- } | {
826
- status: "idle";
827
- snapshot: SnapshotFrom<TMachine>; /** Present when the machine is waiting on unhandled `agent.userInput` invokes: one entry per pending invoke. */
828
- pendingUserInputs?: PendingUserInput[];
829
- /**
830
- * Present alongside `pendingUserInputs`: the JSON-serializable persisted
831
- * snapshot (in-flight children included). Persist THIS one and resume
832
- * with `runAgent(machine, { snapshot: persistedSnapshot, userInput })` —
833
- * the live `snapshot` above cannot round-trip active children.
834
- */
835
- persistedSnapshot?: Snapshot<unknown>;
836
- } | {
837
- status: "error";
838
- cause: RunAgentErrorCause;
839
- error: unknown;
840
- snapshot: SnapshotFrom<TMachine>;
841
- };
842
- /**
843
- * Discriminates a {@link RunAgentResult} `error`:
844
- * - `'aborted'` — the run's `signal` fired.
845
- * - `'max-model-calls'` — the `maxModelCalls` budget was exceeded.
846
- * - `'decision-exhausted'` — the machine reached an error state whose error is
847
- * (or wraps) a {@link DecisionExhaustedError} that no `onError` handled.
848
- * - `'machine'` — any other machine error state.
849
- * - `'stopped'` — the actor was stopped externally (`status === 'stopped'`).
850
- */
851
- type RunAgentErrorCause = "aborted" | "max-model-calls" | "decision-exhausted" | "machine" | "stopped";
852
- /**
853
- * The set of string-keyed actor `src`s the machine's own config invokes
854
- * (top-level, recursing into child STATES but not into invoked child
855
- * machines). {@link provideExecutors} uses it to require an executor only for a
856
- * source the machine actually invokes — the always-registered `agent.*`
857
- * builtins that go unused must not force their executors to be supplied.
858
- * @internal
859
- */
860
- /**
861
- * Runs an agent machine to completion or idle: a `createActor` host that
862
- * binds `options`' host executors onto the machine's `agent.*`/`TextLogic`/
863
- * `DecisionLogic` actor sources, starts (or resumes) the actor, and drives
864
- * it until it settles — {@link RunAgentResult} `done | idle | error`. Unlike
865
- * the step helpers ({@link initialAgentStep} etc — a pure
866
- * transition-at-a-time path for durable hosts), `runAgent` owns a live actor
867
- * internally; there is no continuation callback, so **idle always settles**
868
- * and the caller resumes explicitly by passing the settled `{ snapshot,
869
- * event }` back in. The actor is stopped on every settle path (`done`,
870
- * `idle`, and `error` alike) — resume is always by snapshot, never by
871
- * holding a reference to a live actor.
518
+ * Wraps {@link runAgent} in a canonical run-stream handle: the run's trace
519
+ * events as a pull-based {@link AgentRun.events} async iterator, alongside the
520
+ * unchanged {@link AgentRun.result} promise.
872
521
  *
873
- * Binding happens **before** the actor starts: every invoke the machine
874
- * could reach is walked and checked against the effective actor sources
875
- * (`options.actorSources` merged onto the machine), so a missing
876
- * `streamText`/`decide` executor or any other unbound actor source throws
877
- * immediately — a bind-time error, not a mid-run failure. The one exception
878
- * is `agent.userInput`: unhandled, it binds as a pending placeholder that
879
- * settles the run idle (with `pendingUserInputs`) instead of erroring.
522
+ * Semantics:
880
523
  *
881
- * @example
882
- * ```ts
883
- * const executors = createAiSdkExecutors({ models });
884
- * let r = await runAgent(machine, { input, executors });
885
- * while (r.status === 'idle') {
886
- * const event = await promptUser(getAcceptedEvents(r.snapshot));
887
- * r = await runAgent(machine, { snapshot: r.snapshot, event, executors });
888
- * }
889
- * if (r.status !== 'done') throw new Error(`Run did not complete: ${r.status}`);
890
- * console.log(r.output);
891
- * ```
892
- *
893
- * The `executors`' `generateText`/`streamText` accept the raw Vercel AI SDK
894
- * functions directly (`executors: { generateText, streamText }` with them
895
- * imported from `ai`) — their `{ text }`/`{ textStream }` results are unwrapped
896
- * natively. `decide` cannot be a raw AI SDK function: the tool-per-event mapping
897
- * lives in an adapter use `createAiSdkExecutors` from '@statelyai/agent/ai-sdk'.
524
+ * 1. **Starts immediately.** The underlying `runAgent` is invoked on this call,
525
+ * not on the first `events` iteration — work is already in flight when
526
+ * `createAgentRun` returns.
527
+ * 2. **Buffer, don't stall.** Events are queued in an unbounded in-memory
528
+ * buffer as the run emits them; a slow or absent consumer never applies
529
+ * backpressure to the run. Once `run.end` is delivered, the iterator
530
+ * completes.
531
+ * 3. **Composes `onTrace`.** If `options.onTrace` is passed, it still fires for
532
+ * every event the wrapper adds queue delivery, it does not replace the
533
+ * caller's sink.
534
+ * 4. **`result` mirrors `runAgent`.** Same resolution and rejection behavior
535
+ * (see {@link AgentRun.result}). A no-op rejection handler is attached
536
+ * internally so a caller who reads only `events` never trips an unhandled
537
+ * rejection on a bind-time throw; the returned promise still rejects for a
538
+ * caller who awaits it.
539
+ * 5. **Resume is identical.** Options pass straight through, so starting from a
540
+ * persisted `snapshot` (+ resume `event`) streams that run's events from its
541
+ * own `run.start`, exactly as `runAgent` would run it.
542
+ * 6. **Early termination does not cancel the run.** Breaking out of a
543
+ * `for await` (or calling `events.return()`) stops delivery, but the run
544
+ * keeps going and `result` still settles. Cancelling the run itself is
545
+ * future work — pass `options.signal` to abort it.
546
+ * 7. **`events` is single-consumer.** See {@link AgentRun.events}.
898
547
  */
899
- declare function runAgent<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentOptions<TMachine>): Promise<RunAgentResult<TMachine>>;
900
- /**
901
- * Runs an agent machine to a **final state** and returns its output, for
902
- * run-to-done flows where an idle pause is unexpected. Wraps {@link runAgent}:
903
- *
904
- * - `done` → resolves with `result.output` (the machine's `OutputFrom`).
905
- * - `idle` → throws {@link AgentIdleError} carrying the idle snapshot and the
906
- * event types that could resume it.
907
- * - `error` → throws `result.error` when it is an `Error`; otherwise wraps it
908
- * in an `Error` whose `.cause` is the {@link RunAgentErrorCause} and whose
909
- * `.error` is the raw thrown value.
910
- *
911
- * Use {@link runAgent} directly when idle is an expected outcome you handle
912
- * (human-in-the-loop, resumable flows); use `runAgentToCompletion` when the
913
- * machine is meant to run straight through to a final state.
914
- */
915
- declare function runAgentToCompletion<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentOptions<TMachine>): Promise<OutputFrom<TMachine>>;
916
- /**
917
- * The actor handed to an {@link inspectTransitions} handler: an
918
- * {@link AnyActorRef} widened with the runtime `id`/`src` used to attribute a
919
- * transition to the root machine or a specific invoked child (xstate's static
920
- * `ActorRef` type omits them, but they are always present at runtime).
921
- */
922
- type InspectedActorRef = AnyActorRef & {
923
- id: string;
924
- src?: string | AnyActorLogic;
925
- };
926
- /**
927
- * Wraps a `(snapshot, actorRef) => void` handler into a function usable as
928
- * {@link RunAgentOptions.inspect}: it filters the raw inspection stream to
929
- * `@xstate.transition` events and hands the handler the typed
930
- * {@link AnyMachineSnapshot} and the {@link InspectedActorRef} that
931
- * transitioned. Attribute a child actor via `actorRef.id`/`actorRef.src`. Saves
932
- * the manual `event.type === '@xstate.transition'` filtering and the snapshot/
933
- * actorRef casts.
934
- */
935
- declare function inspectTransitions(handler: (snapshot: AnyMachineSnapshot, actorRef: InspectedActorRef) => void): (inspectionEvent: InspectionEvent) => void;
936
- /**
937
- * An xstate `inspect` handler that emits `machine.transition` trace events onto
938
- * `onTrace`, sharing the SAME versioned envelope and per-root-actor `seq`
939
- * registry as {@link provideExecutors}' `onTrace`. Pair the two on one actor to
940
- * get a single ordered trace stream (request + transition events) for the
941
- * uncontrolled path:
942
- *
943
- * ```ts
944
- * const bound = provideExecutors(machine, executors, { onTrace });
945
- * const actor = createActor(bound, { inspect: traceTransitions(onTrace) });
946
- * ```
947
- *
948
- * Only ROOT-actor transitions are traced (matching `runAgent`'s
949
- * `machine.transition`); child-actor transitions are ignored. Attribute the
950
- * event via its envelope `runId`.
951
- *
952
- * By design this path has NO `run.start`/`run.end` events: `createActor` has no
953
- * run boundary the way `runAgent` does, so the stream starts at the actor's
954
- * first transition. It also does NOT emit `emit` trace events: in this xstate
955
- * build emitted events are delivered through `actor.on(...)`, not the inspection
956
- * protocol, so they are not observable from an `inspect` handler — subscribe
957
- * with `actor.on('*', ...)` if you need them.
958
- */
959
- declare function traceTransitions<TMachine extends AnyStateMachine = AnyStateMachine>(onTrace: (event: AgentTraceEvent<TMachine>) => void): (inspectionEvent: InspectionEvent) => void;
548
+ declare function createAgentRun<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentOptions<TMachine>): AgentRun<TMachine>;
960
549
  //#endregion
961
550
  //#region src/provide-executors.d.ts
962
551
  /** Options for {@link provideExecutors}. */
963
552
  interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMachine> {
964
553
  /**
965
554
  * Extra actor-source overrides merged onto the machine BEFORE binding — the
966
- * same shape as `machine.provide({ actorSources })`. Use it to supply the
555
+ * same shape as `machine.provide({ actors })`. Use it to supply the
967
556
  * `agent.userInput` handler, a custom non-agent actor, or to shadow an agent
968
557
  * source with your own executor-bound logic. Merged first, so an override
969
558
  * that already carries its own executor is left untouched by the binding pass.
970
559
  */
971
- actorSources?: Record<string, AnyActorLogic>;
560
+ actors?: Record<string, AnyActorLogic>;
972
561
  /** Chunk sink threaded to every bound `mode: 'stream'` text source. */
973
562
  onChunk?: (chunk: string) => void;
974
563
  /**
@@ -997,8 +586,8 @@ interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMac
997
586
  *
998
587
  * behaves like a normal XState actor whose agent invokes now reach real models.
999
588
  *
1000
- * Binding pass over `machine.implementations.actorSources` (after merging
1001
- * `options.actorSources`):
589
+ * Binding pass over `machine.sources.actors` (after merging
590
+ * `options.actors`):
1002
591
  * - `mode: 'generate'` text source → `executors.generateText`
1003
592
  * - `mode: 'stream'` text source → `executors.streamText`
1004
593
  * - decision / `agent.decide` source → `executors.decide` (snapshot-driven
@@ -1012,7 +601,7 @@ interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMac
1012
601
  *
1013
602
  * A source that already carries its own executor (`.withExecutor(...)`) is left
1014
603
  * as-is. `agent.userInput` is left UNBOUND — an uncontrolled host handles idle
1015
- * itself, so supply a handler via `options.actorSources` if the machine uses it.
604
+ * itself, so supply a handler via `options.actors` if the machine uses it.
1016
605
  * Non-agent actors are untouched.
1017
606
  *
1018
607
  * Throws at bind time if a source needs an executor kind that `executors` does
@@ -1072,8 +661,8 @@ interface AssertAgentMachineOptions extends LintAgentMachineOptions {
1072
661
  * `diagnostics` holds the findings; the message lists them one per finding,
1073
662
  * so a test runner's failure output reads like the CLI's lint report.
1074
663
  */
1075
- declare class AgentLintError extends Error {
1076
- diagnostics: AgentLintDiagnostic[];
664
+ declare class AgentLintError extends AgentError {
665
+ readonly diagnostics: AgentLintDiagnostic[];
1077
666
  constructor(machineId: string, diagnostics: AgentLintDiagnostic[]);
1078
667
  }
1079
668
  /**
@@ -1229,4 +818,388 @@ interface CanReachResult {
1229
818
  */
1230
819
  declare function canReach(machine: AnyStateMachine, statePath: string, options?: ExplorePathsOptions): Promise<CanReachResult>;
1231
820
  //#endregion
1232
- export { AGENT_TRACE_SCHEMA_VERSION, type AgentDecisionExecutor, type AgentDecisionInput, type AgentDecisionRequest, type AgentEventDescriptor, type AgentEventSchemaInput, type AgentEventSchemaInputMap, type AgentEventToolNameResolver, AgentIdleError, type AgentLintDiagnostic, AgentLintError, type AgentLintSeverity, type AgentMachine, type AgentMachineConfig, type AgentMessage, type AgentMessageInfo, type AgentModelMap, type AgentModelRef, type AgentPathReport, type AgentPathTerminal, type AgentPlanInput, type AgentPlanOutput, type AgentRequestConfig, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestMode, type AgentRequestOptions, type AgentRequestSource, type AgentRunMeta, type AgentSchemaPack, type AgentSetupStateSchema, type AgentSnapshotStore, type AgentStateNarrowing, type AgentStateRequest, type AgentTextRequest, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentToolSchema, type AgentTools, type AgentTraceEvent, type AgentUserInput, type AgentUserInputExecutor, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AiSdkShapedStreamResult, type AiSdkShapedTextResult, type AllowedEventPattern, type AllowedEvents, type AssertAgentMachineOptions, type AssistantMessage, type CanReachResult, type ChosenEvent, type DataContent, type DecisionAttempt, DecisionExhaustedError, type DecisionLogic, type EventPayload, type EventUnion, type ExplorePathsOptions, type FilePart, type FromConfigOptions, IllegalResumeEventError, type ImagePart, type InferOutput, type InspectedActorRef, type LintAgentMachineOptions, type NormalizedEventSchemas, type PendingUserInput, type PlanLogic, type ProvideExecutorsOptions, type ProviderOptions, type RunAgentOptions, type RunAgentResult, type SchemaCompiler, type SimulateAgentOptions, type SimulateAgentResult, type SimulationScript, type SimulationTrailEntry, SnapshotVersionMismatchError, type StandardSchemaV1, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextLogicInput, type TextLogicOutput, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultOutput, type ToolResultPart, type UserMessage, appendMessages, assertAgentMachine, assistantMessage, canReach, createAgentSchemas, createTextLogic, explorePaths, getAcceptedEvents, getAgentMessages, getStateMeta, inspectTransitions, lintAgentMachine, messagesSchema, parseAgentEvent, persistSnapshot, provideExecutors, runAgent, runAgentToCompletion, setupAgent, simulateAgent, systemMessage, toolMessage, traceTransitions, userMessage };
821
+ //#region src/trajectory.d.ts
822
+ /** An event-shaped trajectory item: anything with a string `type`. */
823
+ interface TrajectoryEvent {
824
+ type: string;
825
+ [key: string]: unknown;
826
+ }
827
+ /**
828
+ * One item in a trajectory, on either side of the comparison:
829
+ *
830
+ * - a state value — `'drafting'`, a dot path `'review.editing'`, or the nested
831
+ * object XState reports (`{ review: 'editing' }`),
832
+ * - an event — an {@link AgentLogEntry} from `result.events`, a bare event
833
+ * object, or just the event type as a string,
834
+ * - a machine snapshot, whose `value` is used.
835
+ */
836
+ type TrajectoryItem = StateValue | AgentLogEntry | TrajectoryEvent | {
837
+ value: StateValue;
838
+ };
839
+ /** Options for {@link matchesTrajectory}. */
840
+ interface MatchTrajectoryOptions {
841
+ /**
842
+ * Require the trajectories to be equal: same length, item for item. Default
843
+ * `false` — expected items must appear in `actual` in order, gaps allowed.
844
+ */
845
+ exact?: boolean;
846
+ }
847
+ /** The first expected item that could not be found. */
848
+ interface TrajectoryMiss {
849
+ /** Its position in `expected`. */
850
+ index: number;
851
+ /** The expected item itself. */
852
+ expected: TrajectoryItem;
853
+ /** Where the search for it started in `actual` (everything before was already consumed). */
854
+ searchedFrom: number;
855
+ }
856
+ /**
857
+ * The result of {@link matchesTrajectory}: a boolean for tests, plus enough
858
+ * detail for a scorer's partial credit and a failure message's diagnosis.
859
+ */
860
+ interface TrajectoryMatch {
861
+ /** Every expected item was found, in order (and, in `exact` mode, nothing else). */
862
+ matched: boolean;
863
+ /** How many expected items were matched before the first miss. */
864
+ matchedCount: number;
865
+ /** `expected.length`, so a scorer can compute its own ratio. */
866
+ expectedCount: number;
867
+ /** Partial credit, 0..1. `1` for an empty expectation. */
868
+ score: number;
869
+ /** Absent when `matched`. */
870
+ firstMiss?: TrajectoryMiss;
871
+ }
872
+ /**
873
+ * Matches a run's trajectory against an expected one.
874
+ *
875
+ * Both trajectories may be state values (collected from `onTransition`) or
876
+ * events (`result.events`, whose {@link AgentLogEntry} envelopes are unwrapped);
877
+ * items are compared by shape, so `['prompting', 'drafting']` scores a state
878
+ * path and `['PROMPT_SUBMITTED', 'SEND']` scores an event log with the same
879
+ * call.
880
+ *
881
+ * Semantics are an ordered subsequence: every expected item must appear in
882
+ * `actual`, in order, with gaps allowed. Pass `{ exact: true }` to require
883
+ * equality instead.
884
+ *
885
+ * @example Trajectory assertions in a test
886
+ * ```ts
887
+ * const statePath: unknown[] = [];
888
+ * const result = await runAgent(machine, {
889
+ * input,
890
+ * executors,
891
+ * onTransition: (snapshot) => statePath.push(snapshot.value),
892
+ * });
893
+ *
894
+ * const path = matchesTrajectory(statePath, ['prompting', 'drafting', 'sent']);
895
+ * expect(path.matched, JSON.stringify(path.firstMiss)).toBe(true);
896
+ * expect(matchesTrajectory(result.events, ['PROMPT_SUBMITTED', 'SEND']).matched).toBe(true);
897
+ * ```
898
+ *
899
+ * @example Partial credit in an eval scorer
900
+ * ```ts
901
+ * const match = matchesTrajectory(output.statePath, expected.statePath);
902
+ * return { name: 'state_path', score: match.score, metadata: { ...match.firstMiss } };
903
+ * ```
904
+ */
905
+ declare function matchesTrajectory(actual: readonly unknown[], expected: readonly TrajectoryItem[], options?: MatchTrajectoryOptions): TrajectoryMatch;
906
+ //#endregion
907
+ //#region src/scripted-executors.d.ts
908
+ /**
909
+ * A scripted `decide` answer: either the {@link ChosenEvent} itself (an object
910
+ * with a string `type`), or the executor envelope `{ event, reason?, usage? }`
911
+ * when the entry also reports a `reason` or token `usage`.
912
+ */
913
+ type ScriptedDecisionValue = ChosenEvent | {
914
+ event: ChosenEvent;
915
+ reason?: string;
916
+ usage?: AgentCallUsage;
917
+ [key: string]: unknown;
918
+ };
919
+ /**
920
+ * One entry in the `decisions` queue: a scripted answer, or a function of the
921
+ * {@link AgentDecisionRequest} returning one (for choices that depend on the
922
+ * prompt, the candidate `events`, or the prior failed `attempts`).
923
+ */
924
+ type ScriptedDecisionEntry = ScriptedDecisionValue | ((request: AgentDecisionRequest) => ScriptedDecisionValue | PromiseLike<ScriptedDecisionValue>);
925
+ /**
926
+ * One entry in the `text` queue: the request's output value (a string, or the
927
+ * object a structured request declares), or a function of the
928
+ * {@link AgentTextRequest} returning one.
929
+ *
930
+ * An entry is taken as the raw executor envelope (instead of the value itself)
931
+ * only when its OWN keys are an `output` plus, optionally, `usage`/`raw` —
932
+ * that is how an entry reports token `usage`. Anything else, including an
933
+ * object that merely happens to have an `output` key alongside its own data
934
+ * (`{ output: 'draft', confidence: 0.9 }`), is the output value. For a
935
+ * structured request whose declared output is exactly `{ output }` (or
936
+ * `{ output, usage }`), wrap it once more: `{ output: { output: '…' } }`.
937
+ */
938
+ type ScriptedTextEntry = ((request: AgentTextRequest, info?: AgentRequestExecutorInfo) => unknown) | string | number | boolean | null | object;
939
+ /** The script {@link createScriptedExecutors} plays back. */
940
+ interface ScriptedExecutorsScript {
941
+ /** Answers for `decide` (and `agent.plan`) requests, consumed in order. */
942
+ decisions?: ScriptedDecisionEntry[];
943
+ /** Answers for text requests, consumed in order. `generateText` and `streamText` share this one queue. */
944
+ text?: ScriptedTextEntry[];
945
+ }
946
+ /**
947
+ * Keyless executors that replay a script instead of calling a model. Every
948
+ * slot is provided, so any machine binds; a request with no entry left throws a
949
+ * descriptive error naming what was pending.
950
+ *
951
+ * Queues are consumed FIFO and are copied on creation, so the caller's arrays
952
+ * are never mutated and each call builds a fresh, independent playthrough.
953
+ * Entries may be plain values or functions of the request, which is how one
954
+ * script serves a machine that loops or branches: route on `request.name` (the
955
+ * `setupAgent({ requests })` key) or on the decision's candidate `events`.
956
+ *
957
+ * @example
958
+ * ```ts
959
+ * const result = await runAgent(moderationMachine, {
960
+ * input: { comment: 'honestly this update is terrible', trust: 20 },
961
+ * executors: createScriptedExecutors({
962
+ * decisions: [{ type: 'FLAG', reason: 'Borderline tone.' }],
963
+ * }),
964
+ * });
965
+ * ```
966
+ *
967
+ * @example Dynamic entries
968
+ * ```ts
969
+ * createScriptedExecutors({
970
+ * text: [(request) => `Draft about ${request.prompt}`],
971
+ * decisions: [(request) => ({ type: request.events[0]!.type })],
972
+ * });
973
+ * ```
974
+ */
975
+ declare function createScriptedExecutors(script?: ScriptedExecutorsScript): Required<AgentRequestExecutors>;
976
+ //#endregion
977
+ //#region src/seam.d.ts
978
+ /**
979
+ * Which model call is under test: the Nth call addressed either by request
980
+ * `name` (the `setupAgent({ requests })` key or `createTextLogic({ name })`,
981
+ * the better developer handle) or by `model` key (the `defineModels` key) for
982
+ * requests that carry no name.
983
+ */
984
+ type SeamRef = {
985
+ /** The request's registered `name`. */request: string;
986
+ model?: undefined; /** 0-based occurrence among the calls matching this key. Default `0`. */
987
+ occurrence?: number;
988
+ } | {
989
+ /** The `defineModels` key the request names. */model: string;
990
+ request?: undefined; /** 0-based occurrence among the calls matching this key. Default `0`. */
991
+ occurrence?: number;
992
+ };
993
+ /**
994
+ * One idle pause, handed to {@link RunSeamOptions.respond} so the simulated
995
+ * user answers off the machine's own state rather than a fixed transcript — a
996
+ * live seam may branch differently, and a reactive policy scores that run
997
+ * instead of crashing on it.
998
+ */
999
+ interface SeamTurn<TMachine extends AnyStateMachine> {
1000
+ /** The idle snapshot to answer. */
1001
+ snapshot: SnapshotFrom<TMachine>;
1002
+ /** Its state value, for a `switch` on flat machines. */
1003
+ state: StateValue;
1004
+ /** The merged `meta` of the active state(s) — e.g. a declared `interaction`. */
1005
+ meta: Record<string, unknown>;
1006
+ /** 0-based index of this pause within the run. */
1007
+ turn: number;
1008
+ /** The `idle` result that produced the pause. */
1009
+ result: RunAgentResult<TMachine>;
1010
+ }
1011
+ /** One side of the seam: a trajectory pair ready for `matchesTrajectory`. */
1012
+ interface SeamSlice {
1013
+ /** State values entered on this side of the seam, in order. */
1014
+ statePath: StateValue[];
1015
+ /** Replayable log entries on this side of the seam, in order. */
1016
+ events: AgentLogEntry[];
1017
+ }
1018
+ /** Options for {@link runSeam}. */
1019
+ interface RunSeamOptions<TMachine extends AnyStateMachine> {
1020
+ /** Machine input, passed straight through to `runAgent`. */
1021
+ input?: InputFrom<TMachine>;
1022
+ /**
1023
+ * The call plan: scripted answers per key, consumed in order. A key is a
1024
+ * request `name` when one is scripted under it, else a `model` key, so a
1025
+ * machine whose requests are named routes by name and an unnamed one routes
1026
+ * by model.
1027
+ *
1028
+ * Entries follow {@link ScriptedTextEntry} conventions (a value, an
1029
+ * `{ output, usage? }` envelope, or a function of the request). The LAST
1030
+ * entry of a queue repeats, so a live seam that sends the run down a longer
1031
+ * branch still finds an answer instead of running dry.
1032
+ */
1033
+ scripts?: Record<string, ScriptedTextEntry[]>;
1034
+ /** The call under test. */
1035
+ seam: SeamRef;
1036
+ /**
1037
+ * The executor for the seam — the real model, a candidate prompt, anything
1038
+ * request-shaped. Omit to run the seam scripted too: the whole seam run is
1039
+ * then keyless and deterministic.
1040
+ */
1041
+ candidate?: AgentRequestExecutors["generateText"];
1042
+ /**
1043
+ * The simulated user. Called at every idle pause; return the event to send,
1044
+ * or `null`/`undefined` to stop the run there. Omitted, the run stops at the
1045
+ * first idle pause.
1046
+ */
1047
+ respond?: (turn: SeamTurn<TMachine>) => EventFromLogic<TMachine> | null | undefined;
1048
+ /** Maximum idle pauses to answer before stopping. Default `12`. */
1049
+ maxTurns?: number;
1050
+ /**
1051
+ * Base executors merged UNDER the seam routing — supply `decide` (e.g. from
1052
+ * `createScriptedExecutors({ decisions })`) for a machine that also decides.
1053
+ * Text slots are always owned by the routing.
1054
+ */
1055
+ executors?: Partial<AgentRequestExecutors>;
1056
+ /** Passed through to `runAgent`: the deterministic idle-state predicate. */
1057
+ isSuspended?: RunAgentOptions<TMachine>["isSuspended"];
1058
+ /** Passed through to `runAgent`: actor implementations merged onto the machine. */
1059
+ actors?: RunAgentOptions<TMachine>["actors"];
1060
+ }
1061
+ /** What {@link runSeam} returns: the seam's own answer, plus the run it caused. */
1062
+ interface RunSeamResult<TMachine extends AnyStateMachine> {
1063
+ /**
1064
+ * The final `runAgent` result. Its `events` are the WHOLE run's log (every
1065
+ * leg's entries), while `usage` accounts only for the last leg.
1066
+ */
1067
+ result: RunAgentResult<TMachine>;
1068
+ /** What the seam call returned, or `undefined` when the run never reached it. */
1069
+ seamOutput: unknown;
1070
+ /** Model calls made before the seam, or `-1` when the run never reached it. */
1071
+ callsBeforeSeam: number;
1072
+ /** Everything up to the seam's own effect completion. */
1073
+ before: SeamSlice;
1074
+ /**
1075
+ * Everything from the seam's own effect completion onward — the branch the
1076
+ * seam caused, and the score. Empty when the run never reached the seam.
1077
+ */
1078
+ after: SeamSlice;
1079
+ }
1080
+ /**
1081
+ * Runs a machine end to end with one model call under test, and slices the run
1082
+ * at that call.
1083
+ *
1084
+ * The `before`/`after` slices are the point: `after.statePath` is the branch
1085
+ * the seam chose and `after.events` is the same question against the durable
1086
+ * log, both ready for `matchesTrajectory`. The state slice splits where the
1087
+ * state path stood when the seam answered; the event slice splits at the
1088
+ * seam's own effect completion (the first `xstate.done.*`/`xstate.error.*`
1089
+ * entry appended after the call was made).
1090
+ *
1091
+ * @example Keyless: the seam is scripted too, so the whole thing runs offline.
1092
+ * ```ts
1093
+ * const run = await runSeam(emailDrafter, {
1094
+ * scripts: { promptEvaluator: [vague, complete], emailDrafter: [draft] },
1095
+ * seam: { request: 'evaluatePrompt' },
1096
+ * respond: ({ state }) => (state === 'prompting' ? { type: 'PROMPT_SUBMITTED', prompt } : null),
1097
+ * });
1098
+ *
1099
+ * matchesTrajectory(run.after.statePath, ['needsMoreInfo', 'drafting']);
1100
+ * ```
1101
+ *
1102
+ * @example A candidate prompt at the seam, scored against the same rows.
1103
+ * ```ts
1104
+ * const { generateText } = createAiSdkExecutors({ models });
1105
+ * const run = await runSeam(emailDrafter, { ...row, candidate: generateText });
1106
+ * ```
1107
+ */
1108
+ declare function runSeam<TMachine extends AnyStateMachine>(machine: TMachine, options: RunSeamOptions<TMachine>): Promise<RunSeamResult<TMachine>>;
1109
+ //#endregion
1110
+ //#region src/utils.d.ts
1111
+ /**
1112
+ * Deep-clones a snapshot to a plain-JSON value via a `JSON` round-trip, the
1113
+ * shape you persist and later feed back to `runAgent({ snapshot })`. Asserts
1114
+ * JSON-serializability: functions, `undefined`, and other non-JSON values are
1115
+ * dropped or throw exactly as `JSON.stringify`/`JSON.parse` would. Returns a
1116
+ * plain-JSON deep clone, not a live snapshot.
1117
+ */
1118
+ declare function persistSnapshot<TSnapshot>(snapshot: TSnapshot): TSnapshot;
1119
+ /**
1120
+ * A stable, dependency-free structural fingerprint of a machine — a short hex
1121
+ * `djb2` hash over its **structural** config only: state ids/nesting, transition
1122
+ * event types and targets, invoke `src`s, `initial`, and any other serializable
1123
+ * config fields. Function values (context/output builders, prompts, inline
1124
+ * guards/actions) are excluded entirely, so two machines that differ only in
1125
+ * their prompts or executors hash identically; adding/removing/retargeting a
1126
+ * state or transition changes the hash.
1127
+ *
1128
+ * Used by {@link runAgent} to stamp settled snapshots with a `version` and to
1129
+ * detect a structurally-edited machine on resume. It is a change detector, not
1130
+ * a cryptographic digest — collisions are possible but unlikely for real
1131
+ * configs. Pass an explicit `machineVersion` to `runAgent` to override it.
1132
+ */
1133
+ declare function getMachineStructuralHash(machine: AnyStateMachine): string;
1134
+ /** Builds a {@link UserMessage} from a string or multimodal content parts. */
1135
+ declare function userMessage(content: string | Array<TextPart | ImagePart | FilePart>): UserMessage;
1136
+ /** Builds an {@link AssistantMessage} from a string or content parts (text, files, tool calls/results). */
1137
+ declare function assistantMessage(content: string | Array<TextPart | FilePart | ToolCallPart | ToolResultPart>): AssistantMessage;
1138
+ /** Builds a {@link SystemMessage}. */
1139
+ declare function systemMessage(content: string): SystemMessage;
1140
+ /** Builds a {@link ToolMessage} from one or more tool-result parts. */
1141
+ declare function toolMessage(content: Array<ToolResultPart>): ToolMessage;
1142
+ type MetaOfSnapshot<TSnapshot extends {
1143
+ getMeta(): Record<string, unknown>;
1144
+ }> = NonNullable<ReturnType<TSnapshot["getMeta"]>[keyof ReturnType<TSnapshot["getMeta"]>]>;
1145
+ /**
1146
+ * Returns the merged `meta` of a snapshot's active state(s) — the typed
1147
+ * replacement for the `Object.values(snapshot.getMeta())[0]` dance.
1148
+ *
1149
+ * `snapshot.getMeta()` is keyed by state id; a leaf machine has one active
1150
+ * state, but parallel/nested machines can have several. This shallow-merges
1151
+ * every active state's meta into one object (later/deeper entries win) and
1152
+ * returns `{}` when no active state declares meta.
1153
+ *
1154
+ * The return type is recovered from the snapshot's own `getMeta()` type, so a
1155
+ * schema-typed machine (`setupAgent({ meta })`) yields the meta schema's
1156
+ * output type. Pass an explicit `TMeta` to override when the snapshot is
1157
+ * untyped (e.g. `AnyMachineSnapshot`).
1158
+ *
1159
+ * @example HITL: read the current state's interaction protocol off an idle
1160
+ * snapshot to render for a human.
1161
+ * ```ts
1162
+ * const { interaction } = getStateMeta(result.snapshot);
1163
+ * ```
1164
+ */
1165
+ declare function getStateMeta<TSnapshot extends {
1166
+ getMeta(): Record<string, unknown>;
1167
+ } = AnyMachineSnapshot, TMeta = MetaOfSnapshot<TSnapshot>>(snapshot: TSnapshot): Partial<TMeta>;
1168
+ /**
1169
+ * Reads the run-owned message log off a snapshot settled by a `runAgent` call
1170
+ * that used `getRequests` (or `options.messages`) — the typed replacement for
1171
+ * the `(snapshot as { messages?: AgentMessage[] }).messages` cast. runAgent
1172
+ * stamps the log as a plain enumerable `messages` property (like `agentMeta`),
1173
+ * so it survives a JSON persist/resume round-trip; this accessor works on the
1174
+ * live settled snapshot and on a JSON-parsed persisted one alike. Returns `[]`
1175
+ * when no log was stamped (e.g. a default invoke-driven run).
1176
+ *
1177
+ * The write path is `runAgent(..., { messages })`: an explicit seed that
1178
+ * overrides the resume snapshot's stamped log (fold in a user reply on
1179
+ * resume, or start a run with prior history).
1180
+ */
1181
+ declare function getAgentMessages(snapshot: unknown): AgentMessage[];
1182
+ /**
1183
+ * Structural guard for a {@link StandardSchemaV1}: `true` when `value` carries
1184
+ * the `~standard` marker. Used to tell an already-schema'd tool `inputSchema`
1185
+ * (a Zod/Valibot/… schema) apart from an SDK-specific schema wrapper that core
1186
+ * can't read directly — see the `ai-sdk` tool pass-through.
1187
+ */
1188
+ declare function isStandardSchema(value: unknown): value is StandardSchemaV1;
1189
+ /**
1190
+ * Pulls the JSON Schema off a {@link StandardSchemaV1} via its optional
1191
+ * `~standard.jsonSchema.input()` extension (implemented by e.g. Zod v4's
1192
+ * `z.toJSONSchema`), awaiting it when the producer is async. Returns
1193
+ * `undefined` when the schema doesn't expose the extension. Use this to build
1194
+ * a provider request's `response_format`/tool `parameters` from a schema.
1195
+ */
1196
+ declare function getJsonSchema(schema?: StandardSchemaV1): Promise<Record<string, unknown> | undefined>;
1197
+ /**
1198
+ * Synchronous variant of {@link getJsonSchema}, for call sites that can't
1199
+ * await (building tool/event descriptors inline). An async JSON Schema
1200
+ * producer is treated as absent (returns `undefined`) — in practice Zod's
1201
+ * `z.toJSONSchema` resolves synchronously.
1202
+ */
1203
+ declare function getJsonSchemaSync(schema?: StandardSchemaV1): Record<string, unknown> | undefined;
1204
+ //#endregion
1205
+ export { AGENT_EVENT_SCHEMA_VERSION, AGENT_INIT_EVENT_TYPE, AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, type AgentActorSession, type AgentCallUsage, type AgentDecisionExecutor, AgentDecisionExhaustedError, type AgentDecisionInput, type AgentDecisionRequest, type AgentEffect, type AgentEffectDiff, AgentError, type AgentEventDescriptor, AgentEventLogConflictError, type AgentEventLogDiff, type AgentEventLogStore, type AgentEventToolNameResolver, type AgentExecutorTextRequest, AgentIdleError, AgentIllegalResumeEventError, type AgentLintDiagnostic, AgentLintError, type AgentLintSeverity, type AgentLogEntry, type AgentLogPatchOperation, type AgentLogVerification, type AgentMessage, type AgentMessageInfo, type AgentModelRef, type AgentOutputMode, type AgentPathReport, type AgentPathTerminal, type AgentPlanInput, type AgentPlanOutput, type AgentPlanRequest, AgentReplayDivergenceError, AgentReplayMachineMismatchError, type AgentRequest, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestOptions, type AgentRequestSource, type AgentRun, type AgentRunMeta, type AgentSchemaPack, type AgentSnapshotStore, AgentSnapshotVersionMismatchError, type AgentStateRequest, type AgentStepRequest, type AgentTextRequest, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentTools, type AgentTraceEvent, type AgentUsage, type AgentUsageEvent, type AgentUsageEventPayload, type AgentUserInput, type AgentUserInputExecutor, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AiSdkShapedStreamResult, type AiSdkShapedTextResult, type AllowedEvents, type AssertAgentMachineOptions, type AssistantMessage, type CanReachResult, type ChosenEvent, type CreateReplayEntryOptions, type DecisionAttempt, type DecisionLogicConfig, type ExplorePathsOptions, type FilePart, type FromConfigOptions, type FromConfigResult, type GenerateResult, type GetAgentEffectsOptions, type ImagePart, type InferOutput, type InspectedActorRef, type JsonSerializableTraceEvent, type JsonValue, type LintAgentMachineOptions, type MatchTrajectoryOptions, NonSerializableAgentEventError, PLAN_DONE_EVENT_TYPE, type PendingUserInput, type PlanLogic, type ProvideExecutorsOptions, type ReplayOptions, type ReplayResult, type ResolveDecisionOptions, type RunAgentErrorCause, type RunAgentOptions, type RunAgentResult, type RunSeamOptions, type RunSeamResult, type SchemaCompiler, type ScriptedDecisionEntry, type ScriptedDecisionValue, type ScriptedExecutorsScript, type ScriptedTextEntry, type SeamRef, type SeamSlice, type SeamTurn, type SimulateAgentOptions, type SimulateAgentResult, type SimulationScript, type SimulationTrailEntry, type StandardSchemaV1, type StructuredOutputEnvelope, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultPart, type TrajectoryEvent, type TrajectoryItem, type TrajectoryMatch, type TrajectoryMiss, type UserMessage, type WithAgentUsageEvent, appendMessages, assertAgentLogEntry, assertAgentMachine, assertEventLogStoreConformance, assertJsonSerializable, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentActor, createAgentRun, createAgentSchemas, createInMemoryEventLogStore, createReplayEntry, createScriptedExecutors, createTextLogic, diffEventLogs, executeAgentRequest, explorePaths, generateResult, getAcceptedEvents, getAgentEffects, getAgentMessages, getAgentOutputMode, getCallUsage, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getStateMeta, initEntry, inspectTransitions, isStandardSchema, lintAgentMachine, matchesTrajectory, messagesSchema, parseAgentEvent, parseModelRef, parseOutput, parseStructuredEnvelope, persistSnapshot, provideExecutors, renderDecisionAttempts, replay, resolveDecision, runAgent, runSeam, serializeTraceEvent, setupAgent, simulateAgent, systemMessage, toolMessage, traceTransitions, userMessage, verifyReplay };