@statelyai/agent 1.1.5 → 2.0.0-alpha.10

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 (88) hide show
  1. package/LICENSE +21 -0
  2. package/dist/ai-sdk.cjs +342 -0
  3. package/dist/ai-sdk.d.cts +206 -0
  4. package/dist/ai-sdk.d.mts +206 -0
  5. package/dist/ai-sdk.mjs +331 -0
  6. package/dist/cli.cjs +64 -0
  7. package/dist/cli.d.cts +1 -0
  8. package/dist/cli.d.mts +1 -0
  9. package/dist/cli.mjs +65 -0
  10. package/dist/decision-CQdrKc8k.mjs +978 -0
  11. package/dist/decision-b-lkcs4L.cjs +1295 -0
  12. package/dist/index.cjs +59 -0
  13. package/dist/index.d.cts +212 -0
  14. package/dist/index.d.mts +201 -417
  15. package/dist/index.mjs +4 -583
  16. package/dist/openai-compat.cjs +319 -0
  17. package/dist/openai-compat.d.cts +98 -0
  18. package/dist/openai-compat.d.mts +98 -0
  19. package/dist/openai-compat.mjs +312 -0
  20. package/dist/run-agent-BFMkuI1F.cjs +1599 -0
  21. package/dist/run-agent-BVMd--1l.d.cts +1103 -0
  22. package/dist/run-agent-BoAOq_0Z.mjs +1540 -0
  23. package/dist/run-agent-DzYJb3CK.d.mts +1103 -0
  24. package/dist/src-D-77Ha5p.cjs +1087 -0
  25. package/dist/src-DUeIFjv-.mjs +1016 -0
  26. package/dist/text-logic-C7WJpCIc.d.mts +710 -0
  27. package/dist/text-logic-CZjyACzQ.d.cts +710 -0
  28. package/dist/types-C9QiMjre.d.cts +219 -0
  29. package/dist/types-qm00QF91.d.mts +219 -0
  30. package/dist/utils-Dri7aeEG.d.cts +108 -0
  31. package/dist/utils-Y6GDRGGE.d.mts +108 -0
  32. package/dist/zod.cjs +31 -0
  33. package/dist/zod.d.cts +30 -0
  34. package/dist/zod.d.mts +30 -0
  35. package/dist/zod.mjs +30 -0
  36. package/package.json +110 -29
  37. package/readme.md +143 -6
  38. package/schemas/agent-workflow.json +527 -0
  39. package/.changeset/README.md +0 -8
  40. package/.changeset/config.json +0 -11
  41. package/.env.template +0 -3
  42. package/.github/actions/ci-setup/action.yml +0 -24
  43. package/.github/workflows/release.yml +0 -46
  44. package/.vscode/launch.json +0 -28
  45. package/CHANGELOG.md +0 -215
  46. package/dist/index.d.ts +0 -428
  47. package/dist/index.js +0 -616
  48. package/examples/chatbot.ts +0 -71
  49. package/examples/cot.ts +0 -89
  50. package/examples/email.ts +0 -118
  51. package/examples/example.ts +0 -81
  52. package/examples/goal.ts +0 -94
  53. package/examples/helpers/helpers.ts +0 -17
  54. package/examples/helpers/loader.ts +0 -32
  55. package/examples/helpers/runner.ts +0 -27
  56. package/examples/joke.ts +0 -225
  57. package/examples/multi.ts +0 -103
  58. package/examples/newspaper.ts +0 -324
  59. package/examples/number.ts +0 -102
  60. package/examples/raffle.ts +0 -105
  61. package/examples/sandbox.ts +0 -28
  62. package/examples/simple.ts +0 -39
  63. package/examples/support.ts +0 -147
  64. package/examples/ticTacToe.ts +0 -224
  65. package/examples/todo.ts +0 -137
  66. package/examples/tutor.ts +0 -100
  67. package/examples/verify.ts +0 -120
  68. package/examples/weather.ts +0 -178
  69. package/examples/wiki.ts +0 -30
  70. package/examples/word.ts +0 -171
  71. package/src/adapters/vercel.ts +0 -7
  72. package/src/agent-experimental.ts +0 -221
  73. package/src/agent.test.ts +0 -506
  74. package/src/agent.ts +0 -300
  75. package/src/decision.test.ts +0 -179
  76. package/src/decision.ts +0 -84
  77. package/src/index.ts +0 -4
  78. package/src/memory.ts +0 -25
  79. package/src/planners/shortestPathPlanner.ts +0 -22
  80. package/src/planners/simplePlanner.ts +0 -139
  81. package/src/schemas.ts +0 -11
  82. package/src/strategies/chain-of-note.ts +0 -155
  83. package/src/templates/defaultText.ts +0 -18
  84. package/src/text.ts +0 -236
  85. package/src/types.ts +0 -499
  86. package/src/utils.ts +0 -72
  87. package/tsconfig.json +0 -109
  88. package/vitest.config.ts +0 -9
package/dist/index.d.mts CHANGED
@@ -1,428 +1,212 @@
1
- import { EventObject, AnyStateMachine, AnyEventObject, AnyActorRef, SnapshotFrom, EventFrom, PromiseActorLogic, ActorLogic, TransitionSnapshot, Values, ActorRefFrom, Subscription, StateValue, ObservableActorLogic } from 'xstate';
2
- import { SomeZodObject, ZodType, TypeOf } from 'zod';
3
- import { generateText, streamText, LanguageModel, CoreMessage, GenerateTextResult, StreamTextResult, CoreTool } from 'ai';
1
+ import { A as UserMessage, C as StandardSchemaV1, D as ToolMessage, E as ToolCallPart, O as ToolResultOutput, S as ProviderOptions, T as TextPart, _ as EventUnion, a as AgentTool, b as InferOutput, c as AgentToolExecute, d as AllowedEventPattern, f as AllowedEvents, g as EventPayload, h as DataContent, i as AgentSnapshotStore, k as ToolResultPart, l as AgentToolSchema, m as ChosenEvent, n as AgentEventSchemaInputMap, o as AgentToolChoice, p as AssistantMessage, r as AgentMessage, s as AgentToolDescriptor, t as AgentEventSchemaInput, u as AgentTools, v as FilePart, w as SystemMessage, x as NormalizedEventSchemas, y as ImagePart } from "./types-qm00QF91.mjs";
2
+ import { A as AgentDecisionInput, B as renderDecisionAttempts, C as createTextLogic, D as parseOutput, E as parseModelRef, F as DecisionExhaustedError, G as AgentRequestSource, H as AgentEventDescriptor, I as DecisionLogic, J as matchesEventPattern, K as EVENT_TOOL_PREFIX, L as DecisionLogicConfig, M as AgentPlanInput, N as AgentPlanOutput, O as parseStructuredEnvelope, P as DecisionAttempt, R as PLAN_DONE_EVENT_TYPE, S as buildEnvelopeSchema, T as isStructuredOutputSchema, U as AgentEventToolNameResolver, V as resolveDecision, W as AgentRequestOptions, Y as parseAgentEvent, _ as TextLogicExecuteArgs, a as AgentRequestExecutorInfo, b as TextLogicOutput, c as AgentRequestMode, d as AiSdkShapedStreamResult, f as AiSdkShapedTextResult, g as TextLogicConfig, h as TextLogic, i as AgentRequestExecutor, j as AgentDecisionRequest, k as AgentDecisionExecutor, l as AgentTextRequest, m as StructuredOutputEnvelope, n as AgentModelRef, o as AgentRequestExecutorResult, q as getAcceptedEvents, r as AgentOutputMode, s as AgentRequestExecutors, t as AgentModelMap, u as AgentUserInput, v as TextLogicExecutor, w as getAgentOutputMode, x as bindRequestExecutor, y as TextLogicInput, z as ResolveDecisionOptions } from "./text-logic-C7WJpCIc.mjs";
3
+ import { A as AgentSchemaPack, B as AgentWorkflowStateConfig, C as initialAgentStep, D as AgentMachine, E as transitionAgentStep, F as AgentWorkflowActionConfig, G as messagesSchema, H as FromConfigOptions, I as AgentWorkflowActorConfig, L as AgentWorkflowConfig, M as AgentStateNarrowing, N as createAgentSchemas, O as AgentMachineConfig, P as setupAgent, R as AgentWorkflowInvokeConfig, S as getAgentRequests, T as resolveAgentStep, U as SchemaCompiler, V as AgentWorkflowTransitionConfig, W as appendMessages, _ as AgentRequest, a as AgentUserInputExecutor, b as ResolveAgentRequestsOptions, c as PendingUserInput, d as SnapshotVersionMismatchError, f as inspectTransitions, g as AgentPlanRequest, h as AgentStateRequest, i as AgentTraceEvent, j as AgentSetupStateSchema, k as AgentRequestConfig, l as RunAgentOptions, m as runAgentToCompletion, n as AgentMessageInfo, o as IllegalResumeEventError, p as runAgent, r as AgentRunMeta, s as InspectedActorRef, t as AgentIdleError, u as RunAgentResult, v as AgentStep, w as resolveAgentRequests, x as executeAgentRequest, y as AgentStepRequest, z as AgentWorkflowRequestConfig } from "./run-agent-DzYJb3CK.mjs";
4
+ import { a as getMachineStructuralHash, c as persistSnapshot, d as userMessage, f as validateSchemaSync, i as getJsonSchemaSync, l as systemMessage, n as getAgentMessages, o as getStateMeta, r as getJsonSchema, s as isStandardSchema, t as assistantMessage, u as toolMessage } from "./utils-Y6GDRGGE.mjs";
5
+ import { AnyMachineSnapshot, AnyStateMachine } from "xstate";
4
6
 
5
- type ZodEventMapping = {
6
- [eventType: string]: SomeZodObject;
7
- };
8
- type ZodContextMapping = {
9
- [contextKey: string]: ZodType;
10
- };
11
-
12
- type GenerateTextOptions = Parameters<typeof generateText>[0];
13
- type StreamTextOptions = Parameters<typeof streamText>[0];
14
- type AgentPlanInput<TEvent extends EventObject> = Omit<GenerateTextOptions, 'prompt' | 'messages' | 'tools'> & {
15
- /**
16
- * The currently observed state.
17
- */
18
- state: ObservedState;
19
- /**
20
- * The goal for the agent to accomplish.
21
- * The agent will create a plan based on this goal.
22
- */
23
- goal: string;
24
- /**
25
- * The events that the agent can trigger. This is a mapping of
26
- * event types to Zod event schemas.
27
- */
28
- events: ZodEventMapping;
29
- /**
30
- * The state machine that represents the environment the agent
31
- * is interacting with.
32
- */
33
- machine?: AnyStateMachine;
34
- /**
35
- * The previous plan.
36
- */
37
- previousPlan?: AgentPlan<TEvent>;
38
- };
39
- type AgentPlan<TEvent extends EventObject> = {
40
- goal: string;
41
- state: ObservedState;
42
- content?: string;
43
- /**
44
- * Executes the plan based on the given `state` and resolves with
45
- * a potential next `event` to trigger to achieve the `goal`.
46
- */
47
- execute: (state: ObservedState) => Promise<TEvent | undefined>;
48
- nextEvent: TEvent | undefined;
49
- sessionId: string;
50
- timestamp: number;
51
- };
52
- interface TransitionData {
53
- eventType: string;
54
- description?: string;
55
- guard?: {
56
- type: string;
57
- };
58
- target?: any;
7
+ //#region src/verify.d.ts
8
+ /** Severity of an {@link AgentLintDiagnostic}. `error` findings fail CI/the CLI; `warning`s are advisory. */
9
+ type AgentLintSeverity = "error" | "warning";
10
+ /**
11
+ * One static-analysis finding from {@link lintAgentMachine}. `code` names the
12
+ * check (stable, machine-readable), `path` points at the offending state path
13
+ * or config location, and `message` explains the problem and its remedy.
14
+ */
15
+ interface AgentLintDiagnostic {
16
+ code: "unreachable-state" | "decide-without-events" | "unserializable-context" | "direct-object-src" | "final-without-output" | "final-output-reads-event" | "missing-final";
17
+ severity: AgentLintSeverity;
18
+ /** State path (`parent.child`) or config pointer (e.g. `(root)`, `context`) the finding is about. */
19
+ path: string;
20
+ message: string;
59
21
  }
60
- type PromptTemplate<TEvents extends EventObject> = (data: {
61
- goal: string;
62
- /**
63
- * The observed state
64
- */
65
- state?: ObservedState;
66
- /**
67
- * The context to provide.
68
- * This overrides the observed state.context, if provided.
69
- */
70
- context?: any;
71
- /**
72
- * The state machine model of the observed environment
73
- */
74
- machine?: unknown;
75
- /**
76
- * The potential next transitions that can be taken
77
- * in the state machine
78
- */
79
- transitions?: TransitionData[];
80
- /**
81
- * Past observations
82
- */
83
- observations?: AgentObservation<any>[];
84
- feedback?: AgentFeedback[];
85
- messages?: AgentMessage[];
86
- plans?: AgentPlan<TEvents>[];
87
- }) => string;
88
- type AgentPlanner<T extends AnyAgent> = (agent: T, input: AgentPlanInput<T['types']['events']>) => Promise<AgentPlan<T['types']['events']> | undefined>;
89
- type AgentDecideOptions = {
90
- goal: string;
91
- model?: LanguageModel;
92
- context?: any;
93
- state: ObservedState;
94
- machine: AnyStateMachine;
95
- execute?: (event: AnyEventObject) => Promise<void>;
96
- planner?: AgentPlanner<any>;
97
- events?: ZodEventMapping;
98
- } & Omit<Parameters<typeof generateText>[0], 'model' | 'tools' | 'prompt' | 'messages'>;
99
- interface AgentFeedback {
100
- goal?: string;
101
- observationId?: string;
102
- /**
103
- * The message correlation that the feedback is relevant for
104
- */
105
- correlationId?: string;
106
- attributes: Record<string, any>;
107
- reward: number;
108
- timestamp: number;
109
- sessionId: string;
22
+ /** Options for {@link lintAgentMachine}. Reserved for future check selection. */
23
+ interface LintAgentMachineOptions {
24
+ /** Skip these check codes entirely. */
25
+ disable?: AgentLintDiagnostic["code"][];
110
26
  }
111
- interface AgentFeedbackInput {
112
- goal?: string;
113
- observationId?: string;
114
- correlationId?: string;
115
- attributes?: Record<string, any>;
116
- timestamp?: number;
117
- reward?: number;
27
+ /**
28
+ * Runs static structural checks over a built agent machine and returns the
29
+ * findings ({@link AgentLintDiagnostic}[], empty when clean). Works for
30
+ * TS-authored (`setupAgent(...).createMachine(...)`) and
31
+ * `setupAgent.fromConfig(...)`-compiled machines alike, reading `machine.config`
32
+ * plus the schemas/actor sources the library already retains per machine.
33
+ *
34
+ * No model calls, no API keys — a coding agent that emits an agent machine can
35
+ * call this to catch dead states, undeliverable decisions, un-rebindable
36
+ * invoke srcs, and output-contract gaps before ever running it.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * const errors = lintAgentMachine(machine).filter((d) => d.severity === 'error');
41
+ * if (errors.length) throw new Error(errors.map((e) => `${e.path}: ${e.message}`).join('\n'));
42
+ * ```
43
+ */
44
+ declare function lintAgentMachine(machine: AnyStateMachine, options?: LintAgentMachineOptions): AgentLintDiagnostic[];
45
+ /** Options for {@link assertAgentMachine}. */
46
+ interface AssertAgentMachineOptions extends LintAgentMachineOptions {
47
+ /** Also fail on warning-severity findings. Default: errors only. */
48
+ warnings?: boolean;
118
49
  }
119
- type AgentMessage = CoreMessage & {
120
- timestamp: number;
121
- id: string;
122
- /**
123
- * The response ID of the message, which references
124
- * which message this message is responding to, if any.
125
- */
126
- responseId?: string;
127
- result?: GenerateTextResult<any>;
128
- sessionId: string;
129
- correlationId: string;
130
- parentCorrelationId?: string;
131
- };
132
- type AgentMessageInput = CoreMessage & {
133
- timestamp?: number;
134
- id?: string;
135
- /**
136
- * The response ID of the message, which references
137
- * which message this message is responding to, if any.
138
- */
139
- responseId?: string;
140
- correlationId?: string;
141
- parentCorrelationId?: string;
142
- result?: GenerateTextResult<any>;
143
- };
144
- interface AgentObservation<TActor extends AnyActorRef> {
50
+ /**
51
+ * Thrown by {@link assertAgentMachine} when lint finds failing diagnostics.
52
+ * `diagnostics` holds the findings; the message lists them one per finding,
53
+ * so a test runner's failure output reads like the CLI's lint report.
54
+ */
55
+ declare class AgentLintError extends Error {
56
+ diagnostics: AgentLintDiagnostic[];
57
+ constructor(machineId: string, diagnostics: AgentLintDiagnostic[]);
58
+ }
59
+ /**
60
+ * Asserts a machine passes {@link lintAgentMachine}: returns silently when
61
+ * clean, throws {@link AgentLintError} (with the findings on `.diagnostics`)
62
+ * otherwise. Fails on error-severity findings; set `warnings: true` to fail on
63
+ * warnings too. The one-liner for tests and generation loops:
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * test('agent machine is structurally sound', () => {
68
+ * assertAgentMachine(machine);
69
+ * });
70
+ * ```
71
+ */
72
+ declare function assertAgentMachine(machine: AnyStateMachine, options?: AssertAgentMachineOptions): void;
73
+ /**
74
+ * Scripted responses for a {@link simulateAgent} playthrough. Each channel is a
75
+ * by-`src` map of FIFO queues, consumed in the order the machine reaches the
76
+ * requests:
77
+ * - `text` — output values for text requests, keyed by request src (the
78
+ * `setupAgent({ requests })` key, or `agent.generateText`/`agent.streamText`).
79
+ * - `decisions` — the {@link ChosenEvent} to apply for a decision request,
80
+ * keyed by decision src (usually `agent.decide`).
81
+ * - `userInput` — output values for `agent.userInput` invokes, keyed by src
82
+ * (usually `agent.userInput`).
83
+ */
84
+ interface SimulationScript {
85
+ text?: Record<string, unknown[]>;
86
+ decisions?: Record<string, ChosenEvent[]>;
87
+ userInput?: Record<string, unknown[]>;
88
+ }
89
+ /** One entry in a {@link SimulateAgentResult.trail}: the state after this step, plus what drove the step. */
90
+ interface SimulationTrailEntry {
91
+ /** The machine state value after applying this step. */
92
+ state: unknown;
93
+ /** The chosen event applied (for a decision request). */
94
+ appliedEvent?: ChosenEvent;
95
+ /** The resolved request (for a text/userInput invoke): its kind and src. */
96
+ resolvedRequest?: {
97
+ kind: "text" | "userInput";
98
+ src: string;
145
99
  id: string;
146
- prevState: SnapshotFrom<TActor> | undefined;
147
- event: EventFrom<TActor>;
148
- state: SnapshotFrom<TActor>;
149
- machineHash: string | undefined;
150
- sessionId: string;
151
- timestamp: number;
100
+ };
152
101
  }
153
- interface AgentObservationInput {
154
- id?: string;
155
- prevState: ObservedState | undefined;
156
- event: AnyEventObject;
157
- state: ObservedState;
158
- machine?: AnyStateMachine;
159
- timestamp?: number;
102
+ /** Options for {@link simulateAgent}. */
103
+ interface SimulateAgentOptions {
104
+ input?: unknown;
105
+ script: SimulationScript;
106
+ /** Max steps before returning `'exhausted'`. Default 100. */
107
+ maxSteps?: number;
160
108
  }
161
- type AgentDecisionInput = {
162
- goal: string;
163
- model?: LanguageModel;
164
- context?: any;
165
- } & Omit<Parameters<typeof generateText>[0], 'model' | 'tools' | 'prompt'>;
166
- type AgentDecisionLogic<TEvents extends EventObject> = PromiseActorLogic<AgentPlan<TEvents> | undefined, AgentDecisionInput | string>;
167
- type AgentEmitted<TEvents extends EventObject> = {
168
- type: 'feedback';
169
- feedback: AgentFeedback;
170
- } | {
171
- type: 'observation';
172
- observation: AgentObservation<any>;
173
- } | {
174
- type: 'message';
175
- message: AgentMessage;
176
- } | {
177
- type: 'plan';
178
- plan: AgentPlan<TEvents>;
179
- };
180
- type AgentLogic<TEvents extends EventObject> = ActorLogic<TransitionSnapshot<AgentMemoryContext>, {
181
- type: 'agent.feedback';
182
- feedback: AgentFeedback;
183
- } | {
184
- type: 'agent.observe';
185
- observation: AgentObservation<any>;
186
- } | {
187
- type: 'agent.message';
188
- message: AgentMessage;
189
- } | {
190
- type: 'agent.plan';
191
- plan: AgentPlan<TEvents>;
192
- }, any, // TODO: input
193
- any, AgentEmitted<TEvents>>;
194
- type EventsFromZodEventMapping<TEventSchemas extends ZodEventMapping> = Values<{
195
- [K in keyof TEventSchemas & string]: {
196
- type: K;
197
- } & TypeOf<TEventSchemas[K]>;
198
- }>;
199
- type ContextFromZodContextMapping<TContextSchema extends ZodContextMapping> = {
200
- [K in keyof TContextSchema & string]: TypeOf<TContextSchema[K]>;
201
- };
202
- type Agent<TContext, TEvents extends EventObject> = ActorRefFrom<AgentLogic<TEvents>> & {
203
- /**
204
- * The name of the agent. All agents with the same name are related and
205
- * able to share experiences (observations, feedback) with each other.
206
- */
207
- name?: string;
208
- /**
209
- * The unique identifier for the agent.
210
- */
211
- id?: string;
212
- description?: string;
213
- events: ZodEventMapping;
214
- types: {
215
- events: TEvents;
216
- context: Compute<TContext>;
217
- };
218
- model: LanguageModel;
219
- defaultOptions: GenerateTextOptions;
220
- memory: AgentLongTermMemory | undefined;
221
- /**
222
- * The adapter used to perform LLM actions such as
223
- * `.generateText(…)` and `.streamText(…)`.
224
- *
225
- * Defaults to the Vercel AI SDK.
226
- */
227
- adapter: AIAdapter;
228
- /**
229
- * Resolves with an `AgentPlan` based on the information provided in the `options`, including:
230
- *
231
- * - The `goal` for the agent to achieve
232
- * - The observed current `state`
233
- * - The `machine` (e.g. a state machine) that specifies what can happen next
234
- * - Additional `context`
235
- */
236
- decide: (options: AgentDecideOptions) => Promise<AgentPlan<TEvents> | undefined>;
237
- generateText: (options: AgentGenerateTextOptions) => Promise<AgentGenerateTextResult>;
238
- streamText: (options: AgentStreamTextOptions) => Promise<AgentStreamTextResult>;
239
- addObservation: (observationInput: AgentObservationInput) => AgentObservation<any>;
240
- addMessage: (messageInput: AgentMessageInput) => AgentMessage;
241
- addFeedback: (feedbackInput: AgentFeedbackInput) => AgentFeedback;
242
- addPlan: (plan: AgentPlan<TEvents>) => void;
243
- /**
244
- * Called whenever the agent (LLM assistant) receives or sends a message.
245
- */
246
- onMessage: (callback: (message: AgentMessage) => void) => void;
247
- /**
248
- * Selects agent data from its context.
249
- *
250
- * @deprecated Select from `agent.getSnapshot().context` directly or:
251
- * - `agent.getMessages()`
252
- * - `agent.getObservations()`
253
- * - `agent.getFeedback()`
254
- * - `agent.getPlans()`
255
- */
256
- select: <T>(selector: (context: AgentMemoryContext) => T) => T;
257
- /**
258
- * Retrieves messages from the agent's short-term (local) memory.
259
- */
260
- getMessages: () => AgentMessage[];
261
- /**
262
- * Retrieves observations from the agent's short-term (local) memory.
263
- */
264
- getObservations: () => AgentObservation<Agent<TContext, TEvents>>[];
265
- /**
266
- * Retrieves feedback from the agent's short-term (local) memory.
267
- */
268
- getFeedback: () => AgentFeedback[];
269
- /**
270
- * Retrieves strategies from the agent's short-term (local) memory.
271
- */
272
- getPlans: () => AgentPlan<TEvents>[];
273
- /**
274
- * Interacts with this state machine actor by inspecting state transitions and storing them as observations.
275
- *
276
- * Observations contain the `prevState`, `event`, and current `state` of this
277
- * actor, as well as other properties that are useful when recalled.
278
- * These observations are stored in the `agent`'s short-term (local) memory
279
- * and can be retrieved via `agent.getObservations()`.
280
- *
281
- * @example
282
- * ```ts
283
- * // Only observes the actor's state transitions
284
- * agent.interact(actor);
285
- *
286
- * actor.start();
287
- * ```
288
- */
289
- interact<TActor extends AnyActorRef>(actorRef: TActor): Subscription;
290
- /**
291
- * Interacts with this state machine actor by:
292
- * 1. Inspecting state transitions and storing them as observations
293
- * 2. Deciding what to do next (which event to send the actor) based on
294
- * the agent input returned from `getInput(observation)`, if `getInput(…)` is provided as the 2nd argument.
295
- *
296
- * Observations contain the `prevState`, `event`, and current `state` of this
297
- * actor, as well as other properties that are useful when recalled.
298
- * These observations are stored in the `agent`'s short-term (local) memory
299
- * and can be retrieved via `agent.getObservations()`.
300
- *
301
- * @example
302
- * ```ts
303
- * // Observes the actor's state transitions and
304
- * // makes a decision if on the "summarize" state
305
- * agent.interact(actor, observed => {
306
- * if (observed.state.matches('summarize')) {
307
- * return {
308
- * context: observed.state.context,
309
- * goal: 'Summarize the message'
310
- * }
311
- * }
312
- * });
313
- *
314
- * actor.start();
315
- * ```
316
- */
317
- interact<TActor extends AnyActorRef>(actorRef: TActor, getInput: (observation: AgentObservation<TActor>) => AgentDecisionInput | undefined): Subscription;
318
- };
319
- type AnyAgent = Agent<any, any>;
320
- type FromAgent<T> = T | ((agent: AnyAgent) => T | Promise<T>);
321
- type CommonTextOptions = {
322
- prompt: FromAgent<string>;
323
- model?: LanguageModel;
324
- context?: Record<string, any>;
325
- messages?: FromAgent<CoreMessage[]>;
326
- template?: PromptTemplate<any>;
327
- correlationId?: string;
328
- parentCorrelationId?: string;
329
- };
330
- type TextResultMeta = {
331
- correlationId: string;
332
- parentCorrelationId?: string;
333
- };
334
- type AgentGenerateTextOptions = Omit<GenerateTextOptions, 'model' | 'prompt' | 'messages'> & CommonTextOptions;
335
- type AgentGenerateTextResult = GenerateTextResult<any> & TextResultMeta;
336
- type AgentStreamTextOptions = Omit<StreamTextOptions, 'model' | 'prompt' | 'messages'> & CommonTextOptions;
337
- type AgentStreamTextResult = StreamTextResult<any> & TextResultMeta;
338
- interface ObservedState {
339
- /**
340
- * The current state value of the state machine, e.g.
341
- * `"loading"` or `"processing"` or `"ready"`
342
- */
343
- value: StateValue;
344
- /**
345
- * Additional contextual data related to the current state
346
- */
347
- context: Record<string, unknown>;
109
+ /** The outcome of a {@link simulateAgent} playthrough. */
110
+ interface SimulateAgentResult {
111
+ /** `'done'` = reached a final state; `'idle'` = paused with no pending work; `'exhausted'` = hit `maxSteps`. */
112
+ status: "done" | "idle" | "exhausted";
113
+ snapshot: AnyMachineSnapshot;
114
+ trail: SimulationTrailEntry[];
348
115
  }
349
- type ObservedStateFrom<TActor extends AnyActorRef> = Pick<SnapshotFrom<TActor>, 'value' | 'context'>;
350
- type AgentMemoryContext = {
351
- observations: AgentObservation<any>[];
352
- messages: AgentMessage[];
353
- plans: AgentPlan<any>[];
354
- feedback: AgentFeedback[];
355
- };
356
- type AgentMemory = AppendOnlyStorage<AgentMemoryContext>;
357
- interface AppendOnlyStorage<T extends Record<string, any[]>> {
358
- append<K extends keyof T>(sessionId: string, key: K, item: T[K][0]): Promise<void>;
359
- getAll<K extends keyof T>(sessionId: string, key: K): Promise<T[K] | undefined>;
116
+ /**
117
+ * Deterministically plays a machine through, resolving each request from a
118
+ * {@link SimulationScript} instead of a model — no API keys, no model calls.
119
+ * Runs on the pure step path ({@link initialAgentStep} etc.), so it exercises
120
+ * the real transition logic. Returns the terminal `status`, final `snapshot`,
121
+ * and a `trail` of every step taken.
122
+ *
123
+ * Throws a descriptive error when the script runs dry mid-request, naming the
124
+ * pending request's kind, src, and id so the missing scripted response is
125
+ * obvious.
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * const { status, snapshot } = simulateAgent(machine, {
130
+ * input: { topic: 'state machines' },
131
+ * script: { decisions: { 'agent.decide': [{ type: 'END' }] } },
132
+ * });
133
+ * ```
134
+ */
135
+ declare function simulateAgent(machine: AnyStateMachine, options: SimulateAgentOptions): Promise<SimulateAgentResult>;
136
+ /** Options for {@link explorePaths}. */
137
+ interface ExplorePathsOptions {
138
+ input?: unknown;
139
+ /** Max branch points (decisions + external-event forks) along any path. Default 8. */
140
+ maxDepth?: number;
141
+ /** Total path cap before exploration stops (reported via `hitPathCap`). Default 200. */
142
+ maxPaths?: number;
143
+ /** Canned outputs for text/userInput invokes, keyed by src. A missing src halts that branch with a `needs-output` note. */
144
+ textOutputs?: Record<string, unknown>;
360
145
  }
361
- interface AgentLongTermMemory {
362
- get<K extends keyof AgentMemoryContext>(key: K): Promise<AgentMemoryContext[K]>;
363
- append<K extends keyof AgentMemoryContext>(key: K, item: AgentMemoryContext[K][0]): Promise<void>;
364
- set<K extends keyof AgentMemoryContext>(key: K, items: AgentMemoryContext[K]): Promise<void>;
146
+ /** A single explored path's terminal outcome. */
147
+ interface AgentPathTerminal {
148
+ status: "done" | "idle" | "needs-output" | "max-depth";
149
+ /** The chosen/applied events, in order, that produced this terminal. */
150
+ path: ChosenEvent[];
151
+ /** The final state value on this path. */
152
+ state: unknown;
153
+ /** For `needs-output`: the src whose canned output was missing. */
154
+ missingSrc?: string;
365
155
  }
366
- interface AIAdapter {
367
- generateText: typeof generateText;
368
- streamText: typeof streamText;
156
+ /** The report returned by {@link explorePaths}. */
157
+ interface AgentPathReport {
158
+ /** Every distinct state value (JSON) encountered across all explored paths. */
159
+ reachedStates: unknown[];
160
+ /** One entry per explored path. */
161
+ terminals: AgentPathTerminal[];
162
+ /** How many candidate events were pruned because a guard rejected them. */
163
+ prunedByGuard: number;
164
+ /** Notes about coverage the exploration could not complete (missing outputs, depth/path caps). */
165
+ unexplored: string[];
166
+ /** Total paths explored. */
167
+ pathsExplored: number;
168
+ /** True when the total-paths cap was hit (report is partial). */
169
+ hitPathCap: boolean;
369
170
  }
370
- type Compute<A extends any> = {
371
- [K in keyof A]: A[K];
372
- } & unknown;
373
-
374
- declare function createAgent<const TContextSchema extends ZodContextMapping, const TEventSchemas extends ZodEventMapping, TEvents extends EventObject = EventsFromZodEventMapping<TEventSchemas>, TContext = ContextFromZodContextMapping<TContextSchema>>({ name, description, model, events, context, planner, stringify, getMemory, logic, adapter, ...generateTextOptions }: {
375
- /**
376
- * The unique identifier for the agent.
377
- *
378
- * This should be the same across all sessions of a specific agent, as it can be
379
- * used to retrieve memory for this agent.
380
- *
381
- * @example
382
- * ```ts
383
- * const agent = createAgent({
384
- * id: 'recipe-assistant',
385
- * // ...
386
- * });
387
- * ```
388
- */
389
- id?: string;
390
- /**
391
- * The name of the agent
392
- */
393
- name?: string;
394
- /**
395
- * A description of the role of the agent
396
- */
397
- description?: string;
398
- /**
399
- * Events that the agent can cause (send) in an environment
400
- * that the agent knows about.
401
- */
402
- events: TEventSchemas;
403
- context?: TContextSchema;
404
- planner?: AgentPlanner<Agent<TContext, TEvents>>;
405
- stringify?: typeof JSON.stringify;
406
- /**
407
- * A function that retrieves the agent's long term memory
408
- */
409
- getMemory?: (agent: Agent<TContext, TEvents>) => AgentLongTermMemory;
410
- /**
411
- * Agent logic
412
- */
413
- logic?: AgentLogic<TEvents>;
414
- adapter?: AIAdapter;
415
- } & GenerateTextOptions): Agent<TContext, TEvents>;
416
-
417
- declare function fromTextStream<T extends AnyAgent>(agent: T, defaultOptions?: AgentStreamTextOptions): ObservableActorLogic<{
418
- textDelta: string;
419
- }, Omit<AgentStreamTextOptions, 'context'> & {
420
- context?: AgentStreamTextOptions['context'];
421
- }>;
422
- declare function fromText<T extends AnyAgent>(agent: T, defaultOptions?: AgentGenerateTextOptions): PromiseActorLogic<GenerateTextResult<Record<string, CoreTool<any, any>>>, Omit<AgentGenerateTextOptions, 'context'> & {
423
- context?: AgentGenerateTextOptions['context'];
424
- }>;
425
-
426
- declare function fromDecision(agent: AnyAgent, defaultInput?: AgentDecisionInput): AgentDecisionLogic<any>;
427
-
428
- export { type AIAdapter, type Agent, type AgentDecideOptions, type AgentDecisionInput, type AgentDecisionLogic, type AgentEmitted, type AgentFeedback, type AgentFeedbackInput, type AgentGenerateTextOptions, type AgentGenerateTextResult, type AgentLogic, type AgentLongTermMemory, type AgentMemory, type AgentMemoryContext, type AgentMessage, type AgentMessageInput, type AgentObservation, type AgentObservationInput, type AgentPlan, type AgentPlanInput, type AgentPlanner, type AgentStreamTextOptions, type AgentStreamTextResult, type AnyAgent, type AppendOnlyStorage, type CommonTextOptions, type Compute, type ContextFromZodContextMapping, type EventsFromZodEventMapping, type FromAgent, type GenerateTextOptions, type ObservedState, type ObservedStateFrom, type PromptTemplate, type StreamTextOptions, type TextResultMeta, type TransitionData, createAgent, fromDecision, fromText, fromTextStream };
171
+ /**
172
+ * Enumerates a machine's decision and external-event branches to a bounded
173
+ * depth, model-free, and reports which states are reached and how each path
174
+ * terminates. At each decision request it forks one branch per candidate event
175
+ * (guard-rejected candidates are counted in `prunedByGuard`, not explored); at
176
+ * an idle wait it forks per externally-accepted event. A `agent.plan` request
177
+ * forks the same way — one branch per candidate, including the reserved
178
+ * `agent.plan.done` move — advancing each branch through the real plan protocol
179
+ * (`resolveAgentRequests`), so a plan can consume several depth units. Text/`userInput` invokes
180
+ * are resolved from `textOutputs` (a by-src canned-output map) — a missing src
181
+ * halts that branch with a `needs-output` terminal rather than throwing.
182
+ *
183
+ * Combinatorics are bounded by `maxDepth` (default 8) and `maxPaths` (default
184
+ * 200, reported via `hitPathCap`).
185
+ *
186
+ * @example
187
+ * ```ts
188
+ * const report = await explorePaths(refundMachine, { input: { request: 'x', amount: 5000 } });
189
+ * // report.terminals → both 'refunded' and 'denied'; report.prunedByGuard → 1
190
+ * ```
191
+ */
192
+ declare function explorePaths(machine: AnyStateMachine, options?: ExplorePathsOptions): Promise<AgentPathReport>;
193
+ /** The result of a {@link canReach} query. */
194
+ interface CanReachResult {
195
+ canReach: boolean;
196
+ /** When reachable, the sequence of chosen/applied events that gets there. */
197
+ witness?: ChosenEvent[];
198
+ }
199
+ /**
200
+ * Answers "can the machine reach `statePath`?" by exploring its branches (a
201
+ * thin wrapper over {@link explorePaths}). Returns `{ canReach: true, witness }`
202
+ * with the event sequence that reaches it, or `{ canReach: false }`.
203
+ *
204
+ * @example
205
+ * ```ts
206
+ * const { canReach, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
207
+ * // canReach → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
208
+ * ```
209
+ */
210
+ declare function canReach(machine: AnyStateMachine, statePath: string, options?: ExplorePathsOptions): Promise<CanReachResult>;
211
+ //#endregion
212
+ export { type AgentDecisionExecutor, type AgentDecisionInput, type AgentDecisionRequest, type AgentEventDescriptor, type AgentEventSchemaInput, type AgentEventSchemaInputMap, type AgentEventToolNameResolver, AgentIdleError, type AgentLintDiagnostic, AgentLintError, type AgentLintSeverity, type AgentMachine, type AgentMachineConfig, type AgentMessage, type AgentMessageInfo, type AgentModelMap, type AgentModelRef, type AgentOutputMode, type AgentPathReport, type AgentPathTerminal, type AgentPlanInput, type AgentPlanOutput, type AgentPlanRequest, type AgentRequest, type AgentRequestConfig, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestMode, type AgentRequestOptions, type AgentRequestSource, type AgentRunMeta, type AgentSchemaPack, type AgentSetupStateSchema, type AgentSnapshotStore, type AgentStateNarrowing, type AgentStateRequest, type AgentStep, type AgentStepRequest, type AgentTextRequest, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentToolSchema, type AgentTools, type AgentTraceEvent, type AgentUserInput, type AgentUserInputExecutor, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AiSdkShapedStreamResult, type AiSdkShapedTextResult, type AllowedEventPattern, type AllowedEvents, type AssertAgentMachineOptions, type AssistantMessage, type CanReachResult, type ChosenEvent, type DataContent, type DecisionAttempt, DecisionExhaustedError, type DecisionLogic, type DecisionLogicConfig, EVENT_TOOL_PREFIX, type EventPayload, type EventUnion, type ExplorePathsOptions, type FilePart, type FromConfigOptions, IllegalResumeEventError, type ImagePart, type InferOutput, type InspectedActorRef, type LintAgentMachineOptions, type NormalizedEventSchemas, PLAN_DONE_EVENT_TYPE, type PendingUserInput, type ProviderOptions, type ResolveAgentRequestsOptions, type ResolveDecisionOptions, type RunAgentOptions, type RunAgentResult, type SchemaCompiler, type SimulateAgentOptions, type SimulateAgentResult, type SimulationScript, type SimulationTrailEntry, SnapshotVersionMismatchError, type StandardSchemaV1, type StructuredOutputEnvelope, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextLogicInput, type TextLogicOutput, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultOutput, type ToolResultPart, type UserMessage, appendMessages, assertAgentMachine, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentSchemas, createTextLogic, executeAgentRequest, explorePaths, getAcceptedEvents, getAgentMessages, getAgentOutputMode, getAgentRequests, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getStateMeta, initialAgentStep, inspectTransitions, isStandardSchema, isStructuredOutputSchema, lintAgentMachine, matchesEventPattern, messagesSchema, parseAgentEvent, parseModelRef, parseOutput, parseStructuredEnvelope, persistSnapshot, renderDecisionAttempts, resolveAgentRequests, resolveAgentStep, resolveDecision, runAgent, runAgentToCompletion, setupAgent, simulateAgent, systemMessage, toolMessage, transitionAgentStep, userMessage, validateSchemaSync };