@statelyai/agent 2.0.0-alpha.21 → 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-JWx6n3xR.mjs → decision-BBZ2jMO1.mjs} +542 -84
  6. package/dist/{decision-BnTCsuJv.cjs → decision-Cv6SfNWl.cjs} +629 -99
  7. package/dist/index.cjs +2225 -1032
  8. package/dist/index.d.cts +415 -276
  9. package/dist/index.d.mts +415 -276
  10. package/dist/index.mjs +2163 -983
  11. package/dist/machines.cjs +30 -2
  12. package/dist/machines.d.cts +151 -54
  13. package/dist/machines.d.mts +151 -54
  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-Mmbgb2jy.d.cts → text-logic-C7bSnH_B.d.cts} +238 -44
  28. package/dist/{text-logic-BR5twXCv.d.mts → text-logic-DJBK3LbG.d.mts} +238 -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-DBNI8ETM.d.mts +0 -1098
  42. package/dist/run-agent-Do094mGu.d.cts +0 -1098
  43. package/dist/setup-agent-91FSuZbB.cjs +0 -1641
  44. package/dist/setup-agent-DqqdcdNh.mjs +0 -1521
  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,49 +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 AgentEventToolNameResolver, C as buildEnvelopeSchema, D as parseModelRef, E as getCallUsage, F as DecisionLogicConfig, G as parseAgentEvent, H as AgentRequestSource, I as ResolveDecisionOptions, L as renderDecisionAttempts, M as AgentDecisionInput, N as AgentDecisionRequest, O as parseOutput, P as DecisionAttempt, R as resolveDecision, S as bindRequestExecutor, T as getAgentOutputMode, U as AgentSchemas, V as AgentRequestOptions, W as getAcceptedEvents, _ 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, 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 AgentEventDescriptor } from "./text-logic-Mmbgb2jy.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-Do094mGu.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
- * an array of parts with a known `type`. Use it directly as a context
44
- * schema's `messages` field when authoring with `createAgentSchemas`.
88
+ * an array of role-appropriate parts whose required fields and media payloads
89
+ * have the right runtime types (extra fields are allowed). Use it directly as
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}).
45
94
  */
46
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[];
47
102
  //#endregion
48
103
  //#region src/workflow-config.d.ts
49
104
  type JsonSchemaObject = {
@@ -104,7 +159,7 @@ interface AgentWorkflowConfig {
104
159
  * snapshots idle deterministically instead of using its timing heuristic.
105
160
  * Every listed tag must appear in some state's `tags` — an unused tag is a
106
161
  * build-time error. A `fromConfig(config, { isIdle })` option takes
107
- * precedence; a `runAgent({ isIdle })` host override beats both.
162
+ * precedence over declarative `idleTags`.
108
163
  */
109
164
  idleTags?: string[];
110
165
  meta?: Record<string, unknown>;
@@ -244,16 +299,15 @@ interface FromConfigOptions {
244
299
  * the same machine-carried predicate `setupAgent({ isIdle })` declares
245
300
  * for TS-authored machines, registered here because a function cannot live
246
301
  * in the workflow config itself. Takes precedence over the config's
247
- * declarative {@link AgentWorkflowConfig.idleTags}; a
248
- * `runAgent({ isIdle })` host override beats both. Travels with the
249
- * machine through `machine.provide(...)`.
302
+ * declarative {@link AgentWorkflowConfig.idleTags}. Travels with the machine
303
+ * through `machine.provide(...)`.
250
304
  */
251
305
  isIdle?: (snapshot: AnyMachineSnapshot) => boolean;
252
306
  }
253
307
  //#endregion
254
308
  //#region src/setup-agent.d.ts
255
309
  type Constrain<T, TConstraint> = T extends TConstraint ? T : TConstraint;
256
- type ContextOf<TContextSchema extends StandardSchemaV1> = Constrain<InferOutput<TContextSchema>, MachineContext>;
310
+ type ContextOf$1<TContextSchema extends StandardSchemaV1> = Constrain<InferOutput<TContextSchema>, MachineContext>;
257
311
  type EventsOf<TEventSchemas extends AgentEventSchemaInputMap> = Constrain<EventUnion<TEventSchemas>, EventObject>;
258
312
  /**
259
313
  * The first argument a guard or delay source receives. `context` and `event`
@@ -264,7 +318,7 @@ type EventsOf<TEventSchemas extends AgentEventSchemaInputMap> = Constrain<EventU
264
318
  * real where the machine is built.
265
319
  */
266
320
  type AgentSourceArgs<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap> = {
267
- context: ContextOf<TContextSchema>;
321
+ context: ContextOf$1<TContextSchema>;
268
322
  event: EventsOf<TEventSchemas>;
269
323
  };
270
324
  /** Guard sources for `setupAgent({ guards })`, typed against the agent's own context and events. */
@@ -312,9 +366,12 @@ type AgentUsageEventPayload = Omit<AgentUsageEvent, "type">;
312
366
  * is typed (and autocompletes) without the machine declaring anything.
313
367
  * Idempotent: re-applying it to an already-registered map is a no-op.
314
368
  */
315
- 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> & {
316
370
  [AGENT_USAGE_EVENT_TYPE]: StandardSchemaV1<AgentUsageEventPayload>;
371
+ [AGENT_MESSAGES_EVENT_TYPE]: StandardSchemaV1<AgentMessagesEventPayload>;
317
372
  };
373
+ /** @deprecated Use {@link WithAgentEvents}. */
374
+ type WithAgentUsageEvent<T extends AgentEventSchemaInputMap> = WithAgentEvents<T>;
318
375
  /**
319
376
  * Builds a machine's {@link AgentSchemaPack} from a partial schema
320
377
  * declaration — only `context` is required; `events`/`input`/`output`/`meta`
@@ -371,43 +428,12 @@ type AgentSetupXStateConfig<TContextSchema extends StandardSchemaV1<Record<strin
371
428
  meta: TMetaSchema;
372
429
  } & AgentSetupEventsSchema<TEventSchemas> & AgentSetupEmittedSchema<TEmittedSchemas>;
373
430
  states?: TStateSchemas;
374
- 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>>>;
375
432
  actions?: NonNullable<AnySetupConfig["actions"]>;
376
433
  guards?: NonNullable<AnySetupConfig["guards"]>;
377
434
  delays?: NonNullable<AnySetupConfig["delays"]>;
378
435
  };
379
- /**
380
- * Field-level context-narrowing sugar for one `setupAgent({ states })` entry:
381
- * each `context` entry overrides that field's schema inside the state; every
382
- * other field keeps the base context schema. Sugar for the full xstate form —
383
- * `{ context: { draft: z.string() } }` resolves to
384
- * `{ schemas: { context: <base with draft: string> } }` — so only the fields
385
- * that change are declared, not the whole context schema.
386
- */
387
- interface AgentStateNarrowing {
388
- context: Record<string, StandardSchemaV1>;
389
- states?: Record<string, AgentSetupStateSchema>;
390
- }
391
- /** One `setupAgent({ states })` entry: xstate's {@link SetupStateSchema} full form, or the {@link AgentStateNarrowing} field-level sugar. */
392
- type AgentSetupStateSchema = SetupStateSchema | AgentStateNarrowing;
393
- type NarrowedContext<TContextSchema extends StandardSchemaV1, TFields extends Record<string, StandardSchemaV1>> = Omit<InferOutput<TContextSchema>, keyof TFields> & { [K in keyof TFields]: InferOutput<TFields[K]> };
394
- type ResolveAgentStateSchema<TContextSchema extends StandardSchemaV1, T> = T extends {
395
- context: infer TFields extends Record<string, StandardSchemaV1>;
396
- } ? {
397
- schemas: {
398
- context: StandardSchemaV1<NarrowedContext<TContextSchema, TFields>>;
399
- };
400
- } & (T extends {
401
- states: infer TChildren extends Record<string, AgentSetupStateSchema>;
402
- } ? {
403
- states: ResolveAgentStateSchemas<TContextSchema, TChildren>;
404
- } : {}) : T extends {
405
- states: infer TChildren extends Record<string, AgentSetupStateSchema>;
406
- } ? Omit<T, "states"> & {
407
- states: ResolveAgentStateSchemas<TContextSchema, TChildren>;
408
- } : T;
409
- type ResolveAgentStateSchemas<TContextSchema extends StandardSchemaV1, TStates extends Record<string, AgentSetupStateSchema>> = Constrain<{ [K in keyof TStates]: ResolveAgentStateSchema<TContextSchema, TStates[K]> }, Record<string, SetupStateSchema>>;
410
- 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>> = ({
411
437
  schemas: AgentSchemaPack<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>;
412
438
  } | AgentSchemaConfig<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>) & {
413
439
  models?: TModels;
@@ -416,9 +442,8 @@ type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string,
416
442
  * Per-state schemas, mirroring xstate's `setup({ states })`: narrow
417
443
  * `context` inside a state (invoke `input`, transition fns, final `output`)
418
444
  * — e.g. mark a field non-null in states only reachable after it is set.
419
- * Two forms per state: the {@link AgentStateNarrowing} sugar
420
- * (`{ context: { draft: z.string() } }` — only the fields that change) or
421
- * xstate's full `{ schemas: { context } }` with a complete context schema.
445
+ * Use xstate's native `{ schemas: { context } }` form with a complete
446
+ * context schema.
422
447
  */
423
448
  states?: TStateSchemas;
424
449
  requests?: AgentRequestInput<TRequestSchemas, AgentModelRef<TModels>>;
@@ -430,14 +455,14 @@ type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string,
430
455
  * human approval, an inbound webhook, …) — the machine's own declaration of
431
456
  * what "idle" means for it, so `runAgent` settles those snapshots idle
432
457
  * deterministically instead of using its timing heuristic. Travels with the
433
- * machine through `machine.provide(...)`. A `runAgent({ isIdle })` host
434
- * override takes precedence; with neither, `runAgent` falls back to the timing
435
- * heuristic. Declare your own signal — e.g. `(s) => s.hasTag('awaiting-review')`
436
- * 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.
437
462
  */
438
463
  isIdle?: (snapshot: AnyMachineSnapshot) => boolean;
439
464
  };
440
- 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>>;
441
466
  /**
442
467
  * The object returned by {@link setupAgent}: an xstate `setup(...)` result
443
468
  * (`createMachine`, `assign`, …) extended with `schemas` (the resolved
@@ -446,7 +471,14 @@ type SetupAgentXStateResult<TContextSchema extends StandardSchemaV1<Record<strin
446
471
  * `runAgent` and the free step helpers can resolve their schemas/actors
447
472
  * without re-passing them each call.
448
473
  */
449
- 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"> & {
450
482
  /**
451
483
  * Creates the agent machine — XState's own `createMachine`, plus: the
452
484
  * machine is registered so step helpers and {@link runAgent} can resolve
@@ -456,15 +488,8 @@ type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unk
456
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. */
457
489
  schemas: AgentSchemaPack<TContextSchema, WithAgentUsageEvent<TEventSchemas>, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>; /** The `models` registry passed to `setupAgent(...)`, if any (used to type-narrow `AgentModelRef`). */
458
490
  readonly models: TModels; /** The {@link TextLogic} actors built from `setupAgent({ requests })`, keyed the same way. */
459
- readonly requests: RequestActors<TRequestSchemas>; /** {@link appendMessages}, typed against this agent's context/event schemas. */
460
- appendMessages(resolve: AgentMessage | AgentMessage[] | ((args: {
461
- context: ContextOf<TContextSchema> & {
462
- messages: AgentMessage[];
463
- };
464
- event: any;
465
- }) => AgentMessage | AgentMessage[])): ReturnType<typeof appendMessages<ContextOf<TContextSchema> & {
466
- messages: AgentMessage[];
467
- }, EventsOf<WithAgentUsageEvent<TEventSchemas>>>>;
491
+ readonly requests: RequestActors<TRequestSchemas>; /** {@link appendMessages}, for an explicit top-level `agent.messages` transition. */
492
+ appendMessages: AgentAppendMessages<InferOutput<TContextSchema>>;
468
493
  };
469
494
  /**
470
495
  * Schema-first `setup(...)` for agent machines — the standard entry point
@@ -511,7 +536,7 @@ type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unk
511
536
  * });
512
537
  * ```
513
538
  */
514
- 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>;
515
540
  declare namespace setupAgent {
516
541
  /**
517
542
  * Builds a state machine from a serializable {@link AgentWorkflowConfig}
@@ -544,74 +569,183 @@ declare namespace setupAgent {
544
569
  * authored. Returns `undefined` for machines not built by either (a plain
545
570
  * xstate `createMachine`/`setup` machine).
546
571
  *
547
- * Registration is keyed on the machine object, so a machine returned by
548
- * `machine.provide(...)` carries no pack — read it from the machine the setup
549
- * returned.
572
+ * Registration also travels through `machine.provide(...)`: the pack is keyed
573
+ * on the machine's root `config`, which `.provide` shares by reference.
550
574
  */
551
575
  declare function getAgentSchemas(machine: AnyStateMachine): AgentSchemas | undefined;
552
576
  //#endregion
553
- //#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
+ }
554
591
  /**
555
- * A live handle over a single {@link runAgent} call: its trace events as an
556
- * async stream, plus the same result promise `runAgent` returns.
557
- *
558
- * Build it with {@link createAgentRun}. Use `events` for a pull-based feed
559
- * (SSE, a JSONL logger, a progress UI) and `result` for the final outcome —
560
- * either, both, or neither; nothing about consuming one is required to consume
561
- * 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.
562
595
  */
563
- interface AgentRun<TMachine extends AnyStateMachine = AnyStateMachine> {
564
- /**
565
- * Single-consumer async stream of the run's trace events, in `runAgent`'s
566
- * emission order (`run.start` → request/chunk/transition/emit events →
567
- * `run.end`). Completes right after `run.end` is delivered. Events are
568
- * buffered unboundedly, so a slow or absent consumer never blocks the run
569
- * (see {@link createAgentRun}). Single-consumer: a second `for await` over the
570
- * same iterator picks up only the events not yet pulled — it is one shared
571
- * cursor, not a fresh replay.
572
- */
573
- 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 {
574
629
  /**
575
- * Settles exactly like {@link runAgent}'s return value: resolves with the
576
- * `done | idle | error` {@link RunAgentResult}, and rejects only where
577
- * `runAgent` itself rejects (bind-time programmer errors — a missing
578
- * executor, an illegal resume event, a version mismatch). A run-level failure
579
- * 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).
580
635
  */
581
- result: Promise<RunAgentResult<TMachine>>;
636
+ preserveWhitespace?: boolean;
582
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;
583
652
  /**
584
- * Wraps {@link runAgent} in a canonical run-stream handle: the run's trace
585
- * events as a pull-based {@link AgentRun.events} async iterator, alongside the
586
- * 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.
587
668
  *
588
- * 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:
589
671
  *
590
- * 1. **Starts immediately.** The underlying `runAgent` is invoked on this call,
591
- * not on the first `events` iteration — work is already in flight when
592
- * `createAgentRun` returns.
593
- * 2. **Buffer, don't stall.** Events are queued in an unbounded in-memory
594
- * buffer as the run emits them; a slow or absent consumer never applies
595
- * backpressure to the run. Once `run.end` is delivered, the iterator
596
- * completes.
597
- * 3. **Composes `onTrace`.** If `options.onTrace` is passed, it still fires for
598
- * every event — the wrapper adds queue delivery, it does not replace the
599
- * caller's sink.
600
- * 4. **`result` mirrors `runAgent`.** Same resolution and rejection behavior
601
- * (see {@link AgentRun.result}). A no-op rejection handler is attached
602
- * internally so a caller who reads only `events` never trips an unhandled
603
- * rejection on a bind-time throw; the returned promise still rejects for a
604
- * caller who awaits it.
605
- * 5. **Resume is identical.** Options pass straight through, so starting from a
606
- * persisted `snapshot` (+ resume `event`) streams that run's events from its
607
- * own `run.start`, exactly as `runAgent` would run it.
608
- * 6. **Early termination does not cancel the run.** Breaking out of a
609
- * `for await` (or calling `events.return()`) stops delivery, but the run
610
- * keeps going and `result` still settles. Cancelling the run itself is
611
- * future work — pass `options.signal` to abort it.
612
- * 7. **`events` is single-consumer.** See {@link AgentRun.events}.
672
+ * ```ts
673
+ * import { describe, it } from 'vitest';
674
+ * assertEventLogStoreConformance(createMyStore, { describe, it });
675
+ * ```
613
676
  */
614
- 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>>;
615
749
  //#endregion
616
750
  //#region src/provide-executors.d.ts
617
751
  /** Options for {@link provideExecutors}. */
@@ -690,7 +824,7 @@ type AgentLintSeverity = "error" | "warning";
690
824
  * or config location, and `message` explains the problem and its remedy.
691
825
  */
692
826
  interface AgentLintDiagnostic {
693
- 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";
694
828
  severity: AgentLintSeverity;
695
829
  /** State path (`parent.child`) or config pointer (e.g. `(root)`, `context`) the finding is about. */
696
830
  path: string;
@@ -717,8 +851,9 @@ interface LintAgentMachineOptions {
717
851
  * plus the schemas/actor sources the library already retains per machine.
718
852
  *
719
853
  * No model calls, no API keys — a coding agent that emits an agent machine can
720
- * call this to catch dead states, undeliverable decisions, un-rebindable
721
- * 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.
722
857
  *
723
858
  * Pass `{ throw: true }` for the one-liner form used in tests and generation
724
859
  * loops: it returns silently when the machine is clean and throws
@@ -784,6 +919,14 @@ declare function assertAgentMachine(machine: AnyStateMachine, options?: AssertAg
784
919
  * - `userInput` — a flat FIFO queue of answers for `agent.userInput`, the
785
920
  * shorthand for `invokes: { 'agent.userInput': [...] }`. Entries here are
786
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`.
787
930
  * - `events` — a flat FIFO queue of external (human/host-sent) events. When the
788
931
  * machine settles idle with no pending request or invoke — a human gate — the
789
932
  * next queued event is applied, so a simulation can cross states that a live
@@ -795,6 +938,7 @@ interface SimulationScript {
795
938
  decisions?: Record<string, ChosenEvent[]>;
796
939
  invokes?: Record<string, unknown[]>;
797
940
  userInput?: unknown[];
941
+ errors?: Record<string, unknown[]>;
798
942
  events?: ChosenEvent[];
799
943
  }
800
944
  /**
@@ -819,11 +963,18 @@ interface SimulationTrailEntry {
819
963
  * exhaustion error was routed through the decision invoke's `onError`.
820
964
  */
821
965
  rejectedEvents?: ChosenEvent[];
822
- /** 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
+ */
823
972
  resolvedRequest?: {
824
- kind: "text" | "userInput";
973
+ kind: "text" | "userInput" | "decision";
825
974
  src: string;
826
975
  id: string;
976
+ outcome: "output" | "error";
977
+ error?: unknown;
827
978
  };
828
979
  }
829
980
  /** Options for {@link simulateAgent}. */
@@ -896,16 +1047,40 @@ interface ExplorePathsOptions {
896
1047
  invokes?: Record<string, unknown>;
897
1048
  /** Canned output for `agent.userInput`, the shorthand for `invokes['agent.userInput']`. */
898
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>;
899
1068
  }
900
1069
  /** A single explored path's terminal outcome. */
901
1070
  interface AgentPathTerminal {
902
- 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";
903
1076
  /** The chosen/applied events, in order, that produced this terminal. */
904
1077
  path: ChosenEvent[];
905
1078
  /** The final state value on this path. */
906
1079
  state: unknown;
907
1080
  /** For `needs-output`: the src whose canned output was missing. */
908
1081
  missingSrc?: string;
1082
+ /** For `error`: the failure value that errored the machine. */
1083
+ error?: unknown;
909
1084
  }
910
1085
  /** The report returned by {@link explorePaths}. */
911
1086
  interface AgentPathReport {
@@ -930,7 +1105,9 @@ interface AgentPathReport {
930
1105
  * an idle wait it forks per externally-accepted event. Text requests resolve
931
1106
  * from `text`, other invokes from `invokes` (or `userInput` for
932
1107
  * `agent.userInput`) — all by-src canned-output maps, and a missing src halts
933
- * 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.
934
1111
  *
935
1112
  * Combinatorics are bounded by `maxDepth` (default 8) and `maxPaths` (default
936
1113
  * 200, reported via `hitPathCap`).
@@ -946,9 +1123,16 @@ declare function explorePaths(machine: AnyStateMachine, options?: ExplorePathsOp
946
1123
  interface CanReachResult {
947
1124
  /** True when the target state was reached within the exploration bounds. */
948
1125
  reachable: boolean;
1126
+ /** Resolved XState state-node id for a string target. */
1127
+ target?: string;
949
1128
  /** When reachable, the sequence of chosen/applied events that gets there. */
950
1129
  witness?: ChosenEvent[];
951
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
+ }
952
1136
  /**
953
1137
  * Answers "can the machine reach this?" by exploring its branches (a thin
954
1138
  * wrapper over {@link explorePaths}). The target is either a state path string
@@ -982,16 +1166,19 @@ interface TrajectoryEvent {
982
1166
  type: string;
983
1167
  [key: string]: unknown;
984
1168
  }
1169
+ /** Any host-owned envelope around an event. */
1170
+ interface TrajectoryEventEnvelope {
1171
+ event: TrajectoryEvent;
1172
+ }
985
1173
  /**
986
1174
  * One item in a trajectory, on either side of the comparison:
987
1175
  *
988
1176
  * - a state value — `'drafting'`, a dot path `'review.editing'`, or the nested
989
1177
  * object XState reports (`{ review: 'editing' }`),
990
- * - an event — an {@link AgentLogEntry} from `result.events`, a bare event
991
- * object, or just the event type as a string,
1178
+ * - an event object, or just the event type as a string,
992
1179
  * - a machine snapshot, whose `value` is used.
993
1180
  */
994
- type TrajectoryItem = StateValue | AgentLogEntry | TrajectoryEvent | {
1181
+ type TrajectoryItem = StateValue | TrajectoryEvent | TrajectoryEventEnvelope | {
995
1182
  value: StateValue;
996
1183
  };
997
1184
  /** Options for {@link matchesTrajectory}. */
@@ -1033,8 +1220,8 @@ interface TrajectoryMatch {
1033
1220
  /**
1034
1221
  * Matches a run's trajectory against an expected one.
1035
1222
  *
1036
- * Both trajectories may be state values (collected from `onTransition`) or
1037
- * events (`result.events`, whose {@link AgentLogEntry} envelopes are unwrapped);
1223
+ * Both trajectories may be state values or events collected from
1224
+ * `onTransition`;
1038
1225
  * items are compared by shape, so `['prompting', 'drafting']` scores a state
1039
1226
  * path and `['PROMPT_SUBMITTED', 'SEND']` scores an event log with the same
1040
1227
  * call.
@@ -1054,7 +1241,7 @@ interface TrajectoryMatch {
1054
1241
  *
1055
1242
  * const path = matchesTrajectory(statePath, ['prompting', 'drafting', 'sent']);
1056
1243
  * expect(path.matched, JSON.stringify(path.firstMiss)).toBe(true);
1057
- * expect(matchesTrajectory(result.events, ['PROMPT_SUBMITTED', 'SEND']).matched).toBe(true);
1244
+ * expect(matchesTrajectory(events, ['PROMPT_SUBMITTED', 'SEND']).matched).toBe(true);
1058
1245
  * ```
1059
1246
  *
1060
1247
  * @example Partial credit in an eval scorer
@@ -1077,13 +1264,13 @@ type ScriptedDecisionValue = ChosenEvent | {
1077
1264
  usage?: AgentCallUsage;
1078
1265
  };
1079
1266
  /**
1080
- * One entry in the `decisions` queue: a scripted answer, or a function of the
1267
+ * One scripted `decide` answer, or a function of the
1081
1268
  * {@link AgentDecisionRequest} returning one (for choices that depend on the
1082
1269
  * prompt, the candidate `events`, or the prior failed `attempts`).
1083
1270
  */
1084
1271
  type ScriptedDecisionEntry = ScriptedDecisionValue | ((request: AgentDecisionRequest) => ScriptedDecisionValue | PromiseLike<ScriptedDecisionValue>);
1085
1272
  /**
1086
- * 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
1087
1274
  * object a structured request declares), or a function of the
1088
1275
  * {@link AgentTextRequest} returning one.
1089
1276
  *
@@ -1097,30 +1284,41 @@ type ScriptedDecisionEntry = ScriptedDecisionValue | ((request: AgentDecisionReq
1097
1284
  */
1098
1285
  type ScriptedTextEntry = ((request: AgentTextRequest, info?: AgentRequestExecutorInfo) => unknown) | string | number | boolean | null | object;
1099
1286
  /**
1100
- * One entry in the `userInput` queue: the string the simulated human typed, or
1101
- * 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`)
1102
1303
  * returning one.
1103
1304
  */
1104
1305
  type ScriptedUserInputEntry = string | ((input: AgentUserInput) => string | PromiseLike<string>);
1105
1306
  /**
1106
- * The script {@link createScriptedExecutors} plays back.
1107
- *
1108
- * The key names match `simulateAgent`'s script (`decisions`, `text`,
1109
- * `invokes`, `userInput`), but the shapes differ by design: `simulateAgent`
1110
- * drives the pure step path and keys each channel BY SRC
1111
- * (`text: { summarize: [...] }`), while these executors sit behind the real
1112
- * executor contract, where one flat FIFO queue per channel is the ergonomic
1113
- * form — route per request inside a function entry (`request.name`) when one
1114
- * script must serve several requests. There is no `invokes` queue here:
1115
- * 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.
1116
1310
  */
1117
1311
  interface ScriptedExecutorsScript {
1118
- /** Answers for `decide` requests, consumed in order. */
1119
- decisions?: ScriptedDecisionEntry[];
1120
- /** Answers for text requests, consumed in order. `generateText` and `streamText` share this one queue. */
1121
- 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>;
1122
1318
  /** Answers for `agent.userInput` requests, consumed in order. */
1123
1319
  userInput?: ScriptedUserInputEntry[];
1320
+ /** Default usage attached when an entry does not provide its own. */
1321
+ usage?: AgentCallUsage;
1124
1322
  }
1125
1323
  /**
1126
1324
  * What {@link createScriptedExecutors} returns: the full executor set, plus a
@@ -1129,24 +1327,29 @@ interface ScriptedExecutorsScript {
1129
1327
  */
1130
1328
  type ScriptedExecutors = Required<AgentRequestExecutors> & {
1131
1329
  userInput: (input: AgentUserInput) => Promise<string>;
1330
+ calls: ScriptedExecutorCall[];
1132
1331
  };
1133
1332
  /**
1134
- * Keyless executors that replay a script instead of calling a model. Every
1135
- * slot is provided, so any machine binds; a request with no entry left throws a
1136
- * 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.
1137
1335
  *
1138
- * Queues are consumed FIFO and are copied on creation, so the caller's arrays
1139
- * are never mutated and each call builds a fresh, independent playthrough.
1140
- * Entries may be plain values or functions of the request, which is how one
1141
- * script serves a machine that loops or branches: route on `request.name` (the
1142
- * `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.
1143
1346
  *
1144
1347
  * @example
1145
1348
  * ```ts
1146
1349
  * const result = await runAgent(moderationMachine, {
1147
1350
  * input: { comment: 'honestly this update is terrible', trust: 20 },
1148
1351
  * executors: createScriptedExecutors({
1149
- * decisions: [{ type: 'FLAG', reason: 'Borderline tone.' }],
1352
+ * decisions: { moderate: [{ type: 'FLAG', reason: 'Borderline tone.' }] },
1150
1353
  * }),
1151
1354
  * });
1152
1355
  * ```
@@ -1154,8 +1357,8 @@ type ScriptedExecutors = Required<AgentRequestExecutors> & {
1154
1357
  * @example Dynamic entries
1155
1358
  * ```ts
1156
1359
  * createScriptedExecutors({
1157
- * text: [(request) => `Draft about ${request.prompt}`],
1158
- * decisions: [(request) => ({ type: request.events[0]!.type })],
1360
+ * text: { draft: (request) => `Draft about ${request.prompt}` },
1361
+ * decisions: { route: (request) => ({ type: request.events[0]!.type }) },
1159
1362
  * });
1160
1363
  * ```
1161
1364
  *
@@ -1168,6 +1371,8 @@ type ScriptedExecutors = Required<AgentRequestExecutors> & {
1168
1371
  declare function createScriptedExecutors(script?: ScriptedExecutorsScript): ScriptedExecutors;
1169
1372
  //#endregion
1170
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;
1171
1376
  /**
1172
1377
  * A stable, dependency-free structural fingerprint of a machine — a short hex
1173
1378
  * `djb2` hash over its **structural** config only: state ids/nesting, transition
@@ -1225,19 +1430,28 @@ declare function getStateMeta<TSnapshot extends {
1225
1430
  getMeta(): Record<string, unknown>;
1226
1431
  } = AnyMachineSnapshot, TMeta = MetaOfSnapshot<TSnapshot>>(snapshot: TSnapshot): Partial<TMeta>;
1227
1432
  /**
1228
- * Reads the run-owned message log off a snapshot settled by a `runAgent` call
1229
- * that used `getRequests` (or `options.messages`) — the typed replacement for
1230
- * the `(snapshot as { messages?: AgentMessage[] }).messages` cast. runAgent
1231
- * stamps the log as a plain enumerable `messages` property (like `agentMeta`),
1232
- * so it survives a JSON persist/resume round-trip; this accessor works on the
1233
- * live settled snapshot and on a JSON-parsed persisted one alike. Returns `[]`
1234
- * 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]`.
1235
1445
  *
1236
- * The write path is `runAgent(..., { messages })`: an explicit seed that
1237
- * overrides the resume snapshot's stamped log (fold in a user reply on
1238
- * resume, or start a run with prior history).
1446
+ * @example
1447
+ * ```ts
1448
+ * onTransition: (snapshot) => console.log(getStatePath(snapshot));
1449
+ * ```
1239
1450
  */
1240
- declare function getAgentMessages(snapshot: unknown): AgentMessage[];
1451
+ declare function getStatePath(snapshot: {
1452
+ value: StateValue;
1453
+ status?: string;
1454
+ } | StateValue): string;
1241
1455
  /**
1242
1456
  * Structural guard for a {@link StandardSchemaV1}: `true` when `value` carries
1243
1457
  * the `~standard` marker. Used to tell an already-schema'd tool `inputSchema`
@@ -1319,8 +1533,8 @@ interface SeamCall {
1319
1533
  interface SeamSlice {
1320
1534
  /** State values entered on this side of the seam, in order. */
1321
1535
  statePath: StateValue[];
1322
- /** Replayable log entries on this side of the seam, in order. */
1323
- events: AgentLogEntry[];
1536
+ /** Root-machine transition events on this side of the seam, in order. */
1537
+ events: TrajectoryEvent[];
1324
1538
  }
1325
1539
  /** Options for {@link runSeam}. */
1326
1540
  interface RunSeamOptions<TMachine extends AnyStateMachine> {
@@ -1349,7 +1563,7 @@ interface RunSeamOptions<TMachine extends AnyStateMachine> {
1349
1563
  /**
1350
1564
  * The executor for the seam — the real model, a candidate prompt, anything
1351
1565
  * request-shaped. Omit to run the seam scripted too: the whole seam run is
1352
- * then keyless and deterministic.
1566
+ * then deterministic.
1353
1567
  */
1354
1568
  candidate?: AgentRequestExecutor;
1355
1569
  /**
@@ -1366,16 +1580,13 @@ interface RunSeamOptions<TMachine extends AnyStateMachine> {
1366
1580
  * Text slots are always owned by the routing.
1367
1581
  */
1368
1582
  executors?: Partial<AgentRequestExecutors>;
1369
- /** Passed through to `runAgent`: the deterministic idle-state predicate. */
1370
- isIdle?: RunAgentOptions<TMachine>["isIdle"];
1371
1583
  /** Passed through to `runAgent`: actor implementations merged onto the machine. */
1372
1584
  actors?: RunAgentOptions<TMachine>["actors"];
1373
1585
  }
1374
1586
  /** What {@link runSeam} returns: the seam's own answer, plus the run it caused. */
1375
1587
  interface RunSeamResult<TMachine extends AnyStateMachine> {
1376
1588
  /**
1377
- * The final `runAgent` result. Its `events` are the WHOLE run's log (every
1378
- * leg's entries), while `usage` accounts only for the last leg.
1589
+ * The final `runAgent` result. `usage` accounts for the last leg.
1379
1590
  */
1380
1591
  result: RunAgentResult<TMachine>;
1381
1592
  /** What the seam call returned, or `undefined` when the run never reached it. */
@@ -1410,7 +1621,7 @@ interface RunSeamResult<TMachine extends AnyStateMachine> {
1410
1621
  * seam's own effect completion (the first `xstate.done.*`/`xstate.error.*`
1411
1622
  * entry appended after the call was made).
1412
1623
  *
1413
- * @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.
1414
1625
  * ```ts
1415
1626
  * const run = await runSeam(emailDrafter, {
1416
1627
  * scripts: { promptEvaluator: [vague, complete], emailDrafter: [draft] },
@@ -1429,76 +1640,4 @@ interface RunSeamResult<TMachine extends AnyStateMachine> {
1429
1640
  */
1430
1641
  declare function runSeam<TMachine extends AnyStateMachine>(machine: TMachine, options: RunSeamOptions<TMachine>): Promise<RunSeamResult<TMachine>>;
1431
1642
  //#endregion
1432
- //#region src/durable.d.ts
1433
- /** Options for {@link runDurableAgent}. */
1434
- interface RunDurableAgentOptions<TMachine extends AnyStateMachine> extends Pick<ProvideExecutorsOptions<TMachine>, "actors" | "onChunk" | "onTrace"> {
1435
- /** Machine input for a FRESH run (ignored when `entries` has an init entry). */
1436
- input?: InputFrom<TMachine>;
1437
- /**
1438
- * The journal to resume from — the `entries` a previous
1439
- * {@link runDurableAgent} result returned (or any replay-compatible
1440
- * {@link AgentLogEntry} log with a reserved `@agent.init` first entry).
1441
- */
1442
- entries?: readonly AgentLogEntry[];
1443
- /** One external event to feed after the journal is folded (a user reply, a timer). */
1444
- event?: EventFromLogic<TMachine>;
1445
- /** Host executors, bound with {@link provideExecutors} semantics. */
1446
- executors?: AgentRequestExecutors;
1447
- /** Called with each entry as it is appended, for incremental persistence. */
1448
- onEntry?: (entry: AgentLogEntry) => void;
1449
- /**
1450
- * Settle `idle` when this returns true for the current snapshot even though
1451
- * children are still pending — for machines whose wait states keep a
1452
- * never-resolving invoke in flight (e.g. an unbound `agent.userInput`).
1453
- */
1454
- isIdle?: (snapshot: SnapshotFrom<TMachine>) => boolean;
1455
- /** Explicit machine version for entry stamping; defaults to the structural hash. */
1456
- machineVersion?: string;
1457
- /**
1458
- * Record replay-verification hashes on appended entries. Off by default:
1459
- * hashing replays the whole prefix per entry, which is quadratic in log
1460
- * length.
1461
- */
1462
- verification?: boolean;
1463
- }
1464
- /** The settled result of a {@link runDurableAgent} call. */
1465
- type DurableAgentResult<TMachine extends AnyStateMachine> = {
1466
- /** The machine reached a final state. */status: "done";
1467
- output: OutputFrom<TMachine>;
1468
- snapshot: SnapshotFrom<TMachine>; /** The complete journal; replaying it reproduces this run. */
1469
- entries: AgentLogEntry[];
1470
- } | {
1471
- /** The machine is waiting for an external event. Persist `entries`; resume with them plus `event`. */status: "idle";
1472
- snapshot: SnapshotFrom<TMachine>;
1473
- entries: AgentLogEntry[];
1474
- };
1475
- /**
1476
- * Runs an agent machine as a durable execution: journal in, journal out.
1477
- *
1478
- * A fresh call starts from `input` and appends a reserved init entry; a
1479
- * resume call folds `entries` through pure transitions first — invokes whose
1480
- * completions are journaled are suppressed (their recorded results replay
1481
- * instead of re-executing), while work that was in flight at the crash
1482
- * re-executes live. After the journal, an optional `options.event` is
1483
- * delivered. The call settles:
1484
- *
1485
- * - `done` when the machine reaches a final state, with `output`;
1486
- * - `idle` when the frontier needs an external event the host has not
1487
- * supplied (no live work pending, or `isIdle` says the pending work is a
1488
- * human wait). Persist `entries` and call again with them later.
1489
- *
1490
- * ```ts
1491
- * const first = await runDurableAgent(machine, { input, executors });
1492
- * // ... persist first.entries; later, in a new process:
1493
- * const next = await runDurableAgent(machine, {
1494
- * entries: first.entries,
1495
- * event: { type: "APPROVE" },
1496
- * executors,
1497
- * });
1498
- * ```
1499
- *
1500
- * @experimental Built on xstate's experimental `xstate/durable` entrypoint.
1501
- */
1502
- declare function runDurableAgent<TMachine extends AnyStateMachine>(machine: TMachine, options?: RunDurableAgentOptions<TMachine>): Promise<DurableAgentResult<TMachine>>;
1503
- //#endregion
1504
- 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 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, 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 };