@statelyai/agent 2.0.0-alpha.22 → 2.0.0-alpha.23

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 (48) hide show
  1. package/dist/ai-sdk.cjs +53 -25
  2. package/dist/ai-sdk.d.cts +20 -12
  3. package/dist/ai-sdk.d.mts +20 -12
  4. package/dist/ai-sdk.mjs +53 -25
  5. package/dist/{decision-DxSTqzgZ.mjs → decision-BBZ2jMO1.mjs} +444 -79
  6. package/dist/{decision-1o45_ZrS.cjs → decision-Cv6SfNWl.cjs} +525 -94
  7. package/dist/index.cjs +2224 -1032
  8. package/dist/index.d.cts +413 -275
  9. package/dist/index.d.mts +413 -275
  10. package/dist/index.mjs +2163 -983
  11. package/dist/machines.cjs +30 -2
  12. package/dist/machines.d.cts +1 -1
  13. package/dist/machines.d.mts +1 -1
  14. package/dist/machines.mjs +30 -2
  15. package/dist/openai.cjs +447 -0
  16. package/dist/openai.d.cts +177 -0
  17. package/dist/openai.d.mts +177 -0
  18. package/dist/openai.mjs +437 -0
  19. package/dist/otel.cjs +3 -6
  20. package/dist/otel.d.cts +1 -1
  21. package/dist/otel.d.mts +1 -1
  22. package/dist/otel.mjs +3 -6
  23. package/dist/run-agent-Ck7Sa3Tb.d.mts +968 -0
  24. package/dist/run-agent-DWqA8KiI.d.cts +968 -0
  25. package/dist/setup-agent-CeO2fARv.mjs +639 -0
  26. package/dist/setup-agent-Dl2VELLi.cjs +663 -0
  27. package/dist/{text-logic-BaxPrcLk.d.cts → text-logic-C7bSnH_B.d.cts} +195 -44
  28. package/dist/{text-logic-DhfFWzu9.d.mts → text-logic-DJBK3LbG.d.mts} +195 -44
  29. package/dist/{types-DSdj2tGs.d.cts → types-CjHk5OdH.d.cts} +4 -19
  30. package/dist/{types-CvWRGFxP.d.mts → types-DWA6X9R-.d.mts} +4 -19
  31. package/package.json +17 -21
  32. package/readme.md +32 -17
  33. package/dist/errors-BQRk9eiZ.d.cts +0 -19
  34. package/dist/errors-C9rxnWbX.d.mts +0 -19
  35. package/dist/errors-CeSXQx0v.mjs +0 -23
  36. package/dist/errors-DUBBzRLP.cjs +0 -28
  37. package/dist/event-log-store-Bz7HDBkE.d.cts +0 -145
  38. package/dist/event-log-store-DmIDosD6.mjs +0 -427
  39. package/dist/event-log-store-a_TKy1gk.cjs +0 -468
  40. package/dist/event-log-store-hrA1vqtN.d.mts +0 -145
  41. package/dist/run-agent-0fpEZ1wJ.d.mts +0 -1098
  42. package/dist/run-agent-Zbkx7XP8.d.cts +0 -1098
  43. package/dist/setup-agent-DkCTy5Eu.cjs +0 -1707
  44. package/dist/setup-agent-nSFYrNTP.mjs +0 -1587
  45. package/dist/sqlite.cjs +0 -129
  46. package/dist/sqlite.d.cts +0 -57
  47. package/dist/sqlite.d.mts +0 -57
  48. package/dist/sqlite.mjs +0 -127
package/dist/index.d.cts CHANGED
@@ -1,50 +1,104 @@
1
- import { C as ToolResultPart, S as ToolMessage, T as WithAgentInputSchema, _ as NormalizedEventSchemas, a as AgentToolChoice, b as TextPart, c as AgentTools, d as ChosenEvent, f as EventUnion, g as InferOutput, h as InferInput, 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 StandardSchemaV1, w as UserMessage, x as ToolCallPart, y as SystemMessage } from "./types-DSdj2tGs.cjs";
2
- import { t as AgentError } from "./errors-BQRk9eiZ.cjs";
3
- import { A as AgentDecisionExecutor, B as resolveDecision, C as buildEnvelopeSchema, D as parseModelRef, E as getCallUsage, F as DecisionLogic, G as AgentSchemas, H as AgentEventToolNameResolver, I as DecisionLogicConfig, K as getAcceptedEvents, L as ResolveDecisionOptions, M as AgentDecisionInput, N as AgentDecisionRequest, O as parseOutput, P as DecisionAttempt, R as createDecisionLogic, S as bindRequestExecutor, T as getAgentOutputMode, U as AgentRequestOptions, V as AgentEventDescriptor, W as AgentRequestSource, _ 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 AgentDecisionExhaustedError, k as parseStructuredEnvelope, 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 renderDecisionAttempts } from "./text-logic-BaxPrcLk.cjs";
4
- import { a as AgentLogVerification, c as assertAgentLogEntry, d as assertEventLogStoreConformance, i as AgentLogEntry, l as assertJsonSerializable, n as AgentEventLogConflictError, o as JsonValue, r as AgentEventLogStore, s as NonSerializableAgentEventError, t as AGENT_EVENT_SCHEMA_VERSION, u as createInMemoryEventLogStore } from "./event-log-store-Bz7HDBkE.cjs";
5
- import { A as AgentRequest, B as AgentReplayMachineMismatchError, C as getSnapshotNodes, D as serializeTraceEvent, E as runAgent, F as AgentEffect, G as ReplayResult, H as CreateReplayEntryOptions, I as AgentEffectDiff, J as getAgentEffects, K as createReplayEntry, L as AgentEventLogDiff, M as executeAgentRequest, N as AGENT_INIT_EVENT_TYPE, O as traceTransitions, P as AGENT_USAGE_EVENT_TYPE, R as AgentLogPatchOperation, S as generateResult, T as inspectTransitions, U as GetAgentEffectsOptions, V as AgentUsageEvent, W as ReplayOptions, X as replay, Y as initEntry, _ as PendingUserInput, a as AgentInputFrom, b as RunAgentResult, c as AgentRunMeta, d as AgentTraceEvent, f as AgentUserInputExecutor, g as JsonSerializableTraceEvent, h as InspectedActorRef, i as AgentIllegalResumeEventError, j as AgentStepRequest, k as AgentStateRequest, l as AgentSnapshotNode, m as GetSnapshotRequestsOptions, n as AgentActorSession, o as AgentMaxModelCallsExceededError, p as GenerateResult, q as diffEventLogs, r as AgentIdleError, s as AgentMessageInfo, t as AGENT_TRACE_SCHEMA_VERSION, u as AgentSnapshotVersionMismatchError, v as RunAgentErrorCause, w as getSnapshotRequests, x as createAgentActor, y as RunAgentOptions, z as AgentReplayDivergenceError } from "./run-agent-Zbkx7XP8.cjs";
6
- import { AnyActorLogic, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, EventFromLogic, EventObject, InputFrom, MachineContext, MetaObject, NonReducibleUnknown, OutputFrom, SetupReturnFromConfig, SetupStateSchema, SnapshotFrom, StateValue } from "xstate";
1
+ import { C as UserMessage, S as ToolResultPart, _ as StandardSchemaV1, a as AgentToolDescriptor, b as ToolCallPart, c as AllowedEvents, d as EventUnion, f as FilePart, g as NormalizedEventSchemas, h as InferOutput, i as AgentToolChoice, l as AssistantMessage, m as InferInput, n as AgentMessage, o as AgentToolExecute, p as ImagePart, r as AgentTool, s as AgentTools, t as AgentEventSchemaInputMap, u as ChosenEvent, v as SystemMessage, w as WithAgentInputSchema, x as ToolMessage, y as TextPart } from "./types-CjHk5OdH.cjs";
2
+ import { $ as getAcceptedEvents, A as parseOutput, B as DecisionLogicConfig, C as bindRequestExecutor, D as getCallFinishReason, E as getAgentOutputMode, F as AgentDecisionRequest, G as resolveDecision, H as createDecisionLogic, I as AgentExecutorDecisionRequest, J as AgentInvalidEventPayloadError, K as AgentEventDescriptor, L as CreateDecisionRequestOptions, M as AgentDecisionExecutor, N as AgentDecisionExhaustedError, O as getCallUsage, P as AgentDecisionInput, Q as EventFromSnapshot, R as DecisionAttempt, S as TextLogicExecutor, T as createTextLogic, U as createDecisionRequest, V as ResolveDecisionOptions, W as renderDecisionAttempts, X as AgentRequestSource, Y as AgentRequestOptions, Z as AgentSchemas, _ as BuiltinAgentActors, a as AgentModelRef, b as TextLogicConfig, c as AgentRequestExecutorInfo, d as AgentRequestMode, et as parseAgentEvent, f as AgentTextRequest, g as AiSdkShapedTextResult, h as AiSdkShapedStreamResult, i as AgentModelMap, j as parseStructuredEnvelope, k as parseModelRef, l as AgentRequestExecutorResult, m as AgentUserInput, n as AgentExecutorTextRequest, nt as AgentTruncatedError, o as AgentOutputMode, p as AgentUsage, q as AgentEventToolNameResolver, r as AgentFinishReason, s as AgentRequestExecutor, t as AgentCallUsage, tt as AgentError, u as AgentRequestExecutors, v as StructuredOutputEnvelope, w as buildEnvelopeSchema, x as TextLogicExecuteArgs, y as TextLogic, z as DecisionLogic } from "./text-logic-C7bSnH_B.cjs";
3
+ import { $ as AGENT_USAGE_EVENT_TYPE, A as AgentMachineVersionMismatchError, B as assertJsonSerializable, C as AGENT_EVENT_SCHEMA_VERSION, D as AgentLogEntry, E as AgentInitEvent, F as NonSerializableAgentEventError, G as getUsageFromEvents, H as forkEventLog, I as ReplayOptions, J as replay, K as initEntry, L as ReplayResult, M as AgentReplayDivergenceError, N as CreateReplayEntryOptions, O as AgentLogInit, P as JsonValue, Q as executeAgentRequest, R as agentCallOccurrence, S as createInMemoryEventLogStore, T as AgentEventLogError, U as getLogExecutionId, V as createReplayEntry, W as getSnapshotStateHash, X as AgentRequest, Y as validateReplayEntries, Z as AgentStepRequest, _ as runAgent, a as AgentSnapshotDivergedError, b as AgentEventLogConflictError, c as AgentUserInputExecutor, d as PendingUserInput, et as AgentUsageEvent, f as RunAgentErrorCause, g as isAgentIdle, h as inspectTransitions, i as AgentRunMeta, j as AgentPersistedSnapshot, k as AgentLogVerification, l as InspectedActorRef, m as RunAgentResult, n as AgentInputFrom, o as AgentTraceEvent, p as RunAgentOptions, q as rebindActorSession, r as AgentMaxModelCallsExceededError, s as AgentTransitionHandler, t as AGENT_TRACE_SCHEMA_VERSION, u as JsonSerializableTraceEvent, v as serializeTraceEvent, w as AGENT_INIT_EVENT_TYPE, x as AgentEventLogStore, y as traceTransitions, z as assertAgentLogEntry } from "./run-agent-DWqA8KiI.cjs";
4
+ import { AnyActorLogic, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, ContextFrom, DoneActorEvent, EmittedFrom, EventFromLogic, EventObject, InputFrom, MachineContext, MetaObject, NonReducibleUnknown, OutputFrom, SetupReturnFromConfig, SetupStateSchema, SnapshotFrom, StateValue, StateValueFrom } from "xstate";
7
5
 
6
+ //#region src/type-helpers.d.ts
7
+ type SchemaAt<T, TKey extends PropertyKey> = T extends {
8
+ schemas: Record<TKey, infer TSchema extends StandardSchemaV1>;
9
+ } ? TSchema : never;
10
+ /** Machine context, or a setup's context-schema output. */
11
+ type ContextOf<T> = T extends AnyStateMachine ? ContextFrom<T> : InferOutput<SchemaAt<T, "context">>;
12
+ /** Machine input, or a setup's context-schema input. */
13
+ type InputOf<T> = T extends AnyStateMachine ? InputFrom<T> : InferInput<SchemaAt<T, "input">>;
14
+ /** Machine output, or a setup's output-schema output. */
15
+ type OutputOf<T> = T extends AnyStateMachine ? OutputFrom<T> : InferOutput<SchemaAt<T, "output">>;
16
+ /** Machine event union, or the event union declared by a setup. */
17
+ type EventOf<T> = T extends AnyStateMachine ? EventFromLogic<T> : T extends {
18
+ schemas: {
19
+ events: infer TEvents extends Record<string, StandardSchemaV1>;
20
+ };
21
+ } ? EventUnion<TEvents> : never;
22
+ /** Typed live XState snapshot for a machine. */
23
+ type SnapshotOf<TMachine extends AnyStateMachine> = SnapshotFrom<TMachine>;
24
+ /** Literal state-value union accepted by a machine snapshot's `matches`. */
25
+ type StateValueOf<TMachine extends AnyStateMachine> = StateValueFrom<TMachine>;
26
+ /** State/transition metadata declared by a setup or carried by a machine snapshot. */
27
+ type MetaOf<T> = T extends {
28
+ schemas: {
29
+ meta: infer TSchema extends StandardSchemaV1;
30
+ };
31
+ } ? InferOutput<TSchema> : T extends AnyStateMachine ? ReturnType<SnapshotFrom<T>["getMeta"]> extends Record<string, infer TMeta> ? TMeta : never : never;
32
+ /** Semantic request names registered on a `setupAgent(...)` result. */
33
+ type RequestNamesOf<T> = T extends {
34
+ requests: infer TRequests;
35
+ } ? keyof TRequests & string : never;
36
+ /**
37
+ * XState's canonical `xstate.done.actor` event, typed with a specific actor
38
+ * logic's output (and optionally its id). Use it to type a wildcard
39
+ * `'xstate.done.actor'` handler that reduces dynamically spawned children,
40
+ * where the machine's own event union cannot name them.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * 'xstate.done.actor': ({ context, event }) => {
45
+ * const { actorId, output } = event as DoneActorEventOf<typeof researchLogic>;
46
+ * }
47
+ * ```
48
+ */
49
+ type DoneActorEventOf<TLogic extends AnyActorLogic, TId extends string = string> = DoneActorEvent<OutputFrom<TLogic>, TId>;
50
+ //#endregion
8
51
  //#region src/messages.d.ts
52
+ /** Ordinary machine event emitted after a request returns framework-native messages. */
53
+ declare const AGENT_MESSAGES_EVENT_TYPE: "agent.messages";
54
+ interface AgentMessagesEvent<TMessage = unknown> extends EventObject {
55
+ type: typeof AGENT_MESSAGES_EVENT_TYPE;
56
+ /** Semantic request identity. */
57
+ request: string;
58
+ /** Invoke occurrence identity. */
59
+ actorId: string;
60
+ /** Messages exactly as returned by the executor/framework. */
61
+ messages: TMessage[];
62
+ }
63
+ type AgentMessagesEventPayload = Omit<AgentMessagesEvent, "type">;
9
64
  /**
10
- * Builds a transition-function result that appends one or more
11
- * {@link AgentMessage}s to a context's `messages` array. `resolve` is either
12
- * a message (or array of messages) or a function of `{ context, event }`
13
- * returning them; the returned function is meant to be used directly as (or
14
- * composed into) a transition's result, e.g. `on: { USER_REPLIED:
15
- * agent.appendMessages(({ event }) => userMessage(event.text)) }`. Requires
16
- * `messages: AgentMessage[]` on context — see {@link messagesSchema} for a
17
- * ready-made schema for that field.
65
+ * Appends framework-native messages from `agent.messages` to machine context.
66
+ * Put this on a top-level transition; no hidden transcript state is created.
18
67
  *
19
68
  * @example
20
69
  * ```ts
21
70
  * on: {
22
- * USER_REPLIED: appendMessages(({ event }) => userMessage(event.text)),
71
+ * 'agent.messages': appendMessages(),
23
72
  * }
24
73
  * ```
25
74
  */
26
- declare function appendMessages<TContext extends {
27
- messages: AgentMessage[];
28
- }, TEvent extends EventObject>(resolve: AgentMessage | AgentMessage[] | ((args: {
75
+ type AppendMessagesTransition = <TContext extends object>(args: {
29
76
  context: TContext;
30
- event: TEvent;
31
- }) => AgentMessage | AgentMessage[])): (args: {
32
- context: TContext;
33
- event: TEvent;
77
+ event: EventObject & Partial<Omit<AgentMessagesEvent, "type">>;
34
78
  }) => {
35
- context: {
36
- messages: AgentMessage[];
37
- };
79
+ context: Partial<TContext>;
38
80
  };
81
+ declare function appendMessages<TKey extends string = "messages">(options?: {
82
+ key?: TKey;
83
+ }): AppendMessagesTransition;
39
84
  /**
40
85
  * A {@link StandardSchemaV1} validating an `AgentMessage[]` context field —
41
86
  * checks that every message has a known `role` (`system`/`user`/`assistant`/
42
87
  * `tool`) and that `content` is either a string (where the role allows it) or
43
88
  * an array of role-appropriate parts whose required fields and media payloads
44
89
  * have the right runtime types (extra fields are allowed). Use it directly as
45
- * a context schema's `messages` field when authoring with `createAgentSchemas`.
90
+ * a context schema's `messages` field when authoring with `createAgentSchemas`
91
+ * or `fromConfig`. A zod object cannot nest a Standard Schema, so in a zod
92
+ * context schema write `z.custom<AgentMessage[]>(isAgentMessages)`, which runs
93
+ * this same validator (see {@link isAgentMessages}).
46
94
  */
47
95
  declare const messagesSchema: StandardSchemaV1<AgentMessage[]>;
96
+ /**
97
+ * Type guard over {@link messagesSchema}: `true` when `value` is a valid
98
+ * `AgentMessage[]`. The one-liner for zod context schemas:
99
+ * `messages: z.custom<AgentMessage[]>(isAgentMessages)`.
100
+ */
101
+ declare function isAgentMessages(value: unknown): value is AgentMessage[];
48
102
  //#endregion
49
103
  //#region src/workflow-config.d.ts
50
104
  type JsonSchemaObject = {
@@ -105,7 +159,7 @@ interface AgentWorkflowConfig {
105
159
  * snapshots idle deterministically instead of using its timing heuristic.
106
160
  * Every listed tag must appear in some state's `tags` — an unused tag is a
107
161
  * build-time error. A `fromConfig(config, { isIdle })` option takes
108
- * precedence; a `runAgent({ isIdle })` host override beats both.
162
+ * precedence over declarative `idleTags`.
109
163
  */
110
164
  idleTags?: string[];
111
165
  meta?: Record<string, unknown>;
@@ -245,16 +299,15 @@ interface FromConfigOptions {
245
299
  * the same machine-carried predicate `setupAgent({ isIdle })` declares
246
300
  * for TS-authored machines, registered here because a function cannot live
247
301
  * in the workflow config itself. Takes precedence over the config's
248
- * declarative {@link AgentWorkflowConfig.idleTags}; a
249
- * `runAgent({ isIdle })` host override beats both. Travels with the
250
- * machine through `machine.provide(...)`.
302
+ * declarative {@link AgentWorkflowConfig.idleTags}. Travels with the machine
303
+ * through `machine.provide(...)`.
251
304
  */
252
305
  isIdle?: (snapshot: AnyMachineSnapshot) => boolean;
253
306
  }
254
307
  //#endregion
255
308
  //#region src/setup-agent.d.ts
256
309
  type Constrain<T, TConstraint> = T extends TConstraint ? T : TConstraint;
257
- type ContextOf<TContextSchema extends StandardSchemaV1> = Constrain<InferOutput<TContextSchema>, MachineContext>;
310
+ type ContextOf$1<TContextSchema extends StandardSchemaV1> = Constrain<InferOutput<TContextSchema>, MachineContext>;
258
311
  type EventsOf<TEventSchemas extends AgentEventSchemaInputMap> = Constrain<EventUnion<TEventSchemas>, EventObject>;
259
312
  /**
260
313
  * The first argument a guard or delay source receives. `context` and `event`
@@ -265,7 +318,7 @@ type EventsOf<TEventSchemas extends AgentEventSchemaInputMap> = Constrain<EventU
265
318
  * real where the machine is built.
266
319
  */
267
320
  type AgentSourceArgs<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap> = {
268
- context: ContextOf<TContextSchema>;
321
+ context: ContextOf$1<TContextSchema>;
269
322
  event: EventsOf<TEventSchemas>;
270
323
  };
271
324
  /** Guard sources for `setupAgent({ guards })`, typed against the agent's own context and events. */
@@ -313,9 +366,12 @@ type AgentUsageEventPayload = Omit<AgentUsageEvent, "type">;
313
366
  * is typed (and autocompletes) without the machine declaring anything.
314
367
  * Idempotent: re-applying it to an already-registered map is a no-op.
315
368
  */
316
- type WithAgentUsageEvent<T extends AgentEventSchemaInputMap> = Omit<T, typeof AGENT_USAGE_EVENT_TYPE> & {
369
+ type WithAgentEvents<T extends AgentEventSchemaInputMap> = Omit<T, typeof AGENT_USAGE_EVENT_TYPE | typeof AGENT_MESSAGES_EVENT_TYPE> & {
317
370
  [AGENT_USAGE_EVENT_TYPE]: StandardSchemaV1<AgentUsageEventPayload>;
371
+ [AGENT_MESSAGES_EVENT_TYPE]: StandardSchemaV1<AgentMessagesEventPayload>;
318
372
  };
373
+ /** @deprecated Use {@link WithAgentEvents}. */
374
+ type WithAgentUsageEvent<T extends AgentEventSchemaInputMap> = WithAgentEvents<T>;
319
375
  /**
320
376
  * Builds a machine's {@link AgentSchemaPack} from a partial schema
321
377
  * declaration — only `context` is required; `events`/`input`/`output`/`meta`
@@ -372,43 +428,12 @@ type AgentSetupXStateConfig<TContextSchema extends StandardSchemaV1<Record<strin
372
428
  meta: TMetaSchema;
373
429
  } & AgentSetupEventsSchema<TEventSchemas> & AgentSetupEmittedSchema<TEmittedSchemas>;
374
430
  states?: TStateSchemas;
375
- actors: SetupActors<AgentSetupActors<AgentAllActors<TActors, TRequestSchemas>, Exclude<keyof TEventSchemas & string, typeof AGENT_USAGE_EVENT_TYPE>, AgentModelRef<TModels>>>;
431
+ actors: SetupActors<AgentSetupActors<AgentAllActors<TActors, TRequestSchemas>, Exclude<keyof TEventSchemas & string, typeof AGENT_USAGE_EVENT_TYPE | typeof AGENT_MESSAGES_EVENT_TYPE>, AgentModelRef<TModels>>>;
376
432
  actions?: NonNullable<AnySetupConfig["actions"]>;
377
433
  guards?: NonNullable<AnySetupConfig["guards"]>;
378
434
  delays?: NonNullable<AnySetupConfig["delays"]>;
379
435
  };
380
- /**
381
- * Field-level context-narrowing sugar for one `setupAgent({ states })` entry:
382
- * each `context` entry overrides that field's schema inside the state; every
383
- * other field keeps the base context schema. Sugar for the full xstate form —
384
- * `{ context: { draft: z.string() } }` resolves to
385
- * `{ schemas: { context: <base with draft: string> } }` — so only the fields
386
- * that change are declared, not the whole context schema.
387
- */
388
- interface AgentStateNarrowing {
389
- context: Record<string, StandardSchemaV1>;
390
- states?: Record<string, AgentSetupStateSchema>;
391
- }
392
- /** One `setupAgent({ states })` entry: xstate's {@link SetupStateSchema} full form, or the {@link AgentStateNarrowing} field-level sugar. */
393
- type AgentSetupStateSchema = SetupStateSchema | AgentStateNarrowing;
394
- type NarrowedContext<TContextSchema extends StandardSchemaV1, TFields extends Record<string, StandardSchemaV1>> = Omit<InferOutput<TContextSchema>, keyof TFields> & { [K in keyof TFields]: InferOutput<TFields[K]> };
395
- type ResolveAgentStateSchema<TContextSchema extends StandardSchemaV1, T> = T extends {
396
- context: infer TFields extends Record<string, StandardSchemaV1>;
397
- } ? {
398
- schemas: {
399
- context: StandardSchemaV1<NarrowedContext<TContextSchema, TFields>>;
400
- };
401
- } & (T extends {
402
- states: infer TChildren extends Record<string, AgentSetupStateSchema>;
403
- } ? {
404
- states: ResolveAgentStateSchemas<TContextSchema, TChildren>;
405
- } : {}) : T extends {
406
- states: infer TChildren extends Record<string, AgentSetupStateSchema>;
407
- } ? Omit<T, "states"> & {
408
- states: ResolveAgentStateSchemas<TContextSchema, TChildren>;
409
- } : T;
410
- type ResolveAgentStateSchemas<TContextSchema extends StandardSchemaV1, TStates extends Record<string, AgentSetupStateSchema>> = Constrain<{ [K in keyof TStates]: ResolveAgentStateSchema<TContextSchema, TStates[K]> }, Record<string, SetupStateSchema>>;
411
- 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>> = ({
436
+ 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, SetupStateSchema> = Record<string, SetupStateSchema>> = ({
412
437
  schemas: AgentSchemaPack<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>;
413
438
  } | AgentSchemaConfig<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>) & {
414
439
  models?: TModels;
@@ -417,9 +442,8 @@ type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string,
417
442
  * Per-state schemas, mirroring xstate's `setup({ states })`: narrow
418
443
  * `context` inside a state (invoke `input`, transition fns, final `output`)
419
444
  * — e.g. mark a field non-null in states only reachable after it is set.
420
- * Two forms per state: the {@link AgentStateNarrowing} sugar
421
- * (`{ context: { draft: z.string() } }` — only the fields that change) or
422
- * xstate's full `{ schemas: { context } }` with a complete context schema.
445
+ * Use xstate's native `{ schemas: { context } }` form with a complete
446
+ * context schema.
423
447
  */
424
448
  states?: TStateSchemas;
425
449
  requests?: AgentRequestInput<TRequestSchemas, AgentModelRef<TModels>>;
@@ -431,14 +455,14 @@ type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string,
431
455
  * human approval, an inbound webhook, …) — the machine's own declaration of
432
456
  * what "idle" means for it, so `runAgent` settles those snapshots idle
433
457
  * deterministically instead of using its timing heuristic. Travels with the
434
- * machine through `machine.provide(...)`. A `runAgent({ isIdle })` host
435
- * override takes precedence; with neither, `runAgent` falls back to the timing
436
- * heuristic. Declare your own signal — e.g. `(s) => s.hasTag('awaiting-review')`
437
- * or `(s) => getStateMeta(s).interaction !== undefined`.
458
+ * machine through `machine.provide(...)`. Without one, `runAgent` recognizes
459
+ * resting event-handling states and `meta.interaction` by structure. Use a
460
+ * predicate only for a more specialized machine-owned wait rule. Import and
461
+ * call `isAgentIdle(snapshot)` inside it when expanding the default rule.
438
462
  */
439
463
  isIdle?: (snapshot: AnyMachineSnapshot) => boolean;
440
464
  };
441
- 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>>>;
465
+ 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, SetupStateSchema> = Record<string, SetupStateSchema>> = SetupReturnFromConfig<AgentSetupXStateConfig<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>>;
442
466
  /**
443
467
  * The object returned by {@link setupAgent}: an xstate `setup(...)` result
444
468
  * (`createMachine`, `assign`, …) extended with `schemas` (the resolved
@@ -447,7 +471,14 @@ type SetupAgentXStateResult<TContextSchema extends StandardSchemaV1<Record<strin
447
471
  * `runAgent` and the free step helpers can resolve their schemas/actors
448
472
  * without re-passing them each call.
449
473
  */
450
- 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"> & {
474
+ type ArrayContextKey<TContext> = { [TKey in keyof TContext & string]: TContext[TKey] extends readonly unknown[] ? TKey : never }[keyof TContext & string];
475
+ type AgentAppendMessages<TContext> = {
476
+ (): AppendMessagesTransition;
477
+ <TKey extends ArrayContextKey<TContext>>(options: {
478
+ key: TKey;
479
+ }): AppendMessagesTransition;
480
+ };
481
+ 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, SetupStateSchema> = Record<string, SetupStateSchema>> = Omit<SetupAgentXStateResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>, "createMachine"> & {
451
482
  /**
452
483
  * Creates the agent machine — XState's own `createMachine`, plus: the
453
484
  * machine is registered so step helpers and {@link runAgent} can resolve
@@ -457,15 +488,8 @@ type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unk
457
488
  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. */
458
489
  schemas: AgentSchemaPack<TContextSchema, WithAgentUsageEvent<TEventSchemas>, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>; /** The `models` registry passed to `setupAgent(...)`, if any (used to type-narrow `AgentModelRef`). */
459
490
  readonly models: TModels; /** The {@link TextLogic} actors built from `setupAgent({ requests })`, keyed the same way. */
460
- readonly requests: RequestActors<TRequestSchemas>; /** {@link appendMessages}, typed against this agent's context/event schemas. */
461
- appendMessages(resolve: AgentMessage | AgentMessage[] | ((args: {
462
- context: ContextOf<TContextSchema> & {
463
- messages: AgentMessage[];
464
- };
465
- event: any;
466
- }) => AgentMessage | AgentMessage[])): ReturnType<typeof appendMessages<ContextOf<TContextSchema> & {
467
- messages: AgentMessage[];
468
- }, EventsOf<WithAgentUsageEvent<TEventSchemas>>>>;
491
+ readonly requests: RequestActors<TRequestSchemas>; /** {@link appendMessages}, for an explicit top-level `agent.messages` transition. */
492
+ appendMessages: AgentAppendMessages<InferOutput<TContextSchema>>;
469
493
  };
470
494
  /**
471
495
  * Schema-first `setup(...)` for agent machines — the standard entry point
@@ -512,7 +536,7 @@ type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unk
512
536
  * });
513
537
  * ```
514
538
  */
515
- 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>;
539
+ 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, SetupStateSchema> = Record<string, SetupStateSchema>>(config: SetupAgentBaseConfig<TContextSchema, TEventSchemas, TActors, TInputSchema, TOutputSchema, TMetaSchema, TRequestSchemas, TModels, TEmittedSchemas, TStateSchemas>): SetupAgentResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>;
516
540
  declare namespace setupAgent {
517
541
  /**
518
542
  * Builds a state machine from a serializable {@link AgentWorkflowConfig}
@@ -545,74 +569,183 @@ declare namespace setupAgent {
545
569
  * authored. Returns `undefined` for machines not built by either (a plain
546
570
  * xstate `createMachine`/`setup` machine).
547
571
  *
548
- * Registration is keyed on the machine object, so a machine returned by
549
- * `machine.provide(...)` carries no pack — read it from the machine the setup
550
- * returned.
572
+ * Registration also travels through `machine.provide(...)`: the pack is keyed
573
+ * on the machine's root `config`, which `.provide` shares by reference.
551
574
  */
552
575
  declare function getAgentSchemas(machine: AnyStateMachine): AgentSchemas | undefined;
553
576
  //#endregion
554
- //#region src/agent-run.d.ts
577
+ //#region src/interaction.d.ts
578
+ interface AgentInteractionEvent<TType extends string = string> {
579
+ type: TType;
580
+ label: string;
581
+ style?: string;
582
+ /** Optional fixed fields merged into the event when this choice is selected. */
583
+ event?: Record<string, unknown>;
584
+ }
585
+ interface AgentInteraction<TEvent extends EventObject = EventObject> {
586
+ label: string;
587
+ events: AgentInteractionEvent<TEvent["type"]>[];
588
+ /** Event type used for a free-text response. */
589
+ textEvent?: TEvent["type"];
590
+ }
555
591
  /**
556
- * A live handle over a single {@link runAgent} call: its trace events as an
557
- * async stream, plus the same result promise `runAgent` returns.
558
- *
559
- * Build it with {@link createAgentRun}. Use `events` for a pull-based feed
560
- * (SSE, a JSONL logger, a progress UI) and `result` for the final outcome —
561
- * either, both, or neither; nothing about consuming one is required to consume
562
- * the other.
592
+ * One choice as authored in `meta.interaction.events`: a bare label, or a
593
+ * descriptor carrying a `style` and the fixed `event` fields merged in when the
594
+ * choice is selected.
563
595
  */
564
- interface AgentRun<TMachine extends AnyStateMachine = AnyStateMachine> {
565
- /**
566
- * Single-consumer async stream of the run's trace events, in `runAgent`'s
567
- * emission order (`run.start` → request/chunk/transition/emit events →
568
- * `run.end`). Completes right after `run.end` is delivered. Events are
569
- * buffered unboundedly, so a slow or absent consumer never blocks the run
570
- * (see {@link createAgentRun}). Single-consumer: a second `for await` over the
571
- * same iterator picks up only the events not yet pulled — it is one shared
572
- * cursor, not a fresh replay.
573
- */
574
- events: AsyncIterableIterator<AgentTraceEvent<TMachine>>;
596
+ type AgentInteractionEventMeta = string | {
597
+ label?: string;
598
+ style?: string;
599
+ event?: Record<string, unknown>;
600
+ };
601
+ /** The `interaction` descriptor {@link getInteraction} reads off a state's meta. */
602
+ interface AgentInteractionDescriptor {
603
+ /** Label text, or a function of the machine context. `{path.to.field}` interpolates. */
604
+ label?: string | ((args: {
605
+ context: any;
606
+ }) => string);
607
+ events?: Record<string, AgentInteractionEventMeta>;
608
+ textEvent?: string;
609
+ }
610
+ /**
611
+ * The state-meta shape the interaction protocol reads. Use it as the `meta`
612
+ * type when the machine's only metadata is an interaction; see
613
+ * {@link interactionMetaSchema} for the runtime schema.
614
+ */
615
+ interface AgentInteractionMeta {
616
+ interaction?: AgentInteractionDescriptor;
617
+ }
618
+ /**
619
+ * A {@link StandardSchemaV1} for the state metadata {@link getInteraction}
620
+ * reads: an object whose optional `interaction` declares a `label` (a string
621
+ * with `{context.path}` interpolation, or a function of the context), an
622
+ * `events` map of choices, and a `textEvent` for free-text answers. Pass it
623
+ * straight to `createAgentSchemas({ meta: interactionMetaSchema })` instead of
624
+ * restating the shape per machine.
625
+ */
626
+ declare const interactionMetaSchema: StandardSchemaV1<AgentInteractionMeta>;
627
+ /** Options for {@link getInteraction}. */
628
+ interface GetInteractionOptions {
575
629
  /**
576
- * Settles exactly like {@link runAgent}'s return value: resolves with the
577
- * `done | idle | error` {@link RunAgentResult}, and rejects only where
578
- * `runAgent` itself rejects (bind-time programmer errors — a missing
579
- * executor, an illegal resume event, a version mismatch). A run-level failure
580
- * still resolves with `{ status: 'error' }`, never rejects.
630
+ * Keep label whitespace exactly as authored. Off by default: labels collapse
631
+ * runs of whitespace to single spaces and trim, so a multi-line template
632
+ * literal renders as one line and interpolated context cannot smuggle in
633
+ * layout. Turn it on when the label is deliberately multi-line (a rendered
634
+ * diff, a preformatted block).
581
635
  */
582
- result: Promise<RunAgentResult<TMachine>>;
636
+ preserveWhitespace?: boolean;
583
637
  }
638
+ /** Reads the active state's interaction metadata and filters it through the
639
+ * events XState currently accepts. Returns `undefined` when none is declared. */
640
+ declare function getInteraction<TSnapshot extends AnyMachineSnapshot>(snapshot: TSnapshot, options?: GetInteractionOptions): AgentInteraction<EventFromSnapshot<TSnapshot>> | undefined;
641
+ /** Converts a rendered interaction choice back into a schema-validated machine
642
+ * event. Fixed fields declared in metadata are merged before user fields. */
643
+ declare function eventFromInteraction<TSnapshot extends AnyMachineSnapshot>(snapshot: TSnapshot, choice: ({
644
+ type: string;
645
+ } & Record<string, unknown>) | {
646
+ text: string;
647
+ }): EventFromSnapshot<TSnapshot>;
648
+ //#endregion
649
+ //#region src/event-log-store-conformance.d.ts
650
+ /** Produces a fresh, empty store for one case. */
651
+ type CreateStore = () => Promise<AgentEventLogStore> | AgentEventLogStore;
584
652
  /**
585
- * Wraps {@link runAgent} in a canonical run-stream handle: the run's trace
586
- * events as a pull-based {@link AgentRun.events} async iterator, alongside the
587
- * unchanged {@link AgentRun.result} promise.
653
+ * A test runner's registration functions. `expect` is accepted and unused —
654
+ * every case asserts by throwing, so the suite stays runner-agnostic.
655
+ */
656
+ interface EventLogStoreConformanceHarness {
657
+ describe: (name: string, register: () => void) => void;
658
+ it: (name: string, run: () => Promise<void>) => void;
659
+ expect?: unknown;
660
+ }
661
+ /**
662
+ * Validates a store against the reference's semantics: empty read + zero length
663
+ * for unknown threads; single and multi-entry append; contiguity misuse guard;
664
+ * stale-`expectedIndex` conflict with correct fields; an interleaved concurrent
665
+ * append race (exactly one winner); entry-id uniqueness; `read({ from })`
666
+ * incremental correctness; thread isolation; metadata round-trip; deep-copy
667
+ * isolation on append and read; and the full fork contract.
588
668
  *
589
- * Semantics:
669
+ * Without a `harness`, every case runs in sequence and the first violation
670
+ * throws. With one, each case is registered as its own test:
590
671
  *
591
- * 1. **Starts immediately.** The underlying `runAgent` is invoked on this call,
592
- * not on the first `events` iteration — work is already in flight when
593
- * `createAgentRun` returns.
594
- * 2. **Buffer, don't stall.** Events are queued in an unbounded in-memory
595
- * buffer as the run emits them; a slow or absent consumer never applies
596
- * backpressure to the run. Once `run.end` is delivered, the iterator
597
- * completes.
598
- * 3. **Composes `onTrace`.** If `options.onTrace` is passed, it still fires for
599
- * every event — the wrapper adds queue delivery, it does not replace the
600
- * caller's sink.
601
- * 4. **`result` mirrors `runAgent`.** Same resolution and rejection behavior
602
- * (see {@link AgentRun.result}). A no-op rejection handler is attached
603
- * internally so a caller who reads only `events` never trips an unhandled
604
- * rejection on a bind-time throw; the returned promise still rejects for a
605
- * caller who awaits it.
606
- * 5. **Resume is identical.** Options pass straight through, so starting from a
607
- * persisted `snapshot` (+ resume `event`) streams that run's events from its
608
- * own `run.start`, exactly as `runAgent` would run it.
609
- * 6. **Early termination does not cancel the run.** Breaking out of a
610
- * `for await` (or calling `events.return()`) stops delivery, but the run
611
- * keeps going and `result` still settles. Cancelling the run itself is
612
- * future work — pass `options.signal` to abort it.
613
- * 7. **`events` is single-consumer.** See {@link AgentRun.events}.
672
+ * ```ts
673
+ * import { describe, it } from 'vitest';
674
+ * assertEventLogStoreConformance(createMyStore, { describe, it });
675
+ * ```
614
676
  */
615
- declare function createAgentRun<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentOptions<TMachine>): AgentRun<TMachine>;
677
+ declare function assertEventLogStoreConformance(create: CreateStore, harness?: EventLogStoreConformanceHarness): Promise<void>;
678
+ //#endregion
679
+ //#region src/agent-run.d.ts
680
+ type AgentStreamEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
681
+ kind: "request";
682
+ phase: "start" | "end";
683
+ name: string;
684
+ id: string;
685
+ request: AgentStepRequest;
686
+ output?: unknown;
687
+ raw?: unknown;
688
+ } | {
689
+ kind: "request";
690
+ phase: "error";
691
+ name: string;
692
+ id: string;
693
+ request: AgentStepRequest;
694
+ error: unknown;
695
+ } | {
696
+ kind: "chunk";
697
+ name: string;
698
+ id: string;
699
+ delta: string;
700
+ } | {
701
+ kind: "transition";
702
+ value: StateValue;
703
+ event: EventFromLogic<TMachine>;
704
+ } | {
705
+ kind: "emit";
706
+ event: EmittedFrom<TMachine>;
707
+ } | {
708
+ kind: "done";
709
+ result: Extract<RunAgentResult<TMachine>, {
710
+ status: "done";
711
+ }>;
712
+ } | {
713
+ kind: "idle";
714
+ result: Extract<RunAgentResult<TMachine>, {
715
+ status: "idle";
716
+ }>;
717
+ } | {
718
+ kind: "error";
719
+ result: Extract<RunAgentResult<TMachine>, {
720
+ status: "error";
721
+ }>;
722
+ };
723
+ /**
724
+ * Streams one {@link runAgent} call as agent-level events. The machine remains
725
+ * the single artifact; this function only projects its requests, chunks,
726
+ * transitions, emitted events, and terminal result into an async iterable.
727
+ */
728
+ declare function runAgentStream<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentOptions<TMachine>): AsyncGenerator<AgentStreamEvent<TMachine>, void>;
729
+ //#endregion
730
+ //#region src/run-loop.d.ts
731
+ interface RunAgentLoopOptions<TMachine extends AnyStateMachine> extends Omit<RunAgentOptions<TMachine>, "snapshot" | "event"> {
732
+ /** Called whenever the machine pauses. Return its next event, or nothing to
733
+ * leave the run paused. */
734
+ onIdle?: (result: Extract<RunAgentResult<TMachine>, {
735
+ status: "idle";
736
+ }>) => EventFromLogic<TMachine> | null | undefined | Promise<EventFromLogic<TMachine> | null | undefined>;
737
+ /** Called before `onIdle`, at every pause. Framework/host persistence stays here. */
738
+ persist?: (snapshot: ReturnType<Extract<RunAgentResult<TMachine>, {
739
+ status: "idle";
740
+ }>["persist"]>, result: Extract<RunAgentResult<TMachine>, {
741
+ status: "idle";
742
+ }>) => void | Promise<void>;
743
+ maxTurns?: number;
744
+ }
745
+ /** Drives one machine artifact across as many idle/resume turns as the host
746
+ * supplies. XState snapshots remain the continuation; this helper owns no
747
+ * persistence, retry, tool-loop, or storage policy. */
748
+ declare function runAgentLoop<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentLoopOptions<TMachine>): Promise<RunAgentResult<TMachine>>;
616
749
  //#endregion
617
750
  //#region src/provide-executors.d.ts
618
751
  /** Options for {@link provideExecutors}. */
@@ -691,7 +824,7 @@ type AgentLintSeverity = "error" | "warning";
691
824
  * or config location, and `message` explains the problem and its remedy.
692
825
  */
693
826
  interface AgentLintDiagnostic {
694
- code: "unreachable-state" | "decide-without-events" | "unserializable-context" | "direct-object-src" | "final-without-output" | "final-output-reads-event" | "undeclared-event" | "missing-final";
827
+ code: "decide-without-events" | "direct-object-src" | "invoke-without-on-error" | "unhandled-agent-messages";
695
828
  severity: AgentLintSeverity;
696
829
  /** State path (`parent.child`) or config pointer (e.g. `(root)`, `context`) the finding is about. */
697
830
  path: string;
@@ -718,8 +851,9 @@ interface LintAgentMachineOptions {
718
851
  * plus the schemas/actor sources the library already retains per machine.
719
852
  *
720
853
  * No model calls, no API keys — a coding agent that emits an agent machine can
721
- * call this to catch dead states, undeliverable decisions, un-rebindable
722
- * invoke srcs, and output-contract gaps before ever running it.
854
+ * call this to catch agent-specific mistakes such as undeliverable decisions,
855
+ * un-rebindable request sources, and an unhandled transcript event. General
856
+ * state-machine lint belongs to XState tooling.
723
857
  *
724
858
  * Pass `{ throw: true }` for the one-liner form used in tests and generation
725
859
  * loops: it returns silently when the machine is clean and throws
@@ -785,6 +919,14 @@ declare function assertAgentMachine(machine: AnyStateMachine, options?: AssertAg
785
919
  * - `userInput` — a flat FIFO queue of answers for `agent.userInput`, the
786
920
  * shorthand for `invokes: { 'agent.userInput': [...] }`. Entries here are
787
921
  * consumed before that src's `invokes` queue.
922
+ * - `errors` — failure values to reject a request or invoke with instead of
923
+ * resolving it, keyed by the same srcs the other channels use. An entry here
924
+ * is consumed BEFORE that src's output queue, so a script can fail the first
925
+ * call and let the second succeed. The invoke is rejected with
926
+ * {@link rejectAgentStep}, so the machine takes its `onError`; for
927
+ * `agent.decide` the entry stands in for retry exhaustion. A value can be
928
+ * anything — an `Error`, a string, or an object such as `{ code: 'truncated' }`
929
+ * for a machine that branches on `event.error.code`.
788
930
  * - `events` — a flat FIFO queue of external (human/host-sent) events. When the
789
931
  * machine settles idle with no pending request or invoke — a human gate — the
790
932
  * next queued event is applied, so a simulation can cross states that a live
@@ -796,6 +938,7 @@ interface SimulationScript {
796
938
  decisions?: Record<string, ChosenEvent[]>;
797
939
  invokes?: Record<string, unknown[]>;
798
940
  userInput?: unknown[];
941
+ errors?: Record<string, unknown[]>;
799
942
  events?: ChosenEvent[];
800
943
  }
801
944
  /**
@@ -820,11 +963,18 @@ interface SimulationTrailEntry {
820
963
  * exhaustion error was routed through the decision invoke's `onError`.
821
964
  */
822
965
  rejectedEvents?: ChosenEvent[];
823
- /** The resolved request (for a text/userInput invoke): its kind and src. */
966
+ /**
967
+ * The request this step settled (a text, decision, or scripted invoke): its
968
+ * kind, src, and how it settled. `outcome` is `'output'` when a scripted
969
+ * output resolved it and `'error'` when a `script.errors` entry rejected it,
970
+ * in which case `error` carries the scripted failure value.
971
+ */
824
972
  resolvedRequest?: {
825
- kind: "text" | "userInput";
973
+ kind: "text" | "userInput" | "decision";
826
974
  src: string;
827
975
  id: string;
976
+ outcome: "output" | "error";
977
+ error?: unknown;
828
978
  };
829
979
  }
830
980
  /** Options for {@link simulateAgent}. */
@@ -897,16 +1047,40 @@ interface ExplorePathsOptions {
897
1047
  invokes?: Record<string, unknown>;
898
1048
  /** Canned output for `agent.userInput`, the shorthand for `invokes['agent.userInput']`. */
899
1049
  userInput?: unknown;
1050
+ /**
1051
+ * A canned failure per src, keyed like `text`/`invokes`. A src listed here
1052
+ * forks an extra branch at that invoke, where the invoke is rejected and the
1053
+ * machine takes its `onError` — so states reachable only through a failure
1054
+ * are explored. When the src also has an output, both branches are explored;
1055
+ * when it has only an error, only the failing one is. Each fork counts
1056
+ * against `maxDepth`, and the failing branch records
1057
+ * `{ type: 'xstate.error.actor.<id>' }` in the path.
1058
+ *
1059
+ * A decision invoke can be keyed here too — by its src (usually
1060
+ * `agent.decide`) or by its invoke id — standing in for retry exhaustion.
1061
+ * Its success branch is the usual per-candidate-event fork, so the failing
1062
+ * branch is explored in addition to, not instead of, the candidates.
1063
+ *
1064
+ * A rejection that reaches no `onError` errors the machine, and that path
1065
+ * ends in an `error` terminal.
1066
+ */
1067
+ errors?: Record<string, unknown>;
900
1068
  }
901
1069
  /** A single explored path's terminal outcome. */
902
1070
  interface AgentPathTerminal {
903
- status: "done" | "idle" | "needs-output" | "max-depth";
1071
+ /**
1072
+ * `'error'` is a scripted failure the machine had no `onError` for: the
1073
+ * snapshot is errored, exactly as a live run's unhandled invoke failure.
1074
+ */
1075
+ status: "done" | "idle" | "needs-output" | "max-depth" | "error";
904
1076
  /** The chosen/applied events, in order, that produced this terminal. */
905
1077
  path: ChosenEvent[];
906
1078
  /** The final state value on this path. */
907
1079
  state: unknown;
908
1080
  /** For `needs-output`: the src whose canned output was missing. */
909
1081
  missingSrc?: string;
1082
+ /** For `error`: the failure value that errored the machine. */
1083
+ error?: unknown;
910
1084
  }
911
1085
  /** The report returned by {@link explorePaths}. */
912
1086
  interface AgentPathReport {
@@ -931,7 +1105,9 @@ interface AgentPathReport {
931
1105
  * an idle wait it forks per externally-accepted event. Text requests resolve
932
1106
  * from `text`, other invokes from `invokes` (or `userInput` for
933
1107
  * `agent.userInput`) — all by-src canned-output maps, and a missing src halts
934
- * that branch with a `needs-output` terminal rather than throwing.
1108
+ * that branch with a `needs-output` terminal rather than throwing. A src in
1109
+ * `errors` forks an extra branch where that invoke is rejected, so states
1110
+ * behind an `onError` are explored too.
935
1111
  *
936
1112
  * Combinatorics are bounded by `maxDepth` (default 8) and `maxPaths` (default
937
1113
  * 200, reported via `hitPathCap`).
@@ -947,9 +1123,16 @@ declare function explorePaths(machine: AnyStateMachine, options?: ExplorePathsOp
947
1123
  interface CanReachResult {
948
1124
  /** True when the target state was reached within the exploration bounds. */
949
1125
  reachable: boolean;
1126
+ /** Resolved XState state-node id for a string target. */
1127
+ target?: string;
950
1128
  /** When reachable, the sequence of chosen/applied events that gets there. */
951
1129
  witness?: ChosenEvent[];
952
1130
  }
1131
+ /** Thrown when a string reachability target is not a state in the machine. */
1132
+ declare class AgentUnknownStateError extends AgentError {
1133
+ readonly target: string;
1134
+ constructor(machineId: string, target: string);
1135
+ }
953
1136
  /**
954
1137
  * Answers "can the machine reach this?" by exploring its branches (a thin
955
1138
  * wrapper over {@link explorePaths}). The target is either a state path string
@@ -983,16 +1166,19 @@ interface TrajectoryEvent {
983
1166
  type: string;
984
1167
  [key: string]: unknown;
985
1168
  }
1169
+ /** Any host-owned envelope around an event. */
1170
+ interface TrajectoryEventEnvelope {
1171
+ event: TrajectoryEvent;
1172
+ }
986
1173
  /**
987
1174
  * One item in a trajectory, on either side of the comparison:
988
1175
  *
989
1176
  * - a state value — `'drafting'`, a dot path `'review.editing'`, or the nested
990
1177
  * object XState reports (`{ review: 'editing' }`),
991
- * - an event — an {@link AgentLogEntry} from `result.events`, a bare event
992
- * object, or just the event type as a string,
1178
+ * - an event object, or just the event type as a string,
993
1179
  * - a machine snapshot, whose `value` is used.
994
1180
  */
995
- type TrajectoryItem = StateValue | AgentLogEntry | TrajectoryEvent | {
1181
+ type TrajectoryItem = StateValue | TrajectoryEvent | TrajectoryEventEnvelope | {
996
1182
  value: StateValue;
997
1183
  };
998
1184
  /** Options for {@link matchesTrajectory}. */
@@ -1034,8 +1220,8 @@ interface TrajectoryMatch {
1034
1220
  /**
1035
1221
  * Matches a run's trajectory against an expected one.
1036
1222
  *
1037
- * Both trajectories may be state values (collected from `onTransition`) or
1038
- * events (`result.events`, whose {@link AgentLogEntry} envelopes are unwrapped);
1223
+ * Both trajectories may be state values or events collected from
1224
+ * `onTransition`;
1039
1225
  * items are compared by shape, so `['prompting', 'drafting']` scores a state
1040
1226
  * path and `['PROMPT_SUBMITTED', 'SEND']` scores an event log with the same
1041
1227
  * call.
@@ -1055,7 +1241,7 @@ interface TrajectoryMatch {
1055
1241
  *
1056
1242
  * const path = matchesTrajectory(statePath, ['prompting', 'drafting', 'sent']);
1057
1243
  * expect(path.matched, JSON.stringify(path.firstMiss)).toBe(true);
1058
- * expect(matchesTrajectory(result.events, ['PROMPT_SUBMITTED', 'SEND']).matched).toBe(true);
1244
+ * expect(matchesTrajectory(events, ['PROMPT_SUBMITTED', 'SEND']).matched).toBe(true);
1059
1245
  * ```
1060
1246
  *
1061
1247
  * @example Partial credit in an eval scorer
@@ -1078,13 +1264,13 @@ type ScriptedDecisionValue = ChosenEvent | {
1078
1264
  usage?: AgentCallUsage;
1079
1265
  };
1080
1266
  /**
1081
- * One entry in the `decisions` queue: a scripted answer, or a function of the
1267
+ * One scripted `decide` answer, or a function of the
1082
1268
  * {@link AgentDecisionRequest} returning one (for choices that depend on the
1083
1269
  * prompt, the candidate `events`, or the prior failed `attempts`).
1084
1270
  */
1085
1271
  type ScriptedDecisionEntry = ScriptedDecisionValue | ((request: AgentDecisionRequest) => ScriptedDecisionValue | PromiseLike<ScriptedDecisionValue>);
1086
1272
  /**
1087
- * One entry in the `text` queue: the request's output value (a string, or the
1273
+ * One scripted text answer: the request's output value (a string, or the
1088
1274
  * object a structured request declares), or a function of the
1089
1275
  * {@link AgentTextRequest} returning one.
1090
1276
  *
@@ -1098,30 +1284,41 @@ type ScriptedDecisionEntry = ScriptedDecisionValue | ((request: AgentDecisionReq
1098
1284
  */
1099
1285
  type ScriptedTextEntry = ((request: AgentTextRequest, info?: AgentRequestExecutorInfo) => unknown) | string | number | boolean | null | object;
1100
1286
  /**
1101
- * One entry in the `userInput` queue: the string the simulated human typed, or
1102
- * a function of the {@link AgentUserInput} request (its `prompt`/`metadata`)
1287
+ * A request-name keyed script. The key is the request's resolved `name` — the
1288
+ * authored name, else the invoke `id`. `"*"` is the fallback route.
1289
+ */
1290
+ type ScriptedByName<TEntry> = Record<string, TEntry | TEntry[]>;
1291
+ /** One scripted stream call: chunks, or a function producing chunks. */
1292
+ type ScriptedStreamEntry = string | readonly string[] | ((request: AgentTextRequest, info?: AgentRequestExecutorInfo) => string | readonly string[] | PromiseLike<string | readonly string[]>);
1293
+ /** A call observed by {@link createScriptedExecutors}. */
1294
+ interface ScriptedExecutorCall {
1295
+ kind: "generateText" | "streamText" | "decide" | "userInput";
1296
+ name: string;
1297
+ input: unknown;
1298
+ request: AgentTextRequest | AgentDecisionRequest | AgentUserInput;
1299
+ }
1300
+ /**
1301
+ * One scripted human answer: the string the simulated human typed, or a
1302
+ * function of the {@link AgentUserInput} request (its `prompt`/`metadata`)
1103
1303
  * returning one.
1104
1304
  */
1105
1305
  type ScriptedUserInputEntry = string | ((input: AgentUserInput) => string | PromiseLike<string>);
1106
1306
  /**
1107
- * The script {@link createScriptedExecutors} plays back.
1108
- *
1109
- * The key names match `simulateAgent`'s script (`decisions`, `text`,
1110
- * `invokes`, `userInput`), but the shapes differ by design: `simulateAgent`
1111
- * drives the pure step path and keys each channel BY SRC
1112
- * (`text: { summarize: [...] }`), while these executors sit behind the real
1113
- * executor contract, where one flat FIFO queue per channel is the ergonomic
1114
- * form — route per request inside a function entry (`request.name`) when one
1115
- * script must serve several requests. There is no `invokes` queue here:
1116
- * non-`userInput` invokes are plain actors, supplied via `actors`.
1307
+ * The script {@link createScriptedExecutors} plays back. Every channel is
1308
+ * keyed by request name and consumed in order; the last entry for a name
1309
+ * repeats forever.
1117
1310
  */
1118
1311
  interface ScriptedExecutorsScript {
1119
- /** Answers for `decide` requests, consumed in order. */
1120
- decisions?: ScriptedDecisionEntry[];
1121
- /** Answers for text requests, consumed in order. `generateText` and `streamText` share this one queue. */
1122
- text?: ScriptedTextEntry[];
1312
+ /** Answers for `decide` requests, keyed by request name. */
1313
+ decisions?: ScriptedByName<ScriptedDecisionEntry>;
1314
+ /** Answers for generate requests, keyed by request name. */
1315
+ text?: ScriptedByName<ScriptedTextEntry>;
1316
+ /** Stream chunks keyed by request name. */
1317
+ stream?: Record<string, ScriptedStreamEntry>;
1123
1318
  /** Answers for `agent.userInput` requests, consumed in order. */
1124
1319
  userInput?: ScriptedUserInputEntry[];
1320
+ /** Default usage attached when an entry does not provide its own. */
1321
+ usage?: AgentCallUsage;
1125
1322
  }
1126
1323
  /**
1127
1324
  * What {@link createScriptedExecutors} returns: the full executor set, plus a
@@ -1130,24 +1327,29 @@ interface ScriptedExecutorsScript {
1130
1327
  */
1131
1328
  type ScriptedExecutors = Required<AgentRequestExecutors> & {
1132
1329
  userInput: (input: AgentUserInput) => Promise<string>;
1330
+ calls: ScriptedExecutorCall[];
1133
1331
  };
1134
1332
  /**
1135
- * Keyless executors that replay a script instead of calling a model. Every
1136
- * slot is provided, so any machine binds; a request with no entry left throws a
1137
- * descriptive error naming what was pending.
1333
+ * Executors that replay a script instead of calling a model. Every slot is
1334
+ * provided, so any machine binds.
1138
1335
  *
1139
- * Queues are consumed FIFO and are copied on creation, so the caller's arrays
1140
- * are never mutated and each call builds a fresh, independent playthrough.
1141
- * Entries may be plain values or functions of the request, which is how one
1142
- * script serves a machine that loops or branches: route on `request.name` (the
1143
- * `setupAgent({ requests })` key) or on the decision's candidate `events`.
1336
+ * Answers are keyed by the request's resolved name — its authored `name`, else
1337
+ * the invoke `id` — and `"*"` serves anything unmatched.
1338
+ * Entries for a name are consumed in order and the last one repeats forever, so
1339
+ * a looping machine needs no extra option. A request the script has no route
1340
+ * for throws an ordinary `Error` from inside the executor, which reaches the
1341
+ * machine as an actor error.
1342
+ *
1343
+ * Queues are copied on creation, so the caller's arrays are never mutated and
1344
+ * each call builds a fresh, independent playthrough. Entries may be plain
1345
+ * values or functions of the request.
1144
1346
  *
1145
1347
  * @example
1146
1348
  * ```ts
1147
1349
  * const result = await runAgent(moderationMachine, {
1148
1350
  * input: { comment: 'honestly this update is terrible', trust: 20 },
1149
1351
  * executors: createScriptedExecutors({
1150
- * decisions: [{ type: 'FLAG', reason: 'Borderline tone.' }],
1352
+ * decisions: { moderate: [{ type: 'FLAG', reason: 'Borderline tone.' }] },
1151
1353
  * }),
1152
1354
  * });
1153
1355
  * ```
@@ -1155,8 +1357,8 @@ type ScriptedExecutors = Required<AgentRequestExecutors> & {
1155
1357
  * @example Dynamic entries
1156
1358
  * ```ts
1157
1359
  * createScriptedExecutors({
1158
- * text: [(request) => `Draft about ${request.prompt}`],
1159
- * decisions: [(request) => ({ type: request.events[0]!.type })],
1360
+ * text: { draft: (request) => `Draft about ${request.prompt}` },
1361
+ * decisions: { route: (request) => ({ type: request.events[0]!.type }) },
1160
1362
  * });
1161
1363
  * ```
1162
1364
  *
@@ -1169,6 +1371,8 @@ type ScriptedExecutors = Required<AgentRequestExecutors> & {
1169
1371
  declare function createScriptedExecutors(script?: ScriptedExecutorsScript): ScriptedExecutors;
1170
1372
  //#endregion
1171
1373
  //#region src/utils.d.ts
1374
+ /** Returns the human-readable text carried by a message, ignoring non-text parts. */
1375
+ declare function getMessageText(message: AgentMessage): string;
1172
1376
  /**
1173
1377
  * A stable, dependency-free structural fingerprint of a machine — a short hex
1174
1378
  * `djb2` hash over its **structural** config only: state ids/nesting, transition
@@ -1226,19 +1430,28 @@ declare function getStateMeta<TSnapshot extends {
1226
1430
  getMeta(): Record<string, unknown>;
1227
1431
  } = AnyMachineSnapshot, TMeta = MetaOfSnapshot<TSnapshot>>(snapshot: TSnapshot): Partial<TMeta>;
1228
1432
  /**
1229
- * Reads the run-owned message log off a snapshot settled by a `runAgent` call
1230
- * that used `getRequests` (or `options.messages`) — the typed replacement for
1231
- * the `(snapshot as { messages?: AgentMessage[] }).messages` cast. runAgent
1232
- * stamps the log as a plain enumerable `messages` property (like `agentMeta`),
1233
- * so it survives a JSON persist/resume round-trip; this accessor works on the
1234
- * live settled snapshot and on a JSON-parsed persisted one alike. Returns `[]`
1235
- * when no log was stamped (e.g. a default invoke-driven run).
1433
+ * Renders a snapshot's state value as one deterministic string, so a log line,
1434
+ * a progress field, or a test assertion reads the same on every run.
1435
+ *
1436
+ * - An atomic state is its own name: `'writing'`.
1437
+ * - A nested state joins with dots: `{ review: { editing: 'draft' } }` →
1438
+ * `'review.editing.draft'`.
1439
+ * - A parallel state brackets its regions, sorted by region name, so key order
1440
+ * never leaks into the string: `{ p: { left: 'x', right: { a: 'b' } } }` →
1441
+ * `'p:{left.x,right.a.b}'`.
1442
+ *
1443
+ * Prefer this over `String(snapshot.value)`, which renders every non-atomic
1444
+ * value as `[object Object]`.
1236
1445
  *
1237
- * The write path is `runAgent(..., { messages })`: an explicit seed that
1238
- * overrides the resume snapshot's stamped log (fold in a user reply on
1239
- * resume, or start a run with prior history).
1446
+ * @example
1447
+ * ```ts
1448
+ * onTransition: (snapshot) => console.log(getStatePath(snapshot));
1449
+ * ```
1240
1450
  */
1241
- declare function getAgentMessages(snapshot: unknown): AgentMessage[];
1451
+ declare function getStatePath(snapshot: {
1452
+ value: StateValue;
1453
+ status?: string;
1454
+ } | StateValue): string;
1242
1455
  /**
1243
1456
  * Structural guard for a {@link StandardSchemaV1}: `true` when `value` carries
1244
1457
  * the `~standard` marker. Used to tell an already-schema'd tool `inputSchema`
@@ -1320,8 +1533,8 @@ interface SeamCall {
1320
1533
  interface SeamSlice {
1321
1534
  /** State values entered on this side of the seam, in order. */
1322
1535
  statePath: StateValue[];
1323
- /** Replayable log entries on this side of the seam, in order. */
1324
- events: AgentLogEntry[];
1536
+ /** Root-machine transition events on this side of the seam, in order. */
1537
+ events: TrajectoryEvent[];
1325
1538
  }
1326
1539
  /** Options for {@link runSeam}. */
1327
1540
  interface RunSeamOptions<TMachine extends AnyStateMachine> {
@@ -1350,7 +1563,7 @@ interface RunSeamOptions<TMachine extends AnyStateMachine> {
1350
1563
  /**
1351
1564
  * The executor for the seam — the real model, a candidate prompt, anything
1352
1565
  * request-shaped. Omit to run the seam scripted too: the whole seam run is
1353
- * then keyless and deterministic.
1566
+ * then deterministic.
1354
1567
  */
1355
1568
  candidate?: AgentRequestExecutor;
1356
1569
  /**
@@ -1367,16 +1580,13 @@ interface RunSeamOptions<TMachine extends AnyStateMachine> {
1367
1580
  * Text slots are always owned by the routing.
1368
1581
  */
1369
1582
  executors?: Partial<AgentRequestExecutors>;
1370
- /** Passed through to `runAgent`: the deterministic idle-state predicate. */
1371
- isIdle?: RunAgentOptions<TMachine>["isIdle"];
1372
1583
  /** Passed through to `runAgent`: actor implementations merged onto the machine. */
1373
1584
  actors?: RunAgentOptions<TMachine>["actors"];
1374
1585
  }
1375
1586
  /** What {@link runSeam} returns: the seam's own answer, plus the run it caused. */
1376
1587
  interface RunSeamResult<TMachine extends AnyStateMachine> {
1377
1588
  /**
1378
- * The final `runAgent` result. Its `events` are the WHOLE run's log (every
1379
- * leg's entries), while `usage` accounts only for the last leg.
1589
+ * The final `runAgent` result. `usage` accounts for the last leg.
1380
1590
  */
1381
1591
  result: RunAgentResult<TMachine>;
1382
1592
  /** What the seam call returned, or `undefined` when the run never reached it. */
@@ -1411,7 +1621,7 @@ interface RunSeamResult<TMachine extends AnyStateMachine> {
1411
1621
  * seam's own effect completion (the first `xstate.done.*`/`xstate.error.*`
1412
1622
  * entry appended after the call was made).
1413
1623
  *
1414
- * @example Keyless: the seam is scripted too, so the whole thing runs offline.
1624
+ * @example No API key: the seam is scripted too, so the whole thing runs offline.
1415
1625
  * ```ts
1416
1626
  * const run = await runSeam(emailDrafter, {
1417
1627
  * scripts: { promptEvaluator: [vague, complete], emailDrafter: [draft] },
@@ -1430,76 +1640,4 @@ interface RunSeamResult<TMachine extends AnyStateMachine> {
1430
1640
  */
1431
1641
  declare function runSeam<TMachine extends AnyStateMachine>(machine: TMachine, options: RunSeamOptions<TMachine>): Promise<RunSeamResult<TMachine>>;
1432
1642
  //#endregion
1433
- //#region src/durable.d.ts
1434
- /** Options for {@link runDurableAgent}. */
1435
- interface RunDurableAgentOptions<TMachine extends AnyStateMachine> extends Pick<ProvideExecutorsOptions<TMachine>, "actors" | "onChunk" | "onTrace"> {
1436
- /** Machine input for a FRESH run (ignored when `entries` has an init entry). */
1437
- input?: InputFrom<TMachine>;
1438
- /**
1439
- * The journal to resume from — the `entries` a previous
1440
- * {@link runDurableAgent} result returned (or any replay-compatible
1441
- * {@link AgentLogEntry} log with a reserved `@agent.init` first entry).
1442
- */
1443
- entries?: readonly AgentLogEntry[];
1444
- /** One external event to feed after the journal is folded (a user reply, a timer). */
1445
- event?: EventFromLogic<TMachine>;
1446
- /** Host executors, bound with {@link provideExecutors} semantics. */
1447
- executors?: AgentRequestExecutors;
1448
- /** Called with each entry as it is appended, for incremental persistence. */
1449
- onEntry?: (entry: AgentLogEntry) => void;
1450
- /**
1451
- * Settle `idle` when this returns true for the current snapshot even though
1452
- * children are still pending — for machines whose wait states keep a
1453
- * never-resolving invoke in flight (e.g. an unbound `agent.userInput`).
1454
- */
1455
- isIdle?: (snapshot: SnapshotFrom<TMachine>) => boolean;
1456
- /** Explicit machine version for entry stamping; defaults to the structural hash. */
1457
- machineVersion?: string;
1458
- /**
1459
- * Record replay-verification hashes on appended entries. Off by default:
1460
- * hashing replays the whole prefix per entry, which is quadratic in log
1461
- * length.
1462
- */
1463
- verification?: boolean;
1464
- }
1465
- /** The settled result of a {@link runDurableAgent} call. */
1466
- type DurableAgentResult<TMachine extends AnyStateMachine> = {
1467
- /** The machine reached a final state. */status: "done";
1468
- output: OutputFrom<TMachine>;
1469
- snapshot: SnapshotFrom<TMachine>; /** The complete journal; replaying it reproduces this run. */
1470
- entries: AgentLogEntry[];
1471
- } | {
1472
- /** The machine is waiting for an external event. Persist `entries`; resume with them plus `event`. */status: "idle";
1473
- snapshot: SnapshotFrom<TMachine>;
1474
- entries: AgentLogEntry[];
1475
- };
1476
- /**
1477
- * Runs an agent machine as a durable execution: journal in, journal out.
1478
- *
1479
- * A fresh call starts from `input` and appends a reserved init entry; a
1480
- * resume call folds `entries` through pure transitions first — invokes whose
1481
- * completions are journaled are suppressed (their recorded results replay
1482
- * instead of re-executing), while work that was in flight at the crash
1483
- * re-executes live. After the journal, an optional `options.event` is
1484
- * delivered. The call settles:
1485
- *
1486
- * - `done` when the machine reaches a final state, with `output`;
1487
- * - `idle` when the frontier needs an external event the host has not
1488
- * supplied (no live work pending, or `isIdle` says the pending work is a
1489
- * human wait). Persist `entries` and call again with them later.
1490
- *
1491
- * ```ts
1492
- * const first = await runDurableAgent(machine, { input, executors });
1493
- * // ... persist first.entries; later, in a new process:
1494
- * const next = await runDurableAgent(machine, {
1495
- * entries: first.entries,
1496
- * event: { type: "APPROVE" },
1497
- * executors,
1498
- * });
1499
- * ```
1500
- *
1501
- * @experimental Built on xstate's experimental `xstate/durable` entrypoint.
1502
- */
1503
- declare function runDurableAgent<TMachine extends AnyStateMachine>(machine: TMachine, options?: RunDurableAgentOptions<TMachine>): Promise<DurableAgentResult<TMachine>>;
1504
- //#endregion
1505
- 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 AgentInputFrom, type AgentLintDiagnostic, AgentLintError, type AgentLintSeverity, type AgentLogEntry, type AgentLogPatchOperation, type AgentLogVerification, AgentMaxModelCallsExceededError, type AgentMessage, type AgentMessageInfo, type AgentModelRef, type AgentOutputMode, type AgentPathReport, type AgentPathTerminal, AgentReplayDivergenceError, AgentReplayMachineMismatchError, type AgentRequest, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestOptions, type AgentRequestSource, type AgentRun, type AgentRunMeta, type AgentSchemaPack, type AgentSchemas, type AgentSnapshotNode, 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 DecisionLogic, type DecisionLogicConfig, type DurableAgentResult, type ExplorePathsOptions, type FilePart, type FromConfigOptions, type FromConfigResult, type GenerateResult, type GetAgentEffectsOptions, type GetSnapshotRequestsOptions, type ImagePart, type InferInput, type InferOutput, type InspectedActorRef, type JsonSerializableTraceEvent, type JsonValue, type LintAgentMachineOptions, type MatchTrajectoryOptions, NonSerializableAgentEventError, type PendingUserInput, type ProvideExecutorsOptions, type ReplayOptions, type ReplayResult, type ResolveDecisionOptions, type RunAgentErrorCause, type RunAgentOptions, type RunAgentResult, type RunDurableAgentOptions, type RunSeamOptions, type RunSeamResult, type SchemaCompiler, type ScriptedDecisionEntry, type ScriptedDecisionValue, type ScriptedExecutors, type ScriptedExecutorsScript, type ScriptedTextEntry, type ScriptedUserInputEntry, type SeamCall, 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, createDecisionLogic, createInMemoryEventLogStore, createReplayEntry, createScriptedExecutors, createTextLogic, diffEventLogs, executeAgentRequest, explorePaths, generateResult, getAcceptedEvents, getAgentEffects, getAgentMessages, getAgentOutputMode, getAgentSchemas, getCallUsage, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getSnapshotNodes, getSnapshotRequests, getStateMeta, initEntry, inspectTransitions, isStandardSchema, lintAgentMachine, matchesTrajectory, messagesSchema, parseAgentEvent, parseModelRef, parseOutput, parseStructuredEnvelope, provideExecutors, renderDecisionAttempts, replay, resolveDecision, runAgent, runDurableAgent, runSeam, serializeTraceEvent, setupAgent, simulateAgent, systemMessage, toolMessage, traceTransitions, userMessage };
1643
+ export { AGENT_EVENT_SCHEMA_VERSION, AGENT_INIT_EVENT_TYPE, AGENT_MESSAGES_EVENT_TYPE, AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, type AgentCallUsage, type AgentDecisionExecutor, AgentDecisionExhaustedError, type AgentDecisionInput, type AgentDecisionRequest, AgentError, type AgentEventDescriptor, AgentEventLogConflictError, AgentEventLogError, type AgentEventLogStore, type AgentEventToolNameResolver, type AgentExecutorDecisionRequest, type AgentExecutorTextRequest, type AgentFinishReason, type AgentInitEvent, type AgentInputFrom, type AgentInteraction, type AgentInteractionDescriptor, type AgentInteractionEvent, type AgentInteractionEventMeta, type AgentInteractionMeta, AgentInvalidEventPayloadError, type AgentLintDiagnostic, AgentLintError, type AgentLintSeverity, type AgentLogEntry, type AgentLogInit, type AgentLogVerification, AgentMachineVersionMismatchError, AgentMaxModelCallsExceededError, type AgentMessage, type AgentMessagesEvent, type AgentMessagesEventPayload, type AgentModelRef, type AgentOutputMode, type AgentPathReport, type AgentPathTerminal, type AgentPersistedSnapshot, AgentReplayDivergenceError, type AgentRequest, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestOptions, type AgentRequestSource, type AgentRunMeta, type AgentSchemaPack, type AgentSchemas, AgentSnapshotDivergedError, type AgentStepRequest, type AgentStreamEvent, type AgentTextRequest, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentTools, type AgentTraceEvent, type AgentTransitionHandler, AgentTruncatedError, AgentUnknownStateError, 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 ContextOf, type CreateDecisionRequestOptions, type CreateReplayEntryOptions, type DecisionAttempt, type DecisionLogic, type DecisionLogicConfig, type DoneActorEventOf, type EventLogStoreConformanceHarness, type EventOf, type ExplorePathsOptions, type FilePart, type FromConfigOptions, type FromConfigResult, type GetInteractionOptions, type ImagePart, type InferInput, type InferOutput, type InputOf, type InspectedActorRef, type JsonSerializableTraceEvent, type JsonValue, type LintAgentMachineOptions, type MatchTrajectoryOptions, type MetaOf, NonSerializableAgentEventError, type OutputOf, type PendingUserInput, type ProvideExecutorsOptions, type ReplayOptions, type ReplayResult, type RequestNamesOf, type ResolveDecisionOptions, type RunAgentErrorCause, type RunAgentLoopOptions, type RunAgentOptions, type RunAgentResult, type RunSeamOptions, type RunSeamResult, type SchemaCompiler, type ScriptedByName, type ScriptedDecisionEntry, type ScriptedDecisionValue, type ScriptedExecutors, type ScriptedExecutorsScript, type ScriptedTextEntry, type ScriptedUserInputEntry, type SeamCall, type SeamRef, type SeamSlice, type SeamTurn, type SimulateAgentOptions, type SimulateAgentResult, type SimulationScript, type SimulationTrailEntry, type SnapshotOf, type StandardSchemaV1, type StateValueOf, 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 WithAgentEvents, type WithAgentUsageEvent, agentCallOccurrence, appendMessages, assertAgentLogEntry, assertAgentMachine, assertEventLogStoreConformance, assertJsonSerializable, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentSchemas, createDecisionLogic, createDecisionRequest, createInMemoryEventLogStore, createReplayEntry, createScriptedExecutors, createTextLogic, eventFromInteraction, executeAgentRequest, explorePaths, forkEventLog, getAcceptedEvents, getAgentOutputMode, getAgentSchemas, getCallFinishReason, getCallUsage, getInteraction, getJsonSchema, getJsonSchemaSync, getLogExecutionId, getMachineStructuralHash, getMessageText, getSnapshotStateHash, getStateMeta, getStatePath, getUsageFromEvents, initEntry, inspectTransitions, interactionMetaSchema, isAgentIdle, isAgentMessages, isStandardSchema, lintAgentMachine, matchesTrajectory, messagesSchema, parseAgentEvent, parseModelRef, parseOutput, parseStructuredEnvelope, provideExecutors, rebindActorSession, renderDecisionAttempts, replay, resolveDecision, runAgent, runAgentLoop, runAgentStream, runSeam, serializeTraceEvent, setupAgent, simulateAgent, systemMessage, toolMessage, traceTransitions, userMessage, validateReplayEntries };