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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/ai-sdk.cjs +30 -34
  2. package/dist/ai-sdk.d.cts +27 -31
  3. package/dist/ai-sdk.d.mts +27 -31
  4. package/dist/ai-sdk.mjs +27 -31
  5. package/dist/decision-CM9CYZ6t.cjs +519 -0
  6. package/dist/decision-DzSv1NpD.mjs +453 -0
  7. package/dist/event-log-store-Ba2fsc4E.mjs +576 -0
  8. package/dist/event-log-store-DQmImLYk.cjs +702 -0
  9. package/dist/event-log-store-DvOcs10J.d.cts +338 -0
  10. package/dist/event-log-store-DxyVgnas.d.mts +338 -0
  11. package/dist/index.cjs +429 -4272
  12. package/dist/index.d.cts +104 -1005
  13. package/dist/index.d.mts +104 -1005
  14. package/dist/index.mjs +389 -4202
  15. package/dist/log.cjs +392 -0
  16. package/dist/log.d.cts +32 -0
  17. package/dist/log.d.mts +32 -0
  18. package/dist/log.mjs +371 -0
  19. package/dist/machines.cjs +27 -16
  20. package/dist/machines.d.cts +1 -1
  21. package/dist/machines.d.mts +1 -1
  22. package/dist/machines.mjs +27 -16
  23. package/dist/openai.cjs +16 -15
  24. package/dist/openai.d.cts +9 -9
  25. package/dist/openai.d.mts +9 -9
  26. package/dist/openai.mjs +10 -9
  27. package/dist/otel.d.cts +1 -1
  28. package/dist/otel.d.mts +1 -1
  29. package/dist/{run-agent-Ck7Sa3Tb.d.mts → run-agent-BOfoJg5B.d.cts} +86 -387
  30. package/dist/{run-agent-DWqA8KiI.d.cts → run-agent-CG343kFs.d.mts} +86 -387
  31. package/dist/run-agent-Cb1-LS5P.cjs +1783 -0
  32. package/dist/run-agent-DvDQd4If.mjs +1669 -0
  33. package/dist/{setup-agent-CeO2fARv.mjs → setup-agent-CFW-jPI8.mjs} +9 -20
  34. package/dist/{setup-agent-Dl2VELLi.cjs → setup-agent-CPf7MxnG.cjs} +20 -37
  35. package/dist/testing.cjs +1088 -0
  36. package/dist/testing.d.cts +617 -0
  37. package/dist/testing.d.mts +617 -0
  38. package/dist/testing.mjs +1079 -0
  39. package/dist/{text-logic-DJBK3LbG.d.mts → text-logic-BFEOxyxv.d.cts} +71 -147
  40. package/dist/text-logic-Bl_ZRxDi.mjs +833 -0
  41. package/dist/text-logic-C8xyr6Ag.cjs +1091 -0
  42. package/dist/{text-logic-C7bSnH_B.d.cts → text-logic-hZSiRUo1.d.mts} +71 -147
  43. package/dist/{types-CjHk5OdH.d.cts → types-B1Qs2q3q.d.cts} +2 -1
  44. package/dist/{types-DWA6X9R-.d.mts → types-tA3SdczG.d.mts} +2 -1
  45. package/dist/usage-BdEjFuIi.mjs +5 -0
  46. package/dist/usage-efOQPdf_.cjs +10 -0
  47. package/dist/utils-C2DPqomn.d.mts +109 -0
  48. package/dist/utils-ceStNCOh.d.cts +109 -0
  49. package/package.json +26 -5
  50. package/readme.md +5 -3
  51. package/skills/generate-machine/SKILL.md +4 -6
  52. package/dist/decision-BBZ2jMO1.mjs +0 -1490
  53. package/dist/decision-Cv6SfNWl.cjs +0 -1856
@@ -1,5 +1,6 @@
1
- import { _ as StandardSchemaV1, m as InferInput, s as AgentTools, w as WithAgentInputSchema } from "./types-DWA6X9R-.mjs";
2
- import { F as AgentDecisionRequest, K as AgentEventDescriptor, X as AgentRequestSource, d as AgentRequestMode, f as AgentTextRequest, m as AgentUserInput, p as AgentUsage, r as AgentFinishReason, t as AgentCallUsage, tt as AgentError, u as AgentRequestExecutors } from "./text-logic-DJBK3LbG.mjs";
1
+ import { _ as StandardSchemaV1, m as InferInput, s as AgentTools, w as WithAgentInputSchema } from "./types-B1Qs2q3q.cjs";
2
+ import { G as AgentRequestOptions, K as AgentRequestSource, M as AgentDecisionRequest, U as AgentEventDescriptor, Z as AgentError, d as AgentRequestMode, f as AgentTextRequest, m as AgentUsage, p as AgentTextResult, r as AgentFinishReason, t as AgentCallUsage, u as AgentRequestExecutors } from "./text-logic-BFEOxyxv.cjs";
3
+ import { c as AgentLogEntry, n as AgentEventLogStore } from "./event-log-store-DvOcs10J.cjs";
3
4
  import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, InputFrom, InspectionEvent, OutputFrom, Snapshot, SnapshotFrom } from "xstate";
4
5
 
5
6
  //#region src/usage.d.ts
@@ -16,6 +17,11 @@ interface AgentUsageEvent extends EventObject {
16
17
  name?: string;
17
18
  }
18
19
  //#endregion
20
+ //#region src/internal/registry.d.ts
21
+ type AgentExecutionOptions = Pick<AgentRequestOptions, "schemas" | "actors"> & {
22
+ models?: object;
23
+ };
24
+ //#endregion
19
25
  //#region src/steps.d.ts
20
26
  /**
21
27
  * A pending text request surfaced by step discovery ({@link getAgentRequests}
@@ -36,362 +42,80 @@ interface AgentRequest<TInput extends AgentTextRequest = AgentTextRequest> {
36
42
  /** `AgentStep.requests` element: a text or decision request. */
37
43
  type AgentStepRequest = AgentRequest | AgentDecisionRequest;
38
44
  /**
39
- * Resolves one **text** request against a host's {@link AgentRequestExecutors}
40
- * — merges the request's tools, dispatches to `generateText`/`streamText` per
41
- * `mode`, and validates the result against the request's `outputSchema` if
42
- * present. Accepts either a `kind: 'text'` `AgentEffect` (the step-path shape
43
- * from a custom XState host) or an {@link AgentRequest} envelope.
44
- * **Text-only**: passing a `kind: 'decision'` request throws, directing the
45
- * caller to `resolveDecision(request, executors, ...)` instead. Always
46
- * returns both the normalized `output` and the `raw` executor result (tool
47
- * calls, usage, finish reason — needed for observability and event-sourced
48
- * replay).
49
- */
50
- /** A `kind: 'text'` `AgentEffect` (structural, to avoid an import cycle with effects.ts). */
51
- interface TextEffectLike {
52
- kind: "text";
53
- requestId: string;
54
- request: AgentTextRequest;
55
- mode?: AgentRequestMode;
56
- }
57
- declare function executeAgentRequest(requestOrEffect: AgentRequest | TextEffectLike, executors: Partial<AgentRequestExecutors>): Promise<{
58
- output: unknown;
59
- raw: unknown;
60
- }>;
61
- //#endregion
62
- //#region src/event-log.d.ts
63
- /** The durable entry envelope version. */
64
- declare const AGENT_EVENT_SCHEMA_VERSION: 1;
65
- /**
66
- * The reserved event type of the first entry of every log. It carries the
67
- * machine `input` (fresh start) or a persisted `snapshot` (continuation), so a
68
- * log replays with no side channel. Lives in the reserved `@agent.*` namespace
69
- * so it can never collide with a machine's own vocabulary; it is consumed by
70
- * {@link replay} and never fed to `transition`.
71
- */
72
- declare const AGENT_INIT_EVENT_TYPE: "@agent.init";
73
- /** Values that round-trip through JSON without adapters or silent coercion. */
74
- type JsonValue$1 = null | boolean | number | string | JsonValue$1[] | {
75
- [key: string]: JsonValue$1;
76
- };
77
- /** A persisted (JSON-safe) machine snapshot, as `machine.getPersistedSnapshot()` returns. */
78
- type AgentPersistedSnapshot = Snapshot<unknown>;
79
- /** Recorded projection hash used by {@link replay} verification. */
80
- interface AgentLogVerification {
81
- /** {@link getSnapshotStateHash} of the persisted snapshot after this entry is applied. */
82
- stateHash: string;
83
- }
84
- /**
85
- * One journaled external input, JSON-safe and stored verbatim.
86
- */
87
- interface AgentLogEntry {
88
- /** Version of this outer envelope, independent of the machine event type. */
89
- schemaVersion: typeof AGENT_EVENT_SCHEMA_VERSION;
90
- /** Stable identity within the log. Forked prefixes retain their ids. */
91
- id: string;
92
- /** 0-based position in the log. */
93
- index: number;
94
- /** RFC 3339 wall-clock time when the host accepted the entry. Metadata only. */
95
- recordedAt: string;
96
- /** The authored XState machine id. */
97
- machineId: string;
98
- /** Explicit version or structural hash of the machine that accepted the event. */
99
- machineVersion: string;
100
- event: EventObject;
101
- /** Optional causal parent entry id, scoped to the same log. */
102
- causationId?: string;
103
- /** Host-owned, JSON-safe; stored verbatim, never interpreted. */
104
- metadata?: Record<string, JsonValue$1>;
105
- /** Recorded projection hash used by replay verification. */
106
- verification?: AgentLogVerification;
107
- }
108
- /** The payload of the reserved {@link AGENT_INIT_EVENT_TYPE} first entry. */
109
- interface AgentInitEvent extends EventObject {
110
- type: typeof AGENT_INIT_EVENT_TYPE;
111
- /** Machine input for a fresh start. Mutually exclusive with `snapshot`. */
112
- input?: unknown;
113
- /** Persisted snapshot to continue from. Mutually exclusive with `input`. */
114
- snapshot?: AgentPersistedSnapshot;
115
- }
116
- /** A malformed or internally inconsistent log. */
117
- declare class AgentEventLogError extends AgentError {
118
- constructor(message: string);
45
+ * One checkpoint on the step path: the machine's current snapshot, the
46
+ * executable actions that produced it, the pending
47
+ * {@link AgentStepRequest}s (text/decision work still to resolve), and
48
+ * whether the machine has reached a final state. Produced by
49
+ * {@link initialAgentStep}, {@link transitionAgentStep},
50
+ * {@link resolveAgentStep}, and {@link rejectAgentStep}.
51
+ */
52
+ interface AgentStep<TSnapshot extends AnyMachineSnapshot = AnyMachineSnapshot> {
53
+ snapshot: TSnapshot;
54
+ actions: readonly {
55
+ type?: string;
56
+ params?: unknown;
57
+ }[];
58
+ requests: AgentStepRequest[];
59
+ done: boolean;
119
60
  }
120
- /** A precise failure when an entry would not survive a JSON round-trip. */
121
- declare class NonSerializableAgentEventError extends AgentError {
122
- readonly path: string;
123
- readonly valueType: string;
124
- constructor(path: string, valueType: string);
125
- }
126
- /** Replay reached a state that does not match the entry's recorded hash. */
127
- declare class AgentReplayDivergenceError extends AgentError {
128
- readonly eventId: string;
129
- readonly index: number;
130
- readonly kind: "state" | "missing-verification";
131
- readonly expected?: string | undefined;
132
- readonly actual?: string | undefined;
133
- constructor(eventId: string, index: number, kind: "state" | "missing-verification", expected?: string | undefined, actual?: string | undefined);
134
- }
135
- /**
136
- * An entry was recorded against a different machine (id) or a different
137
- * machine version than the one replaying it. An init-with-snapshot entry is
138
- * exempt: that entry IS the bridge from the old version to the new one.
139
- */
140
- declare class AgentMachineVersionMismatchError extends AgentError {
141
- readonly eventId: string;
142
- readonly index: number;
143
- readonly expected: {
144
- machineId: string;
145
- machineVersion: string;
146
- };
147
- readonly actual: {
148
- machineId: string;
149
- machineVersion: string;
150
- };
151
- constructor(eventId: string, index: number, expected: {
152
- machineId: string;
153
- machineVersion: string;
154
- }, actual: {
155
- machineId: string;
156
- machineVersion: string;
157
- });
158
- }
159
- /**
160
- * Rejects values JSON would drop or coerce. Unlike `JSON.stringify`, this does
161
- * not silently erase `undefined`/functions or turn non-finite numbers into
162
- * `null`; durable entries contain only plain JSON values.
163
- */
164
- declare function assertJsonSerializable(value: unknown, path?: string, ancestors?: WeakSet<object>): asserts value is JsonValue$1;
165
- /** Validates the complete durable envelope before append/export/replay. */
166
- declare function assertAgentLogEntry(entry: unknown): asserts entry is AgentLogEntry;
167
- /**
168
- * The canonical hash of a PERSISTED snapshot (`machine.getPersistedSnapshot()`,
169
- * or {@link replay}'s `persistedSnapshot`) — the value recorded in an entry's
170
- * `verification.stateHash`.
171
- *
172
- * Stripped before hashing, because they are re-minted on every fold and would
173
- * otherwise make two identical runs hash differently: `sessionId`,
174
- * `_nextTimerId` and `_nextActorIds` at the snapshot root, `sessionId` on each
175
- * `children[*]` entry (recursively, through nested child snapshots), and
176
- * `undefined`-valued properties (so a snapshot hashes the same before and
177
- * after a JSON round-trip). Stripping is confined to those structural
178
- * positions: a `sessionId` inside `context`, `output`, `error` or an event
179
- * payload is application data and is hashed. Object keys are sorted, so key
180
- * order is irrelevant.
181
- *
182
- * A change detector, not a cryptographic digest.
183
- */
184
- declare function getSnapshotStateHash(snapshot: AgentPersistedSnapshot | unknown): string;
185
- /** Options controlling the durable envelope created by {@link createReplayEntry}. */
186
- interface CreateReplayEntryOptions {
187
- /** Explicit machine version; defaults to the machine's resolved version. */
188
- machineVersion?: string;
189
- /** Stable entry id; defaults to `evt_` plus the zero-padded index. */
190
- id?: string;
191
- /** RFC 3339 acceptance time; defaults to the current wall clock. */
192
- recordedAt?: string;
193
- causationId?: string;
194
- metadata?: Record<string, JsonValue$1>;
195
- /** Record `verification.stateHash` (default `true`). */
196
- verification?: boolean;
197
- /**
198
- * The snapshot this entry folds to, when the caller already has it — avoids
199
- * re-folding the whole prefix just to compute the hash. Accepts a live or a
200
- * persisted snapshot.
201
- */
202
- snapshot?: AnyMachineSnapshot | AgentPersistedSnapshot;
203
- }
204
- /**
205
- * Creates a JSON-safe, self-describing entry for `event` appended after
206
- * `entries` (which must be the complete prefix, so `index` and the recorded
207
- * state hash line up).
208
- */
209
- declare function createReplayEntry(machine: AnyStateMachine, entries: readonly AgentLogEntry[], event: EventObject, options?: CreateReplayEntryOptions): AgentLogEntry;
210
- /** How a log begins: from machine input, or from a persisted snapshot. */
211
- type AgentLogInit = {
212
- input?: unknown;
213
- snapshot?: never;
214
- } | {
215
- snapshot: AgentPersistedSnapshot;
216
- input?: never;
217
- };
218
- /**
219
- * The reserved first entry of a log. Pass EXACTLY one of:
220
- *
221
- * - `{ input }` — a fresh start; replay folds from `initialTransition`.
222
- * - `{ snapshot }` — a continuation from a persisted snapshot: a version
223
- * bridge, or a legacy snapshot that predates the log. Replay restores it
224
- * purely (no actors started) and folds the rest of the log onto it.
225
- *
226
- * `options.metadata.executionId` names the lineage; this library always sets
227
- * one, and readers must tolerate its absence in logs written elsewhere.
228
- */
229
- declare function initEntry(machine: AnyStateMachine, init?: AgentLogInit, options?: CreateReplayEntryOptions): AgentLogEntry;
230
61
  /**
231
- * The log's execution id: the lineage identity pinned in the init entry's
232
- * `metadata.executionId`.
62
+ * Starts a machine and returns its first {@link AgentStep} — the step-path
63
+ * equivalent of `initialTransition` plus request discovery. Begins the
64
+ * durable/per-model-call-checkpoint loop: resolve each `step.requests` entry
65
+ * (via {@link executeAgentRequest} for `kind: 'text'`, or
66
+ * {@link resolveDecision} for `kind: 'decision'`), then advance with
67
+ * {@link resolveAgentStep} or {@link transitionAgentStep}.
68
+ */
69
+ declare function initialAgentStep<TMachine extends AnyActorLogic>(machine: TMachine, input?: unknown, options?: Partial<AgentExecutionOptions>): AgentStep<SnapshotFrom<TMachine>>;
70
+ /**
71
+ * Applies an externally-sent event (e.g. a decision's chosen event, or a
72
+ * human's reply) and returns the next {@link AgentStep}. Accepts **either**
73
+ * a raw snapshot **or** a prior `AgentStep` as the second argument —
74
+ * `.snapshot` is unwrapped automatically, so callers can thread the whole
75
+ * step object through without manually plucking the snapshot out.
76
+ */
77
+ declare function transitionAgentStep<TMachine extends AnyActorLogic>(machine: TMachine, snapshotOrStep: SnapshotFrom<TMachine> | AgentStep<SnapshotFrom<TMachine>>, event: EventFromLogic<TMachine>, options?: Partial<AgentExecutionOptions>): AgentStep<SnapshotFrom<TMachine>>;
78
+ /**
79
+ * Applies a resolved text request's output (a `kind: 'text'`
80
+ * {@link AgentRequest} — not a decision) as a done event and returns the
81
+ * next {@link AgentStep}. For decisions, resolve with `resolveDecision`
82
+ * (which returns a {@link ChosenEvent}) and apply it with
83
+ * {@link transitionAgentStep} instead — a decision has no output value of
84
+ * its own to feed here.
85
+ */
86
+ declare function resolveAgentStep<TMachine extends AnyActorLogic>(machine: TMachine, step: AgentStep<SnapshotFrom<TMachine>>, request: Pick<AgentRequest, "id"> | string, output: unknown, options?: Partial<AgentExecutionOptions>): AgentStep<SnapshotFrom<TMachine>>;
87
+ /**
88
+ * Rejects a pending invoke — the failure counterpart of
89
+ * {@link resolveAgentStep}. Delivers `error` as the invoke's
90
+ * `xstate.error.actor` event, so the machine takes that invoke's `onError`
91
+ * transition and returns the next {@link AgentStep}. With no `onError` in
92
+ * scope the returned step's snapshot has `status: 'error'`, exactly as a live
93
+ * run's failed invoke does.
233
94
  *
234
- * Minted once per run and inherited verbatim by every resume of that log, so
235
- * it names one lineage rather than one process. Entry ids cannot serve this
236
- * role — the built-in ids are index-derived, so every log's init entry is
237
- * `evt_00000000`. A fork copies the init entry, so it shares its parent's
238
- * execution id by construction.
95
+ * A durable host replays a failed call with this: the log says the call
96
+ * failed, so the replay rejects the invoke instead of resolving it. Scripted
97
+ * playthroughs use it too — see `simulateAgent`'s `script.errors`.
239
98
  *
240
- * Returns `undefined` for a log with no init entry and for one written without
241
- * the field — callers must treat the id as optional.
242
- */
243
- declare function getLogExecutionId(entries: readonly AgentLogEntry[]): string | undefined;
244
- /**
245
- * Validates a log before replay or append: every envelope well-formed, indices
246
- * contiguous from 0, ids unique, the first entry the reserved init entry, and
247
- * one consistent machine identity throughout.
248
- *
249
- * With `machine`, entries are also checked against that machine's id and
250
- * resolved version — a mismatch throws {@link AgentMachineVersionMismatchError}.
251
- * An init-with-snapshot entry is exempt from the version check: that entry is
252
- * itself the bridge from whatever version produced the snapshot.
253
- */
254
- declare function validateReplayEntries(entries: readonly AgentLogEntry[], options?: {
255
- machine?: AnyStateMachine;
256
- machineVersion?: string;
257
- }): void;
258
- /**
259
- * The prefix `[0, upToIndex)` of a log, as a new log. `upToIndex` is exclusive
260
- * and must leave the init entry in place, so the fork is still self-contained.
261
- */
262
- declare function forkEventLog(entries: readonly AgentLogEntry[], upToIndex: number): AgentLogEntry[];
263
- /**
264
- * The 1-based occurrence `n` for the NEXT call at invoke site `siteId`:
265
- * `1 + completions`, where a completion is a journaled `xstate.done.actor` OR
266
- * `xstate.error.actor` for that `actorId` (an error is a semantic completion).
267
- * The one counting rule behind every `${siteId}#${n}` call key, so a live run
268
- * and a replay derive the same `n` by construction.
269
- */
270
- declare function agentCallOccurrence(history: readonly (EventObject | AgentLogEntry)[] | undefined, siteId: string): number;
271
- /**
272
- * Folds the reserved `@agent.usage` entries of a log into one cumulative usage
273
- * total. The log is the source of truth, so the totals are a pure projection of
274
- * it: replay a log, fold it, and you get the numbers the run reported with no
275
- * host-side accumulator in between.
276
- *
277
- * Accepts entries or bare events. Token fields are partial sums: a field stays
278
- * `undefined` until some entry reports it, and non-finite values are ignored.
279
- */
280
- declare function getUsageFromEvents(entries: readonly (EventObject | AgentLogEntry)[]): AgentCallUsage;
281
- /**
282
- * Rewrites a journaled `xstate.done.actor`/`xstate.error.actor` event's
283
- * `sessionId` to the session the CURRENT fold minted for that `actorId`.
284
- *
285
- * Session ids are re-minted on every fold, and XState drops a completion event
286
- * whose `sessionId` does not match the live child — silently, as a no-op
287
- * transition. Rebinding is what makes a journaled completion replayable at all.
288
- * `sessions` caches the mapping per fold, so a later event referring to the
289
- * recorded session of an already-stopped child still resolves.
290
- */
291
- declare function rebindActorSession(event: EventObject, snapshot: AnyMachineSnapshot, sessions: Map<string, string>): EventObject;
292
- /** Options for {@link replay}. */
293
- interface ReplayOptions {
294
- /** Explicit expected machine version; defaults to the machine's resolved version. */
295
- machineVersion?: string;
296
- /**
297
- * `true` (default) checks the entries that carry a `verification.stateHash`;
298
- * `'strict'` additionally requires every entry to carry one; `false` skips
299
- * verification entirely.
300
- */
301
- verify?: boolean | "strict";
302
- }
303
- /** The result of a {@link replay}. */
304
- interface ReplayResult<TMachine extends AnyStateMachine> {
305
- /** The folded live snapshot (no actors started, no effects run). */
306
- snapshot: SnapshotFrom<TMachine>;
307
- /** Its persisted projection — what a host stores, and what hashes. */
308
- persistedSnapshot: AgentPersistedSnapshot;
309
- }
310
- /**
311
- * Folds a log through XState's pure `initialTransition`/`transition` WITHOUT
312
- * executing anything: no actor is started, no action runs, no model is called.
313
- * A journaled `xstate.done.actor` entry carries the completed actor's output
314
- * inline, so the invoke it belongs to is never re-run. Crash recovery, fork
315
- * resume, and time travel in one call.
316
- *
317
- * The first entry is the reserved {@link initEntry}: `input` folds from
318
- * `initialTransition`, `snapshot` restores the persisted snapshot purely
319
- * (`machine.restoreSnapshot`) and folds the rest of the log onto it.
320
- */
321
- declare function replay<TMachine extends AnyStateMachine>(machine: TMachine, entries: readonly AgentLogEntry[], options?: ReplayOptions): ReplayResult<TMachine>;
322
- //#endregion
323
- //#region src/event-log-store.d.ts
324
- /**
325
- * An append-only event log: the authoritative durability artifact of a thread.
326
- * The journal of external inputs IS the source of truth — deterministic
327
- * `replay` derives every snapshot from it, and a fork is a copied log prefix.
328
- *
329
- * Userland stores (a Postgres table with a `(thread_id, index)` primary key, an
330
- * append-only object in blob storage, …) implement this one shape so they
331
- * interoperate; {@link createInMemoryEventLogStore} is the reference, and
332
- * `assertEventLogStoreConformance` checks an implementation against it.
333
- */
334
- interface AgentEventLogStore {
335
- /**
336
- * Append `entries` starting at `expectedIndex` (the current length of the
337
- * thread's log; 0 for a new thread). Atomic — all entries land or none do.
338
- * Rejects with {@link AgentEventLogConflictError} when the thread's length
339
- * differs from `expectedIndex`: a concurrent writer appended first. Each
340
- * entry's `index` must be contiguous from `expectedIndex` (a plain `Error`
341
- * otherwise: that is caller misuse, not a race).
342
- */
343
- append(input: {
344
- threadId: string;
345
- expectedIndex: number;
346
- entries: AgentLogEntry[];
347
- }): Promise<void>;
348
- /**
349
- * Read a thread's entries in log order. `from` (default 0) skips entries
350
- * below that index for incremental catch-up. An unknown thread reads as an
351
- * empty array.
352
- */
353
- read(threadId: string, options?: {
354
- from?: number;
355
- }): Promise<AgentLogEntry[]>;
356
- /** The thread's current log length (0 for an unknown thread) — the next `expectedIndex`. */
357
- length(threadId: string): Promise<number>;
358
- /**
359
- * Copy the prefix `[0, upToIndex)` onto a fresh, empty `newThreadId`.
360
- * Without `upToIndex` the full source is copied. `upToIndex` is exclusive
361
- * and must be an integer in `[1, length]`, so the fork keeps the reserved
362
- * init entry and stays a self-contained log. The fork then appends
363
- * independently. Rejects (plain `Error`) if `newThreadId` already has
364
- * entries, the source is unknown, or `upToIndex` is out of range.
365
- * Implementations may copy-on-write or physically copy; observable behavior
366
- * must match a full copy.
367
- */
368
- fork(input: {
369
- threadId: string;
370
- newThreadId: string; /** Exclusive index cutoff. */
371
- upToIndex?: number;
372
- }): Promise<void>;
373
- }
374
- /**
375
- * Rejection from {@link AgentEventLogStore.append} when the thread's stored
376
- * length is not the `expectedIndex` the writer held — a concurrent writer
377
- * appended first. `actualIndex` is the next index the store would accept.
378
- */
379
- declare class AgentEventLogConflictError extends AgentError {
380
- readonly threadId: string;
381
- readonly expectedIndex: number;
382
- readonly actualIndex: number;
383
- constructor(threadId: string, expectedIndex: number, actualIndex: number);
384
- }
385
- /**
386
- * In-memory reference store, and the baseline the conformance suite runs
387
- * against. Per-thread entries are held in a contiguous, index-ordered list;
388
- * append's check-and-push runs synchronously (no `await` between reading the
389
- * length and writing), so two appends racing on the same `expectedIndex`
390
- * resolve to exactly one winner. Every stored and returned entry is
391
- * `structuredClone`d, so a caller can neither mutate stored state through a
392
- * value it appended nor through a value it read.
393
- */
394
- declare function createInMemoryEventLogStore(): AgentEventLogStore;
99
+ * `error` can be any value. An `Error` instance is the usual one, but a plain
100
+ * object (`{ code: 'truncated' }`) reaches the `onError` transition as
101
+ * `event.error` untouched, so a machine that branches on a failure code is
102
+ * testable without constructing a provider's error class.
103
+ */
104
+ declare function rejectAgentStep<TMachine extends AnyActorLogic>(machine: TMachine, step: AgentStep<SnapshotFrom<TMachine>>, request: Pick<AgentRequest, "id"> | string, error: unknown, options?: Partial<AgentExecutionOptions>): AgentStep<SnapshotFrom<TMachine>>;
105
+ /**
106
+ * Resolves one **text** request ({@link AgentRequest}, from
107
+ * {@link AgentStep.requests}) against a host's {@link AgentRequestExecutors}
108
+ * — merges the request's tools, dispatches to `generateText`/`streamText`
109
+ * per `mode`, and validates the result against the request's
110
+ * `outputSchema` if present. **Text-only**: passing a `kind: 'decision'`
111
+ * request throws, directing the caller to `resolveDecision(request,
112
+ * executors, ...)` instead. Returns the invoke's output — `{ result,
113
+ * messages }`, ready for {@link resolveAgentStep} — plus the `raw` executor
114
+ * result (tool calls, usage, finish reason).
115
+ */
116
+ declare function executeAgentRequest(request: AgentStepRequest, executors: Partial<AgentRequestExecutors>): Promise<AgentTextResult & {
117
+ raw: unknown;
118
+ }>;
395
119
  //#endregion
396
120
  //#region src/run-agent.d.ts
397
121
  type JsonValue = string | number | boolean | null | JsonValue[] | {
@@ -425,10 +149,6 @@ interface AgentRunMeta {
425
149
  /** The log's length at the moment this snapshot was taken. */
426
150
  logIndex: number;
427
151
  }
428
- /** Handler for `agent.userInput` invokes passed as {@link RunAgentOptions.userInput}. Resolves to what the human typed. */
429
- interface AgentUserInputExecutor {
430
- (input: AgentUserInput): PromiseLike<string>;
431
- }
432
152
  /** Typed root-machine transition observer accepted by {@link runAgent}. */
433
153
  type AgentTransitionHandler<TMachine extends AnyStateMachine> = (snapshot: SnapshotFrom<TMachine>, event: EventFromLogic<TMachine>) => void;
434
154
  /**
@@ -460,7 +180,7 @@ type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
460
180
  output: unknown;
461
181
  raw: unknown;
462
182
  /** The model's reasoning, lifted off the raw executor result when the
463
- * request opted into the structured-output envelope's `reasoning` field.
183
+ * request opted into the provider output's `reasoning` field.
464
184
  * Present only when the executor surfaced a string `reasoning`. */
465
185
  reasoning?: string;
466
186
  /** This call's token usage, lifted off the raw executor result's `usage`.
@@ -502,7 +222,6 @@ type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
502
222
  type: "run.end";
503
223
  status: "idle";
504
224
  snapshot: SnapshotFrom<TMachine>;
505
- pendingUserInputs?: PendingUserInput[];
506
225
  } | {
507
226
  type: "run.end";
508
227
  status: "error";
@@ -651,16 +370,6 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
651
370
  verification?: boolean;
652
371
  /** Actor source implementations, merged onto the machine before binding — sugar for `machine.provide({ actors })` ahead of the run. */
653
372
  actors?: Record<string, AnyActorLogic>;
654
- /**
655
- * Optional human-input handler for `agent.userInput` invokes (CLI prompt,
656
- * web form, Slack, …). With a handler, input is gathered inline without
657
- * settling. Without one, an `agent.userInput` invoke becomes a *pending
658
- * placeholder*: it waits indefinitely, does not block idle detection, and
659
- * the run settles `{ status: 'idle', pendingUserInputs }` once no other work
660
- * is in flight — persist with `result.persist()` and resume that snapshot
661
- * with a `userInput` handler that answers it.
662
- */
663
- userInput?: AgentUserInputExecutor;
664
373
  /**
665
374
  * Sugar over {@link onTrace}'s `stream.chunk` events: fires for each streamed
666
375
  * chunk of a `mode: 'stream'` text request, alongside the {@link AgentRequest}
@@ -677,7 +386,7 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
677
386
  * event-sourced replay logging.
678
387
  */
679
388
  onResult?: (request: AgentStepRequest, result: {
680
- output: unknown;
389
+ result: unknown;
681
390
  raw: unknown;
682
391
  }) => void;
683
392
  /** Fires a single ordered stream of run/request/chunk/transition/emit/end events. Intended for eval traces, JSONL logs, and adapter-owned telemetry/exporters. */
@@ -744,19 +453,13 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
744
453
  * underlying actor is stopped on every settle path — there is no live actor to
745
454
  * resume; resume is always by snapshot.
746
455
  */
747
- /** 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. */
748
- interface PendingUserInput {
749
- id: string;
750
- input: AgentUserInput | undefined;
751
- }
752
456
  type RunAgentOutcome<TMachine extends AnyStateMachine> = {
753
457
  status: "done";
754
458
  output: OutputFrom<TMachine>;
755
459
  snapshot: SnapshotFrom<TMachine>;
756
460
  } | {
757
461
  status: "idle";
758
- snapshot: SnapshotFrom<TMachine>; /** Present when the machine is waiting on unhandled `agent.userInput` invokes: one entry per pending invoke. */
759
- pendingUserInputs?: PendingUserInput[];
462
+ snapshot: SnapshotFrom<TMachine>;
760
463
  } | {
761
464
  status: "error";
762
465
  cause: RunAgentErrorCause;
@@ -885,9 +588,7 @@ type AgentInputFrom<TMachine extends AnyStateMachine> = [NonNullable<InputFrom<T
885
588
  * could reach is walked and checked against the effective actor sources
886
589
  * (`options.actors` merged onto the machine), so a missing
887
590
  * `streamText`/`decide` executor or any other unbound actor source throws
888
- * immediately — a bind-time error, not a mid-run failure. The one exception
889
- * is `agent.userInput`: unhandled, it binds as a pending placeholder that
890
- * settles the run idle (with `pendingUserInputs`) instead of erroring.
591
+ * immediately — a bind-time error, not a mid-run failure.
891
592
  *
892
593
  * @example
893
594
  * ```ts
@@ -901,11 +602,9 @@ type AgentInputFrom<TMachine extends AnyStateMachine> = [NonNullable<InputFrom<T
901
602
  * console.log(r.output);
902
603
  * ```
903
604
  *
904
- * The `executors`' `generateText`/`streamText` accept the raw Vercel AI SDK
905
- * functions directly (`executors: { generateText, streamText }` with them
906
- * imported from `ai`) — their `{ text }`/`{ textStream }` results are unwrapped
907
- * natively. `decide` cannot be a raw AI SDK function: the tool-per-event mapping
908
- * lives in an adapter — use `createAiSdkExecutors` from '@statelyai/agent/ai-sdk'.
605
+ * Each executor is a plain function returning `{ result }` (plus optional `messages`/`usage`), or
606
+ * an adapter's set: `createAiSdkExecutors` from '@statelyai/agent/ai-sdk' or
607
+ * `createOpenAiExecutors` from '@statelyai/agent/openai' supply all three.
909
608
  */
910
609
  declare function runAgent<TMachine extends AnyStateMachine>(machine: TMachine, options: RunAgentOptions<TMachine>): Promise<RunAgentResult<TMachine>>;
911
610
  /**
@@ -965,4 +664,4 @@ declare function traceTransitions<TMachine extends AnyStateMachine = AnyStateMac
965
664
  */
966
665
  declare function isAgentIdle(snapshot: AnyMachineSnapshot): boolean;
967
666
  //#endregion
968
- export { AGENT_USAGE_EVENT_TYPE as $, AgentMachineVersionMismatchError as A, assertJsonSerializable as B, AGENT_EVENT_SCHEMA_VERSION as C, AgentLogEntry as D, AgentInitEvent as E, NonSerializableAgentEventError as F, getUsageFromEvents as G, forkEventLog as H, ReplayOptions as I, replay as J, initEntry as K, ReplayResult as L, AgentReplayDivergenceError as M, CreateReplayEntryOptions as N, AgentLogInit as O, JsonValue$1 as P, executeAgentRequest as Q, agentCallOccurrence as R, createInMemoryEventLogStore as S, AgentEventLogError as T, getLogExecutionId as U, createReplayEntry as V, getSnapshotStateHash as W, AgentRequest as X, validateReplayEntries as Y, AgentStepRequest as Z, runAgent as _, AgentSnapshotDivergedError as a, AgentEventLogConflictError as b, AgentUserInputExecutor as c, PendingUserInput as d, AgentUsageEvent as et, RunAgentErrorCause as f, isAgentIdle as g, inspectTransitions as h, AgentRunMeta as i, AgentPersistedSnapshot as j, AgentLogVerification as k, InspectedActorRef as l, RunAgentResult as m, AgentInputFrom as n, AgentTraceEvent as o, RunAgentOptions as p, rebindActorSession as q, AgentMaxModelCallsExceededError as r, AgentTransitionHandler as s, AGENT_TRACE_SCHEMA_VERSION as t, JsonSerializableTraceEvent as u, serializeTraceEvent as v, AGENT_INIT_EVENT_TYPE as w, AgentEventLogStore as x, traceTransitions as y, assertAgentLogEntry as z };
667
+ export { rejectAgentStep as C, AgentUsageEvent as D, AGENT_USAGE_EVENT_TYPE as E, initialAgentStep as S, transitionAgentStep as T, traceTransitions as _, AgentSnapshotDivergedError as a, AgentStepRequest as b, InspectedActorRef as c, RunAgentOptions as d, RunAgentResult as f, serializeTraceEvent as g, runAgent as h, AgentRunMeta as i, JsonSerializableTraceEvent as l, isAgentIdle as m, AgentInputFrom as n, AgentTraceEvent as o, inspectTransitions as p, AgentMaxModelCallsExceededError as r, AgentTransitionHandler as s, AGENT_TRACE_SCHEMA_VERSION as t, RunAgentErrorCause as u, AgentRequest as v, resolveAgentStep as w, executeAgentRequest as x, AgentStep as y };