@statelyai/agent 2.0.0-alpha.24 → 2.0.0-alpha.26

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 (53) hide show
  1. package/dist/ai-sdk.cjs +30 -34
  2. package/dist/ai-sdk.d.cts +27 -31
  3. package/dist/ai-sdk.d.mts +27 -31
  4. package/dist/ai-sdk.mjs +27 -31
  5. package/dist/decision-CM9CYZ6t.cjs +519 -0
  6. package/dist/decision-DzSv1NpD.mjs +453 -0
  7. package/dist/event-log-store-Ba2fsc4E.mjs +576 -0
  8. package/dist/event-log-store-DQmImLYk.cjs +702 -0
  9. package/dist/event-log-store-DvOcs10J.d.cts +338 -0
  10. package/dist/event-log-store-DxyVgnas.d.mts +338 -0
  11. package/dist/index.cjs +429 -4272
  12. package/dist/index.d.cts +104 -1005
  13. package/dist/index.d.mts +104 -1005
  14. package/dist/index.mjs +389 -4202
  15. package/dist/log.cjs +392 -0
  16. package/dist/log.d.cts +32 -0
  17. package/dist/log.d.mts +32 -0
  18. package/dist/log.mjs +371 -0
  19. package/dist/machines.cjs +27 -16
  20. package/dist/machines.d.cts +1 -1
  21. package/dist/machines.d.mts +1 -1
  22. package/dist/machines.mjs +27 -16
  23. package/dist/openai.cjs +16 -15
  24. package/dist/openai.d.cts +9 -9
  25. package/dist/openai.d.mts +9 -9
  26. package/dist/openai.mjs +10 -9
  27. package/dist/otel.d.cts +1 -1
  28. package/dist/otel.d.mts +1 -1
  29. package/dist/{run-agent-Ck7Sa3Tb.d.mts → run-agent-BOfoJg5B.d.cts} +86 -387
  30. package/dist/{run-agent-DWqA8KiI.d.cts → run-agent-CG343kFs.d.mts} +86 -387
  31. package/dist/run-agent-Cb1-LS5P.cjs +1783 -0
  32. package/dist/run-agent-DvDQd4If.mjs +1669 -0
  33. package/dist/{setup-agent-CeO2fARv.mjs → setup-agent-CFW-jPI8.mjs} +9 -20
  34. package/dist/{setup-agent-Dl2VELLi.cjs → setup-agent-CPf7MxnG.cjs} +20 -37
  35. package/dist/testing.cjs +1088 -0
  36. package/dist/testing.d.cts +617 -0
  37. package/dist/testing.d.mts +617 -0
  38. package/dist/testing.mjs +1079 -0
  39. package/dist/{text-logic-DJBK3LbG.d.mts → text-logic-BFEOxyxv.d.cts} +71 -147
  40. package/dist/text-logic-Bl_ZRxDi.mjs +833 -0
  41. package/dist/text-logic-C8xyr6Ag.cjs +1091 -0
  42. package/dist/{text-logic-C7bSnH_B.d.cts → text-logic-hZSiRUo1.d.mts} +71 -147
  43. package/dist/{types-CjHk5OdH.d.cts → types-B1Qs2q3q.d.cts} +2 -1
  44. package/dist/{types-DWA6X9R-.d.mts → types-tA3SdczG.d.mts} +2 -1
  45. package/dist/usage-BdEjFuIi.mjs +5 -0
  46. package/dist/usage-efOQPdf_.cjs +10 -0
  47. package/dist/utils-C2DPqomn.d.mts +109 -0
  48. package/dist/utils-ceStNCOh.d.cts +109 -0
  49. package/package.json +26 -5
  50. package/readme.md +5 -3
  51. package/skills/generate-machine/SKILL.md +4 -6
  52. package/dist/decision-BBZ2jMO1.mjs +0 -1490
  53. package/dist/decision-Cv6SfNWl.cjs +0 -1856
package/dist/index.d.cts CHANGED
@@ -1,6 +1,8 @@
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";
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-B1Qs2q3q.cjs";
2
+ import { A as AgentDecisionExhaustedError, B as createDecisionRequest, C as getAgentOutputMode, D as parseProviderOutput, E as parseOutput, F as DecisionAttempt, G as AgentRequestOptions, H as resolveDecision, I as DecisionLogic, J as EventFromSnapshot, K as AgentRequestSource, L as DecisionLogicConfig, M as AgentDecisionRequest, N as AgentExecutorDecisionRequest, O as providerOutputSchema, P as CreateDecisionRequestOptions, Q as AgentTruncatedError, R as ResolveDecisionOptions, S as createTextLogic, T as getCallUsage, U as AgentEventDescriptor, V as renderDecisionAttempts, W as AgentInvalidEventPayloadError, X as parseAgentEvent, Y as getAcceptedEvents, Z as AgentError, _ as TextLogic, a as AgentModelRef, b as TextLogicExecutor, c as AgentRequestExecutorInfo, d as AgentRequestMode, f as AgentTextRequest, g as ProviderStructuredOutput, h as BuiltinAgentActors, i as AgentModelMap, j as AgentDecisionInput, k as AgentDecisionExecutor, l as AgentRequestExecutorResult, m as AgentUsage, n as AgentExecutorTextRequest, o as AgentOutputMode, p as AgentTextResult, q as AgentSchemas, r as AgentFinishReason, s as AgentRequestExecutor, t as AgentCallUsage, u as AgentRequestExecutors, v as TextLogicConfig, w as getCallFinishReason, x as bindRequestExecutor, y as TextLogicExecuteArgs, z as createDecisionLogic } from "./text-logic-BFEOxyxv.cjs";
3
+ import { C as rejectAgentStep, D as AgentUsageEvent, E as AGENT_USAGE_EVENT_TYPE, S as initialAgentStep, T as transitionAgentStep, _ as traceTransitions, a as AgentSnapshotDivergedError, b as AgentStepRequest, c as InspectedActorRef, d as RunAgentOptions, f as RunAgentResult, g as serializeTraceEvent, h as runAgent, i as AgentRunMeta, l as JsonSerializableTraceEvent, m as isAgentIdle, n as AgentInputFrom, o as AgentTraceEvent, p as inspectTransitions, r as AgentMaxModelCallsExceededError, s as AgentTransitionHandler, t as AGENT_TRACE_SCHEMA_VERSION, u as RunAgentErrorCause, v as AgentRequest, w as resolveAgentStep, x as executeAgentRequest, y as AgentStep } from "./run-agent-BOfoJg5B.cjs";
4
+ import { c as AgentLogEntry, d as AgentMachineVersionMismatchError, n as AgentEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-DvOcs10J.cjs";
5
+ import { a as getMachineStructuralHash, c as getStatePath, d as toolMessage, f as userMessage, i as getJsonSchemaSync, l as isStandardSchema, n as assistantMessage, o as getMessageText, r as getJsonSchema, s as getStateMeta, u as systemMessage } from "./utils-ceStNCOh.cjs";
4
6
  import { AnyActorLogic, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, ContextFrom, DoneActorEvent, EmittedFrom, EventFromLogic, EventObject, InputFrom, MachineContext, MetaObject, NonReducibleUnknown, OutputFrom, SetupReturnFromConfig, SetupStateSchema, SnapshotFrom, StateValue, StateValueFrom } from "xstate";
5
7
 
6
8
  //#region src/type-helpers.d.ts
@@ -49,38 +51,6 @@ type RequestNamesOf<T> = T extends {
49
51
  type DoneActorEventOf<TLogic extends AnyActorLogic, TId extends string = string> = DoneActorEvent<OutputFrom<TLogic>, TId>;
50
52
  //#endregion
51
53
  //#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">;
64
- /**
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.
67
- *
68
- * @example
69
- * ```ts
70
- * on: {
71
- * 'agent.messages': appendMessages(),
72
- * }
73
- * ```
74
- */
75
- type AppendMessagesTransition = <TContext extends object>(args: {
76
- context: TContext;
77
- event: EventObject & Partial<Omit<AgentMessagesEvent, "type">>;
78
- }) => {
79
- context: Partial<TContext>;
80
- };
81
- declare function appendMessages<TKey extends string = "messages">(options?: {
82
- key?: TKey;
83
- }): AppendMessagesTransition;
84
54
  /**
85
55
  * A {@link StandardSchemaV1} validating an `AgentMessage[]` context field —
86
56
  * checks that every message has a known `role` (`system`/`user`/`assistant`/
@@ -100,6 +70,84 @@ declare const messagesSchema: StandardSchemaV1<AgentMessage[]>;
100
70
  */
101
71
  declare function isAgentMessages(value: unknown): value is AgentMessage[];
102
72
  //#endregion
73
+ //#region src/interaction.d.ts
74
+ interface AgentInteractionEvent<TType extends string = string> {
75
+ type: TType;
76
+ label: string;
77
+ style?: string;
78
+ /** Optional fixed fields merged into the event when this choice is selected. */
79
+ event?: Record<string, unknown>;
80
+ }
81
+ interface AgentInteraction<TEvent extends EventObject = EventObject> {
82
+ label: string;
83
+ events: AgentInteractionEvent<TEvent["type"]>[];
84
+ /** Event type used for a free-text response. */
85
+ textEvent?: TEvent["type"];
86
+ }
87
+ /**
88
+ * One choice as authored in `meta.interaction.events`: a bare label, or a
89
+ * descriptor carrying a `style` and the fixed `event` fields merged in when the
90
+ * choice is selected.
91
+ */
92
+ type AgentInteractionEventMeta = string | {
93
+ label?: string;
94
+ style?: string;
95
+ event?: Record<string, unknown>;
96
+ };
97
+ /**
98
+ * The `interaction` descriptor {@link getInteraction} reads off a state's meta.
99
+ * `TEvent` is the machine's event-type union, so a choice or `textEvent` that
100
+ * names an event the machine never declared is a compile error.
101
+ */
102
+ interface AgentInteractionDescriptor<TEvent extends string = string> {
103
+ /** Label text, or a function of the machine context. `{path.to.field}` interpolates. */
104
+ label?: string | ((args: {
105
+ context: any;
106
+ }) => string);
107
+ events?: { [K in TEvent]?: AgentInteractionEventMeta };
108
+ textEvent?: TEvent;
109
+ }
110
+ /**
111
+ * The state-meta shape the interaction protocol reads. `setupAgent` types
112
+ * every state's `meta` as this by default, with `TEvent` narrowed to the
113
+ * machine's declared events; see {@link interactionMetaSchema} for the runtime
114
+ * schema when a machine declares its own `meta` schema.
115
+ */
116
+ interface AgentInteractionMeta<TEvent extends string = string> {
117
+ interaction?: AgentInteractionDescriptor<TEvent>;
118
+ }
119
+ /**
120
+ * A {@link StandardSchemaV1} for the state metadata {@link getInteraction}
121
+ * reads: an object whose optional `interaction` declares a `label` (a string
122
+ * with `{context.path}` interpolation, or a function of the context), an
123
+ * `events` map of choices, and a `textEvent` for free-text answers. This is
124
+ * the default `meta` type `setupAgent` gives a machine; pass it to
125
+ * `createAgentSchemas({ meta: interactionMetaSchema })` only when building a
126
+ * schema pack by hand.
127
+ */
128
+ declare const interactionMetaSchema: StandardSchemaV1<AgentInteractionMeta>;
129
+ /** Options for {@link getInteraction}. */
130
+ interface GetInteractionOptions {
131
+ /**
132
+ * Keep label whitespace exactly as authored. Off by default: labels collapse
133
+ * runs of whitespace to single spaces and trim, so a multi-line template
134
+ * literal renders as one line and interpolated context cannot smuggle in
135
+ * layout. Turn it on when the label is deliberately multi-line (a rendered
136
+ * diff, a preformatted block).
137
+ */
138
+ preserveWhitespace?: boolean;
139
+ }
140
+ /** Reads the active state's interaction metadata and filters it through the
141
+ * events XState currently accepts. Returns `undefined` when none is declared. */
142
+ declare function getInteraction<TSnapshot extends AnyMachineSnapshot>(snapshot: TSnapshot, options?: GetInteractionOptions): AgentInteraction<EventFromSnapshot<TSnapshot>> | undefined;
143
+ /** Converts a rendered interaction choice back into a schema-validated machine
144
+ * event. Fixed fields declared in metadata are merged before user fields. */
145
+ declare function eventFromInteraction<TSnapshot extends AnyMachineSnapshot>(snapshot: TSnapshot, choice: ({
146
+ type: string;
147
+ } & Record<string, unknown>) | {
148
+ text: string;
149
+ }): EventFromSnapshot<TSnapshot>;
150
+ //#endregion
103
151
  //#region src/workflow-config.d.ts
104
152
  type JsonSchemaObject = {
105
153
  type?: string | string[];
@@ -176,7 +224,7 @@ interface AgentWorkflowRequestConfig {
176
224
  output: JsonSchemaObject;
177
225
  tools?: AgentTools;
178
226
  toolChoice?: AgentToolChoice | unknown;
179
- /** Opt into the structured-output envelope's `reasoning` field (see `AgentTextRequest.includeReasoning`). */
227
+ /** Opt into the provider output's `reasoning` field (see `AgentTextRequest.includeReasoning`). */
180
228
  includeReasoning?: boolean;
181
229
  temperature?: unknown;
182
230
  maxOutputTokens?: unknown;
@@ -327,6 +375,13 @@ type AgentGuardSources<TContextSchema extends StandardSchemaV1<Record<string, un
327
375
  type AgentDelaySources<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap> = Record<string, number | ((args: AgentSourceArgs<TContextSchema, TEventSchemas>) => number)>;
328
376
  type SetupActors<TActors extends { [K in keyof TActors]: AnyActorLogic }> = { [K in keyof TActors]: TActors[K] extends AsyncActorLogic<infer TOutput, infer TInput> ? AsyncActorLogic<TOutput, TInput> : TActors[K] };
329
377
  type AgentSetupActors<TActors extends { [K in keyof TActors]: AnyActorLogic }, TEvent extends string = string, TModel extends string = string> = TActors & BuiltinAgentActors<TEvent, TModel>;
378
+ /**
379
+ * The default `meta` type of an agent machine: the interaction descriptor
380
+ * `getInteraction` reads, keyed by the machine's own event types (the
381
+ * reserved `@agent.*` events excluded). A machine that declares `meta`
382
+ * replaces this default.
383
+ */
384
+ type AgentDefaultMeta<TEventSchemas extends AgentEventSchemaInputMap> = AgentInteractionMeta<Exclude<keyof TEventSchemas & string, typeof AGENT_USAGE_EVENT_TYPE>>;
330
385
  /**
331
386
  * A machine's full schema set — context, event payloads, machine input/
332
387
  * output, and state/transition meta — as returned by {@link createAgentSchemas}
@@ -337,7 +392,7 @@ type AgentSetupActors<TActors extends { [K in keyof TActors]: AnyActorLogic }, T
337
392
  * is required — `events`/`input`/`output`/`meta` default to empty/unknown
338
393
  * schemas when not supplied.
339
394
  */
340
- interface AgentSchemaPack<TContextSchema extends StandardSchemaV1<Record<string, unknown>> = StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap = AgentEventSchemaInputMap, TInputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TMetaSchema extends StandardSchemaV1 = StandardSchemaV1<MetaObject>, TEmittedSchemas extends Record<string, StandardSchemaV1> = Record<string, StandardSchemaV1>> {
395
+ interface AgentSchemaPack<TContextSchema extends StandardSchemaV1<Record<string, unknown>> = StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap = AgentEventSchemaInputMap, TInputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TMetaSchema extends StandardSchemaV1 = StandardSchemaV1<AgentDefaultMeta<TEventSchemas>>, TEmittedSchemas extends Record<string, StandardSchemaV1> = Record<string, StandardSchemaV1>> {
341
396
  context: TContextSchema;
342
397
  events: NormalizedEventSchemas<TEventSchemas>;
343
398
  input: TInputSchema;
@@ -366,9 +421,8 @@ type AgentUsageEventPayload = Omit<AgentUsageEvent, "type">;
366
421
  * is typed (and autocompletes) without the machine declaring anything.
367
422
  * Idempotent: re-applying it to an already-registered map is a no-op.
368
423
  */
369
- type WithAgentEvents<T extends AgentEventSchemaInputMap> = Omit<T, typeof AGENT_USAGE_EVENT_TYPE | typeof AGENT_MESSAGES_EVENT_TYPE> & {
424
+ type WithAgentEvents<T extends AgentEventSchemaInputMap> = Omit<T, typeof AGENT_USAGE_EVENT_TYPE> & {
370
425
  [AGENT_USAGE_EVENT_TYPE]: StandardSchemaV1<AgentUsageEventPayload>;
371
- [AGENT_MESSAGES_EVENT_TYPE]: StandardSchemaV1<AgentMessagesEventPayload>;
372
426
  };
373
427
  /** @deprecated Use {@link WithAgentEvents}. */
374
428
  type WithAgentUsageEvent<T extends AgentEventSchemaInputMap> = WithAgentEvents<T>;
@@ -380,7 +434,7 @@ type WithAgentUsageEvent<T extends AgentEventSchemaInputMap> = WithAgentEvents<T
380
434
  * directly into `setupAgent({ context, events, ... })` — both forms are
381
435
  * accepted).
382
436
  */
383
- declare function createAgentSchemas<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap = {}, TInputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TMetaSchema extends StandardSchemaV1 = StandardSchemaV1<MetaObject>, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}>(schemas: AgentSchemaConfig<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>): AgentSchemaPack<TContextSchema, WithAgentUsageEvent<TEventSchemas>, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>;
437
+ declare function createAgentSchemas<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap = {}, TInputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TMetaSchema extends StandardSchemaV1 = StandardSchemaV1<AgentDefaultMeta<TEventSchemas>>, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}>(schemas: AgentSchemaConfig<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>): AgentSchemaPack<TContextSchema, WithAgentUsageEvent<TEventSchemas>, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>;
384
438
  type AgentRequestSchemaMap = Record<string, {
385
439
  input?: StandardSchemaV1;
386
440
  output?: StandardSchemaV1;
@@ -428,7 +482,7 @@ type AgentSetupXStateConfig<TContextSchema extends StandardSchemaV1<Record<strin
428
482
  meta: TMetaSchema;
429
483
  } & AgentSetupEventsSchema<TEventSchemas> & AgentSetupEmittedSchema<TEmittedSchemas>;
430
484
  states?: TStateSchemas;
431
- actors: SetupActors<AgentSetupActors<AgentAllActors<TActors, TRequestSchemas>, Exclude<keyof TEventSchemas & string, typeof AGENT_USAGE_EVENT_TYPE | typeof AGENT_MESSAGES_EVENT_TYPE>, AgentModelRef<TModels>>>;
485
+ actors: SetupActors<AgentSetupActors<AgentAllActors<TActors, TRequestSchemas>, Exclude<keyof TEventSchemas & string, typeof AGENT_USAGE_EVENT_TYPE>, AgentModelRef<TModels>>>;
432
486
  actions?: NonNullable<AnySetupConfig["actions"]>;
433
487
  guards?: NonNullable<AnySetupConfig["guards"]>;
434
488
  delays?: NonNullable<AnySetupConfig["delays"]>;
@@ -466,18 +520,11 @@ type SetupAgentXStateResult<TContextSchema extends StandardSchemaV1<Record<strin
466
520
  /**
467
521
  * The object returned by {@link setupAgent}: an xstate `setup(...)` result
468
522
  * (`createMachine`, `assign`, …) extended with `schemas` (the resolved
469
- * {@link AgentSchemaPack}), `models`, `requests` (the built request actors),
470
- * and {@link appendMessages}. Machines created here are registered so
523
+ * {@link AgentSchemaPack}), `models`, and `requests` (the built request
524
+ * actors). Machines created here are registered so
471
525
  * `runAgent` and the free step helpers can resolve their schemas/actors
472
526
  * without re-passing them each call.
473
527
  */
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
528
  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"> & {
482
529
  /**
483
530
  * Creates the agent machine — XState's own `createMachine`, plus: the
@@ -488,8 +535,7 @@ type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unk
488
535
  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. */
489
536
  schemas: AgentSchemaPack<TContextSchema, WithAgentUsageEvent<TEventSchemas>, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>; /** The `models` registry passed to `setupAgent(...)`, if any (used to type-narrow `AgentModelRef`). */
490
537
  readonly models: TModels; /** The {@link TextLogic} actors built from `setupAgent({ requests })`, keyed the same way. */
491
- readonly requests: RequestActors<TRequestSchemas>; /** {@link appendMessages}, for an explicit top-level `agent.messages` transition. */
492
- appendMessages: AgentAppendMessages<InferOutput<TContextSchema>>;
538
+ readonly requests: RequestActors<TRequestSchemas>;
493
539
  };
494
540
  /**
495
541
  * Schema-first `setup(...)` for agent machines — the standard entry point
@@ -498,11 +544,11 @@ type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unk
498
544
  * executors. Context, events, machine input, machine output, and
499
545
  * state/transition meta are all standard schemas — no `{} as Type` casts —
500
546
  * and are retained on `result.schemas` for runtime validation. Also
501
- * registers the `agent.generateText`/`agent.streamText`/`agent.userInput`/
547
+ * registers the `agent.generateText`/`agent.streamText`/
502
548
  * `agent.decide` builtin actors and lowers `requests`/`actors` into the
503
549
  * machine's actor sources. The result is the xstate `setup(...)` object with
504
550
  * a wrapped `result.createMachine(...)` plus `result.schemas`/`models`/
505
- * `requests`/`appendMessages` attached. Also has a
551
+ * `requests` attached. Also has a
506
552
  * `setupAgent.fromConfig(...)` namespace member for building a machine from
507
553
  * a serializable {@link AgentWorkflowConfig} instead of this TS API.
508
554
  *
@@ -536,7 +582,7 @@ type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unk
536
582
  * });
537
583
  * ```
538
584
  */
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>;
585
+ 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<AgentDefaultMeta<TEventSchemas>>, 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>;
540
586
  declare namespace setupAgent {
541
587
  /**
542
588
  * Builds a state machine from a serializable {@link AgentWorkflowConfig}
@@ -574,108 +620,6 @@ declare namespace setupAgent {
574
620
  */
575
621
  declare function getAgentSchemas(machine: AnyStateMachine): AgentSchemas | undefined;
576
622
  //#endregion
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
- }
591
- /**
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.
595
- */
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 {
629
- /**
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).
635
- */
636
- preserveWhitespace?: boolean;
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;
652
- /**
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.
668
- *
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:
671
- *
672
- * ```ts
673
- * import { describe, it } from 'vitest';
674
- * assertEventLogStoreConformance(createMyStore, { describe, it });
675
- * ```
676
- */
677
- declare function assertEventLogStoreConformance(create: CreateStore, harness?: EventLogStoreConformanceHarness): Promise<void>;
678
- //#endregion
679
623
  //#region src/agent-run.d.ts
680
624
  type AgentStreamEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
681
625
  kind: "request";
@@ -727,33 +671,13 @@ type AgentStreamEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
727
671
  */
728
672
  declare function runAgentStream<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentOptions<TMachine>): AsyncGenerator<AgentStreamEvent<TMachine>, void>;
729
673
  //#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>>;
749
- //#endregion
750
674
  //#region src/provide-executors.d.ts
751
675
  /** Options for {@link provideExecutors}. */
752
676
  interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMachine> {
753
677
  /**
754
678
  * Extra actor-source overrides merged onto the machine BEFORE binding — the
755
679
  * same shape as `machine.provide({ actors })`. Use it to supply the
756
- * `agent.userInput` handler, a custom non-agent actor, or to shadow an agent
680
+ * a custom non-agent actor, or to shadow an agent
757
681
  * source with your own executor-bound logic. Merged first, so an override
758
682
  * that already carries its own executor is left untouched by the binding pass.
759
683
  */
@@ -799,7 +723,7 @@ interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMac
799
723
  * `inspect` to also capture `machine.transition` events in the same stream.
800
724
  *
801
725
  * A source that already carries its own executor (`.withExecutor(...)`) is left
802
- * as-is. `agent.userInput` is left UNBOUND — an uncontrolled host handles idle
726
+ * as-is.
803
727
  * itself, so supply a handler via `options.actors` if the machine uses it.
804
728
  * Non-agent actors are untouched.
805
729
  *
@@ -815,829 +739,4 @@ interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMac
815
739
  */
816
740
  declare function provideExecutors<TMachine extends AnyStateMachine>(machine: TMachine, executors: AgentRequestExecutors, options?: ProvideExecutorsOptions<TMachine>): TMachine;
817
741
  //#endregion
818
- //#region src/verify.d.ts
819
- /** Severity of an {@link AgentLintDiagnostic}. `error` findings fail CI/the CLI; `warning`s are advisory. */
820
- type AgentLintSeverity = "error" | "warning";
821
- /**
822
- * One static-analysis finding from {@link lintAgentMachine}. `code` names the
823
- * check (stable, machine-readable), `path` points at the offending state path
824
- * or config location, and `message` explains the problem and its remedy.
825
- */
826
- interface AgentLintDiagnostic {
827
- code: "decide-without-events" | "direct-object-src" | "invoke-without-on-error" | "unhandled-agent-messages";
828
- severity: AgentLintSeverity;
829
- /** State path (`parent.child`) or config pointer (e.g. `(root)`, `context`) the finding is about. */
830
- path: string;
831
- message: string;
832
- }
833
- /** Options for {@link lintAgentMachine}. */
834
- interface LintAgentMachineOptions {
835
- /** Skip these check codes entirely. */
836
- disable?: AgentLintDiagnostic["code"][];
837
- /**
838
- * Throw {@link AgentLintError} on failing diagnostics instead of returning
839
- * them. Fails on error-severity findings; add `warnings: true` to fail on
840
- * warnings too.
841
- */
842
- throw?: boolean;
843
- /** With `throw: true`, also fail on warning-severity findings. Default: errors only. */
844
- warnings?: boolean;
845
- }
846
- /**
847
- * Runs static structural checks over a built agent machine and returns the
848
- * findings ({@link AgentLintDiagnostic}[], empty when clean). Works for
849
- * TS-authored (`setupAgent(...).createMachine(...)`) and
850
- * `setupAgent.fromConfig(...)`-compiled machines alike, reading `machine.config`
851
- * plus the schemas/actor sources the library already retains per machine.
852
- *
853
- * No model calls, no API keys — a coding agent that emits an agent machine can
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.
857
- *
858
- * Pass `{ throw: true }` for the one-liner form used in tests and generation
859
- * loops: it returns silently when the machine is clean and throws
860
- * {@link AgentLintError} (findings on `.diagnostics`) on error-severity
861
- * findings, or on warnings too with `{ throw: true, warnings: true }`.
862
- *
863
- * @example
864
- * ```ts
865
- * const errors = lintAgentMachine(machine).filter((d) => d.severity === 'error');
866
- * if (errors.length) throw new Error(errors.map((e) => `${e.path}: ${e.message}`).join('\n'));
867
- * ```
868
- *
869
- * @example Throwing form
870
- * ```ts
871
- * test('agent machine is structurally sound', () => {
872
- * lintAgentMachine(machine, { throw: true });
873
- * });
874
- * ```
875
- */
876
- declare function lintAgentMachine(machine: AnyStateMachine, options?: LintAgentMachineOptions): AgentLintDiagnostic[];
877
- /**
878
- * Thrown by `lintAgentMachine(machine, { throw: true })` (and its
879
- * {@link assertAgentMachine} alias) when lint finds failing diagnostics.
880
- * `diagnostics` holds the findings; the message lists them one per finding,
881
- * so a test runner's failure output reads like the CLI's lint report.
882
- */
883
- declare class AgentLintError extends AgentError {
884
- readonly diagnostics: AgentLintDiagnostic[];
885
- constructor(machineId: string, diagnostics: AgentLintDiagnostic[]);
886
- }
887
- /** Options for {@link assertAgentMachine}. */
888
- interface AssertAgentMachineOptions extends LintAgentMachineOptions {
889
- /** Also fail on warning-severity findings. Default: errors only. */
890
- warnings?: boolean;
891
- }
892
- /**
893
- * Asserts a machine passes {@link lintAgentMachine}: returns silently when
894
- * clean, throws {@link AgentLintError} (with the findings on `.diagnostics`)
895
- * otherwise — sugar for `lintAgentMachine(machine, { ...options, throw: true })`.
896
- * Fails on error-severity findings; set `warnings: true` to fail on warnings
897
- * too. The one-liner for tests and generation loops:
898
- *
899
- * @example
900
- * ```ts
901
- * test('agent machine is structurally sound', () => {
902
- * assertAgentMachine(machine);
903
- * });
904
- * ```
905
- */
906
- declare function assertAgentMachine(machine: AnyStateMachine, options?: AssertAgentMachineOptions): void;
907
- /**
908
- * Scripted responses for a {@link simulateAgent} playthrough. Each channel is a
909
- * by-`src` map of FIFO queues, consumed in the order the machine reaches the
910
- * requests:
911
- * - `text` — output values for text requests, keyed by request src (the
912
- * `setupAgent({ requests })` key, or `agent.generateText`/`agent.streamText`).
913
- * - `decisions` — the {@link ChosenEvent} to apply for a decision request,
914
- * keyed by decision src (usually `agent.decide`). An invoke whose src is an
915
- * inline logic object has only an auto-generated src, so its queue may be
916
- * keyed by the invoke's `id` instead.
917
- * - `invokes` — output values for scripted invokes (any actor whose output must
918
- * be canned), keyed by src.
919
- * - `userInput` — a flat FIFO queue of answers for `agent.userInput`, the
920
- * shorthand for `invokes: { 'agent.userInput': [...] }`. Entries here are
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`.
930
- * - `events` — a flat FIFO queue of external (human/host-sent) events. When the
931
- * machine settles idle with no pending request or invoke — a human gate — the
932
- * next queued event is applied, so a simulation can cross states that a live
933
- * run crosses via `actor.send(...)`. An event the current state cannot take
934
- * (no handler, or guard-rejected) throws rather than silently vanishing.
935
- */
936
- interface SimulationScript {
937
- text?: Record<string, unknown[]>;
938
- decisions?: Record<string, ChosenEvent[]>;
939
- invokes?: Record<string, unknown[]>;
940
- userInput?: unknown[];
941
- errors?: Record<string, unknown[]>;
942
- events?: ChosenEvent[];
943
- }
944
- /**
945
- * One entry in a {@link SimulateAgentResult.trail}: the state after this step,
946
- * plus what drove the step. The first entry is always the machine's initial
947
- * state, with no `appliedEvent`/`resolvedRequest` — so `trail.map((e) =>
948
- * e.state)` is the complete state path, directly comparable with
949
- * `matchesTrajectory` without prepending the initial state by hand.
950
- */
951
- interface SimulationTrailEntry {
952
- /** The machine state value after applying this step. */
953
- state: unknown;
954
- /** The chosen event applied (for a decision request), or the external event applied (when `external`). */
955
- appliedEvent?: ChosenEvent;
956
- /** True when `appliedEvent` came from the script's `events` queue (an external/user event), not a decision. */
957
- external?: boolean;
958
- /**
959
- * Scripted decisions that failed validation (unknown event, invalid payload,
960
- * or guard-rejected — live-run retry parity, see {@link simulateAgent})
961
- * before this step settled. Present with an `appliedEvent` when a later
962
- * scripted attempt succeeded, or alone when every attempt failed and the
963
- * exhaustion error was routed through the decision invoke's `onError`.
964
- */
965
- rejectedEvents?: ChosenEvent[];
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
- */
972
- resolvedRequest?: {
973
- kind: "text" | "userInput" | "decision";
974
- src: string;
975
- id: string;
976
- outcome: "output" | "error";
977
- error?: unknown;
978
- };
979
- }
980
- /** Options for {@link simulateAgent}. */
981
- interface SimulateAgentOptions {
982
- input?: unknown;
983
- script: SimulationScript;
984
- /** Max steps before returning `'exhausted'`. Default 100. */
985
- maxSteps?: number;
986
- }
987
- /** The outcome of a {@link simulateAgent} playthrough. */
988
- interface SimulateAgentResult {
989
- /** `'done'` = reached a final state; `'idle'` = paused with no pending work; `'exhausted'` = hit `maxSteps`. */
990
- status: "done" | "idle" | "exhausted";
991
- snapshot: AnyMachineSnapshot;
992
- trail: SimulationTrailEntry[];
993
- }
994
- /**
995
- * Deterministically plays a machine through, resolving each request from a
996
- * {@link SimulationScript} instead of a model — no API keys, no model calls.
997
- * Runs on the pure step path ({@link initialAgentStep} etc.), so it exercises
998
- * the real transition logic. Returns the terminal `status`, final `snapshot`,
999
- * and a `trail` of every step taken.
1000
- *
1001
- * Decisions run through the live run's own validation/retry core,
1002
- * {@link resolveDecision}, with the script standing in for the model: each
1003
- * attempt consumes the next queued {@link ChosenEvent} for that src, so an
1004
- * unknown, payload-invalid, or guard-rejected event is NOT silently swallowed
1005
- * — the next queued decision is tried, exactly as a live run re-asks the
1006
- * model. The decision logic's `maxRetries` caps attempts as it would live;
1007
- * when retries continue past the end of the queue, the last queued decision
1008
- * repeats (a scripted model that insists). The repeat applies only within one
1009
- * decision request's retries — each new decision request must have its own
1010
- * queued entry, or the dry-script error throws as usual. Exhausting all
1011
- * attempts delivers
1012
- * the resulting {@link AgentDecisionExhaustedError} to the machine as the
1013
- * decision invoke's error (so an `onError` transition observes it, as it
1014
- * would live); with no `onError` to catch it, it is thrown.
1015
- *
1016
- * Throws a descriptive error when the script runs dry mid-request, naming the
1017
- * pending request's kind, src, and id so the missing scripted response is
1018
- * obvious.
1019
- *
1020
- * @example
1021
- * ```ts
1022
- * const { status, snapshot } = simulateAgent(machine, {
1023
- * input: { topic: 'state machines' },
1024
- * script: {
1025
- * decisions: { 'agent.decide': [{ type: 'ESCALATE' }] },
1026
- * events: [{ type: 'APPROVE' }], // crosses the human gate
1027
- * },
1028
- * });
1029
- * ```
1030
- */
1031
- declare function simulateAgent(machine: AnyStateMachine, options: SimulateAgentOptions): Promise<SimulateAgentResult>;
1032
- /** Options for {@link explorePaths}. */
1033
- interface ExplorePathsOptions {
1034
- input?: unknown;
1035
- /** Max branch points (decisions + external-event forks) along any path. Default 8. */
1036
- maxDepth?: number;
1037
- /** Total path cap before exploration stops (reported via `hitPathCap`). Default 200. */
1038
- maxPaths?: number;
1039
- /**
1040
- * Canned output for each text request, keyed by src (the
1041
- * `setupAgent({ requests })` key, or `agent.generateText`/`agent.streamText`).
1042
- * One value per src, reused every time that src is reached. A missing src
1043
- * halts that branch with a `needs-output` terminal.
1044
- */
1045
- text?: Record<string, unknown>;
1046
- /** Canned output for scripted invokes, keyed by src. Same one-value-per-src rule as `text`. */
1047
- invokes?: Record<string, unknown>;
1048
- /** Canned output for `agent.userInput`, the shorthand for `invokes['agent.userInput']`. */
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>;
1068
- }
1069
- /** A single explored path's terminal outcome. */
1070
- interface AgentPathTerminal {
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";
1076
- /** The chosen/applied events, in order, that produced this terminal. */
1077
- path: ChosenEvent[];
1078
- /** The final state value on this path. */
1079
- state: unknown;
1080
- /** For `needs-output`: the src whose canned output was missing. */
1081
- missingSrc?: string;
1082
- /** For `error`: the failure value that errored the machine. */
1083
- error?: unknown;
1084
- }
1085
- /** The report returned by {@link explorePaths}. */
1086
- interface AgentPathReport {
1087
- /** Every distinct state value (JSON) encountered across all explored paths. */
1088
- reachedStates: unknown[];
1089
- /** One entry per explored path. */
1090
- terminals: AgentPathTerminal[];
1091
- /** How many candidate events were pruned because a guard rejected them. */
1092
- prunedByGuard: number;
1093
- /** Notes about coverage the exploration could not complete (missing outputs, depth/path caps). */
1094
- unexplored: string[];
1095
- /** Total paths explored. */
1096
- pathsExplored: number;
1097
- /** True when the total-paths cap was hit (report is partial). */
1098
- hitPathCap: boolean;
1099
- }
1100
- /**
1101
- * Enumerates a machine's decision and external-event branches to a bounded
1102
- * depth, model-free, and reports which states are reached and how each path
1103
- * terminates. At each decision request it forks one branch per candidate event
1104
- * (guard-rejected candidates are counted in `prunedByGuard`, not explored); at
1105
- * an idle wait it forks per externally-accepted event. Text requests resolve
1106
- * from `text`, other invokes from `invokes` (or `userInput` for
1107
- * `agent.userInput`) — all by-src canned-output maps, and a missing src halts
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.
1111
- *
1112
- * Combinatorics are bounded by `maxDepth` (default 8) and `maxPaths` (default
1113
- * 200, reported via `hitPathCap`).
1114
- *
1115
- * @example
1116
- * ```ts
1117
- * const report = await explorePaths(refundMachine, { input: { request: 'x', amount: 5000 } });
1118
- * // report.terminals → both 'refunded' and 'denied'; report.prunedByGuard → 1
1119
- * ```
1120
- */
1121
- declare function explorePaths(machine: AnyStateMachine, options?: ExplorePathsOptions): Promise<AgentPathReport>;
1122
- /** The result of a {@link canReach} query. */
1123
- interface CanReachResult {
1124
- /** True when the target state was reached within the exploration bounds. */
1125
- reachable: boolean;
1126
- /** Resolved XState state-node id for a string target. */
1127
- target?: string;
1128
- /** When reachable, the sequence of chosen/applied events that gets there. */
1129
- witness?: ChosenEvent[];
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
- }
1136
- /**
1137
- * Answers "can the machine reach this?" by exploring its branches (a thin
1138
- * wrapper over {@link explorePaths}). The target is either a state path string
1139
- * (`snapshot.matches(...)` semantics) or a snapshot predicate — the predicate
1140
- * form checks any property (a context invariant, a tag, a state+context
1141
- * combination) without reifying a sentinel state for it. Returns
1142
- * `{ reachable: true, witness }` with the event sequence that reaches it, or
1143
- * `{ reachable: false }`.
1144
- *
1145
- * @example
1146
- * ```ts
1147
- * const { reachable, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
1148
- * // reachable → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
1149
- * ```
1150
- *
1151
- * @example Predicate target — a violation property, no sentinel state needed
1152
- * ```ts
1153
- * const violation = await canReach(
1154
- * refundMachine,
1155
- * (snapshot) => snapshot.matches('issued') && !snapshot.context.approved,
1156
- * { input: { amount: 5000 } },
1157
- * );
1158
- * // violation.reachable → false is the safety proof
1159
- * ```
1160
- */
1161
- declare function canReach(machine: AnyStateMachine, target: string | ((snapshot: AnyMachineSnapshot) => boolean), options?: ExplorePathsOptions): Promise<CanReachResult>;
1162
- //#endregion
1163
- //#region src/trajectory.d.ts
1164
- /** An event-shaped trajectory item: anything with a string `type`. */
1165
- interface TrajectoryEvent {
1166
- type: string;
1167
- [key: string]: unknown;
1168
- }
1169
- /** Any host-owned envelope around an event. */
1170
- interface TrajectoryEventEnvelope {
1171
- event: TrajectoryEvent;
1172
- }
1173
- /**
1174
- * One item in a trajectory, on either side of the comparison:
1175
- *
1176
- * - a state value — `'drafting'`, a dot path `'review.editing'`, or the nested
1177
- * object XState reports (`{ review: 'editing' }`),
1178
- * - an event object, or just the event type as a string,
1179
- * - a machine snapshot, whose `value` is used.
1180
- */
1181
- type TrajectoryItem = StateValue | TrajectoryEvent | TrajectoryEventEnvelope | {
1182
- value: StateValue;
1183
- };
1184
- /** Options for {@link matchesTrajectory}. */
1185
- interface MatchTrajectoryOptions {
1186
- /**
1187
- * Require the trajectories to be equal: same length, item for item. Default
1188
- * `false` — expected items must appear in `actual` in order, gaps allowed.
1189
- */
1190
- exact?: boolean;
1191
- }
1192
- /** The first expected item that could not be found. */
1193
- interface TrajectoryMiss {
1194
- /** Its position in `expected`. */
1195
- index: number;
1196
- /** The expected item itself. */
1197
- expected: TrajectoryItem;
1198
- /** Where the search for it started in `actual` (everything before was already consumed). */
1199
- searchedFrom: number;
1200
- }
1201
- /**
1202
- * The result of {@link matchesTrajectory}: a boolean for tests, plus enough
1203
- * detail for a scorer's partial credit and a failure message's diagnosis.
1204
- */
1205
- interface TrajectoryMatch {
1206
- /** Every expected item was found, in order (and, in `exact` mode, nothing else). */
1207
- matched: boolean;
1208
- /** How many expected items were matched before the first miss. */
1209
- matchedCount: number;
1210
- /** `expected.length`, so a scorer can compute its own ratio. */
1211
- expectedCount: number;
1212
- /**
1213
- * Partial credit, 0..1. `1` for an empty expectation. Denominator is
1214
- * `max(expectedCount, actual.length)` in `exact` mode, `expectedCount` otherwise.
1215
- */
1216
- score: number;
1217
- /** Absent when `matched`. */
1218
- firstMiss?: TrajectoryMiss;
1219
- }
1220
- /**
1221
- * Matches a run's trajectory against an expected one.
1222
- *
1223
- * Both trajectories may be state values or events collected from
1224
- * `onTransition`;
1225
- * items are compared by shape, so `['prompting', 'drafting']` scores a state
1226
- * path and `['PROMPT_SUBMITTED', 'SEND']` scores an event log with the same
1227
- * call.
1228
- *
1229
- * Semantics are an ordered subsequence: every expected item must appear in
1230
- * `actual`, in order, with gaps allowed. Pass `{ exact: true }` to require
1231
- * equality instead.
1232
- *
1233
- * @example Trajectory assertions in a test
1234
- * ```ts
1235
- * const statePath: unknown[] = [];
1236
- * const result = await runAgent(machine, {
1237
- * input,
1238
- * executors,
1239
- * onTransition: (snapshot) => statePath.push(snapshot.value),
1240
- * });
1241
- *
1242
- * const path = matchesTrajectory(statePath, ['prompting', 'drafting', 'sent']);
1243
- * expect(path.matched, JSON.stringify(path.firstMiss)).toBe(true);
1244
- * expect(matchesTrajectory(events, ['PROMPT_SUBMITTED', 'SEND']).matched).toBe(true);
1245
- * ```
1246
- *
1247
- * @example Partial credit in an eval scorer
1248
- * ```ts
1249
- * const match = matchesTrajectory(output.statePath, expected.statePath);
1250
- * return { name: 'state_path', score: match.score, metadata: { ...match.firstMiss } };
1251
- * ```
1252
- */
1253
- declare function matchesTrajectory(actual: readonly unknown[], expected: readonly TrajectoryItem[], options?: MatchTrajectoryOptions): TrajectoryMatch;
1254
- //#endregion
1255
- //#region src/scripted-executors.d.ts
1256
- /**
1257
- * A scripted `decide` answer: either the {@link ChosenEvent} itself (an object
1258
- * with a string `type`), or the executor envelope `{ event, reason?, usage? }`
1259
- * when the entry also reports a `reason` or token `usage`.
1260
- */
1261
- type ScriptedDecisionValue = ChosenEvent | {
1262
- event: ChosenEvent;
1263
- reason?: string;
1264
- usage?: AgentCallUsage;
1265
- };
1266
- /**
1267
- * One scripted `decide` answer, or a function of the
1268
- * {@link AgentDecisionRequest} returning one (for choices that depend on the
1269
- * prompt, the candidate `events`, or the prior failed `attempts`).
1270
- */
1271
- type ScriptedDecisionEntry = ScriptedDecisionValue | ((request: AgentDecisionRequest) => ScriptedDecisionValue | PromiseLike<ScriptedDecisionValue>);
1272
- /**
1273
- * One scripted text answer: the request's output value (a string, or the
1274
- * object a structured request declares), or a function of the
1275
- * {@link AgentTextRequest} returning one.
1276
- *
1277
- * An entry is taken as the raw executor envelope (instead of the value itself)
1278
- * only when its OWN keys are an `output` plus, optionally, `usage`/`raw` —
1279
- * that is how an entry reports token `usage`. Anything else, including an
1280
- * object that merely happens to have an `output` key alongside its own data
1281
- * (`{ output: 'draft', confidence: 0.9 }`), is the output value. For a
1282
- * structured request whose declared output is exactly `{ output }` (or
1283
- * `{ output, usage }`), wrap it once more: `{ output: { output: '…' } }`.
1284
- */
1285
- type ScriptedTextEntry = ((request: AgentTextRequest, info?: AgentRequestExecutorInfo) => unknown) | string | number | boolean | null | object;
1286
- /**
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`)
1303
- * returning one.
1304
- */
1305
- type ScriptedUserInputEntry = string | ((input: AgentUserInput) => string | PromiseLike<string>);
1306
- /**
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.
1310
- */
1311
- interface ScriptedExecutorsScript {
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>;
1318
- /** Answers for `agent.userInput` requests, consumed in order. */
1319
- userInput?: ScriptedUserInputEntry[];
1320
- /** Default usage attached when an entry does not provide its own. */
1321
- usage?: AgentCallUsage;
1322
- }
1323
- /**
1324
- * What {@link createScriptedExecutors} returns: the full executor set, plus a
1325
- * `userInput` handler for `runAgent`'s own `userInput` option (the builtin
1326
- * `agent.userInput` actor is not an executor slot).
1327
- */
1328
- type ScriptedExecutors = Required<AgentRequestExecutors> & {
1329
- userInput: (input: AgentUserInput) => Promise<string>;
1330
- calls: ScriptedExecutorCall[];
1331
- };
1332
- /**
1333
- * Executors that replay a script instead of calling a model. Every slot is
1334
- * provided, so any machine binds.
1335
- *
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.
1346
- *
1347
- * @example
1348
- * ```ts
1349
- * const result = await runAgent(moderationMachine, {
1350
- * input: { comment: 'honestly this update is terrible', trust: 20 },
1351
- * executors: createScriptedExecutors({
1352
- * decisions: { moderate: [{ type: 'FLAG', reason: 'Borderline tone.' }] },
1353
- * }),
1354
- * });
1355
- * ```
1356
- *
1357
- * @example Dynamic entries
1358
- * ```ts
1359
- * createScriptedExecutors({
1360
- * text: { draft: (request) => `Draft about ${request.prompt}` },
1361
- * decisions: { route: (request) => ({ type: request.events[0]!.type }) },
1362
- * });
1363
- * ```
1364
- *
1365
- * @example Scripted human input
1366
- * ```ts
1367
- * const scripted = createScriptedExecutors({ userInput: ['ship it'] });
1368
- * await runAgent(machine, { executors: scripted, userInput: scripted.userInput });
1369
- * ```
1370
- */
1371
- declare function createScriptedExecutors(script?: ScriptedExecutorsScript): ScriptedExecutors;
1372
- //#endregion
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;
1376
- /**
1377
- * A stable, dependency-free structural fingerprint of a machine — a short hex
1378
- * `djb2` hash over its **structural** config only: state ids/nesting, transition
1379
- * event types and targets, invoke `src`s, `initial`, and any other serializable
1380
- * config fields. Function values (context/output builders, prompts, inline
1381
- * guards/actions) are excluded entirely, so two machines that differ only in
1382
- * their prompts or executors hash identically; adding/removing/retargeting a
1383
- * state or transition changes the hash.
1384
- *
1385
- * Used by {@link runAgent} to stamp settled snapshots with a `version` and to
1386
- * detect a structurally-edited machine on resume. It is a change detector, not
1387
- * a cryptographic digest — collisions are possible but unlikely for real
1388
- * configs. Declare `createMachine({ version })` to pin an explicit version instead.
1389
- */
1390
- declare function getMachineStructuralHash(machine: AnyStateMachine): string;
1391
- /** Builds a {@link UserMessage} from a string or multimodal content parts. */
1392
- declare function userMessage(content: string | Array<TextPart | ImagePart | FilePart>): UserMessage;
1393
- /** Builds an {@link AssistantMessage} from a string or content parts (text, files, tool calls/results). */
1394
- declare function assistantMessage(content: string | Array<TextPart | FilePart | ToolCallPart | ToolResultPart>): AssistantMessage;
1395
- /** Builds a {@link SystemMessage}. */
1396
- declare function systemMessage(content: string): SystemMessage;
1397
- /** Builds a {@link ToolMessage} from one or more tool-result parts. */
1398
- declare function toolMessage(content: Array<ToolResultPart>): ToolMessage;
1399
- type MetaOfSnapshot<TSnapshot extends {
1400
- getMeta(): Record<string, unknown>;
1401
- }> = NonNullable<ReturnType<TSnapshot["getMeta"]>[keyof ReturnType<TSnapshot["getMeta"]>]>;
1402
- /**
1403
- * Returns the merged `meta` of a snapshot's active state(s) — the typed
1404
- * replacement for the `Object.values(snapshot.getMeta())[0]` dance.
1405
- *
1406
- * `snapshot.getMeta()` is keyed by state id; a leaf machine has one active
1407
- * state, but parallel/nested machines can have several. This shallow-merges
1408
- * every active state's meta into one object and returns `{}` when no active
1409
- * state declares meta.
1410
- *
1411
- * Merge order is fixed and does not depend on XState's internal node order:
1412
- * entries are sorted by structural depth (the state node's distance from the
1413
- * root, regardless of custom `id` strings), then by state id lexicographically,
1414
- * and merged in that order. So a deeper state's key wins over an ancestor's,
1415
- * and between equal-depth parallel siblings the later state id alphabetically
1416
- * wins.
1417
- *
1418
- * The return type is recovered from the snapshot's own `getMeta()` type, so a
1419
- * schema-typed machine (`setupAgent({ meta })`) yields the meta schema's
1420
- * output type. Pass an explicit `TMeta` to override when the snapshot is
1421
- * untyped (e.g. `AnyMachineSnapshot`).
1422
- *
1423
- * @example HITL: read the current state's interaction protocol off an idle
1424
- * snapshot to render for a human.
1425
- * ```ts
1426
- * const { interaction } = getStateMeta(result.snapshot);
1427
- * ```
1428
- */
1429
- declare function getStateMeta<TSnapshot extends {
1430
- getMeta(): Record<string, unknown>;
1431
- } = AnyMachineSnapshot, TMeta = MetaOfSnapshot<TSnapshot>>(snapshot: TSnapshot): Partial<TMeta>;
1432
- /**
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]`.
1445
- *
1446
- * @example
1447
- * ```ts
1448
- * onTransition: (snapshot) => console.log(getStatePath(snapshot));
1449
- * ```
1450
- */
1451
- declare function getStatePath(snapshot: {
1452
- value: StateValue;
1453
- status?: string;
1454
- } | StateValue): string;
1455
- /**
1456
- * Structural guard for a {@link StandardSchemaV1}: `true` when `value` carries
1457
- * the `~standard` marker. Used to tell an already-schema'd tool `inputSchema`
1458
- * (a Zod/Valibot/… schema) apart from an SDK-specific schema wrapper that core
1459
- * can't read directly — see the `ai-sdk` tool pass-through.
1460
- */
1461
- declare function isStandardSchema(value: unknown): value is StandardSchemaV1;
1462
- /**
1463
- * Pulls the JSON Schema off a {@link StandardSchemaV1} via its optional
1464
- * `~standard.jsonSchema.input()` extension (implemented by e.g. Zod v4's
1465
- * `z.toJSONSchema`), awaiting it when the producer is async. Returns
1466
- * `undefined` when the schema doesn't expose the extension. Use this to build
1467
- * a provider request's `response_format`/tool `parameters` from a schema.
1468
- */
1469
- declare function getJsonSchema(schema?: StandardSchemaV1): Promise<Record<string, unknown> | undefined>;
1470
- /**
1471
- * Synchronous variant of {@link getJsonSchema}, for call sites that can't
1472
- * await (building tool/event descriptors inline). An async JSON Schema
1473
- * producer is treated as absent (returns `undefined`) — in practice Zod's
1474
- * `z.toJSONSchema` resolves synchronously.
1475
- */
1476
- declare function getJsonSchemaSync(schema?: StandardSchemaV1): Record<string, unknown> | undefined;
1477
- //#endregion
1478
- //#region src/seam.d.ts
1479
- /**
1480
- * Which model call is under test: the Nth call with this request `name` (the
1481
- * `setupAgent({ requests })` key, or `createTextLogic({ name })`). Name the
1482
- * requests you want to score — a seam is a developer-facing handle, not a
1483
- * model binding, so there is no addressing by model key.
1484
- */
1485
- interface SeamRef {
1486
- /** The request's registered `name`. */
1487
- request: string;
1488
- /** 0-based occurrence among the calls with this name. Default `0`. */
1489
- occurrence?: number;
1490
- }
1491
- /**
1492
- * One idle pause, handed to {@link RunSeamOptions.respond} so the simulated
1493
- * user answers off the machine's own state rather than a fixed transcript — a
1494
- * live seam may branch differently, and a reactive policy scores that run
1495
- * instead of crashing on it.
1496
- */
1497
- interface SeamTurn<TMachine extends AnyStateMachine> {
1498
- /** The idle snapshot to answer. */
1499
- snapshot: SnapshotFrom<TMachine>;
1500
- /** Its state value, for a `switch` on flat machines. */
1501
- state: StateValue;
1502
- /**
1503
- * The merged `meta` of the active state(s), e.g. a declared `interaction`.
1504
- * Typed from the machine's own meta schema (`setupAgent({ meta })`).
1505
- */
1506
- meta: Partial<MetaOfSnapshot<SnapshotFrom<TMachine>>>;
1507
- /** 0-based index of this pause within the run. */
1508
- turn: number;
1509
- /** The `idle` result that produced the pause. */
1510
- result: RunAgentResult<TMachine>;
1511
- }
1512
- /**
1513
- * One text call in a {@link runSeam} run's ledger, in call order — the receipt
1514
- * that says which answers came from the script and which one came from the
1515
- * candidate, so "everything else stayed scripted" is a plain assertion on
1516
- * {@link RunSeamResult.calls} rather than a recording function wrapped around
1517
- * every script entry. Text calls only: `decide` and other base executors are
1518
- * not routed by the seam and do not appear.
1519
- */
1520
- interface SeamCall {
1521
- /** The request's `name`, when it has one. */
1522
- name?: string;
1523
- /** The request's model key. */
1524
- model: string;
1525
- /** The `scripts` queue key that routed this call. */
1526
- key: string;
1527
- /** Where the answer came from: the script, or the seam's `candidate`. */
1528
- source: "script" | "candidate";
1529
- /** True for the seam call itself — scripted or candidate. */
1530
- seam: boolean;
1531
- }
1532
- /** One side of the seam: a trajectory pair ready for `matchesTrajectory`. */
1533
- interface SeamSlice {
1534
- /** State values entered on this side of the seam, in order. */
1535
- statePath: StateValue[];
1536
- /** Root-machine transition events on this side of the seam, in order. */
1537
- events: TrajectoryEvent[];
1538
- }
1539
- /** Options for {@link runSeam}. */
1540
- interface RunSeamOptions<TMachine extends AnyStateMachine> {
1541
- /** Machine input, passed straight through to `runAgent`. */
1542
- input?: InputFrom<TMachine>;
1543
- /**
1544
- * The call plan: scripted answers per key, consumed in order. A key is a
1545
- * request `name` when one is scripted under it, else a `model` key, so a
1546
- * machine whose requests are named routes by name and an unnamed one routes
1547
- * by model.
1548
- *
1549
- * Entries follow {@link ScriptedTextEntry} conventions (a value, an
1550
- * `{ output, usage? }` envelope, or a function of the request). A queue that
1551
- * runs dry throws; set {@link RunSeamOptions.repeatLast} to replay its last
1552
- * entry instead.
1553
- */
1554
- scripts?: Record<string, ScriptedTextEntry[]>;
1555
- /**
1556
- * Replay the LAST entry of a queue once it is exhausted, so a live seam that
1557
- * sends the run down a longer branch still finds an answer. Off by default:
1558
- * a dry queue throws, the same as every other scripted surface.
1559
- */
1560
- repeatLast?: boolean;
1561
- /** The call under test. */
1562
- seam: SeamRef;
1563
- /**
1564
- * The executor for the seam — the real model, a candidate prompt, anything
1565
- * request-shaped. Omit to run the seam scripted too: the whole seam run is
1566
- * then deterministic.
1567
- */
1568
- candidate?: AgentRequestExecutor;
1569
- /**
1570
- * The simulated user. Called at every idle pause; return the event to send,
1571
- * or `null`/`undefined` to stop the run there. Omitted, the run stops at the
1572
- * first idle pause.
1573
- */
1574
- respond?: (turn: SeamTurn<TMachine>) => EventFromLogic<TMachine> | null | undefined;
1575
- /** Maximum idle pauses to answer before stopping. Default `12`. */
1576
- maxTurns?: number;
1577
- /**
1578
- * Base executors merged UNDER the seam routing — supply `decide` (e.g. from
1579
- * `createScriptedExecutors({ decisions })`) for a machine that also decides.
1580
- * Text slots are always owned by the routing.
1581
- */
1582
- executors?: Partial<AgentRequestExecutors>;
1583
- /** Passed through to `runAgent`: actor implementations merged onto the machine. */
1584
- actors?: RunAgentOptions<TMachine>["actors"];
1585
- }
1586
- /** What {@link runSeam} returns: the seam's own answer, plus the run it caused. */
1587
- interface RunSeamResult<TMachine extends AnyStateMachine> {
1588
- /**
1589
- * The final `runAgent` result. `usage` accounts for the last leg.
1590
- */
1591
- result: RunAgentResult<TMachine>;
1592
- /** What the seam call returned, or `undefined` when the run never reached it. */
1593
- seamOutput: unknown;
1594
- /**
1595
- * The seam call's own reported token usage — the cost of the one live call
1596
- * when a `candidate` is a real model. `undefined` when the run never reached
1597
- * the seam or its answer reported no usage (scripted entries report usage
1598
- * only via the `{ output, usage }` envelope).
1599
- */
1600
- seamUsage?: AgentCallUsage;
1601
- /** Model calls made before the seam, or `-1` when the run never reached it. */
1602
- callsBeforeSeam: number;
1603
- /** The run's text calls in order: what was served, and by whom. */
1604
- calls: SeamCall[];
1605
- /** Everything up to the seam's own effect completion. */
1606
- before: SeamSlice;
1607
- /**
1608
- * Everything from the seam's own effect completion onward — the branch the
1609
- * seam caused, and the score. Empty when the run never reached the seam.
1610
- */
1611
- after: SeamSlice;
1612
- }
1613
- /**
1614
- * Runs a machine end to end with one model call under test, and slices the run
1615
- * at that call.
1616
- *
1617
- * The `before`/`after` slices are the point: `after.statePath` is the branch
1618
- * the seam chose and `after.events` is the same question against the durable
1619
- * log, both ready for `matchesTrajectory`. The state slice splits where the
1620
- * state path stood when the seam answered; the event slice splits at the
1621
- * seam's own effect completion (the first `xstate.done.*`/`xstate.error.*`
1622
- * entry appended after the call was made).
1623
- *
1624
- * @example No API key: the seam is scripted too, so the whole thing runs offline.
1625
- * ```ts
1626
- * const run = await runSeam(emailDrafter, {
1627
- * scripts: { promptEvaluator: [vague, complete], emailDrafter: [draft] },
1628
- * seam: { request: 'evaluatePrompt' },
1629
- * respond: ({ state }) => (state === 'prompting' ? { type: 'PROMPT_SUBMITTED', prompt } : null),
1630
- * });
1631
- *
1632
- * matchesTrajectory(run.after.statePath, ['needsMoreInfo', 'drafting']);
1633
- * ```
1634
- *
1635
- * @example A candidate prompt at the seam, scored against the same rows.
1636
- * ```ts
1637
- * const { generateText } = createAiSdkExecutors({ models });
1638
- * const run = await runSeam(emailDrafter, { ...row, candidate: generateText });
1639
- * ```
1640
- */
1641
- declare function runSeam<TMachine extends AnyStateMachine>(machine: TMachine, options: RunSeamOptions<TMachine>): Promise<RunSeamResult<TMachine>>;
1642
- //#endregion
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 };
742
+ export { AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, type AgentCallUsage, type AgentDecisionExecutor, AgentDecisionExhaustedError, type AgentDecisionInput, type AgentDecisionRequest, type AgentDefaultMeta, AgentError, type AgentEventDescriptor, AgentEventLogConflictError, type AgentEventLogStore, type AgentExecutorDecisionRequest, type AgentExecutorTextRequest, type AgentFinishReason, type AgentInputFrom, type AgentInteraction, type AgentInteractionDescriptor, type AgentInteractionEvent, type AgentInteractionEventMeta, type AgentInteractionMeta, AgentInvalidEventPayloadError, type AgentLogEntry, AgentMachineVersionMismatchError, AgentMaxModelCallsExceededError, type AgentMessage, type AgentModelRef, type AgentOutputMode, type AgentRequest, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestOptions, type AgentRequestSource, type AgentRunMeta, type AgentSchemaPack, type AgentSchemas, AgentSnapshotDivergedError, type AgentStep, type AgentStepRequest, type AgentStreamEvent, type AgentTextRequest, type AgentTextResult, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentTools, type AgentTraceEvent, type AgentTransitionHandler, AgentTruncatedError, type AgentUsage, type AgentUsageEvent, type AgentUsageEventPayload, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AllowedEvents, type AssistantMessage, type ChosenEvent, type ContextOf, type CreateDecisionRequestOptions, type DecisionAttempt, type DecisionLogic, type DecisionLogicConfig, type DoneActorEventOf, type EventOf, type FilePart, type FromConfigOptions, type FromConfigResult, type GetInteractionOptions, type ImagePart, type InferInput, type InferOutput, type InputOf, type InspectedActorRef, type JsonSerializableTraceEvent, type MetaOf, type OutputOf, type ProvideExecutorsOptions, type ProviderStructuredOutput, type RequestNamesOf, type ResolveDecisionOptions, type RunAgentErrorCause, type RunAgentOptions, type RunAgentResult, type SchemaCompiler, type SnapshotOf, type StandardSchemaV1, type StateValueOf, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultPart, type UserMessage, type WithAgentEvents, type WithAgentUsageEvent, assistantMessage, bindRequestExecutor, createAgentSchemas, createDecisionLogic, createDecisionRequest, createTextLogic, eventFromInteraction, executeAgentRequest, getAcceptedEvents, getAgentOutputMode, getAgentSchemas, getCallFinishReason, getCallUsage, getInteraction, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getMessageText, getStateMeta, getStatePath, initialAgentStep, inspectTransitions, interactionMetaSchema, isAgentIdle, isAgentMessages, isStandardSchema, messagesSchema, parseAgentEvent, parseOutput, parseProviderOutput, provideExecutors, providerOutputSchema, rejectAgentStep, renderDecisionAttempts, resolveAgentStep, resolveDecision, runAgent, runAgentStream, serializeTraceEvent, setupAgent, systemMessage, toolMessage, traceTransitions, transitionAgentStep, userMessage };