@statelyai/agent 2.0.0-alpha.28 → 2.0.0-alpha.30

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 (80) hide show
  1. package/dist/ai-sdk.cjs +150 -27
  2. package/dist/ai-sdk.d.cts +59 -36
  3. package/dist/ai-sdk.d.mts +59 -36
  4. package/dist/ai-sdk.mjs +148 -24
  5. package/dist/{decision-RQ0iv0oZ.mjs → decision-BHkvuImD.mjs} +74 -8
  6. package/dist/{decision-CmM8-HHz.cjs → decision-CIb7ddIv.cjs} +113 -30
  7. package/dist/{text-logic-f5F5sCdc.cjs → event-log-BZRfBRd7.cjs} +814 -7
  8. package/dist/{text-logic-CIqHAmBi.mjs → event-log-DJCMHek_.mjs} +680 -4
  9. package/dist/{event-log-store-BIPOz-di.d.mts → event-log-store-CIIJohjj.d.mts} +90 -5
  10. package/dist/{event-log-store-2xzFmgr2.d.cts → event-log-store-CLAC9q2Y.d.cts} +90 -5
  11. package/dist/event-log-store-DZR4IIWe.cjs +95 -0
  12. package/dist/event-log-store-DsP6GCRh.mjs +84 -0
  13. package/dist/index.cjs +576 -58
  14. package/dist/index.d.cts +104 -510
  15. package/dist/index.d.mts +104 -510
  16. package/dist/index.mjs +547 -32
  17. package/dist/log.cjs +77 -20
  18. package/dist/log.d.cts +5 -5
  19. package/dist/log.d.mts +5 -5
  20. package/dist/log.mjs +58 -3
  21. package/dist/machines.cjs +1 -1
  22. package/dist/machines.d.cts +15 -15
  23. package/dist/machines.d.mts +15 -15
  24. package/dist/machines.mjs +1 -1
  25. package/dist/model-source-BCKg4qJ1.cjs +44 -0
  26. package/dist/model-source-BaHwJ1wK.mjs +39 -0
  27. package/dist/openai.cjs +11 -11
  28. package/dist/openai.d.cts +28 -26
  29. package/dist/openai.d.mts +28 -26
  30. package/dist/openai.mjs +3 -3
  31. package/dist/otel.cjs +5 -4
  32. package/dist/otel.d.cts +5 -7
  33. package/dist/otel.d.mts +5 -7
  34. package/dist/otel.mjs +5 -3
  35. package/dist/{run-agent-xNTxpt82.mjs → run-agent-BpHqkaZw.mjs} +181 -44
  36. package/dist/{run-agent-COXXc0RW.d.mts → run-agent-CAVt5R-r.d.mts} +95 -30
  37. package/dist/{run-agent-ByO-Bxyd.d.cts → run-agent-CTlMc3Jb.d.cts} +95 -30
  38. package/dist/{run-agent-Dmf8GV2d.cjs → run-agent-ctLCvNgL.cjs} +230 -88
  39. package/dist/{setup-agent-BuanDXeh.mjs → setup-agent-7rV_cujV.mjs} +15 -9
  40. package/dist/setup-agent-CGELn1qZ.d.mts +577 -0
  41. package/dist/setup-agent-CLPCkXsu.d.cts +577 -0
  42. package/dist/{setup-agent-DV4cTou-.cjs → setup-agent-DoUk7EdC.cjs} +31 -20
  43. package/dist/tanstack-ai.cjs +627 -0
  44. package/dist/tanstack-ai.d.cts +204 -0
  45. package/dist/tanstack-ai.d.mts +204 -0
  46. package/dist/tanstack-ai.mjs +618 -0
  47. package/dist/testing.cjs +204 -985
  48. package/dist/testing.d.cts +132 -347
  49. package/dist/testing.d.mts +132 -347
  50. package/dist/testing.mjs +191 -973
  51. package/dist/{text-logic-IjfYy9DP.d.cts → text-logic-BRYOPWvY.d.mts} +52 -12
  52. package/dist/{text-logic-D-czVPYp.d.mts → text-logic-DmciuVUQ.d.cts} +52 -12
  53. package/dist/{types-BgNbNKnJ.d.mts → types-Dp5_Ru4R.d.cts} +2 -2
  54. package/dist/{types-hR5f5YXa.d.cts → types-Dp5_Ru4R.d.mts} +2 -2
  55. package/dist/usage-BkM3z02Y.d.mts +17 -0
  56. package/dist/usage-Cm_ovz9V.d.cts +17 -0
  57. package/dist/{utils-_q7F-AZu.d.mts → utils-BnXdWih3.d.mts} +1 -2
  58. package/dist/{utils-o4YRdHJX.d.cts → utils-ebVpCYoF.d.cts} +1 -2
  59. package/dist/validate.cjs +239 -8
  60. package/dist/validate.d.cts +110 -3
  61. package/dist/validate.d.mts +110 -3
  62. package/dist/validate.mjs +238 -7
  63. package/dist/verify-COFWyprJ.mjs +1181 -0
  64. package/dist/verify-CVlsTZ-V.cjs +1222 -0
  65. package/dist/verify-Cn86rT8l.d.mts +414 -0
  66. package/dist/verify-Dzwd4Mvk.d.cts +414 -0
  67. package/package.json +44 -31
  68. package/readme.md +40 -28
  69. package/skills/add-evals/SKILL.md +129 -0
  70. package/skills/add-traces/SKILL.md +135 -0
  71. package/skills/generate-machine/SKILL.md +143 -69
  72. package/skills/graph-engineering/SKILL.md +33 -0
  73. package/skills/improve-machine/SKILL.md +241 -0
  74. package/skills/improve-machine/reference.md +101 -0
  75. package/skills/loop-to-machine/SKILL.md +183 -0
  76. package/skills/loop-to-machine/policy.md +158 -0
  77. package/dist/event-log-store-2pAFiWuc.mjs +0 -576
  78. package/dist/event-log-store-C-COhIXP.cjs +0 -702
  79. package/dist/usage-BdEjFuIi.mjs +0 -5
  80. package/dist/usage-efOQPdf_.cjs +0 -10
package/dist/index.d.mts CHANGED
@@ -1,10 +1,11 @@
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-BgNbNKnJ.mjs";
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-D-czVPYp.mjs";
3
- import { C as serializeTraceEvent, D as AGENT_USAGE_EVENT_TYPE, E as AgentStepRequest, O as AgentUsageEvent, S as runToQuiescence, T as AgentRequest, _ as InspectedActorRef, a as AgentRunErrorCause, b as inspectTransitions, c as AgentRunResult, d as AgentRuntimeOptions, f as AgentSnapshotDivergedError, g as AgentTransitionHandler, h as AgentTraceEvent, i as AgentMaxModelCallsExceededError, l as AgentRunStart, m as AgentTimerScheduler, n as AgentEffects, o as AgentRunInit, p as AgentTimerEvent, r as AgentInputFrom, s as AgentRunMeta, t as AGENT_TRACE_SCHEMA_VERSION, u as AgentRuntime, v as JsonSerializableTraceEvent, w as traceTransitions, x as isAgentIdle, y as createAgentRuntime } from "./run-agent-COXXc0RW.mjs";
4
- import { c as AgentLogEntry, d as AgentMachineVersionMismatchError, n as AgentEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-BIPOz-di.mjs";
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-_q7F-AZu.mjs";
6
- import { AnyActorLogic, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, ContextFrom, DoneActorEvent, EventFromLogic, EventObject, InputFrom, MachineContext, MetaObject, NonReducibleUnknown, OutputFrom, SetupReturnFromConfig, SetupStateSchema, SnapshotFrom, StateValueFrom } from "xstate";
7
-
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, 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, u as ChosenEvent, v as SystemMessage, x as ToolMessage, y as TextPart } from "./types-Dp5_Ru4R.mjs";
2
+ import { $ as AgentTruncatedError, A as AgentDecisionExhaustedError, B as createDecisionLogic, C as getAgentOutputMode, D as parseProviderOutput, E as parseOutput, F as CreateDecisionRequestOptions, G as AgentInvalidEventPayloadError, H as renderDecisionAttempts, I as DecisionAttempt, J as AgentSchemas, K as AgentRequestOptions, L as DecisionLogic, M as AgentDecisionOption, N as AgentDecisionRequest, O as providerOutputSchema, P as AgentExecutorDecisionRequest, Q as AgentError, R as DecisionLogicConfig, S as createTextLogic, T as getCallUsage, U as resolveDecision, V as createDecisionRequest, W as AgentEventDescriptor, X as getAcceptedEvents, Y as EventFromSnapshot, Z as parseAgentEvent, _ as TextLogic, a as AgentModelRef, b as TextLogicExecutor, c as AgentRequestExecutorInfo, f as AgentTextRequest, g as ProviderStructuredOutput, j as AgentDecisionInput, k as AgentDecisionExecutor, l as AgentRequestExecutorResult, m as AgentUsage, n as AgentExecutorTextRequest, o as AgentOutputMode, p as AgentTextResult, q as AgentRequestSource, 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 ResolveDecisionOptions } from "./text-logic-BRYOPWvY.mjs";
3
+ import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-BkM3z02Y.mjs";
4
+ import { C as AgentInteractionEventMeta, D as getInteraction, E as eventFromInteraction, O as interactionMetaSchema, S as AgentInteractionEvent, T as GetInteractionOptions, _ as FromConfigResult, a as WithAgentUsageEvent, b as AgentInteractionChoice, c as setupAgent, d as AgentWorkflowConfig, f as AgentWorkflowInvokeConfig, g as FromConfigOptions, h as AgentWorkflowTransitionConfig, i as WithAgentEvents, l as AgentWorkflowActionConfig, m as AgentWorkflowStateConfig, n as AgentSchemaPack, o as createAgentSchemas, p as AgentWorkflowRequestConfig, r as AgentUsageEventPayload, s as getAgentSchemas, t as AgentDefaultMeta, u as AgentWorkflowActorConfig, v as SchemaCompiler, w as AgentInteractionMeta, x as AgentInteractionDescriptor, y as AgentInteraction } from "./setup-agent-CGELn1qZ.mjs";
5
+ import { C as runAgent, D as AgentRequest, E as traceTransitions, O as AgentStepRequest, S as isAgentIdle, T as serializeTraceEvent, _ as AgentTransitionHandler, a as AgentRunErrorCause, b as createAgentRuntime, c as AgentRunOptions, d as AgentRuntime, f as AgentRuntimeOptions, g as AgentTraceEvent, h as AgentTimerScheduler, i as AgentMaxModelCallsExceededError, l as AgentRunResult, m as AgentTimerEvent, n as AgentEffects, o as AgentRunInit, p as AgentSnapshotDivergedError, r as AgentInputFrom, s as AgentRunMeta, t as AGENT_TRACE_SCHEMA_VERSION, u as AgentRunStart, v as InspectedActorRef, w as runToQuiescence, x as inspectTransitions, y as JsonSerializableTraceEvent } from "./run-agent-CAVt5R-r.mjs";
6
+ import { c as AgentLogEntry, d as AgentMachineVersionMismatchError, n as AgentEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-CIIJohjj.mjs";
7
+ 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-BnXdWih3.mjs";
8
+ import { AnyActorLogic, AnyMachineSnapshot, AnyStateMachine, ContextFrom, DoneActorEvent, EventFromLogic, InputFrom, OutputFrom, SnapshotFrom, StateValueFrom } from "xstate";
8
9
  //#region src/type-helpers.d.ts
9
10
  type SchemaAt<T, TKey extends PropertyKey> = T extends {
10
11
  schemas: Record<TKey, infer TSchema extends StandardSchemaV1>;
@@ -62,534 +63,127 @@ type DoneActorEventOf<TLogic extends AnyActorLogic, TId extends string = string>
62
63
  * context schema write `z.custom<AgentMessage[]>(isAgentMessages)`, which runs
63
64
  * this same validator (see {@link isAgentMessages}).
64
65
  */
65
- declare const messagesSchema: StandardSchemaV1<AgentMessage[]>;
66
+ export declare const messagesSchema: StandardSchemaV1<AgentMessage[]>;
66
67
  /**
67
68
  * Type guard over {@link messagesSchema}: `true` when `value` is a valid
68
69
  * `AgentMessage[]`. The one-liner for zod context schemas:
69
70
  * `messages: z.custom<AgentMessage[]>(isAgentMessages)`.
70
71
  */
71
- declare function isAgentMessages(value: unknown): value is AgentMessage[];
72
+ export declare function isAgentMessages(value: unknown): value is AgentMessage[];
72
73
  //#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>;
74
+ //#region src/describe-machine.d.ts
75
+ /** Options for {@link describeMachine}. */
76
+ interface DescribeMachineOptions {
77
+ /** Marks the state nodes active in this snapshot with `*`. */
78
+ snapshot?: AnyMachineSnapshot;
118
79
  }
119
80
  /**
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
151
- //#region src/workflow-config.d.ts
152
- type JsonSchemaObject = {
153
- type?: string | string[];
154
- properties?: Record<string, JsonSchemaObject>;
155
- required?: string[];
156
- items?: JsonSchemaObject;
157
- enum?: unknown[];
158
- const?: unknown;
159
- additionalProperties?: unknown;
160
- [key: string]: unknown;
161
- };
162
- /**
163
- * Compiles a JSON Schema object (from an `AgentWorkflowConfig`) into a
164
- * runtime `StandardSchemaV1` validator. `setupAgent.fromConfig(...)` calls
165
- * this once per schema in the config (context/events/input/output/meta,
166
- * request input/output) — bring your own engine (Ajv, @cfworker/json-schema,
167
- * a compiled-Zod-from-JSON-Schema pipeline, ...). Core intentionally ships no
168
- * JSON Schema engine.
169
- */
170
- type SchemaCompiler = (jsonSchema: Record<string, unknown>, name: string) => StandardSchemaV1;
171
- /**
172
- * Serializable JSON/YAML machine definition — the config a database, visual
173
- * editor, or LLM could produce and hand to `setupAgent.fromConfig(config, {
174
- * compileSchema })` to get back the same kind of `AnyStateMachine`
175
- * TypeScript `setupAgent(...)` authoring would build. JS/TS authoring should
176
- * use `setupAgent(...)` directly instead of this JSON form. Any `unknown`-
177
- * typed field here (`model`, `guard`, action `params`, …) accepts either a
178
- * literal JSON value or a `"{{ path.to.value }}"` template-expression string
179
- * resolved against `{ context, event, input, output }` at machine-build/
180
- * transition time — see the sibling `evaluateWorkflowConfigValue` lowering.
181
- */
182
- interface AgentWorkflowConfig {
183
- /** JSON Schema reference (`"$schema"`) editors attach to a config file. Ignored by the lowering. */
184
- $schema?: string;
185
- key?: string;
186
- id?: string;
187
- version?: string;
188
- description?: string;
189
- schemas?: {
190
- input?: JsonSchemaObject;
191
- context?: JsonSchemaObject;
192
- events?: Record<string, JsonSchemaObject>;
193
- emitted?: Record<string, JsonSchemaObject>;
194
- output?: JsonSchemaObject;
195
- meta?: JsonSchemaObject;
196
- };
197
- context?: Record<string, unknown>;
198
- requests?: Record<string, AgentWorkflowRequestConfig>;
199
- actors?: Record<string, AgentWorkflowActorConfig>;
200
- initial: string;
201
- states: Record<string, AgentWorkflowStateConfig>;
202
- meta?: Record<string, unknown>;
203
- }
204
- /** A `requests` entry in {@link AgentWorkflowConfig} — the JSON equivalent of a `setupAgent({ requests })` `TextLogicConfig`. Fields beyond `input`/`output`/`tools`/`mode`/`description` are `unknown` because they accept template-expression strings (see {@link AgentWorkflowConfig}). */
205
- interface AgentWorkflowRequestConfig {
206
- mode?: AgentRequestMode;
207
- description?: string;
208
- model: unknown;
209
- system?: unknown;
210
- prompt?: unknown;
211
- messages?: unknown;
212
- input: JsonSchemaObject;
213
- output: JsonSchemaObject;
214
- tools?: AgentTools;
215
- toolChoice?: AgentToolChoice | unknown;
216
- /** Opt into the provider output's `reasoning` field (see `AgentTextRequest.includeReasoning`). */
217
- includeReasoning?: boolean;
218
- temperature?: unknown;
219
- maxOutputTokens?: unknown;
220
- topP?: unknown;
221
- topK?: unknown;
222
- seed?: unknown;
223
- stopSequences?: unknown;
224
- metadata?: unknown;
225
- }
226
- /** An `actors` entry in {@link AgentWorkflowConfig} — declares a placeholder actor source (by key) with no host execution wired from JSON; provide it via `machine.provide({ actors })` after `setupAgent.fromConfig(...)`. */
227
- interface AgentWorkflowActorConfig {
228
- input?: JsonSchemaObject;
229
- output?: JsonSchemaObject;
230
- description?: string;
231
- }
232
- /** A `states` entry in {@link AgentWorkflowConfig} — the JSON equivalent of an XState state node config. */
233
- interface AgentWorkflowStateConfig {
234
- description?: string;
235
- type?: "parallel" | "history" | "final" | "choice";
236
- initial?: string;
237
- states?: Record<string, AgentWorkflowStateConfig>;
238
- choice?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
239
- invoke?: AgentWorkflowInvokeConfig | AgentWorkflowInvokeConfig[];
240
- on?: Record<string, AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[]>;
241
- always?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
242
- onDone?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
243
- after?: Record<string, AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[]>;
244
- entry?: AgentWorkflowActionConfig | AgentWorkflowActionConfig[];
245
- exit?: AgentWorkflowActionConfig | AgentWorkflowActionConfig[];
246
- tags?: string[];
247
- output?: unknown;
248
- meta?: Record<string, unknown>;
249
- }
250
- /**
251
- * An `invoke` entry in {@link AgentWorkflowStateConfig}. For `src:
252
- * 'agent.decide'`, the chosen event is delivered automatically and handled by
253
- * the state's `on` transitions — a decision has no output of its own, so an
254
- * `onDone` there is always a config error and is rejected at
255
- * `setupAgent.fromConfig(...)` time. `onError` handles retries-exhausted.
256
- */
257
- interface AgentWorkflowInvokeConfig {
258
- id?: string;
259
- src: string;
260
- input?: unknown;
261
- onDone?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
262
- onError?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
263
- meta?: Record<string, unknown>;
264
- }
265
- /**
266
- * A transition target in {@link AgentWorkflowConfig}
267
- * (`on`/`always`/`onDone`/`after`/invoke `onDone`/`onError`) — the JSON
268
- * equivalent of an XState transition config. A string `guard` containing
269
- * `{{ ... }}` is a template expression evaluated as truthy/falsy; any other
270
- * string is a named guard reference resolved against the `guards` passed to
271
- * `setupAgent.fromConfig(config, { guards })` (unresolvable references throw
272
- * at build time).
273
- */
274
- interface AgentWorkflowTransitionConfig {
275
- target?: string | string[];
276
- guard?: unknown;
277
- assign?: Record<string, unknown>;
278
- actions?: AgentWorkflowActionConfig | AgentWorkflowActionConfig[];
279
- description?: string;
280
- reenter?: boolean;
281
- meta?: Record<string, unknown>;
282
- }
283
- /** An `entry`/`exit`/transition `actions` entry in {@link AgentWorkflowConfig} — a bare context `assign`, an `emit`, or a named action `type` (with template-expression `params`) resolved against the `actions` passed to `setupAgent.fromConfig(config, { actions })`. */
284
- interface AgentWorkflowActionConfig {
285
- type?: string;
286
- params?: unknown;
287
- assign?: Record<string, unknown>;
288
- emit?: unknown;
289
- [key: string]: unknown;
290
- }
291
- /**
292
- * What `setupAgent.fromConfig(...)` returns: the built machine plus the
293
- * schema pack compiled from the config's `schemas` (with `compileSchema`).
294
- * The pack is what hosts need for the runtime work the machine's types can't
295
- * do for a JSON-authored agent — e.g. validating an inbound raw event:
81
+ * Describes a machine in plain text for a model to read. The machine's
82
+ * `description` is its goal, so it leads: `Machine <id>`, then `Goal: …`.
83
+ * Then every state node, indented by depth, with its type, tags, interaction
84
+ * label and description (`*` marks the active ones when `snapshot` is given),
85
+ * and under it every transition leaving it, one per line: `on EVENT`,
86
+ * `always`, `after <delay>`, invoke `done`/`error`, and `choice` branches,
87
+ * each with its guard (`if …`), where it goes (`→ review`), and what it sets
88
+ * in context (`sets draft, attempts`). An `Events` section lists the
89
+ * machine's event schemas with their descriptions and fields.
90
+ *
91
+ * A transition written as a function shows the targets its source names
92
+ * (`→ review (conditional)` when it may decline or pick among several),
93
+ * `(stays)` when its source has no `target`, or `→ ?` when no target can be
94
+ * read. A `setupAgent.fromConfig(...)` machine is read from its config, so
95
+ * its targets, guards and context patches are always known.
296
96
  *
297
97
  * @example
298
98
  * ```ts
299
- * const { machine, schemas } = setupAgent.fromConfig(config, { compileSchema });
300
- * const event = parseAgentEvent(snapshot, raw, { events: schemas.events });
99
+ * const prompt = `Propose a better machine for this goal.\n\n${describeMachine(machine)}`;
301
100
  * ```
302
101
  */
303
- interface FromConfigResult {
304
- machine: AnyStateMachine;
305
- /** Compiled `context`/`events`/`input`/`output`/`meta`/`emitted` schemas — the same pack `createAgentRuntime` executes this machine with. */
306
- schemas: AgentSchemaPack<StandardSchemaV1<Record<string, unknown>>, Record<string, StandardSchemaV1>, StandardSchemaV1, StandardSchemaV1, StandardSchemaV1<MetaObject>>;
307
- }
308
- /** Options for `setupAgent.fromConfig(...)`. */
309
- interface FromConfigOptions {
102
+ export declare function describeMachine(machine: AnyStateMachine, options?: DescribeMachineOptions): string;
103
+ //#endregion
104
+ //#region src/decide-next.d.ts
105
+ /** Options for {@link decideNext}. */
106
+ interface DecideNextOptions<TSnapshot extends AnyMachineSnapshot = AnyMachineSnapshot> {
107
+ /** The decide executor that asks a model to pick one option. */
108
+ decide: AgentDecisionExecutor;
109
+ /** Model ref, passed through to the executor. */
110
+ model: string;
111
+ /** Event types the model may choose: exact types or wildcards (`'desk.*'`, `'*'`). */
112
+ allowedEvents: string | readonly string[];
310
113
  /**
311
- * Compile a JSON Schema from the config into a runtime validator. Bring
312
- * your own engine (Ajv, @cfworker/json-schema, a compiled-Zod-from-JSON-Schema
313
- * pipeline, ...). Core intentionally ships no JSON Schema engine.
114
+ * Concrete payloads per event type, without `type`. One option per payload.
115
+ * A candidate type with no key is offered bare, as `{ type }`; an empty list
116
+ * offers nothing for it. To withhold a type, give it `[]`:
117
+ * `(s) => ({ "desk.refund": [{ amount: s.context.requested }], "desk.close": [] })`.
314
118
  */
315
- compileSchema: SchemaCompiler;
119
+ payloads?: (snapshot: TSnapshot) => Partial<Record<string, Record<string, unknown>[]>>;
120
+ system?: string;
121
+ prompt?: string;
122
+ /** Semantic request name, for traces and scripted executors. Default `'decideNext'`. */
123
+ name?: string;
316
124
  /**
317
- * Host guard implementations for named guard references in the config
318
- * (`guard: "isFromHuman"`). Each is called with `{ context, event }` and
319
- * returns a boolean. A named guard reference with no implementation here is
320
- * a build-time error — a guard is never silently dropped.
125
+ * Describe what each option changes: the state value and the changed
126
+ * top-level context keys, computed with xstate's pure `transition()`.
127
+ * An array limits which context keys are reported (a state value change is
128
+ * always reported). Each reported value is cut to 120 characters.
321
129
  */
322
- guards?: Record<string, (args: {
323
- context: any;
324
- event: any;
325
- }) => boolean>;
130
+ lookahead?: boolean | readonly string[];
131
+ /** Retries after a failed choice. Default `2`. */
132
+ maxRetries?: number;
133
+ signal?: AbortSignal;
134
+ }
135
+ /** Result of {@link decideNext}. */
136
+ interface DecideNextResult<TEvent = ChosenEvent> {
137
+ /** The chosen event, or `null` when the snapshot accepts none of the options. */
138
+ event: TEvent | null;
139
+ /** Failed attempts before the choice landed. */
140
+ attempts: DecisionAttempt[];
141
+ /** The request built for the executor, with the offered `options` and the same `withheld`. */
142
+ request: AgentDecisionRequest;
326
143
  /**
327
- * Host action implementations for named action types in the config
328
- * (`{ type: "notify", params: ... }`). Each is called with the
329
- * template-resolved `params` as its only argument — pull context/event data
330
- * into `params` via `{{ ... }}` templates. A named action type with no
331
- * implementation here is a build-time error.
144
+ * The candidates the snapshot rejected: every `allowedEvents` type × payload,
145
+ * built the same way as the offered options, where `snapshot.can(event)` was
146
+ * false. Never offered to the model. Filled when nothing is offered too.
332
147
  */
333
- actions?: Record<string, (params: any) => unknown>;
148
+ withheld: ChosenEvent[];
334
149
  }
335
- //#endregion
336
- //#region src/setup-agent.d.ts
337
- type Constrain<T, TConstraint> = T extends TConstraint ? T : TConstraint;
338
- type ContextOf$1<TContextSchema extends StandardSchemaV1> = Constrain<InferOutput<TContextSchema>, MachineContext>;
339
- type EventsOf<TEventSchemas extends AgentEventSchemaInputMap> = Constrain<EventUnion<TEventSchemas>, EventObject>;
340
- /**
341
- * The first argument a guard or delay source receives. `context` and `event`
342
- * come from the agent's own schemas, so an inline source is contextually typed
343
- * and an annotated one stays assignable. XState's remaining fields (`self`,
344
- * `parent`, `value`, `children`, `stateNode`) are deliberately not modeled:
345
- * `setupAgent` only forwards these sources to `setup()`, which types them for
346
- * real where the machine is built.
347
- */
348
- type AgentSourceArgs<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap> = {
349
- context: ContextOf$1<TContextSchema>;
350
- event: EventsOf<TEventSchemas>;
351
- };
352
- /** Guard sources for `setupAgent({ guards })`, typed against the agent's own context and events. */
353
- type AgentGuardSources<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap> = Record<string, (args: AgentSourceArgs<TContextSchema, TEventSchemas>, ...params: any[]) => boolean>;
354
- /** Delay sources for `setupAgent({ delays })`, typed the same way as {@link AgentGuardSources}. */
355
- type AgentDelaySources<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap> = Record<string, number | ((args: AgentSourceArgs<TContextSchema, TEventSchemas>) => number)>;
356
- 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] };
357
- type AgentSetupActors<TActors extends { [K in keyof TActors]: AnyActorLogic }, TEvent extends string = string, TModel extends string = string> = TActors & BuiltinAgentActors<TEvent, TModel>;
358
- /**
359
- * The default `meta` type of an agent machine: the interaction descriptor
360
- * `getInteraction` reads, keyed by the machine's own event types (the
361
- * reserved `@agent.*` events excluded). A machine that declares `meta`
362
- * replaces this default.
363
- */
364
- type AgentDefaultMeta<TEventSchemas extends AgentEventSchemaInputMap> = AgentInteractionMeta<Exclude<keyof TEventSchemas & string, typeof AGENT_USAGE_EVENT_TYPE>>;
365
- /**
366
- * A machine's full schema set — context, event payloads, machine input/
367
- * output, and state/transition meta — as returned by {@link createAgentSchemas}
368
- * and retained on `setupAgent(...)`'s `result.schemas` for runtime
369
- * validation (e.g. by `getAcceptedEvents` to attach event payload schemas). Unlike
370
- * `AgentSchemaConfig` (the input to `createAgentSchemas`), every field here
371
- * is required — `events`/`input`/`output`/`meta` default to empty/unknown
372
- * schemas when not supplied.
373
- */
374
- 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>> {
375
- context: TContextSchema;
376
- events: NormalizedEventSchemas<TEventSchemas>;
377
- input: TInputSchema;
378
- output: TOutputSchema;
379
- meta: TMetaSchema;
380
- /** Schemas for events the machine emits (`enq.emit(...)`), keyed by event type — they type `enq.emit` in the machine and the `on` handlers of {@link createAgentRuntime}. Optional: omitted means emitted events stay untyped. */
381
- emitted?: TEmittedSchemas;
382
- }
383
- type AgentSchemaConfig<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TEmittedSchemas extends Record<string, StandardSchemaV1> = Record<string, StandardSchemaV1>> = {
384
- context: TContextSchema;
385
- events?: TEventSchemas;
386
- input?: TInputSchema;
387
- output?: TOutputSchema;
388
- meta?: TMetaSchema;
389
- emitted?: TEmittedSchemas;
390
- };
391
- /**
392
- * The payload of the reserved `'@agent.usage'` event — {@link AgentUsageEvent}
393
- * without its `type`. It is what a machine's `'@agent.usage'` handler receives
394
- * alongside `type`, since event schemas describe payloads only.
395
- */
396
- type AgentUsageEventPayload = Omit<AgentUsageEvent, "type">;
397
- /**
398
- * An authored event schema map with the reserved `'@agent.usage'` entry added —
399
- * every agent machine's event union includes it, so `on: { '@agent.usage': … }`
400
- * is typed (and autocompletes) without the machine declaring anything.
401
- * Idempotent: re-applying it to an already-registered map is a no-op.
402
- */
403
- type WithAgentEvents<T extends AgentEventSchemaInputMap> = Omit<T, typeof AGENT_USAGE_EVENT_TYPE> & {
404
- [AGENT_USAGE_EVENT_TYPE]: StandardSchemaV1<AgentUsageEventPayload>;
405
- };
406
- /** @deprecated Use {@link WithAgentEvents}. */
407
- type WithAgentUsageEvent<T extends AgentEventSchemaInputMap> = WithAgentEvents<T>;
408
- /**
409
- * Builds a machine's {@link AgentSchemaPack} from a partial schema
410
- * declaration — only `context` is required; `events`/`input`/`output`/`meta`
411
- * default to empty/unknown schemas when omitted. Pass the result as
412
- * `setupAgent({ schemas })`'s `schemas` (or spread the individual fields
413
- * directly into `setupAgent({ context, events, ... })` — both forms are
414
- * accepted).
415
- */
416
- 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>;
417
- type AgentRequestSchemaMap = Record<string, {
418
- input?: StandardSchemaV1;
419
- output?: StandardSchemaV1;
420
- }>;
421
- type ResolvedRequestSchema<TSchema, TFallback> = [NonNullable<TSchema>] extends [never] ? TFallback : [NonNullable<TSchema>] extends [StandardSchemaV1] ? NonNullable<TSchema> : TFallback;
422
- type RequestInputSchema<TSchemas extends {
423
- input?: StandardSchemaV1;
424
- }> = ResolvedRequestSchema<TSchemas["input"], StandardSchemaV1<undefined>>;
425
- type RequestOutputSchema<TSchemas extends {
426
- output?: StandardSchemaV1;
427
- }> = ResolvedRequestSchema<TSchemas["output"], StandardSchemaV1<string>>;
428
- type AgentRequestInput<TRequestSchemas extends AgentRequestSchemaMap, TModel extends string = string> = { [K in keyof TRequestSchemas]: Omit<TextLogicConfig<RequestInputSchema<TRequestSchemas[K]>, RequestOutputSchema<TRequestSchemas[K]>, Record<string, unknown>, TModel>, "schemas"> & {
429
- schemas: TRequestSchemas[K];
430
- } };
431
- type RequestActors<TRequestSchemas extends AgentRequestSchemaMap> = { [K in keyof TRequestSchemas]: TextLogic<RequestInputSchema<TRequestSchemas[K]>, RequestOutputSchema<TRequestSchemas[K]>> };
432
- type AgentAllActors<TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap> = TActors & RequestActors<TRequestSchemas>;
433
- type AgentSetupEventsSchema<TEventSchemas extends AgentEventSchemaInputMap> = {
434
- events: NormalizedEventSchemas<WithAgentUsageEvent<TEventSchemas>>;
435
- };
436
- type AgentSetupEmittedSchema<TEmittedSchemas extends Record<string, StandardSchemaV1>> = [keyof TEmittedSchemas] extends [never] ? {} : {
437
- emitted: TEmittedSchemas;
438
- };
439
150
  /**
440
- * The input schema as handed to xstate's `setup(...)`, with the machine's input
441
- * type branded by the schema it came from.
151
+ * Asks a model to choose the next event for ANY XState snapshot, including a
152
+ * machine built with plain `createMachine`/`setup` that knows nothing about AI.
153
+ * The candidates are the `allowedEvents` an active state handles, one option per
154
+ * payload, kept only where `snapshot.can(event)` is true; the rest come back as
155
+ * `withheld`. Each option is
156
+ * described from the transition's `description`, else the event schema's,
157
+ * plus (with `lookahead`) what it changes. The chosen event must equal one
158
+ * offered option; anything else is retried.
442
159
  *
443
- * XState resolves `schemas.input` to a single type used both by
444
- * `createActor`'s `input` option and by the `context: ({ input })` factory —
445
- * and it never validates, so a schema default reads as a required field at the
446
- * call site while being absent at runtime. The runtime validates the input
447
- * (filling defaults) and reads this brand back through `AgentInputFrom` to
448
- * accept the schema's looser *input* side, while the factory keeps seeing the
449
- * validated *output* side.
450
- *
451
- * Only object-shaped input is branded: with no declared input schema the
452
- * resolved type is xstate's `NonReducibleUnknown` (a union including `null`),
453
- * and intersecting a brand into that collapses members to `never`.
454
- */
455
- type BrandedInputSchema<TInputSchema extends StandardSchemaV1> = InferOutput<TInputSchema> extends Record<string, unknown> ? StandardSchemaV1<InferInput<TInputSchema>, InferOutput<TInputSchema> & WithAgentInputSchema<TInputSchema>> : TInputSchema;
456
- type AgentSetupXStateConfig<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, SetupStateSchema> = Record<string, SetupStateSchema>> = {
457
- schemas: {
458
- context: TContextSchema;
459
- input: BrandedInputSchema<TInputSchema>;
460
- output: TOutputSchema;
461
- meta: TMetaSchema;
462
- } & AgentSetupEventsSchema<TEventSchemas> & AgentSetupEmittedSchema<TEmittedSchemas>;
463
- states?: TStateSchemas;
464
- actors: SetupActors<AgentSetupActors<AgentAllActors<TActors, TRequestSchemas>, Exclude<keyof TEventSchemas & string, typeof AGENT_USAGE_EVENT_TYPE>, AgentModelRef<TModels>>>;
465
- actions?: NonNullable<AnySetupConfig["actions"]>;
466
- guards?: NonNullable<AnySetupConfig["guards"]>;
467
- delays?: NonNullable<AnySetupConfig["delays"]>;
468
- };
469
- 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>> = ({
470
- schemas: AgentSchemaPack<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>;
471
- } | AgentSchemaConfig<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>) & {
472
- models?: TModels;
473
- actors?: TActors;
474
- /**
475
- * Per-state schemas, mirroring xstate's `setup({ states })`: narrow
476
- * `context` inside a state (invoke `input`, transition fns, final `output`)
477
- * — e.g. mark a field non-null in states only reachable after it is set.
478
- * Use xstate's native `{ schemas: { context } }` form with a complete
479
- * context schema.
480
- */
481
- states?: TStateSchemas;
482
- requests?: AgentRequestInput<TRequestSchemas, AgentModelRef<TModels>>;
483
- actions?: NonNullable<AnySetupConfig["actions"]>;
484
- guards?: AgentGuardSources<TContextSchema, TEventSchemas>;
485
- delays?: AgentDelaySources<TContextSchema, TEventSchemas>;
486
- };
487
- 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>>;
488
- /**
489
- * The object returned by {@link setupAgent}: an xstate `setup(...)` result
490
- * (`createMachine`, `assign`, …) extended with `schemas` (the resolved
491
- * {@link AgentSchemaPack}), `models`, and `requests` (the built request
492
- * actors). Machines created here are registered so
493
- * `createAgentRuntime` can resolve their schemas/actors
494
- * without re-passing them each call.
495
- */
496
- 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"> & {
497
- /**
498
- * Creates the agent machine — XState's own `createMachine`, plus: the
499
- * machine is registered so {@link createAgentRuntime} can resolve
500
- * its schemas/actors without re-passing them, and a single final state's
501
- * `output` is copied to the machine root when the root declares none.
502
- */
503
- 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. */
504
- schemas: AgentSchemaPack<TContextSchema, WithAgentUsageEvent<TEventSchemas>, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>; /** The `models` registry passed to `setupAgent(...)`, if any (used to type-narrow `AgentModelRef`). */
505
- readonly models: TModels; /** The {@link TextLogic} actors built from `setupAgent({ requests })`, keyed the same way. */
506
- readonly requests: RequestActors<TRequestSchemas>;
507
- };
508
- /**
509
- * Schema-first `setup(...)` for agent machines — the standard entry point
510
- * for authoring a machine (the blueprint) that this library then runs (via
511
- * {@link createAgentRuntime}) against host-supplied model/decision
512
- * executors. Context, events, machine input, machine output, and
513
- * state/transition meta are all standard schemas — no `{} as Type` casts —
514
- * and are retained on `result.schemas` for runtime validation. Also
515
- * registers the `agent.generateText`/`agent.streamText`/
516
- * `agent.decide` builtin actors and lowers `requests`/`actors` into the
517
- * machine's actor sources. The result is the xstate `setup(...)` object with
518
- * a wrapped `result.createMachine(...)` plus `result.schemas`/`models`/
519
- * `requests` attached. Also has a
520
- * `setupAgent.fromConfig(...)` namespace member for building a machine from
521
- * a serializable {@link AgentWorkflowConfig} instead of this TS API.
160
+ * It never sends. The host sends the event, re-checking `can` first, because
161
+ * the actor may have moved while the model was thinking. With no options it
162
+ * returns `{ event: null }` without calling the executor. Exhausting retries
163
+ * throws `AgentDecisionExhaustedError`.
522
164
  *
523
165
  * @example
524
- * ```ts
525
- * const schemas = createAgentSchemas({
526
- * context: z.object({ topic: z.string(), joke: z.string().nullable() }),
527
- * input: z.object({ topic: z.string() }),
528
- * output: z.object({ joke: z.string() }),
529
- * });
530
- *
531
- * const agent = setupAgent({
532
- * schemas,
533
- * actors: { tellJoke },
534
- * });
535
- *
536
- * const jokeMachine = agent.createMachine({
537
- * context: ({ input }) => ({ topic: input.topic, joke: null }),
538
- * initial: 'telling',
539
- * states: {
540
- * telling: {
541
- * invoke: {
542
- * id: 'joke',
543
- * src: 'tellJoke',
544
- * input: ({ context }) => ({ topic: context.topic }),
545
- * onDone: ({ output }) => ({ target: 'done', context: { joke: output } }),
546
- * },
547
- * },
548
- * done: { type: 'final', output: ({ context }) => ({ joke: context.joke ?? '' }) },
549
- * },
166
+ * ```ts no-check
167
+ * let busy = false;
168
+ * actor.subscribe(async (snapshot) => {
169
+ * if (busy || !snapshot.matches('reviewing')) return;
170
+ * busy = true;
171
+ * try {
172
+ * const { event } = await decideNext(snapshot, {
173
+ * decide,
174
+ * model: 'quick',
175
+ * allowedEvents: 'desk.*',
176
+ * payloads: (s) => ({ 'desk.refund': [{ amount: s.context.requested }] }),
177
+ * lookahead: true,
178
+ * });
179
+ * if (event && actor.getSnapshot().can(event)) actor.send(event);
180
+ * } finally {
181
+ * busy = false;
182
+ * }
550
183
  * });
551
184
  * ```
552
185
  */
553
- 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>;
554
- declare namespace setupAgent {
555
- /**
556
- * Builds a state machine from a serializable {@link AgentWorkflowConfig}
557
- * (JSON/YAML) instead of the TypeScript `setupAgent(...)` API — the same
558
- * kind of machine a database, visual editor, or LLM could produce and hand
559
- * back. Requires a `compileSchema` (see {@link FromConfigOptions}) since
560
- * the library bundles no JSON Schema engine itself; bring Ajv,
561
- * @cfworker/json-schema, or another compiler that returns Standard Schema.
562
- *
563
- * Returns the built `machine` plus the compiled `schemas` pack (context,
564
- * events, input, output, meta, emitted) — a JSON-authored agent has no
565
- * TypeScript types, so hosts need the runtime schemas for things like
566
- * validating an inbound raw event with `parseAgentEvent`.
567
- *
568
- * @example
569
- * ```ts
570
- * const { machine, schemas } = setupAgent.fromConfig(workflowConfig, {
571
- * compileSchema,
572
- * });
573
- * const result = await runToQuiescence(
574
- * createAgentRuntime(machine, { executors: { generateText, decide } }),
575
- * { input: { ticket } },
576
- * );
577
- * const event = parseAgentEvent(result.snapshot, raw, { events: schemas.events });
578
- * ```
579
- */
580
- function fromConfig(config: AgentWorkflowConfig, options: FromConfigOptions): FromConfigResult;
581
- }
582
- /**
583
- * The schema pack a machine was built with — `setupAgent(...).createMachine`
584
- * and `setupAgent.fromConfig(...)` both register one, so hosts can read a
585
- * machine's input/event schemas at runtime without knowing how it was
586
- * authored. Returns `undefined` for machines not built by either (a plain
587
- * xstate `createMachine`/`setup` machine).
588
- *
589
- * Registration also travels through `machine.provide(...)`: the pack is keyed
590
- * on the machine's root `config`, which `.provide` shares by reference.
591
- */
592
- declare function getAgentSchemas(machine: AnyStateMachine): AgentSchemas | undefined;
186
+ export declare function decideNext<TSnapshot extends AnyMachineSnapshot>(snapshot: TSnapshot, options: DecideNextOptions<TSnapshot>): Promise<DecideNextResult<EventFromSnapshot<TSnapshot>>>;
593
187
  //#endregion
594
188
  //#region src/provide-executors.d.ts
595
189
  /** Options for {@link provideExecutors}. */
@@ -657,6 +251,6 @@ interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMac
657
251
  * with `.withExecutor(...)` or register the child as a string-keyed source. A
658
252
  * source that already carries its own executor is never overwritten.
659
253
  */
660
- declare function provideExecutors<TMachine extends AnyStateMachine>(machine: TMachine, executors: AgentRequestExecutors, options?: ProvideExecutorsOptions<TMachine>): TMachine;
254
+ export declare function provideExecutors<TMachine extends AnyStateMachine>(machine: TMachine, executors: AgentRequestExecutors, options?: ProvideExecutorsOptions<TMachine>): TMachine;
661
255
  //#endregion
662
- export { AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, type AgentCallUsage, type AgentDecisionExecutor, AgentDecisionExhaustedError, type AgentDecisionInput, type AgentDecisionRequest, type AgentDefaultMeta, type AgentEffects, 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 AgentRunErrorCause, type AgentRunInit, type AgentRunMeta, type AgentRunResult, type AgentRunStart, type AgentRuntime, type AgentRuntimeOptions, type AgentSchemaPack, type AgentSchemas, AgentSnapshotDivergedError, type AgentStepRequest, type AgentTextRequest, type AgentTextResult, type AgentTimerEvent, type AgentTimerScheduler, 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 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, createAgentRuntime, createAgentSchemas, createDecisionLogic, createDecisionRequest, createTextLogic, eventFromInteraction, getAcceptedEvents, getAgentOutputMode, getAgentSchemas, getCallFinishReason, getCallUsage, getInteraction, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getMessageText, getStateMeta, getStatePath, inspectTransitions, interactionMetaSchema, isAgentIdle, isAgentMessages, isStandardSchema, messagesSchema, parseAgentEvent, parseOutput, parseProviderOutput, provideExecutors, providerOutputSchema, renderDecisionAttempts, resolveDecision, runToQuiescence, serializeTraceEvent, setupAgent, systemMessage, toolMessage, traceTransitions, userMessage };
256
+ export { AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, type AgentCallUsage, type AgentDecisionExecutor, AgentDecisionExhaustedError, type AgentDecisionInput, type AgentDecisionOption, type AgentDecisionRequest, type AgentDefaultMeta, type AgentEffects, AgentError, type AgentEventDescriptor, AgentEventLogConflictError, type AgentEventLogStore, type AgentExecutorDecisionRequest, type AgentExecutorTextRequest, type AgentFinishReason, type AgentInputFrom, type AgentInteraction, type AgentInteractionChoice, 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 AgentRunErrorCause, type AgentRunInit, type AgentRunMeta, type AgentRunOptions, type AgentRunResult, type AgentRunStart, type AgentRuntime, type AgentRuntimeOptions, type AgentSchemaPack, type AgentSchemas, AgentSnapshotDivergedError, type AgentStepRequest, type AgentTextRequest, type AgentTextResult, type AgentTimerEvent, type AgentTimerScheduler, 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 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, createAgentRuntime, createAgentSchemas, createDecisionLogic, createDecisionRequest, createTextLogic, eventFromInteraction, getAcceptedEvents, getAgentOutputMode, getAgentSchemas, getCallFinishReason, getCallUsage, getInteraction, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getMessageText, getStateMeta, getStatePath, inspectTransitions, interactionMetaSchema, isAgentIdle, isStandardSchema, parseAgentEvent, parseOutput, parseProviderOutput, providerOutputSchema, renderDecisionAttempts, resolveDecision, runAgent, runToQuiescence, serializeTraceEvent, setupAgent, systemMessage, toolMessage, traceTransitions, userMessage };