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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/ai-sdk.cjs +53 -25
  2. package/dist/ai-sdk.d.cts +20 -12
  3. package/dist/ai-sdk.d.mts +20 -12
  4. package/dist/ai-sdk.mjs +53 -25
  5. package/dist/{decision-DxSTqzgZ.mjs → decision-BBZ2jMO1.mjs} +444 -79
  6. package/dist/{decision-1o45_ZrS.cjs → decision-Cv6SfNWl.cjs} +525 -94
  7. package/dist/index.cjs +2224 -1032
  8. package/dist/index.d.cts +413 -275
  9. package/dist/index.d.mts +413 -275
  10. package/dist/index.mjs +2163 -983
  11. package/dist/machines.cjs +30 -2
  12. package/dist/machines.d.cts +1 -1
  13. package/dist/machines.d.mts +1 -1
  14. package/dist/machines.mjs +30 -2
  15. package/dist/openai.cjs +447 -0
  16. package/dist/openai.d.cts +177 -0
  17. package/dist/openai.d.mts +177 -0
  18. package/dist/openai.mjs +437 -0
  19. package/dist/otel.cjs +3 -6
  20. package/dist/otel.d.cts +1 -1
  21. package/dist/otel.d.mts +1 -1
  22. package/dist/otel.mjs +3 -6
  23. package/dist/run-agent-Ck7Sa3Tb.d.mts +968 -0
  24. package/dist/run-agent-DWqA8KiI.d.cts +968 -0
  25. package/dist/setup-agent-CeO2fARv.mjs +639 -0
  26. package/dist/setup-agent-Dl2VELLi.cjs +663 -0
  27. package/dist/{text-logic-BaxPrcLk.d.cts → text-logic-C7bSnH_B.d.cts} +195 -44
  28. package/dist/{text-logic-DhfFWzu9.d.mts → text-logic-DJBK3LbG.d.mts} +195 -44
  29. package/dist/{types-DSdj2tGs.d.cts → types-CjHk5OdH.d.cts} +4 -19
  30. package/dist/{types-CvWRGFxP.d.mts → types-DWA6X9R-.d.mts} +4 -19
  31. package/package.json +17 -21
  32. package/readme.md +32 -17
  33. package/dist/errors-BQRk9eiZ.d.cts +0 -19
  34. package/dist/errors-C9rxnWbX.d.mts +0 -19
  35. package/dist/errors-CeSXQx0v.mjs +0 -23
  36. package/dist/errors-DUBBzRLP.cjs +0 -28
  37. package/dist/event-log-store-Bz7HDBkE.d.cts +0 -145
  38. package/dist/event-log-store-DmIDosD6.mjs +0 -427
  39. package/dist/event-log-store-a_TKy1gk.cjs +0 -468
  40. package/dist/event-log-store-hrA1vqtN.d.mts +0 -145
  41. package/dist/run-agent-0fpEZ1wJ.d.mts +0 -1098
  42. package/dist/run-agent-Zbkx7XP8.d.cts +0 -1098
  43. package/dist/setup-agent-DkCTy5Eu.cjs +0 -1707
  44. package/dist/setup-agent-nSFYrNTP.mjs +0 -1587
  45. package/dist/sqlite.cjs +0 -129
  46. package/dist/sqlite.d.cts +0 -57
  47. package/dist/sqlite.d.mts +0 -57
  48. package/dist/sqlite.mjs +0 -127
@@ -1,1098 +0,0 @@
1
- import { T as WithAgentInputSchema, c as AgentTools, d as ChosenEvent, h as InferInput, n as AgentMessage, v as StandardSchemaV1 } from "./types-CvWRGFxP.mjs";
2
- import { t as AgentError } from "./errors-C9rxnWbX.mjs";
3
- import { N as AgentDecisionRequest, U as AgentRequestOptions, V as AgentEventDescriptor, W as AgentRequestSource, d as AgentTextRequest, f as AgentUsage, l as AgentRequestExecutors, p as AgentUserInput, t as AgentCallUsage, u as AgentRequestMode } from "./text-logic-DhfFWzu9.mjs";
4
- import { i as AgentLogEntry, o as JsonValue } from "./event-log-store-hrA1vqtN.mjs";
5
- import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, ExecutableActionObject, InputFrom, InspectionEvent, OutputFrom, Snapshot, SnapshotFrom, createActor } from "xstate";
6
-
7
- //#region src/internal/registry.d.ts
8
- type AgentExecutionOptions = Pick<AgentRequestOptions, "schemas" | "actors"> & {
9
- models?: object;
10
- };
11
- //#endregion
12
- //#region src/effects.d.ts
13
- /**
14
- * One thing a host does at the frontier. Effect kinds mirror what a machine
15
- * can start in a single transition, each carrying everything the host needs to
16
- * run it and to journal its completion so replay is deterministic:
17
- *
18
- * - `text` — a `TextLogic`/`agent.generateText` invoke. Resolve with the model
19
- * (`executeAgentRequest`), then journal `toDoneEvent(output)` (or
20
- * `toErrorEvent(error)`).
21
- * - `decision` — an `agent.decide`/`DecisionLogic` invoke. Resolve with
22
- * `resolveDecision` and journal the CHOSEN machine event directly (a decision
23
- * has no output value of its own; the chosen event advances the machine).
24
- * - `task` — any other invoke/spawn: a plain host-run task keyed by `src` +
25
- * `input`. Run it, then journal `toDoneEvent`/`toErrorEvent`.
26
- * - `delay` — an `after(...)` timer. Schedule it; when it fires, journal
27
- * `event` (a normal external entry).
28
- * - `execute` — a fire-and-forget action (a custom entry action, `sendTo`,
29
- * `cancel`, …). Run `exec()` once at the frontier; NEVER journaled, never
30
- * replayed (replay re-derives it).
31
- */
32
- type AgentEffect = {
33
- kind: "text";
34
- requestId: string;
35
- request: AgentTextRequest; /** `'stream'` when the authored request wants `streamText`; default `'generate'`. */
36
- mode?: AgentRequestMode;
37
- toDoneEvent(output: unknown): EventObject;
38
- toErrorEvent(error: unknown): EventObject;
39
- } | {
40
- kind: "decision";
41
- requestId: string;
42
- request: AgentDecisionRequest;
43
- } | {
44
- kind: "task";
45
- requestId: string;
46
- id: string;
47
- src: string;
48
- input: unknown;
49
- toDoneEvent(output: unknown): EventObject;
50
- toErrorEvent(error: unknown): EventObject;
51
- } | {
52
- kind: "delay";
53
- requestId: string;
54
- id: string;
55
- delayMs: number; /** The `{ type: 'xstate.timer', id }` event the host journals when the timer fires. */
56
- event: EventObject;
57
- } | {
58
- kind: "execute";
59
- action: ExecutableActionObject;
60
- exec(): void;
61
- };
62
- /**
63
- * The reserved journal event type of the {@link initEntry} first entry: it
64
- * carries the machine `input` so a log replays with no side-channel. Named in
65
- * the `agent.*` builtin-actor namespace so it never collides with a machine's
66
- * own event vocabulary. Consumed by {@link replay}; never fed to `transition`.
67
- */
68
- declare const AGENT_INIT_EVENT_TYPE: "@agent.init";
69
- /**
70
- * The reserved event type `runAgent` delivers to the running machine after
71
- * every settled model call that reported usage — the one seam that puts a
72
- * call's tokens in reach of ordinary `context` and guards, so a token budget
73
- * is a plain machine transition instead of host bookkeeping.
74
- *
75
- * Like {@link AGENT_INIT_EVENT_TYPE} it lives in the reserved `@agent.*`
76
- * namespace: it can never collide with a machine's own vocabulary, and
77
- * `getAcceptedEvents`/`parseAgentEvent` never offer it — a model can neither
78
- * be shown it as a decision candidate nor forge one.
79
- *
80
- * Delivery is opt-in BY CONSTRUCTION: the event is sent only when the live
81
- * snapshot can currently take it (i.e. the machine declares an
82
- * `'@agent.usage'` transition, usually machine-level `on`). A machine without
83
- * one sees no extra transition, no extra trace event, and no extra log entry.
84
- * When it IS taken it rides the event log like any other external input, so
85
- * events-only recovery (`runAgent({ events })`) replays the folded tokens
86
- * without re-calling a model.
87
- */
88
- declare const AGENT_USAGE_EVENT_TYPE: "@agent.usage";
89
- /**
90
- * The payload of the reserved {@link AGENT_USAGE_EVENT_TYPE} event: the
91
- * settled call's normalized usage plus enough attribution to bill it (per
92
- * model, per request). Every field is JSON-safe, so the event round-trips
93
- * through the durable event log unchanged.
94
- *
95
- * Attribution fields are optional because not every call site has them — a
96
- * `getRequests` interpret-pass call reports usage with no invoke identity at
97
- * all, and only text requests carry a registered `name`.
98
- */
99
- interface AgentUsageEvent extends EventObject {
100
- type: typeof AGENT_USAGE_EVENT_TYPE;
101
- /** The settled call's token usage, as reported by the executor. */
102
- usage: AgentCallUsage;
103
- /** Which kind of request reported it. */
104
- kind?: "text" | "decision";
105
- /** The reporting request's durable invoke id. */
106
- id?: string;
107
- /** The reporting request's invoke `src`. */
108
- src?: string;
109
- /** The model ref the request targeted. */
110
- model?: string;
111
- /** The reporting text request's registered `name`, when it declared one. */
112
- name?: string;
113
- }
114
- /** Options controlling the durable envelope created by {@link createReplayEntry}. */
115
- interface CreateReplayEntryOptions {
116
- /** Explicit machine version; defaults to the machine's structural hash. */
117
- machineVersion?: string;
118
- /** Stable entry id; defaults to `evt_` plus the zero-padded index. */
119
- id?: string;
120
- /** RFC 3339 acceptance time; defaults to the current wall clock. */
121
- recordedAt?: string;
122
- causationId?: string;
123
- correlationId?: string;
124
- metadata?: Record<string, JsonValue>;
125
- /** Omit hashes when recording only a post-snapshot suffix without its prefix. */
126
- verification?: boolean;
127
- }
128
- /**
129
- * Creates a JSON-safe, self-describing entry and records the state/effect
130
- * hashes produced after replaying it. `entries` must be the complete prefix.
131
- */
132
- declare function createReplayEntry<TMachine extends AnyStateMachine>(machine: TMachine, entries: readonly AgentLogEntry[], event: EventObject, options?: CreateReplayEntryOptions): AgentLogEntry;
133
- /** Reserved first replay entry carrying machine input and verification hashes. */
134
- declare function initEntry<TMachine extends AnyStateMachine>(machine: TMachine, input?: unknown, options?: CreateReplayEntryOptions): AgentLogEntry;
135
- /** Options accepted by {@link getAgentEffects} and {@link replay}. */
136
- interface GetAgentEffectsOptions extends Partial<AgentExecutionOptions> {
137
- /**
138
- * The journal so far — an `EventObject[]` OR an `AgentLogEntry[]` (both
139
- * accepted). Occurrence counts (the `n` in a `requestId`) are derived from
140
- * it, so requestIds are stable across replay by construction.
141
- */
142
- history?: readonly (EventObject | AgentLogEntry)[];
143
- }
144
- /**
145
- * Maps a transition's ORDERED executable actions (plus the still-owed effects
146
- * visible only on the snapshot) into an ordered {@link AgentEffect} list the
147
- * host starts at the frontier.
148
- *
149
- * Ordering is load-bearing: a single transition's actions are emitted in
150
- * document order (a custom entry action, a spawn, and a `sendTo` in that order
151
- * yield `execute`, then `task`/agent effect, then `execute` — never a
152
- * reordered set). Effects visible only on the snapshot (children spawned by
153
- * an EARLIER transition that
154
- * have not completed yet — the fan-out / crash-resume case) are appended after
155
- * the action-derived effects, deduped by site id.
156
- *
157
- * Every `requestId` is `${siteId}#${n}`, `n` the 1-based occurrence derived
158
- * from `options.history` — so the same log yields identical requestIds on every
159
- * replay. XState alpha.24 prunes a child when its matching completion is
160
- * folded; the history check also prevents older/restored snapshots from
161
- * re-surfacing completed work. A re-entered invoke site instead re-derives
162
- * from the action list each fresh entry (so `#2`, `#3`, … stay correct).
163
- */
164
- declare function getAgentEffects(machine: AnyActorLogic, snapshot: AnyMachineSnapshot, actions: readonly ExecutableActionObject[], options?: GetAgentEffectsOptions): AgentEffect[];
165
- /** The result of a {@link replay}: the final snapshot and the effects still owed. */
166
- interface ReplayResult<TMachine extends AnyActorLogic> {
167
- snapshot: SnapshotFrom<TMachine>;
168
- effects: AgentEffect[];
169
- }
170
- /** Options for {@link replay}. */
171
- interface ReplayOptions extends Partial<AgentExecutionOptions> {
172
- /**
173
- * Machine input, used only when `entries` has no reserved {@link initEntry}
174
- * first entry. An init entry (the self-contained log) takes precedence.
175
- */
176
- input?: unknown;
177
- /** Explicit expected machine version; defaults to the structural hash. */
178
- machineVersion?: string;
179
- /** Check recorded hashes when present; `'strict'` additionally requires them. */
180
- verify?: boolean | "strict";
181
- }
182
- declare class AgentReplayMachineMismatchError extends AgentError {
183
- readonly eventId: string;
184
- readonly index: number;
185
- readonly expected: {
186
- machineId: string;
187
- machineVersion: string;
188
- };
189
- readonly actual: {
190
- machineId: string;
191
- machineVersion: string;
192
- };
193
- constructor(eventId: string, index: number, expected: {
194
- machineId: string;
195
- machineVersion: string;
196
- }, actual: {
197
- machineId: string;
198
- machineVersion: string;
199
- });
200
- }
201
- declare class AgentReplayDivergenceError extends AgentError {
202
- readonly eventId: string;
203
- readonly index: number;
204
- readonly kind: "state" | "effects" | "missing-verification";
205
- readonly expected?: string | undefined;
206
- readonly actual?: string | undefined;
207
- constructor(eventId: string, index: number, kind: "state" | "effects" | "missing-verification", expected?: string | undefined, actual?: string | undefined);
208
- }
209
- /** JSON Patch operation returned by {@link diffEventLogs}. */
210
- type AgentLogPatchOperation = {
211
- op: "add";
212
- path: string;
213
- value: JsonValue;
214
- } | {
215
- op: "remove";
216
- path: string;
217
- } | {
218
- op: "replace";
219
- path: string;
220
- value: JsonValue;
221
- };
222
- interface AgentEffectDiff {
223
- added: JsonValue[];
224
- removed: JsonValue[];
225
- changed: Array<{
226
- before: JsonValue;
227
- after: JsonValue;
228
- }>;
229
- }
230
- interface AgentEventLogDiff<TMachine extends AnyStateMachine> {
231
- commonPrefix: {
232
- length: number;
233
- throughEventId?: string;
234
- };
235
- parentOnly: AgentLogEntry[];
236
- forkOnly: AgentLogEntry[];
237
- parent: ReplayResult<TMachine>;
238
- fork: ReplayResult<TMachine>;
239
- stateChanges: AgentLogPatchOperation[];
240
- effectChanges: AgentEffectDiff;
241
- }
242
- declare function replay<TMachine extends AnyStateMachine>(machine: TMachine, entries: readonly AgentLogEntry[], options?: ReplayOptions): ReplayResult<TMachine>;
243
- /** Structural event-tail, logical-state, and owed-effect comparison. */
244
- declare function diffEventLogs<TMachine extends AnyStateMachine>(machine: TMachine, parentEntries: readonly AgentLogEntry[], forkEntries: readonly AgentLogEntry[], options?: ReplayOptions): AgentEventLogDiff<TMachine>;
245
- //#endregion
246
- //#region src/steps.d.ts
247
- /**
248
- * A pending text request surfaced by step discovery ({@link getAgentRequests}
249
- * / {@link AgentStep.requests}): the machine has spawned a
250
- * `TextLogic`-backed invoke and is waiting on its result. Resolve it with
251
- * {@link executeAgentRequest} (or by hand, then feed the output into
252
- * {@link resolveAgentStep} via `xstate.done.actor` + `actorId`).
253
- */
254
- interface AgentRequest<TInput extends AgentTextRequest = AgentTextRequest> {
255
- kind: "text";
256
- id: string;
257
- src: AgentRequestSource;
258
- mode?: AgentRequestMode;
259
- input: TInput;
260
- tools: AgentTools;
261
- events: AgentEventDescriptor[];
262
- }
263
- /** `AgentStep.requests` element: a text or decision request. */
264
- type AgentStepRequest = AgentRequest | AgentDecisionRequest;
265
- /**
266
- * Resolves one **text** request against a host's {@link AgentRequestExecutors}
267
- * — merges the request's tools, dispatches to `generateText`/`streamText` per
268
- * `mode`, and validates the result against the request's `outputSchema` if
269
- * present. Accepts either a `kind: 'text'` `AgentEffect` (the step-path shape
270
- * from `getAgentEffects`) or an {@link AgentRequest} envelope.
271
- * **Text-only**: passing a `kind: 'decision'` request throws, directing the
272
- * caller to `resolveDecision(request, executors, ...)` instead. Always
273
- * returns both the normalized `output` and the `raw` executor result (tool
274
- * calls, usage, finish reason — needed for observability and event-sourced
275
- * replay).
276
- */
277
- /** A `kind: 'text'` `AgentEffect` (structural, to avoid an import cycle with effects.ts). */
278
- interface TextEffectLike {
279
- kind: "text";
280
- requestId: string;
281
- request: AgentTextRequest;
282
- mode?: AgentRequestMode;
283
- }
284
- declare function executeAgentRequest(requestOrEffect: AgentRequest | TextEffectLike, executors: Partial<AgentRequestExecutors>): Promise<{
285
- output: unknown;
286
- raw: unknown;
287
- }>;
288
- //#endregion
289
- //#region src/internal/state-request-pass.d.ts
290
- /**
291
- * One model request read off the machine's CURRENT snapshot by a
292
- * `RunAgentOptions.getRequests` hook. `model` is an executor model NAME — the
293
- * same string every {@link AgentTextRequest.model} carries, resolved by the
294
- * run's executors (e.g. a `defineModels` key when using
295
- * `createAiSdkExecutors`) — never a model instance.
296
- */
297
- interface AgentStateRequest {
298
- /** Instruction for this request's model call, appended to the run's message log as a user message. */
299
- prompt: string;
300
- /** System prompt for this request's model call(s). */
301
- system?: string;
302
- /** Executor model name (resolved by the run's executors). */
303
- model: string;
304
- /**
305
- * `'text'` (default): a `generateText` call with the message log +
306
- * `prompt`; the reply is appended to the log, then the machine is advanced
307
- * per {@link AgentStateRequest.onDone}. `'decision'`: no text call — a
308
- * single `decide` call (log + `prompt`) chooses the event. Use for pure
309
- * routing states.
310
- */
311
- kind?: "text" | "decision";
312
- /**
313
- * What to send when this request's text call resolves — the EXPLICIT
314
- * advancement contract, always an event OBJECT (the same shape
315
- * `actor.send` takes; no string shorthand). A literal event sends exactly
316
- * that; a function receives the text output (plus the live snapshot and
317
- * message log) and returns the event to send — payload included — or
318
- * `undefined` to send nothing. Omitted: a `decide` call chooses among the
319
- * candidate events (requires a `decide` executor) — there is no implicit
320
- * auto-send. A resolved event whose type the state does not accept throws
321
- * (programmer error); one a guard rejects is simply not sent. Ignored for
322
- * `kind: 'decision'` (the decide call IS the advancement).
323
- */
324
- onDone?: ChosenEvent | ((args: {
325
- output: unknown;
326
- snapshot: AnyMachineSnapshot;
327
- messages: readonly AgentMessage[];
328
- }) => ChosenEvent | undefined);
329
- /** Restricts this request's candidate outcome events for the `decide` fallback (default: every currently-accepted event). */
330
- allowedEvents?: readonly string[];
331
- /** Trace/request id; defaults to `interpret_<n>`. */
332
- id?: string;
333
- }
334
- //#endregion
335
- //#region src/run-agent.d.ts
336
- /**
337
- * Thrown by {@link runAgent} when resuming with a `snapshot` + `event` whose
338
- * `type` the restored state cannot accept (a type-level check via
339
- * {@link getAcceptedEvents}). A programmer/integration error, in the same
340
- * class as runAgent's bind-time throws — it throws rather than settling an
341
- * `error` result. A type-legal event a guard rejects is NOT this error (the
342
- * machine simply takes no transition). Always enforced; there is no opt-out.
343
- */
344
- declare class AgentIllegalResumeEventError extends AgentError {
345
- readonly eventType: string;
346
- readonly acceptedTypes: string[];
347
- constructor(eventType: string, acceptedTypes: string[]);
348
- }
349
- /**
350
- * Thrown by {@link runAgent} when resuming from a `snapshot` whose stamped
351
- * `agentMeta.version` differs from the current machine's version, under the
352
- * default `onVersionMismatch: 'throw'` and with no `migrateSnapshot` hook. The
353
- * structural fingerprint of the machine changed since the snapshot was
354
- * persisted (a state/transition/invoke was added, removed, or retargeted), so
355
- * the snapshot may no longer resume cleanly. `from` is the snapshot's version,
356
- * `to` the current machine's.
357
- */
358
- declare class AgentSnapshotVersionMismatchError extends AgentError {
359
- readonly from: string;
360
- readonly to: string;
361
- readonly machineId: string;
362
- constructor(from: string, to: string, machineId: string);
363
- }
364
- /**
365
- * Thrown by {@link generateResult} when the run settles `idle` instead of
366
- * `done`: the machine paused for external input. Carries the idle `snapshot`
367
- * and `acceptedTypes` (the event types that could resume it, via
368
- * {@link getAcceptedEvents}). Use {@link runAgent} directly when idle is an
369
- * expected outcome you handle.
370
- */
371
- declare class AgentIdleError extends AgentError {
372
- readonly snapshot: AnyMachineSnapshot;
373
- readonly acceptedTypes: string[];
374
- constructor(snapshot: AnyMachineSnapshot, acceptedTypes: string[]);
375
- }
376
- /** Handler for `agent.userInput` invokes passed as {@link RunAgentOptions.userInput}. Resolves to what the human typed. */
377
- interface AgentUserInputExecutor {
378
- (input: AgentUserInput): PromiseLike<string>;
379
- }
380
- /**
381
- * The run's machine identity, stamped onto every settled snapshot's `agentMeta`.
382
- * `machineId` is the machine's `id`; `version` is the machine's own
383
- * `version` (XState's `createMachine({ version })`) or, when unversioned, the
384
- * {@link getMachineStructuralHash} of the machine. Trace events and the
385
- * `onMessage` info arg carry the same identity flattened, as
386
- * `machineId`/`machineVersion`.
387
- */
388
- interface AgentRunMeta {
389
- machineId: string;
390
- version: string;
391
- }
392
- /**
393
- * Second argument passed to {@link RunAgentOptions.onMessage}: the run's
394
- * identity, carried alongside each live message. Not stamped onto the message
395
- * itself (messages stay clean model input).
396
- */
397
- interface AgentMessageInfo {
398
- runId: string;
399
- machineId: string;
400
- /** The machine's own `version`, else its structural hash. */
401
- machineVersion: string;
402
- }
403
- /**
404
- * The version of the {@link AgentTraceEvent} envelope every trace event carries
405
- * as `schemaVersion`. Bumped only on a breaking change to the envelope or any
406
- * payload shape, so a consumer can gate on it. Emitted identically by
407
- * {@link runAgent}, {@link provideExecutors}' `onTrace`, and
408
- * {@link traceTransitions}.
409
- */
410
- declare const AGENT_TRACE_SCHEMA_VERSION = 1;
411
- type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
412
- /** The {@link AGENT_TRACE_SCHEMA_VERSION} the event was produced with. */schemaVersion: typeof AGENT_TRACE_SCHEMA_VERSION;
413
- runId: string;
414
- seq: number;
415
- timestamp: string;
416
- machineId: string; /** The machine's own `version`, else its structural hash. */
417
- machineVersion: string;
418
- } & ({
419
- type: "run.start";
420
- input?: InputFrom<TMachine>;
421
- snapshot?: Snapshot<unknown>;
422
- event?: EventFromLogic<TMachine>;
423
- } | {
424
- type: "request.start";
425
- request: AgentStepRequest;
426
- } | {
427
- type: "request.end";
428
- request: AgentStepRequest;
429
- output: unknown;
430
- raw: unknown;
431
- /** The model's reasoning, lifted off the raw executor result when the
432
- * request opted into the structured-output envelope's `reasoning` field.
433
- * Present only when the executor surfaced a string `reasoning`. */
434
- reasoning?: string;
435
- /** This call's token usage, lifted off the raw executor result's `usage`.
436
- * Present only when the executor reported it. The run-level total is
437
- * {@link RunAgentResult.usage}. */
438
- usage?: AgentCallUsage;
439
- } | {
440
- type: "request.error";
441
- request: AgentStepRequest;
442
- error: unknown;
443
- } | {
444
- type: "stream.chunk";
445
- request: AgentRequest;
446
- chunk: string;
447
- } | {
448
- type: "machine.transition";
449
- snapshot: SnapshotFrom<TMachine>;
450
- event: EventFromLogic<TMachine>; /** Durable replay-entry id when this transition corresponds to one. */
451
- eventId?: string;
452
- } | {
453
- type: "emit";
454
- event: EmittedFrom<TMachine>;
455
- } | {
456
- /** A reserved `@agent.usage` event the run declined to deliver. The
457
- * tokens still fold into {@link RunAgentResult.usage}; only the machine
458
- * event is dropped. */
459
- type: "usage.dropped";
460
- event: AgentUsageEvent; /** `'settled'`: the call settled after the run's cycle had resolved. */
461
- reason: "settled";
462
- } | ({
463
- type: "run.end";
464
- status: "done";
465
- output: OutputFrom<TMachine>;
466
- snapshot: SnapshotFrom<TMachine>;
467
- } | {
468
- type: "run.end";
469
- status: "idle";
470
- snapshot: SnapshotFrom<TMachine>;
471
- pendingUserInputs?: PendingUserInput[];
472
- persistedSnapshot?: Snapshot<unknown>;
473
- } | {
474
- type: "run.end";
475
- status: "error";
476
- cause: RunAgentErrorCause;
477
- error: unknown;
478
- snapshot: SnapshotFrom<TMachine>;
479
- }));
480
- /**
481
- * Fields a JSON projection keeps VERBATIM: {@link TRACE_ENVELOPE_KEYS} (the
482
- * envelope, the `type`/`status`/`cause` discriminants, and the payload fields
483
- * that are already plain strings) plus `usage.dropped`'s `reason`, which is a
484
- * string literal — sanitizing it is the identity, so it keeps its literal type.
485
- * Every other payload field narrows to {@link JsonValue}. @internal
486
- */
487
- type TraceVerbatimKey = (typeof TRACE_ENVELOPE_KEYS)[number] | "reason";
488
- /** One trace variant's JSON projection. Homomorphic, so `?` modifiers survive. @internal */
489
- type JsonProjectedTraceVariant<TEvent> = { [K in keyof TEvent]: K extends TraceVerbatimKey ? TEvent[K] : JsonValue };
490
- /**
491
- * `raw` is written only when `includeRaw` was set, so it is optional on the
492
- * JSON side even though the live trace always carries it. @internal
493
- */
494
- type WithOptionalRaw<T> = "raw" extends keyof T ? Omit<T, "raw"> & {
495
- raw?: JsonValue;
496
- } : T;
497
- /**
498
- * The JSON-safe projection of an {@link AgentTraceEvent} produced by
499
- * {@link serializeTraceEvent}: the envelope fields are unchanged, and every
500
- * payload field that can hold a live object (snapshots, machine events, request
501
- * objects, raw SDK results, errors) is narrowed to a {@link JsonValue}. Safe to
502
- * hand straight to `JSON.stringify` for a JSONL trace file.
503
- *
504
- * DERIVED from {@link AgentTraceEvent}, so a new trace variant cannot silently
505
- * miss the JSON side. `src/serialize-trace-event.test.ts` pins the result to
506
- * the shape this type had when it was hand-maintained.
507
- */
508
- type JsonSerializableTraceEvent = AgentTraceEvent extends infer TEvent ? TEvent extends unknown ? WithOptionalRaw<JsonProjectedTraceVariant<TEvent>> : never : never;
509
- declare const TRACE_ENVELOPE_KEYS: readonly ["schemaVersion", "runId", "seq", "timestamp", "machineId", "machineVersion", "type", "status", "cause", "eventId", "reasoning", "chunk"];
510
- /**
511
- * Projects an {@link AgentTraceEvent} into a guaranteed JSON-safe envelope —
512
- * the form the trace stream is actually sold for (one `JSON.stringify` per line
513
- * in a JSONL file). Live values are sanitized rather than trusted:
514
- *
515
- * - Snapshots (`run.start`, `machine.transition`, `run.end`) go through the
516
- * same JSON round-trip as `machine.getPersistedSnapshot(...)`, so what lands on disk is
517
- * what a resume would see.
518
- * - `request.end`'s `raw` (a provider SDK object, frequently cyclic) is DROPPED
519
- * unless `includeRaw` is set, in which case it is sanitized like everything
520
- * else.
521
- * - Non-serializable values anywhere (functions, symbols, `undefined`, cyclic
522
- * back-references) are dropped; `Error`s become `{ name, message, stack?,
523
- * code? }` instead of `{}`. Nothing throws.
524
- *
525
- * @example
526
- * ```ts
527
- * await appendFile('trace.jsonl', JSON.stringify(serializeTraceEvent(event)) + '\n');
528
- * ```
529
- */
530
- declare function serializeTraceEvent(event: AgentTraceEvent, options?: {
531
- includeRaw?: boolean;
532
- }): JsonSerializableTraceEvent;
533
- /**
534
- * Options for {@link runAgent}.
535
- *
536
- * Host executors are passed as a single {@link AgentRequestExecutors}-shaped
537
- * set under `executors` (the same shape the step path takes). Each executor
538
- * kind is required only if the machine actually reaches a request of that kind
539
- * — checked at bind time, before any actor runs. The whole `executors` field is
540
- * optional: a machine whose agent sources all carry their own executor
541
- * (`.withExecutor(...)`) needs none.
542
- */
543
- interface RunAgentOptions<TMachine extends AnyStateMachine> {
544
- /**
545
- * The host executor set backing the machine's agent actors — build it with
546
- * `createAiSdkExecutors({ models })` from '@statelyai/agent/ai-sdk', or supply
547
- * `{ generateText?, streamText?, decide? }` by hand. Every slot is optional
548
- * here (unlike the step path's {@link AgentRequestExecutors}): each kind is
549
- * bind-time-checked only when the machine actually reaches a request of that
550
- * kind, so e.g. a stream-only machine may pass `{ streamText }` alone.
551
- */
552
- executors?: Partial<AgentRequestExecutors>;
553
- /**
554
- * Machine input. Validated against the machine's declared input schema —
555
- * defaults filled, transforms applied — before it reaches
556
- * `createActor(machine, { input })` and the replayable event log; invalid
557
- * input throws an {@link AgentError} with code `invalid-machine-input`.
558
- * Typed as {@link AgentInputFrom}, so fields the schema defaults are optional
559
- * here. Omit when resuming via `snapshot`.
560
- */
561
- input?: AgentInputFrom<TMachine>;
562
- /** A previously-settled run's `result.snapshot`, to resume from instead of starting fresh. Pair with `event` to deliver the event that unblocks the resumed idle state. */
563
- snapshot?: Snapshot<unknown>;
564
- /** An event to send immediately after starting/resuming the actor (e.g. the human's answer to an idle-state prompt). */
565
- event?: EventFromLogic<TMachine>;
566
- /**
567
- * A prior `runAgent` result's replayable `events`, copied as the prefix of
568
- * this result's event log. Pass this alongside `snapshot` + `event` when
569
- * resuming so the next result retains the complete, replayable history;
570
- * with a `snapshot` these events are history only (`snapshot` is the live
571
- * resume source).
572
- *
573
- * **Events-only resume:** with NO `snapshot` and a self-contained log (a
574
- * reserved `@agent.init` first entry — every log started by `runAgent` from
575
- * scratch has one), the resume snapshot is derived by replaying the log:
576
- * recorded model/tool results are reused, never re-executed, and a request
577
- * that was still in flight when the log ended re-executes idempotently on
578
- * restore. This is the crash-recovery path: persist entries via `onEvent`
579
- * (or an event-log store) and resume from the log alone.
580
- */
581
- events?: readonly AgentLogEntry[];
582
- /**
583
- * How to handle a resume `snapshot` whose stamped `agentMeta.version` differs
584
- * from the current machine's `version` (XState's `createMachine({ version })`
585
- * prop — the single source of truth; an unversioned machine falls back to its
586
- * {@link getMachineStructuralHash}). `'throw'` (default) throws
587
- * {@link AgentSnapshotVersionMismatchError} with `from`/`to`; `'warn'`
588
- * `console.warn`s once and proceeds; `'ignore'` proceeds silently. Ignored
589
- * when {@link migrateSnapshot} is provided (that runs instead), and never
590
- * triggers for an unstamped snapshot (no `agentMeta`).
591
- */
592
- onVersionMismatch?: "throw" | "warn" | "ignore";
593
- /**
594
- * Called instead of {@link onVersionMismatch} when a resume snapshot's
595
- * version mismatches the current machine's: receives the incoming snapshot
596
- * and `{ from, to }`, and its return value is used as the snapshot to resume
597
- * from. A throw propagates.
598
- *
599
- * Prefer XState's own `createMachine({ version, migrate })` hook when the
600
- * migration belongs to the machine: a machine that declares `migrate` is left
601
- * to xstate, and runAgent neither throws nor rewrites the snapshot's version
602
- * before restore. This option stays for host-owned migrations (a machine you
603
- * do not control, or a migration that needs run-scoped context).
604
- */
605
- migrateSnapshot?: (snapshot: Snapshot<unknown>, info: {
606
- from: string;
607
- to: string;
608
- }) => Snapshot<unknown>;
609
- /** Actor source implementations, merged onto the machine before binding — sugar for `machine.provide({ actors })` ahead of the run. */
610
- actors?: Record<string, AnyActorLogic>;
611
- /**
612
- * Optional human-input handler for `agent.userInput` invokes (CLI prompt,
613
- * web form, Slack, …). With a handler, input is gathered inline without
614
- * settling. Without one, an `agent.userInput` invoke becomes a *pending
615
- * placeholder*: it waits indefinitely, does not block idle detection, and
616
- * the run settles `{ status: 'idle', pendingUserInputs, persistedSnapshot }`
617
- * once no other work is in flight — resume by passing `persistedSnapshot`
618
- * back as `snapshot` together with a `userInput` handler that answers it.
619
- */
620
- userInput?: AgentUserInputExecutor;
621
- /**
622
- * Host override for detecting a snapshot that is an INTENTIONAL wait for an
623
- * external event — the deterministic replacement for the timing heuristic
624
- * runAgent uses to settle idle. Resolution order: this option (host override)
625
- * → the machine-carried predicate declared via `setupAgent({ isIdle })`
626
- * → the timing heuristic (when neither is present). When the resolved
627
- * predicate returns true and nothing is in flight (no live requests/
628
- * invokes; the `agent.userInput` placeholder exemption still applies), runAgent
629
- * settles idle immediately, without the `setTimeout` heuristic. It does NOT
630
- * force-settle while agent work is in flight, and whole-machine idle semantics
631
- * are unchanged; a machine with no predicate falls back to the heuristic
632
- * exactly as before (with a one-time dev warning suggesting a predicate).
633
- * Declare your own signal, e.g. `(s) => s.hasTag('awaiting-review')`.
634
- */
635
- isIdle?: (snapshot: AnyMachineSnapshot) => boolean;
636
- /**
637
- * The override to runAgent's DEFAULT contract. By default agent work is
638
- * whatever the machine *invokes* (`agent.generateText`, TextLogic,
639
- * `agent.decide`, …). With `getRequests`, whenever the machine would
640
- * otherwise settle idle, this hook reads the snapshot and returns the model
641
- * request(s) to run instead — prompts from state `description`s, `meta`,
642
- * tags, a lookup table keyed by state value, wherever you keep them. Return
643
- * nothing to settle idle (human-wait states).
644
- *
645
- * There is no blessed source for the prompts — this is a recipe seam. The
646
- * shipped prompts-in-descriptions recipe is {@link getSnapshotRequests}:
647
- *
648
- * ```ts
649
- * getRequests: (snapshot) => getSnapshotRequests(snapshot, { model: 'writer' }),
650
- * ```
651
- *
652
- * Reach for {@link getSnapshotNodes} when you want to build requests some
653
- * other way — between them, host code never touches `snapshot._nodes`.
654
- *
655
- * Each request runs per {@link AgentStateRequest.kind}, appends to the
656
- * run's message log (see {@link RunAgentOptions.messages}), and advances
657
- * the machine per {@link AgentStateRequest.onDone} — explicitly named/
658
- * computed event, or a `decide` call when omitted — always gated by
659
- * `snapshot.can`. Multiple requests run concurrently (parallel regions —
660
- * scope each with `allowedEvents`, e.g. the node's `ownEvents`). A pass
661
- * that sends no event settles idle. Every model call counts against
662
- * `maxModelCalls`.
663
- */
664
- getRequests?: (snapshot: SnapshotFrom<TMachine>, agentContext: {
665
- messages: readonly AgentMessage[];
666
- }) => AgentStateRequest | readonly AgentStateRequest[] | undefined;
667
- /**
668
- * Adds to the run's aggregated message log (the working memory
669
- * `getRequests` requests read and append to). The log starts as the resume
670
- * `snapshot`'s stamped `messages` (else `[]`); an ARRAY here is APPENDED to
671
- * that history — the safe default for folding in a user reply on resume,
672
- * never silently erasing prior conversation. Pass a FUNCTION
673
- * `(prior) => AgentMessage[]` to take full control (replace, filter,
674
- * compact). The final log is stamped onto every settled result's
675
- * `snapshot.messages` (like `agentMeta`), so persist/resume round-trips it
676
- * with no extra wiring — read it with `getAgentMessages(snapshot)`.
677
- */
678
- messages?: AgentMessage[] | ((prior: AgentMessage[]) => AgentMessage[]);
679
- /**
680
- * Sugar over {@link onTrace}'s `stream.chunk` events: fires for each streamed
681
- * chunk of a `mode: 'stream'` text request, alongside the {@link AgentRequest}
682
- * that produced it (parallel states can interleave multiple streams). Purely
683
- * observational.
684
- */
685
- onChunk?: (chunk: string, info: {
686
- request: AgentRequest;
687
- }) => void;
688
- /**
689
- * Sugar over {@link onTrace}'s `request.end` events: fires once per resolved
690
- * text/decision request with its normalized output and the raw executor
691
- * result (tool calls, usage, …) — the seam for tracing/observability and
692
- * event-sourced replay logging.
693
- */
694
- onResult?: (request: AgentStepRequest, result: {
695
- output: unknown;
696
- raw: unknown;
697
- }) => void;
698
- /**
699
- * Fires as each new replayable external input is appended to this run's
700
- * event log. A fresh run begins with `@agent.init`; raised and other internal
701
- * events are excluded. History supplied through {@link events} is not
702
- * re-emitted. Purely observational, like {@link onTransition}.
703
- */
704
- onEvent?: (entry: AgentLogEntry) => void;
705
- /** Fires a single ordered stream of run/request/chunk/transition/emit/end events. Intended for eval traces, JSONL logs, and adapter-owned telemetry/exporters. */
706
- onTrace?: (event: AgentTraceEvent<TMachine>) => void;
707
- /**
708
- * Sugar over {@link onTrace}'s `machine.transition` events: fires on every
709
- * root-machine transition (snapshot + causing event). Pure observation —
710
- * progress UIs, logging, tracing. Cannot send events.
711
- */
712
- onTransition?: (snapshot: SnapshotFrom<TMachine>, event: EventFromLogic<TMachine>) => void;
713
- /**
714
- * Fires for each message appended to the run's aggregated log (see
715
- * {@link RunAgentOptions.messages}) the moment a `getRequests` request
716
- * appends it — the live view of the log a caller otherwise only reads off
717
- * the settled snapshot via `getAgentMessages`. Purely observational, like
718
- * {@link onTransition}. Never fires for the seeded history, and never fires
719
- * on a default invoke-driven run (nothing appends there).
720
- */
721
- onMessage?: (message: AgentMessage, info: AgentMessageInfo) => void;
722
- /**
723
- * Handlers for events the machine emits (`enq.emit(...)`), keyed by emitted
724
- * event type — `'*'` catches all. Typed from the machine's `emitted`
725
- * schemas (`setupAgent({ emitted: { ... } })`). Purely observational, like
726
- * {@link onTransition}: the machine narrates progress on its own vocabulary
727
- * (not xstate internals) and the host renders it — a progress UI, an SSE
728
- * stream, a log line.
729
- */
730
- on?: { [TType in EmittedFrom<TMachine>["type"] | "*"]?: (emitted: EmittedFrom<TMachine> & (TType extends "*" ? unknown : {
731
- type: TType;
732
- })) => void };
733
- /**
734
- * Raw xstate inspection passthrough: fires for every inspection event in
735
- * the whole actor system — root machine, invoked child machines, spawned
736
- * actors — each carrying its `actorRef` (`event.actorRef.id`/`.src`). This
737
- * is the system-wide seam {@link onTransition} (root transitions only)
738
- * cannot give you: filter `event.type === '@xstate.transition'` and read
739
- * `event.actorRef` to attribute a child machine's states to the child.
740
- * Purely observational, like the other callbacks. Unlike them it also
741
- * fires during the final settle (a child's last transition and stop events
742
- * arrive while the run is tearing down).
743
- *
744
- * Accepts a function or an observer (`{ next }`), matching `createActor`'s
745
- * `inspect` option, so `@statelyai/sdk`'s `inspector.inspect` plugs in
746
- * directly.
747
- */
748
- inspect?: ((inspectionEvent: InspectionEvent) => void) | {
749
- next?: (inspectionEvent: InspectionEvent) => void;
750
- };
751
- /**
752
- * Caps the number of model/decision calls this run may make (each retry of a
753
- * decision counts separately). Default 100. The overrun is thrown into the
754
- * invoke that would have made the call, as an
755
- * {@link AgentMaxModelCallsExceededError} with `code: 'max-model-calls'` — so
756
- * an `onError` can branch on it and route to a degraded state. Unhandled, it
757
- * settles `{ status: 'error', cause: 'max-model-calls' }`.
758
- */
759
- maxModelCalls?: number;
760
- /** Aborts the run; settles `{ status: 'error', cause: 'aborted' }` with `signal.reason` as the error. */
761
- signal?: AbortSignal;
762
- }
763
- /**
764
- * One active state node of a snapshot, as {@link getSnapshotRequests} and
765
- * {@link getSnapshotNodes} surface it: the prompt-bearing `description`, the
766
- * `tags` a recipe branches on, the state `meta`, and `ownEvents` (the event
767
- * types this node itself declares transitions for). The shape hosts used to
768
- * reach for through the private `snapshot._nodes` array.
769
- */
770
- interface AgentSnapshotNode {
771
- /** The node's full id (e.g. `writer.drafting`). */
772
- id: string;
773
- /** The node's own key (e.g. `drafting`). */
774
- key: string;
775
- /** The node's `description` — the prompt, in the prompts-in-descriptions recipe. */
776
- description?: string;
777
- tags: string[];
778
- meta?: unknown;
779
- /** Event types this node declares transitions for (xstate's `ownEvents`). */
780
- ownEvents: string[];
781
- /** True when the node has no child states. */
782
- leaf: boolean;
783
- }
784
- /**
785
- * The active state nodes of a snapshot, as plain {@link AgentSnapshotNode}
786
- * descriptors. The escape hatch under {@link getSnapshotRequests}: use it when
787
- * your `getRequests` hook needs to build requests some other way, so host code
788
- * never touches xstate's private `snapshot._nodes`.
789
- */
790
- declare function getSnapshotNodes(snapshot: AnyMachineSnapshot): AgentSnapshotNode[];
791
- /** Options for {@link getSnapshotRequests}. */
792
- interface GetSnapshotRequestsOptions {
793
- /** Executor model name every produced request carries. */
794
- model: string;
795
- /**
796
- * Which active nodes produce a request. Default: every node with a
797
- * `description` that is NOT tagged `'waiting'` (a human-wait state settles
798
- * idle instead).
799
- */
800
- filter?: (node: AgentSnapshotNode) => boolean;
801
- /**
802
- * Shapes (or drops, by returning `undefined`) each node's request before it
803
- * is returned — set `system`, `allowedEvents`, a custom `onDone`, …
804
- */
805
- map?: (request: AgentStateRequest, node: AgentSnapshotNode) => AgentStateRequest | undefined;
806
- }
807
- /**
808
- * Builds the {@link AgentStateRequest}s for a snapshot straight from its active
809
- * state nodes — the prompts-in-descriptions recipe as a function, so a
810
- * {@link RunAgentOptions.getRequests} hook is one line and never reaches into
811
- * xstate's private `snapshot._nodes`:
812
- *
813
- * ```ts
814
- * runAgent(machine, {
815
- * executors,
816
- * getRequests: (snapshot) => getSnapshotRequests(snapshot, { model: 'writer' }),
817
- * });
818
- * ```
819
- *
820
- * Each described active node becomes one request: `prompt` from the node's
821
- * `description`, `kind: 'decision'` when it is tagged `'decision'`, `system`
822
- * from `meta.role` when present, `allowedEvents` scoped to the node's own
823
- * events, and an explicit `onDone` when the node has exactly one own event
824
- * (single-outcome states advance deterministically; anything else falls
825
- * through to a `decide` call). Nodes tagged `'waiting'` produce nothing, so the
826
- * run settles idle for a human. Override any of it with `filter`/`map`.
827
- */
828
- declare function getSnapshotRequests(snapshot: AnyMachineSnapshot, options: GetSnapshotRequestsOptions): AgentStateRequest[];
829
- /**
830
- * The outcome of a {@link runAgent} call — always exactly one of three
831
- * variants, never a throw for a waiting or failed machine (programmer
832
- * errors like a missing executor still throw, at bind time before any actor
833
- * runs). `done`: a final state was reached (`output` is the machine's
834
- * `OutputFrom`). `idle`: the run settled with no in-flight work — resume by
835
- * calling `runAgent` again with `{ snapshot, event }`. `error`: a run-level
836
- * failure, discriminated by `cause` (`'aborted'`, `'max-model-calls'`,
837
- * `'decision-exhausted'`, `'machine'` for any other machine error state, or
838
- * `'stopped'` for an external stop — see {@link RunAgentErrorCause}). Every
839
- * variant carries the final `snapshot` plus a replayable `events` array. The
840
- * underlying actor is stopped on every settle path — there is no live actor to
841
- * resume; resume is always by snapshot.
842
- */
843
- /** A pending unhandled `agent.userInput` invoke surfaced on an idle settle — `id` is the invoke's id, `input` its resolved invoke input (prompt, metadata). Answer it by resuming with a `userInput` handler. */
844
- interface PendingUserInput {
845
- id: string;
846
- input: AgentUserInput | undefined;
847
- }
848
- type RunAgentOutcome<TMachine extends AnyStateMachine> = {
849
- status: "done";
850
- output: OutputFrom<TMachine>;
851
- snapshot: SnapshotFrom<TMachine>;
852
- } | {
853
- status: "idle";
854
- snapshot: SnapshotFrom<TMachine>; /** Present when the machine is waiting on unhandled `agent.userInput` invokes: one entry per pending invoke. */
855
- pendingUserInputs?: PendingUserInput[];
856
- /**
857
- * The JSON-serializable persisted snapshot (in-flight children included,
858
- * WITH their own state). Persist THIS one and resume with
859
- * `runAgent(machine, { snapshot: persistedSnapshot, ... })` — the live
860
- * `snapshot` above cannot round-trip active children, so resuming from
861
- * it restarts every invoked child from scratch.
862
- */
863
- persistedSnapshot: Snapshot<unknown>;
864
- } | {
865
- status: "error";
866
- cause: RunAgentErrorCause;
867
- error: unknown;
868
- snapshot: SnapshotFrom<TMachine>;
869
- };
870
- type RunAgentResult<TMachine extends AnyStateMachine> = RunAgentOutcome<TMachine> & {
871
- /**
872
- * Versioned, JSON-safe envelopes around replayable external inputs observed
873
- * through this run: machine input, effect completions/failures, user events,
874
- * and timer firings. Raised/internal events are excluded because replay
875
- * re-derives them. Each entry carries timestamp, machine identity/version,
876
- * and strict replay hashes.
877
- *
878
- * A fresh run starts with `@agent.init`. When resuming from a snapshot, pass
879
- * the preceding result's `events` through {@link RunAgentOptions.events} to
880
- * retain a self-contained history.
881
- */
882
- events: AgentLogEntry[];
883
- /**
884
- * Aggregated model-call usage for THIS run — `modelCalls` plus the token
885
- * fields every executor reported (see {@link AgentUsage} for the
886
- * partial-sum rule). Present on all three variants: an `idle` or `error`
887
- * result accounts for the calls made before the run settled.
888
- *
889
- * A resumed run counts only its own calls, not the history behind
890
- * `snapshot`/`events`.
891
- */
892
- usage: AgentUsage;
893
- };
894
- /**
895
- * Discriminates a {@link RunAgentResult} `error`:
896
- * - `'aborted'` — the run's `signal` fired.
897
- * - `'max-model-calls'` — the `maxModelCalls` budget was exceeded.
898
- * - `'decision-exhausted'` — the machine reached an error state whose error is
899
- * (or wraps) a {@link AgentDecisionExhaustedError} that no `onError` handled.
900
- * - `'machine'` — any other machine error state.
901
- * - `'stopped'` — the actor was stopped externally (`status === 'stopped'`).
902
- */
903
- type RunAgentErrorCause = "aborted" | "max-model-calls" | "decision-exhausted" | "machine" | "stopped";
904
- /**
905
- * Thrown into the invoke that would have made the call once
906
- * {@link RunAgentOptions.maxModelCalls} is spent. It reaches the machine
907
- * through the normal error channel, so an invoke's `onError` can branch on it
908
- * (`error.code === 'max-model-calls'`, the same string the settled result's
909
- * `cause` uses) and route to a degraded/finish state instead of failing the
910
- * run. Unhandled, it settles `{ status: 'error', cause: 'max-model-calls' }`.
911
- *
912
- * ```ts
913
- * onError: [
914
- * { guard: ({ event }) => event.error?.code === 'max-model-calls', target: 'budgetSpent' },
915
- * { target: 'failed' },
916
- * ]
917
- * ```
918
- */
919
- declare class AgentMaxModelCallsExceededError extends AgentError {
920
- /** The budget that was exceeded (`options.maxModelCalls`). */
921
- readonly maxModelCalls: number;
922
- constructor(maxModelCalls: number);
923
- }
924
- /**
925
- * The machine input a run accepts, which is the schema's *pre*-validation side.
926
- *
927
- * XState's `schemas` are types only — it never validates, and it resolves
928
- * `schemas.input` to one type shared by `createActor`'s `input` option and the
929
- * `context: ({ input })` factory. A schema field declared with a default
930
- * therefore reads as required at the call site even though the caller is meant
931
- * to omit it. `setupAgent` brands the machine's input type with its own schema
932
- * ({@link WithAgentInputSchema}), so this recovers the looser caller-facing
933
- * side while the factory keeps seeing the validated one. Machines with no
934
- * declared input schema — and machines reached through `.provide(...)`, which
935
- * drops the brand — fall back to xstate's `InputFrom`.
936
- */
937
- type AgentInputFrom<TMachine extends AnyStateMachine> = [NonNullable<InputFrom<TMachine>>] extends [WithAgentInputSchema<infer TInputSchema>] ? [TInputSchema] extends [StandardSchemaV1] ? InferInput<TInputSchema> : InputFrom<TMachine> : InputFrom<TMachine>;
938
- /**
939
- * Runs an agent machine to completion or idle: a `createActor` host that
940
- * binds `options`' host executors onto the machine's `agent.*`/`TextLogic`/
941
- * `DecisionLogic` actor sources, starts (or resumes) the actor, and drives
942
- * it until it settles — {@link RunAgentResult} `done | idle | error`. Unlike
943
- * the step helpers ({@link initialAgentStep} etc — a pure
944
- * transition-at-a-time path for durable hosts), `runAgent` owns a live actor
945
- * internally; there is no continuation callback, so **idle always settles**
946
- * and the caller resumes explicitly by passing the settled `{ snapshot,
947
- * event }` back in. The actor is stopped on every settle path (`done`,
948
- * `idle`, and `error` alike) — resume is always by snapshot, never by
949
- * holding a reference to a live actor.
950
- *
951
- * Binding happens **before** the actor starts: every invoke the machine
952
- * could reach is walked and checked against the effective actor sources
953
- * (`options.actors` merged onto the machine), so a missing
954
- * `streamText`/`decide` executor or any other unbound actor source throws
955
- * immediately — a bind-time error, not a mid-run failure. The one exception
956
- * is `agent.userInput`: unhandled, it binds as a pending placeholder that
957
- * settles the run idle (with `pendingUserInputs`) instead of erroring.
958
- *
959
- * @example
960
- * ```ts
961
- * const executors = createAiSdkExecutors({ models });
962
- * let r = await runAgent(machine, { input, executors });
963
- * while (r.status === 'idle') {
964
- * const event = await promptUser(getAcceptedEvents(r.snapshot));
965
- * r = await runAgent(machine, { snapshot: r.snapshot, event, executors });
966
- * }
967
- * if (r.status !== 'done') throw new Error(`Run did not complete: ${r.status}`);
968
- * console.log(r.output);
969
- * ```
970
- *
971
- * The `executors`' `generateText`/`streamText` accept the raw Vercel AI SDK
972
- * functions directly (`executors: { generateText, streamText }` with them
973
- * imported from `ai`) — their `{ text }`/`{ textStream }` results are unwrapped
974
- * natively. `decide` cannot be a raw AI SDK function: the tool-per-event mapping
975
- * lives in an adapter — use `createAiSdkExecutors` from '@statelyai/agent/ai-sdk'.
976
- */
977
- declare function runAgent<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentOptions<TMachine>): Promise<RunAgentResult<TMachine>>;
978
- /**
979
- * A long-lived agent session returned by {@link createAgentActor}: the same
980
- * engine as {@link runAgent} (executor binding at any depth, the replayable
981
- * event log, budgets, traces), but the actor stays alive across idle settles.
982
- *
983
- * One **cycle** runs from start (or the event that re-opened the session) to
984
- * the next quiescence. `settled()` resolves with the current cycle's
985
- * {@link RunAgentResult}; after an `idle` settle, sending the actor an event
986
- * re-opens the cycle and the next `settled()` call tracks it. The event log
987
- * spans the whole session — every turn appends to one replayable history.
988
- * `done`, `error`, and external stop are final: the actor stops and every
989
- * later `settled()` resolves with that final result.
990
- */
991
- interface AgentActorSession<TMachine extends AnyStateMachine> {
992
- /** The live bound actor. Drive it directly: `session.actor.send(event)`. */
993
- actor: ReturnType<typeof createActor<TMachine>>;
994
- /** The session's replayable event log (live; grows across cycles). */
995
- readonly events: readonly AgentLogEntry[];
996
- /** Cumulative session usage (all cycles). */
997
- usage(): AgentUsage;
998
- /** Resolves with the current cycle's settled result (`done | idle | error`). */
999
- settled(): Promise<RunAgentResult<TMachine>>;
1000
- /** Stops the actor. A not-yet-settled cycle settles `error`/`stopped`. */
1001
- stop(): void;
1002
- }
1003
- /**
1004
- * Session mode: {@link runAgent}'s engine with a long-lived actor. Use it when
1005
- * the agent is a *session* fed by external events (chat turns, device or
1006
- * timer events, a socket) rather than a one-shot job — you keep the log,
1007
- * budget, traces, and idle semantics that bare `provideExecutors` +
1008
- * `createActor` would forfeit.
1009
- *
1010
- * ```ts
1011
- * const session = createAgentActor(machine, { input, executors });
1012
- * let result = await session.settled(); // first quiescence
1013
- * while (result.status === "idle") {
1014
- * session.actor.send(await nextUserEvent(result.snapshot));
1015
- * result = await session.settled(); // next quiescence, same log
1016
- * }
1017
- * session.stop();
1018
- * ```
1019
- *
1020
- * Accepts the same options as {@link runAgent} (including `snapshot`/`events`
1021
- * resume). Not yet supported in session mode: `getRequests` re-interpretation
1022
- * across cycles behaves per-cycle exactly as in `runAgent`.
1023
- */
1024
- declare function createAgentActor<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentOptions<TMachine>): AgentActorSession<TMachine>;
1025
- /**
1026
- * The resolved value of {@link generateResult}: the `done`-narrowed
1027
- * {@link RunAgentResult} — `output` plus run metadata (`snapshot`, replayable
1028
- * `events`, aggregated `usage`), mirroring how the AI SDK's `generateText`
1029
- * resolves `text` alongside its call metadata.
1030
- */
1031
- type GenerateResult<TMachine extends AnyStateMachine> = Extract<RunAgentResult<TMachine>, {
1032
- status: "done";
1033
- }>;
1034
- /**
1035
- * Runs an agent machine to a **final state**, for run-to-done flows where an
1036
- * idle pause is unexpected. Wraps {@link runAgent}:
1037
- *
1038
- * - `done` → resolves with the done result: `result.output` (the machine's
1039
- * `OutputFrom`) plus metadata — `result.snapshot`, the replayable
1040
- * `result.events`, and the aggregated `result.usage` — the same shape
1041
- * `generateText` users expect (`text` + call metadata).
1042
- * - `idle` → throws {@link AgentIdleError} carrying the idle snapshot and the
1043
- * event types that could resume it.
1044
- * - `error` → throws `result.error` when it is an `Error`; otherwise wraps it
1045
- * in an `Error` whose `.cause` is the {@link RunAgentErrorCause} and whose
1046
- * `.error` is the raw thrown value.
1047
- *
1048
- * Use {@link runAgent} directly when idle is an expected outcome you handle
1049
- * (human-in-the-loop, resumable flows); use `generateResult` when the
1050
- * machine is meant to run straight through to a final state.
1051
- */
1052
- declare function generateResult<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentOptions<TMachine>): Promise<GenerateResult<TMachine>>;
1053
- /**
1054
- * The actor handed to an {@link inspectTransitions} handler: an
1055
- * {@link AnyActorRef} widened with the runtime `id`/`src` used to attribute a
1056
- * transition to the root machine or a specific invoked child (xstate's static
1057
- * `ActorRef` type omits them, but they are always present at runtime).
1058
- */
1059
- type InspectedActorRef = AnyActorRef & {
1060
- id: string;
1061
- src?: string | AnyActorLogic;
1062
- };
1063
- /**
1064
- * Wraps a `(snapshot, actorRef) => void` handler into a function usable as
1065
- * {@link RunAgentOptions.inspect}: it filters the raw inspection stream to
1066
- * `@xstate.transition` events and hands the handler the typed
1067
- * {@link AnyMachineSnapshot} and the {@link InspectedActorRef} that
1068
- * transitioned. Attribute a child actor via `actorRef.id`/`actorRef.src`. Saves
1069
- * the manual `event.type === '@xstate.transition'` filtering and the snapshot/
1070
- * actorRef casts.
1071
- */
1072
- declare function inspectTransitions(handler: (snapshot: AnyMachineSnapshot, actorRef: InspectedActorRef) => void): (inspectionEvent: InspectionEvent) => void;
1073
- /**
1074
- * An xstate `inspect` handler that emits `machine.transition` trace events onto
1075
- * `onTrace`, sharing the SAME versioned envelope and per-root-actor `seq`
1076
- * registry as {@link provideExecutors}' `onTrace`. Pair the two on one actor to
1077
- * get a single ordered trace stream (request + transition events) for the
1078
- * uncontrolled path:
1079
- *
1080
- * ```ts
1081
- * const bound = provideExecutors(machine, executors, { onTrace });
1082
- * const actor = createActor(bound, { inspect: traceTransitions(onTrace) });
1083
- * ```
1084
- *
1085
- * Only ROOT-actor transitions are traced (matching `runAgent`'s
1086
- * `machine.transition`); child-actor transitions are ignored. Attribute the
1087
- * event via its envelope `runId`.
1088
- *
1089
- * By design this path has NO `run.start`/`run.end` events: `createActor` has no
1090
- * run boundary the way `runAgent` does, so the stream starts at the actor's
1091
- * first transition. It also does NOT emit `emit` trace events: in this xstate
1092
- * build emitted events are delivered through `actor.on(...)`, not the inspection
1093
- * protocol, so they are not observable from an `inspect` handler — subscribe
1094
- * with `actor.on('*', ...)` if you need them.
1095
- */
1096
- declare function traceTransitions<TMachine extends AnyStateMachine = AnyStateMachine>(onTrace: (event: AgentTraceEvent<TMachine>) => void): (inspectionEvent: InspectionEvent) => void;
1097
- //#endregion
1098
- export { AgentRequest as A, AgentReplayMachineMismatchError as B, getSnapshotNodes as C, serializeTraceEvent as D, runAgent as E, AgentEffect as F, ReplayResult as G, CreateReplayEntryOptions as H, AgentEffectDiff as I, getAgentEffects as J, createReplayEntry as K, AgentEventLogDiff as L, executeAgentRequest as M, AGENT_INIT_EVENT_TYPE as N, traceTransitions as O, AGENT_USAGE_EVENT_TYPE as P, AgentLogPatchOperation as R, generateResult as S, inspectTransitions as T, GetAgentEffectsOptions as U, AgentUsageEvent as V, ReplayOptions as W, replay as X, initEntry as Y, PendingUserInput as _, AgentInputFrom as a, RunAgentResult as b, AgentRunMeta as c, AgentTraceEvent as d, AgentUserInputExecutor as f, JsonSerializableTraceEvent as g, InspectedActorRef as h, AgentIllegalResumeEventError as i, AgentStepRequest as j, AgentStateRequest as k, AgentSnapshotNode as l, GetSnapshotRequestsOptions as m, AgentActorSession as n, AgentMaxModelCallsExceededError as o, GenerateResult as p, diffEventLogs as q, AgentIdleError as r, AgentMessageInfo as s, AGENT_TRACE_SCHEMA_VERSION as t, AgentSnapshotVersionMismatchError as u, RunAgentErrorCause as v, getSnapshotRequests as w, createAgentActor as x, RunAgentOptions as y, AgentReplayDivergenceError as z };