@statelyai/agent 2.0.0-alpha.26 → 2.0.0-alpha.28
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.
- package/dist/ai-sdk.cjs +4 -4
- package/dist/ai-sdk.d.cts +6 -6
- package/dist/ai-sdk.d.mts +6 -6
- package/dist/ai-sdk.mjs +4 -4
- package/dist/{decision-CM9CYZ6t.cjs → decision-CmM8-HHz.cjs} +10 -9
- package/dist/{decision-DzSv1NpD.mjs → decision-RQ0iv0oZ.mjs} +10 -9
- package/dist/{event-log-store-Ba2fsc4E.mjs → event-log-store-2pAFiWuc.mjs} +1 -1
- package/dist/{event-log-store-DvOcs10J.d.cts → event-log-store-2xzFmgr2.d.cts} +1 -1
- package/dist/{event-log-store-DxyVgnas.d.mts → event-log-store-BIPOz-di.d.mts} +1 -1
- package/dist/{event-log-store-DQmImLYk.cjs → event-log-store-C-COhIXP.cjs} +1 -1
- package/dist/index.cjs +13 -195
- package/dist/index.d.cts +25 -105
- package/dist/index.d.mts +25 -105
- package/dist/index.mjs +12 -189
- package/dist/log.cjs +1 -1
- package/dist/log.d.cts +1 -1
- package/dist/log.d.mts +1 -1
- package/dist/log.mjs +1 -1
- package/dist/machines.cjs +4 -7
- package/dist/machines.d.cts +5 -7
- package/dist/machines.d.mts +5 -7
- package/dist/machines.mjs +4 -7
- package/dist/openai.cjs +3 -3
- package/dist/openai.d.cts +5 -5
- package/dist/openai.d.mts +5 -5
- package/dist/openai.mjs +3 -3
- package/dist/otel.cjs +2 -2
- package/dist/otel.d.cts +3 -3
- package/dist/otel.d.mts +3 -3
- package/dist/otel.mjs +2 -2
- package/dist/{run-agent-CG343kFs.d.mts → run-agent-ByO-Bxyd.d.cts} +184 -179
- package/dist/{run-agent-BOfoJg5B.d.cts → run-agent-COXXc0RW.d.mts} +184 -179
- package/dist/{run-agent-Cb1-LS5P.cjs → run-agent-Dmf8GV2d.cjs} +539 -737
- package/dist/{run-agent-DvDQd4If.mjs → run-agent-xNTxpt82.mjs} +537 -705
- package/dist/{setup-agent-CFW-jPI8.mjs → setup-agent-BuanDXeh.mjs} +6 -28
- package/dist/{setup-agent-CPf7MxnG.cjs → setup-agent-DV4cTou-.cjs} +6 -28
- package/dist/testing.cjs +276 -27
- package/dist/testing.d.cts +17 -15
- package/dist/testing.d.mts +17 -15
- package/dist/testing.mjs +260 -12
- package/dist/{text-logic-Bl_ZRxDi.mjs → text-logic-CIqHAmBi.mjs} +10 -26
- package/dist/{text-logic-BFEOxyxv.d.cts → text-logic-D-czVPYp.d.mts} +27 -28
- package/dist/{text-logic-hZSiRUo1.d.mts → text-logic-IjfYy9DP.d.cts} +27 -28
- package/dist/{text-logic-C8xyr6Ag.cjs → text-logic-f5F5sCdc.cjs} +9 -43
- package/dist/{types-B1Qs2q3q.d.cts → types-BgNbNKnJ.d.mts} +3 -3
- package/dist/{types-tA3SdczG.d.mts → types-hR5f5YXa.d.cts} +3 -3
- package/dist/{utils-C2DPqomn.d.mts → utils-_q7F-AZu.d.mts} +2 -2
- package/dist/{utils-ceStNCOh.d.cts → utils-o4YRdHJX.d.cts} +2 -2
- package/dist/validate.cjs +0 -8
- package/dist/validate.mjs +0 -8
- package/package.json +3 -3
- package/readme.md +26 -18
- package/schemas/agent-workflow.json +0 -8
- package/skills/generate-machine/SKILL.md +6 -8
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { _ as StandardSchemaV1, m as InferInput, s as AgentTools, w as WithAgentInputSchema } from "./types-
|
|
2
|
-
import {
|
|
3
|
-
import { c as AgentLogEntry, n as AgentEventLogStore } from "./event-log-store-
|
|
1
|
+
import { _ as StandardSchemaV1, m as InferInput, s as AgentTools, w as WithAgentInputSchema } from "./types-hR5f5YXa.cjs";
|
|
2
|
+
import { K as AgentRequestSource, M as AgentDecisionRequest, U as AgentEventDescriptor, Z as AgentError, d as AgentRequestMode, f as AgentTextRequest, m as AgentUsage, r as AgentFinishReason, t as AgentCallUsage, u as AgentRequestExecutors } from "./text-logic-IjfYy9DP.cjs";
|
|
3
|
+
import { c as AgentLogEntry, n as AgentEventLogStore } from "./event-log-store-2xzFmgr2.cjs";
|
|
4
4
|
import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, InputFrom, InspectionEvent, OutputFrom, Snapshot, SnapshotFrom } from "xstate";
|
|
5
|
+
import { DurableExecution } from "xstate/durable";
|
|
5
6
|
|
|
6
7
|
//#region src/usage.d.ts
|
|
7
8
|
/** Reserved event delivered after a model call reports token usage. */
|
|
@@ -17,11 +18,6 @@ interface AgentUsageEvent extends EventObject {
|
|
|
17
18
|
name?: string;
|
|
18
19
|
}
|
|
19
20
|
//#endregion
|
|
20
|
-
//#region src/internal/registry.d.ts
|
|
21
|
-
type AgentExecutionOptions = Pick<AgentRequestOptions, "schemas" | "actors"> & {
|
|
22
|
-
models?: object;
|
|
23
|
-
};
|
|
24
|
-
//#endregion
|
|
25
21
|
//#region src/steps.d.ts
|
|
26
22
|
/**
|
|
27
23
|
* A pending text request surfaced by step discovery ({@link getAgentRequests}
|
|
@@ -41,88 +37,13 @@ interface AgentRequest<TInput extends AgentTextRequest = AgentTextRequest> {
|
|
|
41
37
|
}
|
|
42
38
|
/** `AgentStep.requests` element: a text or decision request. */
|
|
43
39
|
type AgentStepRequest = AgentRequest | AgentDecisionRequest;
|
|
44
|
-
/**
|
|
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;
|
|
60
|
-
}
|
|
61
|
-
/**
|
|
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.
|
|
94
|
-
*
|
|
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`.
|
|
98
|
-
*
|
|
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
|
-
}>;
|
|
119
40
|
//#endregion
|
|
120
41
|
//#region src/run-agent.d.ts
|
|
121
42
|
type JsonValue = string | number | boolean | null | JsonValue[] | {
|
|
122
43
|
[key: string]: JsonValue;
|
|
123
44
|
};
|
|
124
45
|
/**
|
|
125
|
-
* Thrown by {@link
|
|
46
|
+
* Thrown by {@link AgentRuntime.start} when a resume is given BOTH an `events` log and a
|
|
126
47
|
* `snapshot` that claims a position in that log (`agentMeta.logIndex`), and the
|
|
127
48
|
* two disagree about the state at that position. The log is the source of
|
|
128
49
|
* truth, so this is a host bug (a snapshot cached from a different lineage, or
|
|
@@ -136,10 +57,10 @@ declare class AgentSnapshotDivergedError extends AgentError {
|
|
|
136
57
|
constructor(expected: string, actual: string, logIndex: number);
|
|
137
58
|
}
|
|
138
59
|
/**
|
|
139
|
-
* The stamp {@link
|
|
60
|
+
* The stamp {@link AgentRunResult.persist} writes onto the persisted snapshot:
|
|
140
61
|
* the machine identity that produced it plus the position in the event log it
|
|
141
62
|
* caches. Read back by the next resume to decide whether the snapshot can be
|
|
142
|
-
* trusted without replaying the log (see {@link
|
|
63
|
+
* trusted without replaying the log (see {@link AgentRunStart.events}).
|
|
143
64
|
*/
|
|
144
65
|
interface AgentRunMeta {
|
|
145
66
|
machineId: string;
|
|
@@ -149,13 +70,13 @@ interface AgentRunMeta {
|
|
|
149
70
|
/** The log's length at the moment this snapshot was taken. */
|
|
150
71
|
logIndex: number;
|
|
151
72
|
}
|
|
152
|
-
/** Typed root-machine transition observer accepted by {@link
|
|
73
|
+
/** Typed root-machine transition observer accepted by {@link createAgentRuntime}. */
|
|
153
74
|
type AgentTransitionHandler<TMachine extends AnyStateMachine> = (snapshot: SnapshotFrom<TMachine>, event: EventFromLogic<TMachine>) => void;
|
|
154
75
|
/**
|
|
155
76
|
* The version of the {@link AgentTraceEvent} envelope every trace event carries
|
|
156
77
|
* as `schemaVersion`. Bumped only on a breaking change to the envelope or any
|
|
157
78
|
* payload shape, so a consumer can gate on it. Emitted identically by
|
|
158
|
-
* {@link
|
|
79
|
+
* {@link createAgentRuntime}, {@link provideExecutors}' `onTrace`, and
|
|
159
80
|
* {@link traceTransitions}.
|
|
160
81
|
*/
|
|
161
82
|
declare const AGENT_TRACE_SCHEMA_VERSION = 1;
|
|
@@ -185,7 +106,7 @@ type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
|
|
|
185
106
|
reasoning?: string;
|
|
186
107
|
/** This call's token usage, lifted off the raw executor result's `usage`.
|
|
187
108
|
* Present only when the executor reported it. The run-level total is
|
|
188
|
-
* {@link
|
|
109
|
+
* {@link AgentRunResult.usage}. */
|
|
189
110
|
usage?: AgentCallUsage;
|
|
190
111
|
/** Why the call stopped, lifted off the raw executor result's
|
|
191
112
|
* `finishReason` and normalized. Present only when the executor reported
|
|
@@ -208,7 +129,7 @@ type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
|
|
|
208
129
|
event: EmittedFrom<TMachine>;
|
|
209
130
|
} | {
|
|
210
131
|
/** A reserved `@agent.usage` event the run declined to deliver. The
|
|
211
|
-
* tokens still fold into {@link
|
|
132
|
+
* tokens still fold into {@link AgentRunResult.usage}; only the machine
|
|
212
133
|
* event is dropped. */
|
|
213
134
|
type: "usage.dropped";
|
|
214
135
|
event: AgentUsageEvent; /** `'settled'`: the call settled after the run's cycle had resolved. */
|
|
@@ -225,7 +146,7 @@ type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
|
|
|
225
146
|
} | {
|
|
226
147
|
type: "run.end";
|
|
227
148
|
status: "error";
|
|
228
|
-
cause:
|
|
149
|
+
cause: AgentRunErrorCause;
|
|
229
150
|
error: unknown;
|
|
230
151
|
snapshot: SnapshotFrom<TMachine>;
|
|
231
152
|
}));
|
|
@@ -283,63 +204,27 @@ declare function serializeTraceEvent(event: AgentTraceEvent, options?: {
|
|
|
283
204
|
includeRaw?: boolean;
|
|
284
205
|
}): JsonSerializableTraceEvent;
|
|
285
206
|
/**
|
|
286
|
-
* Options for {@link
|
|
207
|
+
* Options for {@link createAgentRuntime}: what the runtime binds and observes.
|
|
208
|
+
* The run's `input`/`snapshot`/`events` go to {@link AgentRuntime.start} (or
|
|
209
|
+
* {@link runToQuiescence}) instead.
|
|
287
210
|
*
|
|
288
211
|
* Host executors are passed as a single {@link AgentRequestExecutors}-shaped
|
|
289
|
-
* set under `executors
|
|
212
|
+
* set under `executors`. Each executor
|
|
290
213
|
* kind is required only if the machine actually reaches a request of that kind
|
|
291
214
|
* — checked at bind time, before any actor runs. The whole `executors` field is
|
|
292
215
|
* optional: a machine whose agent sources all carry their own executor
|
|
293
216
|
* (`.withExecutor(...)`) needs none.
|
|
294
217
|
*/
|
|
295
|
-
interface
|
|
218
|
+
interface AgentRuntimeOptions<TMachine extends AnyStateMachine> {
|
|
296
219
|
/**
|
|
297
220
|
* The host executor set backing the machine's agent actors — build it with
|
|
298
221
|
* `createAiSdkExecutors({ models })` from '@statelyai/agent/ai-sdk', or supply
|
|
299
222
|
* `{ generateText?, streamText?, decide? }` by hand. Every slot is optional
|
|
300
|
-
* here
|
|
223
|
+
* here: each kind is
|
|
301
224
|
* bind-time-checked only when the machine actually reaches a request of that
|
|
302
225
|
* kind, so e.g. a stream-only machine may pass `{ streamText }` alone.
|
|
303
226
|
*/
|
|
304
227
|
executors?: Partial<AgentRequestExecutors>;
|
|
305
|
-
/**
|
|
306
|
-
* Machine input. Validated against the machine's declared input schema —
|
|
307
|
-
* defaults filled, transforms applied — before it reaches
|
|
308
|
-
* `createActor(machine, { input })`; invalid
|
|
309
|
-
* input throws an {@link AgentError} with code `invalid-machine-input`.
|
|
310
|
-
* Typed as {@link AgentInputFrom}, so fields the schema defaults are optional
|
|
311
|
-
* here. Omit when resuming via `snapshot`.
|
|
312
|
-
*/
|
|
313
|
-
input?: AgentInputFrom<TMachine>;
|
|
314
|
-
/** A previously-settled run's `result.persist()`, to resume from instead of starting fresh. Pair with `event` to deliver the event that unblocks the resumed idle state. */
|
|
315
|
-
snapshot?: Snapshot<unknown>;
|
|
316
|
-
/**
|
|
317
|
-
* An event to send immediately after starting/resuming the actor (e.g. the
|
|
318
|
-
* human's answer to an idle-state prompt), typed as the machine's event
|
|
319
|
-
* union. If the resumed state has no transition for it, the machine ignores
|
|
320
|
-
* it — the run settles normally and the result carries
|
|
321
|
-
* {@link RunAgentResult.ignored}. For a payload off the wire, parse it first
|
|
322
|
-
* with `parseAgentEvent(machine, payload)`.
|
|
323
|
-
*/
|
|
324
|
-
event?: EventFromLogic<TMachine>;
|
|
325
|
-
/**
|
|
326
|
-
* A prior run's `result.events` — the replayable log to resume from and keep
|
|
327
|
-
* appending to. THE LOG IS THE SOURCE OF TRUTH: journaled model/tool results
|
|
328
|
-
* are folded back in rather than re-executed, so a crashed run resumes from
|
|
329
|
-
* its log alone.
|
|
330
|
-
*
|
|
331
|
-
* A `snapshot` passed alongside is a CACHE of that log: it is trusted only
|
|
332
|
-
* when it is stamped (see {@link AgentRunMeta}) at the log's current tail and
|
|
333
|
-
* hashes to what the tail entry recorded; otherwise the log is replayed and
|
|
334
|
-
* the cache is verified against the position it claims (a genuine
|
|
335
|
-
* disagreement throws {@link AgentSnapshotDivergedError}).
|
|
336
|
-
*
|
|
337
|
-
* When the log was written by a DIFFERENT machine version, a `snapshot` is
|
|
338
|
-
* required (XState's own `migrate` applies on restore) and the run starts a
|
|
339
|
-
* NEW log segment whose init entry records where it bridged from; without one
|
|
340
|
-
* it throws `AgentMachineVersionMismatchError`.
|
|
341
|
-
*/
|
|
342
|
-
events?: readonly AgentLogEntry[];
|
|
343
228
|
/**
|
|
344
229
|
* Durable log storage, write-ahead. With a `store` the run reads the thread's
|
|
345
230
|
* log to resume from (unless `events` is given, which wins) and writes every
|
|
@@ -349,15 +234,15 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
|
|
|
349
234
|
* write (an {@link AgentEventLogConflictError} from a concurrent writer, or
|
|
350
235
|
* any other failure) stops the run: `{ status: 'error', cause: 'journal' }`.
|
|
351
236
|
*
|
|
352
|
-
* Requires {@link
|
|
237
|
+
* Requires {@link AgentRuntimeOptions.threadId}.
|
|
353
238
|
*/
|
|
354
239
|
store?: AgentEventLogStore;
|
|
355
|
-
/** The {@link
|
|
240
|
+
/** The {@link AgentRuntimeOptions.store} thread this run reads and appends to. Required whenever `store` is given. */
|
|
356
241
|
threadId?: string;
|
|
357
242
|
/**
|
|
358
243
|
* Called synchronously as each log entry is appended, init entry first. An
|
|
359
244
|
* observer, never awaited: persisting here is at-least-once and the run does
|
|
360
|
-
* not wait for it. Use {@link
|
|
245
|
+
* not wait for it. Use {@link AgentRuntimeOptions.store} for write-ahead
|
|
361
246
|
* durability.
|
|
362
247
|
*/
|
|
363
248
|
onEvent?: (entry: AgentLogEntry) => void;
|
|
@@ -437,23 +322,26 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
|
|
|
437
322
|
maxModelCalls?: number;
|
|
438
323
|
/** Aborts the run; settles `{ status: 'error', cause: 'aborted' }` with `signal.reason` as the error. */
|
|
439
324
|
signal?: AbortSignal;
|
|
325
|
+
/** Where root `after` timers live. Default `"in-process"`. See {@link AgentTimerScheduler}. */
|
|
326
|
+
timers?: AgentTimerScheduler;
|
|
440
327
|
}
|
|
441
328
|
/**
|
|
442
|
-
* The outcome of a {@link
|
|
443
|
-
* variants, never a throw for a waiting or
|
|
444
|
-
* errors like a missing executor still throw,
|
|
445
|
-
*
|
|
446
|
-
* `
|
|
447
|
-
*
|
|
329
|
+
* The outcome of a run ({@link AgentRuntime.finish} / {@link runToQuiescence})
|
|
330
|
+
* — always exactly one of three variants, never a throw for a waiting or
|
|
331
|
+
* failed machine (programmer errors like a missing executor still throw,
|
|
332
|
+
* synchronously from {@link createAgentRuntime} before any actor runs).
|
|
333
|
+
* `done`: a final state was reached (`output` is the machine's `OutputFrom`).
|
|
334
|
+
* `idle`: the run went quiescent (no child, request or in-process timer in
|
|
335
|
+
* flight) — resume with a new runtime and `{ snapshot, event }`. `error`: a run-level
|
|
448
336
|
* failure, discriminated by `cause` (`'aborted'`, `'max-model-calls'`,
|
|
449
337
|
* `'decision-exhausted'`, `'machine'` for any other machine error state, or
|
|
450
|
-
* `'stopped'` for an external stop — see {@link
|
|
338
|
+
* `'stopped'` for an external stop — see {@link AgentRunErrorCause}). Every
|
|
451
339
|
* variant carries the final `snapshot` and a native XState persistence
|
|
452
340
|
* function. The
|
|
453
341
|
* underlying actor is stopped on every settle path — there is no live actor to
|
|
454
342
|
* resume; resume is always by snapshot.
|
|
455
343
|
*/
|
|
456
|
-
type
|
|
344
|
+
type AgentRunOutcome<TMachine extends AnyStateMachine> = {
|
|
457
345
|
status: "done";
|
|
458
346
|
output: OutputFrom<TMachine>;
|
|
459
347
|
snapshot: SnapshotFrom<TMachine>;
|
|
@@ -462,16 +350,16 @@ type RunAgentOutcome<TMachine extends AnyStateMachine> = {
|
|
|
462
350
|
snapshot: SnapshotFrom<TMachine>;
|
|
463
351
|
} | {
|
|
464
352
|
status: "error";
|
|
465
|
-
cause:
|
|
353
|
+
cause: AgentRunErrorCause;
|
|
466
354
|
error: unknown;
|
|
467
355
|
snapshot: SnapshotFrom<TMachine>;
|
|
468
356
|
};
|
|
469
|
-
type
|
|
357
|
+
type AgentRunResult<TMachine extends AnyStateMachine> = AgentRunOutcome<TMachine> & {
|
|
470
358
|
/**
|
|
471
359
|
* The complete, self-contained replayable log for this run — the resumed
|
|
472
360
|
* prefix (if any) plus every entry this run appended, starting with the
|
|
473
361
|
* reserved `@agent.init` entry. Pass it back as
|
|
474
|
-
* {@link
|
|
362
|
+
* {@link AgentRunStart.events} to resume; fold it with
|
|
475
363
|
* `getUsageFromEvents` for cumulative spend; hand it to `replay` for
|
|
476
364
|
* crash recovery or time travel.
|
|
477
365
|
*/
|
|
@@ -489,7 +377,7 @@ type RunAgentResult<TMachine extends AnyStateMachine> = RunAgentOutcome<TMachine
|
|
|
489
377
|
*/
|
|
490
378
|
persist(): Snapshot<unknown>;
|
|
491
379
|
/**
|
|
492
|
-
* Resolves once every {@link
|
|
380
|
+
* Resolves once every {@link AgentRuntimeOptions.store} write issued so far has
|
|
493
381
|
* landed — including a straggler `@agent.usage` entry appended by a call
|
|
494
382
|
* that settled after the run returned, which the result itself does not wait
|
|
495
383
|
* for. Await it before terminating the process if those entries matter.
|
|
@@ -508,7 +396,7 @@ type RunAgentResult<TMachine extends AnyStateMachine> = RunAgentOutcome<TMachine
|
|
|
508
396
|
*/
|
|
509
397
|
usage: AgentUsage;
|
|
510
398
|
/**
|
|
511
|
-
* The {@link
|
|
399
|
+
* The {@link AgentRunInit.event} the machine did not handle: present only
|
|
512
400
|
* when the resumed state had no transition for it, so sending it was a
|
|
513
401
|
* no-op (no state change, no actions). The run settles normally — usually
|
|
514
402
|
* back to `idle` at the same state — and the event is still journaled, so a
|
|
@@ -526,20 +414,20 @@ type RunAgentResult<TMachine extends AnyStateMachine> = RunAgentOutcome<TMachine
|
|
|
526
414
|
ignored?: EventObject;
|
|
527
415
|
};
|
|
528
416
|
/**
|
|
529
|
-
* Discriminates a {@link
|
|
417
|
+
* Discriminates a {@link AgentRunResult} `error`:
|
|
530
418
|
* - `'aborted'` — the run's `signal` fired.
|
|
531
419
|
* - `'max-model-calls'` — the `maxModelCalls` budget was exceeded.
|
|
532
420
|
* - `'decision-exhausted'` — the machine reached an error state whose error is
|
|
533
421
|
* (or wraps) a {@link AgentDecisionExhaustedError} that no `onError` handled.
|
|
534
422
|
* - `'machine'` — any other machine error state.
|
|
535
423
|
* - `'stopped'` — the actor was stopped externally (`status === 'stopped'`).
|
|
536
|
-
* - `'journal'` — a {@link
|
|
424
|
+
* - `'journal'` — a {@link AgentRuntimeOptions.store} write rejected (a concurrent
|
|
537
425
|
* writer's {@link AgentEventLogConflictError}, or any other storage failure).
|
|
538
426
|
*/
|
|
539
|
-
type
|
|
427
|
+
type AgentRunErrorCause = "aborted" | "max-model-calls" | "decision-exhausted" | "machine" | "stopped" | "journal";
|
|
540
428
|
/**
|
|
541
429
|
* Thrown into the invoke that would have made the call once
|
|
542
|
-
* {@link
|
|
430
|
+
* {@link AgentRuntimeOptions.maxModelCalls} is spent. It reaches the machine
|
|
543
431
|
* through the normal error channel, so an invoke's `onError` can branch on it
|
|
544
432
|
* (`error.code === 'max-model-calls'`, the same string the settled result's
|
|
545
433
|
* `cause` uses) and route to a degraded/finish state instead of failing the
|
|
@@ -572,31 +460,150 @@ declare class AgentMaxModelCallsExceededError extends AgentError {
|
|
|
572
460
|
*/
|
|
573
461
|
type AgentInputFrom<TMachine extends AnyStateMachine> = [NonNullable<InputFrom<TMachine>>] extends [WithAgentInputSchema<infer TInputSchema>] ? [TInputSchema] extends [StandardSchemaV1] ? InferInput<TInputSchema> : InputFrom<TMachine> : InputFrom<TMachine>;
|
|
574
462
|
/**
|
|
575
|
-
*
|
|
576
|
-
*
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
*
|
|
581
|
-
*
|
|
582
|
-
*
|
|
583
|
-
*
|
|
584
|
-
*
|
|
585
|
-
*
|
|
463
|
+
* The durable effects one transition produced. Hand them to
|
|
464
|
+
* {@link AgentRuntime.execute}; nothing in them has run yet.
|
|
465
|
+
*/
|
|
466
|
+
type AgentEffects = Parameters<DurableExecution<AnyStateMachine>["executeEffects"]>[0];
|
|
467
|
+
/**
|
|
468
|
+
* Where a run's `after` timers live. The default (`"in-process"`) arms them
|
|
469
|
+
* with `setTimeout` and counts a pending timer as work in flight, so a loop
|
|
470
|
+
* keeps reading its mailbox until the timer fires. A host with its own
|
|
471
|
+
* durable timers (a Temporal timer, a Durable Object alarm, an Inngest sleep)
|
|
472
|
+
* passes `schedule`/`cancel`: the loop then treats a pending timer as the
|
|
473
|
+
* outside world's business, and the host delivers `{ type: "xstate.timer", id }`
|
|
474
|
+
* through {@link AgentRuntime.transition} when it fires.
|
|
475
|
+
*/
|
|
476
|
+
type AgentTimerScheduler = "in-process" | {
|
|
477
|
+
schedule(timer: {
|
|
478
|
+
id: string;
|
|
479
|
+
delay: number;
|
|
480
|
+
}): void;
|
|
481
|
+
cancel(id: string): void;
|
|
482
|
+
};
|
|
483
|
+
/**
|
|
484
|
+
* A host-owned timer firing: what a host with its own durable timers (see
|
|
485
|
+
* {@link AgentTimerScheduler}) delivers when the `id` it was asked to
|
|
486
|
+
* schedule comes due.
|
|
487
|
+
*/
|
|
488
|
+
interface AgentTimerEvent {
|
|
489
|
+
type: "xstate.timer";
|
|
490
|
+
id: string;
|
|
491
|
+
}
|
|
492
|
+
/** How {@link AgentRuntime.start} opens a run. */
|
|
493
|
+
interface AgentRunStart<TMachine extends AnyStateMachine> {
|
|
494
|
+
/**
|
|
495
|
+
* Machine input. Validated against the machine's declared input schema —
|
|
496
|
+
* defaults filled, transforms applied — before it reaches
|
|
497
|
+
* `createActor(machine, { input })`; invalid
|
|
498
|
+
* input throws an {@link AgentError} with code `invalid-machine-input`.
|
|
499
|
+
* Typed as {@link AgentInputFrom}, so fields the schema defaults are optional
|
|
500
|
+
* here. Omit when resuming via `snapshot`.
|
|
501
|
+
*/
|
|
502
|
+
input?: AgentInputFrom<TMachine>;
|
|
503
|
+
/** A previously-settled run's `result.persist()`, to resume from instead of starting fresh. Pair with `event` to deliver the event that unblocks the resumed idle state. */
|
|
504
|
+
snapshot?: Snapshot<unknown>;
|
|
505
|
+
/**
|
|
506
|
+
* A prior run's `result.events` — the replayable log to resume from and keep
|
|
507
|
+
* appending to. THE LOG IS THE SOURCE OF TRUTH: journaled model/tool results
|
|
508
|
+
* are folded back in rather than re-executed, so a crashed run resumes from
|
|
509
|
+
* its log alone.
|
|
510
|
+
*
|
|
511
|
+
* A `snapshot` passed alongside is a CACHE of that log: it is trusted only
|
|
512
|
+
* when it is stamped (see {@link AgentRunMeta}) at the log's current tail and
|
|
513
|
+
* hashes to what the tail entry recorded; otherwise the log is replayed and
|
|
514
|
+
* the cache is verified against the position it claims (a genuine
|
|
515
|
+
* disagreement throws {@link AgentSnapshotDivergedError}).
|
|
516
|
+
*
|
|
517
|
+
* When the log was written by a DIFFERENT machine version, a `snapshot` is
|
|
518
|
+
* required (XState's own `migrate` applies on restore) and the run starts a
|
|
519
|
+
* NEW log segment whose init entry records where it bridged from; without one
|
|
520
|
+
* it throws `AgentMachineVersionMismatchError`.
|
|
521
|
+
*/
|
|
522
|
+
events?: readonly AgentLogEntry[];
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* The agent loop's helpers for one run. The host owns the loop:
|
|
526
|
+
*
|
|
527
|
+
* ```ts
|
|
528
|
+
* let [state, effects] = await runtime.start({ input });
|
|
529
|
+
* await runtime.execute(effects);
|
|
530
|
+
* for (let event; (event = await runtime.nextEvent()); ) {
|
|
531
|
+
* [state, effects] = runtime.transition(state, event);
|
|
532
|
+
* await runtime.execute(effects);
|
|
533
|
+
* }
|
|
534
|
+
* const result = await runtime.finish();
|
|
535
|
+
* ```
|
|
536
|
+
*
|
|
537
|
+
* `execute` only starts work. Every completion, failure, child message and
|
|
538
|
+
* timer lands in one mailbox, and `nextEvent` hands out whichever arrived
|
|
539
|
+
* first. It resolves `undefined` once nothing but the outside world can move
|
|
540
|
+
* the machine: no effect, child or timer is in flight and the mailbox is
|
|
541
|
+
* empty (or the run finished, was cancelled, or lost its journal).
|
|
542
|
+
*
|
|
543
|
+
* "In flight" means any running child that is not a machine at rest: a model
|
|
544
|
+
* request, an async actor, a child machine whose own children are running.
|
|
545
|
+
* A callback or subscription child never finishes on its own, so while one
|
|
546
|
+
* is running the loop keeps reading until it stops; a host that invokes one
|
|
547
|
+
* for the life of a state should expect `nextEvent` to keep waiting there.
|
|
548
|
+
*/
|
|
549
|
+
interface AgentRuntime<TMachine extends AnyStateMachine> {
|
|
550
|
+
/** Opens the run: a fresh start from `input`, a resume from `snapshot`, or recovery from a log. */
|
|
551
|
+
start(init?: AgentRunStart<TMachine>): Promise<[SnapshotFrom<TMachine>, AgentEffects]>;
|
|
552
|
+
/** Applies one event: journals it, traces it, and returns the next state plus its effects. */
|
|
553
|
+
transition(state: SnapshotFrom<TMachine>, event: EventFromLogic<TMachine> | AgentTimerEvent): [SnapshotFrom<TMachine>, AgentEffects];
|
|
554
|
+
/** Starts the effects' work and returns once it is accepted, not once it finishes. */
|
|
555
|
+
execute(effects: AgentEffects): Promise<void>;
|
|
556
|
+
/** The next event that arrived, or `undefined` once the run is quiescent. */
|
|
557
|
+
nextEvent(): Promise<EventFromLogic<TMachine> | undefined>;
|
|
558
|
+
/** Settles the run: stops what is still running and returns the outcome. */
|
|
559
|
+
finish(): Promise<AgentRunResult<TMachine>>;
|
|
560
|
+
}
|
|
561
|
+
/** How {@link runToQuiescence} opens a run: {@link AgentRunStart} plus one event to deliver. */
|
|
562
|
+
interface AgentRunInit<TMachine extends AnyStateMachine> extends AgentRunStart<TMachine> {
|
|
563
|
+
/**
|
|
564
|
+
* An event to send immediately after starting/resuming the actor (e.g. the
|
|
565
|
+
* human's answer to an idle-state prompt), typed as the machine's event
|
|
566
|
+
* union. If the resumed state has no transition for it, the machine ignores
|
|
567
|
+
* it — the run settles normally and the result carries
|
|
568
|
+
* {@link AgentRunResult.ignored}. For a payload off the wire, parse it first
|
|
569
|
+
* with `parseAgentEvent(machine, payload)`. A host-owned timer that came
|
|
570
|
+
* due is delivered the same way, as an {@link AgentTimerEvent}.
|
|
571
|
+
*/
|
|
572
|
+
event?: EventFromLogic<TMachine> | AgentTimerEvent;
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* The blocking host: opens the run, delivers `event` if given, then applies
|
|
576
|
+
* every event that arrives until the run is quiescent, and returns the
|
|
577
|
+
* outcome. A request handler or durable engine writes the same loop with its
|
|
578
|
+
* own stop policy; this one is for scripts and tests.
|
|
579
|
+
*/
|
|
580
|
+
declare function runToQuiescence<TMachine extends AnyStateMachine>(runtime: AgentRuntime<TMachine>, init?: AgentRunInit<TMachine>): Promise<AgentRunResult<TMachine>>;
|
|
581
|
+
/**
|
|
582
|
+
* Creates the helpers for one run of `machine`: executors bound to its
|
|
583
|
+
* requests, the write-ahead log, traces, the budget, and a mailbox over
|
|
584
|
+
* XState's durable transition loop (`xstate/durable`). See
|
|
585
|
+
* {@link AgentRuntime} for the loop a host writes around it, and
|
|
586
|
+
* {@link runToQuiescence} for the blocking host. {@link AgentRuntime.finish}
|
|
587
|
+
* stops whatever is still running on every settle path (`done`, `idle`, and
|
|
588
|
+
* `error` alike) — resume is always by snapshot (or log), never by holding a
|
|
589
|
+
* reference to a live actor.
|
|
586
590
|
*
|
|
587
|
-
* Binding happens **before**
|
|
591
|
+
* Binding happens **before** any actor starts: every invoke the machine
|
|
588
592
|
* could reach is walked and checked against the effective actor sources
|
|
589
593
|
* (`options.actors` merged onto the machine), so a missing
|
|
590
594
|
* `streamText`/`decide` executor or any other unbound actor source throws
|
|
591
|
-
*
|
|
595
|
+
* synchronously from this call — a bind-time error, not a mid-run failure.
|
|
592
596
|
*
|
|
593
597
|
* @example
|
|
594
598
|
* ```ts
|
|
595
599
|
* const executors = createAiSdkExecutors({ models });
|
|
596
|
-
* let r = await
|
|
600
|
+
* let r = await runToQuiescence(createAgentRuntime(machine, { executors }), { input });
|
|
597
601
|
* while (r.status === 'idle') {
|
|
598
602
|
* const event = await promptUser(getAcceptedEvents(r.snapshot));
|
|
599
|
-
* r = await
|
|
603
|
+
* r = await runToQuiescence(createAgentRuntime(machine, { executors }), {
|
|
604
|
+
* snapshot: r.snapshot,
|
|
605
|
+
* event,
|
|
606
|
+
* });
|
|
600
607
|
* }
|
|
601
608
|
* if (r.status !== 'done') throw new Error(`Run did not complete: ${r.status}`);
|
|
602
609
|
* console.log(r.output);
|
|
@@ -606,7 +613,7 @@ type AgentInputFrom<TMachine extends AnyStateMachine> = [NonNullable<InputFrom<T
|
|
|
606
613
|
* an adapter's set: `createAiSdkExecutors` from '@statelyai/agent/ai-sdk' or
|
|
607
614
|
* `createOpenAiExecutors` from '@statelyai/agent/openai' supply all three.
|
|
608
615
|
*/
|
|
609
|
-
declare function
|
|
616
|
+
declare function createAgentRuntime<TMachine extends AnyStateMachine>(machine: TMachine, options?: AgentRuntimeOptions<TMachine>): AgentRuntime<TMachine>;
|
|
610
617
|
/**
|
|
611
618
|
* The actor handed to an {@link inspectTransitions} handler: an
|
|
612
619
|
* {@link AnyActorRef} widened with the runtime `id`/`src` used to attribute a
|
|
@@ -619,7 +626,7 @@ type InspectedActorRef = AnyActorRef & {
|
|
|
619
626
|
};
|
|
620
627
|
/**
|
|
621
628
|
* Wraps a `(snapshot, actorRef) => void` handler into a function usable as
|
|
622
|
-
* {@link
|
|
629
|
+
* {@link AgentRuntimeOptions.inspect}: it filters the raw inspection stream to
|
|
623
630
|
* `@xstate.transition` events and hands the handler the typed
|
|
624
631
|
* {@link AnyMachineSnapshot} and the {@link InspectedActorRef} that
|
|
625
632
|
* transitioned. Attribute a child actor via `actorRef.id`/`actorRef.src`. Saves
|
|
@@ -639,12 +646,12 @@ declare function inspectTransitions(handler: (snapshot: AnyMachineSnapshot, acto
|
|
|
639
646
|
* const actor = createActor(bound, { inspect: traceTransitions(onTrace) });
|
|
640
647
|
* ```
|
|
641
648
|
*
|
|
642
|
-
* Only ROOT-actor transitions are traced (matching
|
|
649
|
+
* Only ROOT-actor transitions are traced (matching the runtime's
|
|
643
650
|
* `machine.transition`); child-actor transitions are ignored. Attribute the
|
|
644
651
|
* event via its envelope `runId`.
|
|
645
652
|
*
|
|
646
653
|
* By design this path has NO `run.start`/`run.end` events: `createActor` has no
|
|
647
|
-
* run boundary the way `
|
|
654
|
+
* run boundary the way `createAgentRuntime` does, so the stream starts at the actor's
|
|
648
655
|
* first transition. It also does NOT emit `emit` trace events: in this xstate
|
|
649
656
|
* build emitted events are delivered through `actor.on(...)`, not the inspection
|
|
650
657
|
* protocol, so they are not observable from an `inspect` handler — subscribe
|
|
@@ -652,16 +659,14 @@ declare function inspectTransitions(handler: (snapshot: AnyMachineSnapshot, acto
|
|
|
652
659
|
*/
|
|
653
660
|
declare function traceTransitions<TMachine extends AnyStateMachine = AnyStateMachine>(onTrace: (event: AgentTraceEvent<TMachine>) => void): (inspectionEvent: InspectionEvent) => void;
|
|
654
661
|
/**
|
|
655
|
-
*
|
|
662
|
+
* Whether a snapshot is asking the outside world for something: an active
|
|
656
663
|
* snapshot that accepts an external event anywhere in its active hierarchy,
|
|
657
664
|
* or declares interaction metadata on an active state.
|
|
658
665
|
*
|
|
659
|
-
*
|
|
660
|
-
*
|
|
661
|
-
*
|
|
662
|
-
* runner, so this function only answers whether the state is an intentional
|
|
663
|
-
* external wait.
|
|
666
|
+
* The runtime does not use this to stop; a run settles when nothing is in
|
|
667
|
+
* flight. Use it once the run is quiescent, to tell a human wait (render
|
|
668
|
+
* `getInteraction(snapshot)`) from a machine that is simply stuck.
|
|
664
669
|
*/
|
|
665
670
|
declare function isAgentIdle(snapshot: AnyMachineSnapshot): boolean;
|
|
666
671
|
//#endregion
|
|
667
|
-
export {
|
|
672
|
+
export { serializeTraceEvent as C, AGENT_USAGE_EVENT_TYPE as D, AgentStepRequest as E, AgentUsageEvent as O, runToQuiescence as S, AgentRequest as T, InspectedActorRef as _, AgentRunErrorCause as a, inspectTransitions as b, AgentRunResult as c, AgentRuntimeOptions as d, AgentSnapshotDivergedError as f, AgentTransitionHandler as g, AgentTraceEvent as h, AgentMaxModelCallsExceededError as i, AgentRunStart as l, AgentTimerScheduler as m, AgentEffects as n, AgentRunInit as o, AgentTimerEvent as p, AgentInputFrom as r, AgentRunMeta as s, AGENT_TRACE_SCHEMA_VERSION as t, AgentRuntime as u, JsonSerializableTraceEvent as v, traceTransitions as w, isAgentIdle as x, createAgentRuntime as y };
|