@statelyai/agent 1.1.6 → 2.0.0-alpha.11

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 (92) hide show
  1. package/LICENSE +21 -0
  2. package/dist/adapter.cjs +15 -0
  3. package/dist/adapter.d.cts +4 -0
  4. package/dist/adapter.d.mts +4 -0
  5. package/dist/adapter.mjs +2 -0
  6. package/dist/ai-sdk.cjs +306 -0
  7. package/dist/ai-sdk.d.cts +96 -0
  8. package/dist/ai-sdk.d.mts +96 -0
  9. package/dist/ai-sdk.mjs +304 -0
  10. package/dist/decision-C3k4ve51.mjs +227 -0
  11. package/dist/decision-D8wJrM8W.cjs +286 -0
  12. package/dist/events-CRQj3VtP.cjs +1010 -0
  13. package/dist/events-JiVPYrct.mjs +759 -0
  14. package/dist/index.cjs +2528 -0
  15. package/dist/index.d.cts +1232 -0
  16. package/dist/index.d.mts +1217 -413
  17. package/dist/index.mjs +2489 -584
  18. package/dist/openai-compat.cjs +309 -0
  19. package/dist/openai-compat.d.cts +59 -0
  20. package/dist/openai-compat.d.mts +59 -0
  21. package/dist/openai-compat.mjs +308 -0
  22. package/dist/steps-BALp1eZo.d.mts +198 -0
  23. package/dist/steps-CVe54GPP.cjs +420 -0
  24. package/dist/steps-CkyyyuHd.mjs +379 -0
  25. package/dist/steps-MjnQI4aB.d.cts +198 -0
  26. package/dist/steps.cjs +12 -0
  27. package/dist/steps.d.cts +3 -0
  28. package/dist/steps.d.mts +3 -0
  29. package/dist/steps.mjs +3 -0
  30. package/dist/text-logic-CaKqgX4Y.d.mts +710 -0
  31. package/dist/text-logic-Ckhr2kKC.d.cts +710 -0
  32. package/dist/types-C9QiMjre.d.cts +219 -0
  33. package/dist/types-qm00QF91.d.mts +219 -0
  34. package/dist/utils-BYqT_Dyv.d.cts +108 -0
  35. package/dist/utils-Do5wIJrh.d.mts +108 -0
  36. package/dist/zod.cjs +31 -0
  37. package/dist/zod.d.cts +30 -0
  38. package/dist/zod.d.mts +30 -0
  39. package/dist/zod.mjs +30 -0
  40. package/package.json +132 -28
  41. package/readme.md +153 -6
  42. package/schemas/agent-workflow.json +526 -0
  43. package/.changeset/README.md +0 -8
  44. package/.changeset/config.json +0 -11
  45. package/.env.template +0 -3
  46. package/.github/actions/ci-setup/action.yml +0 -24
  47. package/.github/workflows/release.yml +0 -46
  48. package/.vscode/launch.json +0 -28
  49. package/CHANGELOG.md +0 -222
  50. package/dist/index.d.ts +0 -428
  51. package/dist/index.js +0 -621
  52. package/examples/chatbot.ts +0 -71
  53. package/examples/cot.ts +0 -89
  54. package/examples/email.ts +0 -118
  55. package/examples/example.ts +0 -81
  56. package/examples/goal.ts +0 -94
  57. package/examples/helpers/helpers.ts +0 -17
  58. package/examples/helpers/loader.ts +0 -32
  59. package/examples/helpers/runner.ts +0 -27
  60. package/examples/joke.ts +0 -225
  61. package/examples/multi.ts +0 -103
  62. package/examples/newspaper.ts +0 -324
  63. package/examples/number.ts +0 -102
  64. package/examples/raffle.ts +0 -105
  65. package/examples/sandbox.ts +0 -28
  66. package/examples/simple.ts +0 -39
  67. package/examples/support.ts +0 -147
  68. package/examples/ticTacToe.ts +0 -224
  69. package/examples/todo.ts +0 -137
  70. package/examples/tutor.ts +0 -100
  71. package/examples/verify.ts +0 -120
  72. package/examples/weather.ts +0 -178
  73. package/examples/wiki.ts +0 -30
  74. package/examples/word.ts +0 -171
  75. package/src/adapters/vercel.ts +0 -7
  76. package/src/agent-experimental.ts +0 -221
  77. package/src/agent.test.ts +0 -506
  78. package/src/agent.ts +0 -300
  79. package/src/decision.test.ts +0 -179
  80. package/src/decision.ts +0 -84
  81. package/src/index.ts +0 -4
  82. package/src/memory.ts +0 -25
  83. package/src/planners/shortestPathPlanner.ts +0 -22
  84. package/src/planners/simplePlanner.ts +0 -139
  85. package/src/schemas.ts +0 -11
  86. package/src/strategies/chain-of-note.ts +0 -155
  87. package/src/templates/defaultText.ts +0 -18
  88. package/src/text.ts +0 -241
  89. package/src/types.ts +0 -499
  90. package/src/utils.ts +0 -72
  91. package/tsconfig.json +0 -109
  92. package/vitest.config.ts +0 -9
@@ -0,0 +1,379 @@
1
+ import { E as getRegisteredAgentExecutionOptions, H as validateSchemaSync, _ as isTextLogic, a as sanitizeEventToolName, m as executeAgentTextRequest, t as getAcceptedEvents } from "./events-JiVPYrct.mjs";
2
+ import { c as isPlanLogic, n as PLAN_DONE_EVENT_TYPE, r as advancePlanLedger, s as isDecisionLogic, u as resolveDecision } from "./decision-C3k4ve51.mjs";
3
+ import { initialTransition, transition } from "xstate";
4
+ //#region src/steps.ts
5
+ /**
6
+ * The step path: durable, per-model-call-checkpoint hosting of an agent
7
+ * machine. Public vocabulary — `initialAgentStep`, `transitionAgentStep`,
8
+ * `resolveAgentStep`, `getAgentRequests`, `executeAgentRequest`,
9
+ * `resolveAgentRequests`.
10
+ * @module
11
+ */
12
+ /** @internal Normalizes current and legacy XState invoke effect shapes. */
13
+ function getInvokeEffectMetadata(action) {
14
+ if (action.type === "@xstate.spawn") return action;
15
+ if (action.type === "xstate.spawnChild") {
16
+ const params = action.params;
17
+ return params ? {
18
+ ...params,
19
+ logic: action.logic
20
+ } : void 0;
21
+ }
22
+ if (action.type === "@xstate.start" && typeof action.src === "string") return action;
23
+ }
24
+ /**
25
+ * Scans a set of executable actions (as returned by xstate's `transition`/
26
+ * `initialTransition`) for spawned `TextLogic`/`DecisionLogic` invokes and
27
+ * lowers each into an {@link AgentStepRequest}. The hand-passed-schemas
28
+ * implementation detail behind the public {@link getAgentRequests} — it needs
29
+ * `schemas`/`actorSources` passed explicitly, whereas `getAgentRequests`
30
+ * pre-fills them from the machine's registered `setupAgent` options.
31
+ * `options.snapshot` is required to resolve a decision's candidate events
32
+ * (intersecting declared `allowedEvents` with what's currently legal) — omit
33
+ * it and decision requests report an empty `events` list.
34
+ *
35
+ * @internal
36
+ */
37
+ function getAgentRequestsWith(actions, options = {}) {
38
+ return [...actions.flatMap((action) => {
39
+ const params = getInvokeEffectMetadata(action);
40
+ if (!params || typeof params.src !== "string") return [];
41
+ if (typeof params.id !== "string" || params.id.length === 0) throw new Error(`Agent invoke '${params.src}' must define a durable string id.`);
42
+ const registeredLogic = isTextLogic(params.logic) || isDecisionLogic(params.logic) ? params.logic : options.actorSources?.[params.src];
43
+ if (isDecisionLogic(registeredLogic)) {
44
+ const decisionRequest = registeredLogic.request(params.input);
45
+ const allowedEventTypes = registeredLogic.allowedEventTypes?.(params.input);
46
+ const events = options.snapshot ? getAcceptedEvents(options.snapshot, {
47
+ events: options.events,
48
+ schemas: options.schemas,
49
+ eventTypes: allowedEventTypes,
50
+ eventToolName: options.eventToolName
51
+ }) : [];
52
+ return [{
53
+ ...decisionRequest,
54
+ id: params.id,
55
+ events
56
+ }];
57
+ }
58
+ const textLogic = isTextLogic(registeredLogic) ? registeredLogic : void 0;
59
+ const input = textLogic ? textLogic.request(params.input) : void 0;
60
+ if (!input) return [];
61
+ return [{
62
+ kind: "text",
63
+ id: params.id,
64
+ src: params.src,
65
+ ...textLogic ? { mode: textLogic.mode } : {},
66
+ input,
67
+ tools: input.tools ?? {},
68
+ events: []
69
+ }];
70
+ }), ...getActivePlanRequests(options)];
71
+ }
72
+ /**
73
+ * Scans the live snapshot's children for active `agent.plan` (plan-logic)
74
+ * invokes and lowers each into an {@link AgentPlanRequest} — the re-surfacing
75
+ * half of plan discovery. Reads the applied-event trail and remaining budget
76
+ * from the child's own ledger `context` ({@link PlanLedgerContext}), recomputes
77
+ * the currently-legal candidates (∩ declared `allowedEvents`) plus the reserved
78
+ * `agent.plan.done` move, and takes `stepsRemaining` from the ledger (falling
79
+ * back to `maxSteps - applied.length` for a snapshot with no context yet).
80
+ * Returns `[]` when no snapshot is available (candidates need a live snapshot).
81
+ *
82
+ * @internal
83
+ */
84
+ function getActivePlanRequests(options) {
85
+ const snapshot = options.snapshot;
86
+ if (!snapshot) return [];
87
+ const children = snapshot.children;
88
+ if (!children) return [];
89
+ const requests = [];
90
+ for (const [id, child] of Object.entries(children)) {
91
+ const ref = child;
92
+ if (typeof ref?.getSnapshot !== "function") continue;
93
+ const src = typeof ref.src === "string" ? ref.src : void 0;
94
+ const logic = (src ? options.actorSources?.[src] : void 0) ?? ref.logic;
95
+ if (!isPlanLogic(logic)) continue;
96
+ const childSnapshot = ref.getSnapshot();
97
+ if (childSnapshot?.status !== "active") continue;
98
+ const input = childSnapshot.input ?? {};
99
+ const maxSteps = input.maxSteps ?? 8;
100
+ const ledger = childSnapshot.context ?? {};
101
+ const applied = ledger.applied ?? [];
102
+ const stepsRemaining = ledger.stepsRemaining ?? maxSteps - applied.length;
103
+ const machineEvents = getAcceptedEvents(snapshot, {
104
+ events: options.events,
105
+ schemas: options.schemas,
106
+ eventTypes: logic.allowedEventTypes(input) ?? void 0,
107
+ eventToolName: options.eventToolName
108
+ });
109
+ const events = machineEvents.some((event) => event.type === "agent.plan.done") ? machineEvents : [...machineEvents, {
110
+ type: PLAN_DONE_EVENT_TYPE,
111
+ toolName: sanitizeEventToolName(PLAN_DONE_EVENT_TYPE)
112
+ }];
113
+ requests.push({
114
+ kind: "plan",
115
+ id,
116
+ src: src ?? "",
117
+ input,
118
+ events,
119
+ applied,
120
+ stepsRemaining: Math.max(0, stepsRemaining)
121
+ });
122
+ }
123
+ return requests;
124
+ }
125
+ /**
126
+ * Builds the synthetic `xstate.done.actor.<id>` event xstate's `transition()`
127
+ * expects to resolve a spawned invoke — the event {@link resolveAgentStep}
128
+ * applies internally.
129
+ *
130
+ * @internal
131
+ */
132
+ function doneEvent(request, output) {
133
+ return {
134
+ type: `xstate.done.actor.${typeof request === "string" ? request : request.id}`,
135
+ output
136
+ };
137
+ }
138
+ /**
139
+ * Applies a request's `output` as a done event via `transition(...)`,
140
+ * returning the raw `[snapshot, actions]` tuple. Lower-level than
141
+ * {@link resolveAgentStep} — that helper wraps this and also runs
142
+ * {@link getAgentRequests} to produce the next {@link AgentStep}.
143
+ *
144
+ * @internal
145
+ */
146
+ function transitionResult(logic, snapshot, request, output) {
147
+ const event = doneEvent(request, output);
148
+ const result = transition(logic, snapshot, event);
149
+ applyFinalStateOutput(logic, result[0], event);
150
+ return result;
151
+ }
152
+ /**
153
+ * Starts a machine and returns its first {@link AgentStep} — the step-path
154
+ * equivalent of `initialTransition` plus request discovery. Begins the
155
+ * durable/per-model-call-checkpoint loop: resolve each `step.requests` entry
156
+ * (via {@link executeAgentRequest} for `kind: 'text'`, or
157
+ * {@link resolveDecision} for `kind: 'decision'`), then advance with
158
+ * {@link resolveAgentStep} or {@link transitionAgentStep}.
159
+ */
160
+ function initialAgentStep(machine, input, options) {
161
+ const [snapshot, actions] = initialTransition(machine, input);
162
+ return createAgentStep(machine, snapshot, actions, getRegisteredAgentExecutionOptions(machine, options));
163
+ }
164
+ /**
165
+ * Applies an externally-sent event (e.g. a decision's chosen event, or a
166
+ * human's reply) and returns the next {@link AgentStep}. Accepts **either**
167
+ * a raw snapshot **or** a prior `AgentStep` as the second argument —
168
+ * `.snapshot` is unwrapped automatically, so callers can thread the whole
169
+ * step object through without manually plucking the snapshot out.
170
+ */
171
+ function transitionAgentStep(machine, snapshotOrStep, event, options) {
172
+ const [nextSnapshot, actions] = transition(machine, isAgentStep(snapshotOrStep) ? snapshotOrStep.snapshot : snapshotOrStep, event);
173
+ return createAgentStep(machine, nextSnapshot, actions, getRegisteredAgentExecutionOptions(machine, options));
174
+ }
175
+ /**
176
+ * Applies a resolved text request's output (a `kind: 'text'`
177
+ * {@link AgentRequest} — not a decision) as a done event and returns the
178
+ * next {@link AgentStep}. For decisions, resolve with `resolveDecision`
179
+ * (which returns a {@link ChosenEvent}) and apply it with
180
+ * {@link transitionAgentStep} instead — a decision has no output value of
181
+ * its own to feed here.
182
+ */
183
+ function resolveAgentStep(machine, step, request, output, options) {
184
+ const [snapshot, actions] = transitionResult(machine, step.snapshot, request, output);
185
+ return createAgentStep(machine, snapshot, actions, getRegisteredAgentExecutionOptions(machine, options));
186
+ }
187
+ /**
188
+ * Snapshot in, requests out: scans executable actions for spawned agent
189
+ * invokes and lowers each into an {@link AgentStepRequest}, pre-filled with
190
+ * the machine's registered `setupAgent` schemas/actorSources (so callers
191
+ * don't pass them by hand each call) — merged with any `options` passed here,
192
+ * which take precedence. The step path's public discovery primitive;
193
+ * `initialAgentStep`/`transitionAgentStep`/`resolveAgentStep` call it
194
+ * internally to populate `AgentStep.requests`.
195
+ */
196
+ function getAgentRequests(machine, actions, snapshot, options = {}) {
197
+ return getAgentRequestsWith(actions, {
198
+ ...getRegisteredAgentExecutionOptions(machine, options),
199
+ ...options,
200
+ snapshot
201
+ });
202
+ }
203
+ async function executeAgentRequest(request, executors, options) {
204
+ if (request.kind === "decision") throw new Error("executeAgentRequest(...) is text-only. Resolve a 'decision' request with resolveDecision(request, executors.decide, ...) instead.");
205
+ assertTextExecutor(request, executors);
206
+ const { output, raw } = await executeAgentTextRequest(request.mode ?? "generate", request.id, request.input, executors, request.tools);
207
+ const normalizedOutput = request.input.outputSchema ? validateSchemaSync(request.input.outputSchema, output) : output;
208
+ return options?.verbose ? {
209
+ output: normalizedOutput,
210
+ raw
211
+ } : normalizedOutput;
212
+ }
213
+ /**
214
+ * Resolves the current step's pending requests and returns the next
215
+ * {@link AgentStep} — one iteration of the durable step loop, collapsing the
216
+ * manual `request.kind` dispatch a host would otherwise write by hand.
217
+ *
218
+ * For each pending request, in order: a `kind: 'text'` request is run with
219
+ * {@link executeAgentRequest} then fed back via {@link resolveAgentStep}; a
220
+ * `kind: 'decision'` request is resolved with `resolveDecision` (wiring
221
+ * `canTake` to `step.snapshot.can` so guard-rejected choices retry) then
222
+ * applied with {@link transitionAgentStep}. The **current** step is re-read
223
+ * after each application — the machine may advance and its `requests` change —
224
+ * so this always resolves against the live step, never a stale list.
225
+ *
226
+ * A `kind: 'plan'` request (`agent.plan`) is resolved natively too: one plan
227
+ * step per call. It resolves a single decision from `request.events` (wiring
228
+ * `canTake` to `step.snapshot.can`, exempting the reserved `agent.plan.done`
229
+ * move and `stopOn` events), then either applies the chosen machine event and
230
+ * lets the next step re-surface the plan, or completes the plan (feeding its
231
+ * `{ steps, stopped }` output back) on the done move / a `stopOn` event / an
232
+ * exhausted budget / no legal events. The plan's applied trail is carried in
233
+ * the invoke child's snapshot, so persisting the step between calls resumes the
234
+ * plan identically.
235
+ *
236
+ * Missing the executor a request needs throws a clear error
237
+ * (`generateText`/`streamText` for text, `decide` for decisions and plans).
238
+ *
239
+ * A complete durable host is two lines:
240
+ *
241
+ * ```ts
242
+ * let step = initialAgentStep(machine, input);
243
+ * while (!step.done) step = await resolveAgentRequests(machine, step, executors);
244
+ * ```
245
+ *
246
+ * All pending **text** requests of a step are resolved in parallel
247
+ * (`Promise.all`) — parallel statechart regions are genuinely concurrent, so
248
+ * their model calls run concurrently — then their outputs apply in
249
+ * **request-array order** (deterministic for durable replay regardless of which
250
+ * call finishes first). Decisions and plans stay **one at a time**: applying
251
+ * either changes the set of legal candidates for what follows, so they cannot be
252
+ * resolved against a stale snapshot. A host that instead wants strictly
253
+ * sequential text resolution loops the manual per-request helpers
254
+ * ({@link executeAgentRequest} + {@link resolveAgentStep}) one at a time.
255
+ */
256
+ async function resolveAgentRequests(machine, step, executors, options) {
257
+ const [request] = step.requests;
258
+ if (!request) return step;
259
+ if (request.kind === "decision") {
260
+ if (!executors.decide) throw new Error(`this step's decision request '${request.id}' needs a 'decide' executor but none was provided.`);
261
+ return transitionAgentStep(machine, step, await resolveDecision(request, executors.decide, {
262
+ canTake: (event) => step.snapshot.can(event),
263
+ maxRetries: options?.maxRetries
264
+ }), options);
265
+ }
266
+ if (request.kind === "plan") return resolvePlanRequest(machine, step, request, executors, options);
267
+ const textRequests = step.requests.filter((candidate) => candidate.kind === "text");
268
+ for (const textRequest of textRequests) assertTextExecutor(textRequest, executors);
269
+ const outputs = await Promise.all(textRequests.map((textRequest) => executeAgentRequest(textRequest, executors)));
270
+ let next = step;
271
+ for (let index = 0; index < textRequests.length; index++) next = resolveAgentStep(machine, next, textRequests[index], outputs[index], options);
272
+ return next;
273
+ }
274
+ function assertTextExecutor(request, executors) {
275
+ const mode = request.mode ?? "generate";
276
+ const kind = mode === "stream" ? "streamText" : "generateText";
277
+ if (!(mode === "stream" ? executors.streamText : executors.generateText)) throw new Error(`this step's text request '${request.src}' needs a '${kind}' executor but none was provided.`);
278
+ }
279
+ async function resolvePlanRequest(machine, step, request, executors, options) {
280
+ if (!executors.decide) throw new Error(`this step's plan request '${request.src}' needs a 'decide' executor but none was provided.`);
281
+ const stopOn = new Set(request.input.stopOn ?? []);
282
+ if (request.stepsRemaining <= 0) return completePlan(machine, step, request.id, request.applied, "max-steps", options);
283
+ if (request.events.filter((event) => event.type !== "agent.plan.done").length === 0) return completePlan(machine, step, request.id, request.applied, "no-legal-events", options);
284
+ const chosen = await resolveDecision(planStepDecisionRequest(request), executors.decide, {
285
+ maxRetries: options?.maxRetries,
286
+ canTake: (event) => {
287
+ if (event.type === "agent.plan.done" || stopOn.has(event.type)) return true;
288
+ return step.snapshot.can(event);
289
+ }
290
+ });
291
+ if (chosen.type === "agent.plan.done") return completePlan(machine, step, request.id, request.applied, "done", options);
292
+ const applied = [...request.applied, chosen];
293
+ advancePlanChildLedger(step.snapshot, request.id, {
294
+ type: "plan.applied",
295
+ event: chosen
296
+ });
297
+ const next = transitionAgentStep(machine, step, chosen, options);
298
+ if (stopOn.has(chosen.type)) {
299
+ if (isPlanActive(next.snapshot, request.id)) return completePlan(machine, next, request.id, applied, "stop-event", options);
300
+ }
301
+ return next;
302
+ }
303
+ function completePlan(machine, step, id, steps, stopped, options) {
304
+ return resolveAgentStep(machine, step, { id }, {
305
+ steps,
306
+ stopped
307
+ }, options);
308
+ }
309
+ function planStepDecisionRequest(request) {
310
+ const { input, applied, events, id } = request;
311
+ const trail = applied.length === 0 ? "" : `\n\nEvents already applied in this plan, in order:\n${applied.map((step) => JSON.stringify(step)).join("\n")}\nContinue from here; do not repeat applied events.`;
312
+ const doneHint = `\n\nWhen the request is fully handled (or no action is needed), choose '${PLAN_DONE_EVENT_TYPE}'.`;
313
+ return {
314
+ kind: "decision",
315
+ id: `${id}[${applied.length}]`,
316
+ model: input.model,
317
+ system: input.system,
318
+ prompt: `${input.prompt ?? ""}${trail}${doneHint}`,
319
+ messages: input.messages,
320
+ events,
321
+ attempts: [],
322
+ temperature: input.temperature,
323
+ maxOutputTokens: input.maxOutputTokens,
324
+ topP: input.topP,
325
+ topK: input.topK,
326
+ seed: input.seed,
327
+ stopSequences: input.stopSequences,
328
+ metadata: input.metadata
329
+ };
330
+ }
331
+ function advancePlanChildLedger(snapshot, id, event) {
332
+ const child = snapshot.children?.[id];
333
+ const childSnapshot = child?.getSnapshot?.();
334
+ if (!isPlanLogic(child?.logic) || !childSnapshot || typeof childSnapshot !== "object") return;
335
+ Object.assign(childSnapshot, advancePlanLedger(child.logic, childSnapshot, event));
336
+ }
337
+ function isPlanActive(snapshot, id) {
338
+ return (snapshot.children?.[id])?.getSnapshot?.()?.status === "active";
339
+ }
340
+ function createAgentStep(machine, snapshot, actions, options) {
341
+ applyFinalStateOutput(machine, snapshot);
342
+ return {
343
+ snapshot,
344
+ actions,
345
+ requests: getAgentRequestsWith(actions, {
346
+ ...options,
347
+ snapshot
348
+ }),
349
+ done: snapshot.status === "done"
350
+ };
351
+ }
352
+ function resolveStateValueConfig(config, value) {
353
+ if (typeof value === "string") return config.states?.[value];
354
+ if (!value || typeof value !== "object") return;
355
+ for (const [key, childValue] of Object.entries(value)) {
356
+ const childConfig = config.states?.[key];
357
+ if (!childConfig) continue;
358
+ if (childConfig.type === "final") return childConfig;
359
+ const nested = resolveStateValueConfig(childConfig, childValue);
360
+ if (nested) return nested;
361
+ }
362
+ }
363
+ function applyFinalStateOutput(logic, snapshot, event) {
364
+ const machineSnapshot = snapshot;
365
+ if (machineSnapshot.status !== "done" || machineSnapshot.output !== void 0 || !("config" in logic)) return;
366
+ const config = logic.config;
367
+ if (!config) return;
368
+ const output = resolveStateValueConfig(config, machineSnapshot.value)?.output;
369
+ if (output === void 0) return;
370
+ machineSnapshot.output = typeof output === "function" ? output({
371
+ context: machineSnapshot.context,
372
+ event
373
+ }) : output;
374
+ }
375
+ function isAgentStep(value) {
376
+ return !!value && typeof value === "object" && "snapshot" in value && "actions" in value && "requests" in value;
377
+ }
378
+ //#endregion
379
+ export { resolveAgentRequests as a, initialAgentStep as i, getAgentRequests as n, resolveAgentStep as o, getInvokeEffectMetadata as r, transitionAgentStep as s, executeAgentRequest as t };
@@ -0,0 +1,198 @@
1
+ import { m as ChosenEvent, u as AgentTools } from "./types-C9QiMjre.cjs";
2
+ import { G as AgentRequestOptions, K as AgentRequestSource, M as AgentPlanInput, U as AgentEventDescriptor, c as AgentRequestMode, j as AgentDecisionRequest, l as AgentTextRequest, s as AgentRequestExecutors } from "./text-logic-Ckhr2kKC.cjs";
3
+ import { AnyActorLogic, AnyMachineSnapshot, AnyStateMachine, AsyncActorLogic, EventFromLogic, SnapshotFrom } from "xstate";
4
+
5
+ //#region src/internal/registry.d.ts
6
+ type AgentExecutionOptions = Pick<AgentRequestOptions, "schemas" | "actorSources"> & {
7
+ models?: object;
8
+ };
9
+ //#endregion
10
+ //#region src/steps.d.ts
11
+ /**
12
+ * A pending text request surfaced by step discovery ({@link getAgentRequests}
13
+ * / {@link AgentStep.requests}): the machine has spawned a
14
+ * `TextLogic`-backed invoke and is waiting on its result. Resolve it with
15
+ * {@link executeAgentRequest} (or by hand, then feed the output into
16
+ * {@link resolveAgentStep} via `xstate.done.actor.<id>`).
17
+ */
18
+ interface AgentRequest<TInput extends AgentTextRequest = AgentTextRequest> {
19
+ kind: "text";
20
+ id: string;
21
+ src: AgentRequestSource;
22
+ mode?: AgentRequestMode;
23
+ input: TInput;
24
+ tools: AgentTools;
25
+ events: AgentEventDescriptor[];
26
+ }
27
+ /**
28
+ * A pending **plan** request re-surfaced by step discovery: the machine
29
+ * invoked `agent.plan`, which applies an ordered sequence of legal events
30
+ * (each one a decision) rather than a single one. Unlike text/decision
31
+ * requests — surfaced once and resolved once — a plan request **re-surfaces on
32
+ * every step** while the plan is in flight, its `events`/`applied`/
33
+ * `stepsRemaining` updated each time, until it terminates.
34
+ *
35
+ * All fields are plain serializable data. Resolve ONE decision per step from
36
+ * `events` (via {@link resolveDecision}, wiring `canTake` to
37
+ * `snapshot.can` exactly like a single decision) then apply it: a real machine
38
+ * event advances the plan (the next step re-surfaces this request); the
39
+ * reserved `agent.plan.done` move, a `stopOn` event, an exhausted budget, or no
40
+ * legal events completes it (its invoke resolves with `{ steps, stopped }`).
41
+ * {@link resolveAgentRequests} does all of this natively — one decision (or one
42
+ * completion) per call.
43
+ *
44
+ * The in-progress plan state (`applied` trail + remaining budget) lives in the
45
+ * plan invoke child's own `createLogic` snapshot `context`
46
+ * (`children.<id>.snapshot.context`), so it survives a full JSON
47
+ * `getPersistedSnapshot` → restore round-trip: a host that persists the step
48
+ * after every event and reloads resumes the plan identically.
49
+ */
50
+ interface AgentPlanRequest {
51
+ kind: "plan";
52
+ /** Durable invoke id of the `agent.plan` invoke. */
53
+ id: string;
54
+ /** Invoke src (`'agent.plan'` or a registered plan-logic source name). */
55
+ src: AgentRequestSource;
56
+ /** The resolved plan input (`model`/`system`/`prompt`/`allowedEvents`/`stopOn`/`maxSteps`/…). */
57
+ input: AgentPlanInput;
58
+ /**
59
+ * The legal candidates for the NEXT plan step: the currently
60
+ * snapshot-legal machine events (∩ declared `allowedEvents`) plus the
61
+ * reserved `agent.plan.done` move.
62
+ */
63
+ events: AgentEventDescriptor[];
64
+ /** The events applied so far in this plan, in order (the trail). */
65
+ applied: ChosenEvent[];
66
+ /** How many more events the plan may apply (`maxSteps - applied.length`). */
67
+ stepsRemaining: number;
68
+ }
69
+ /** `AgentStep.requests` element: a text, decision, or plan request. */
70
+ type AgentStepRequest = AgentRequest | AgentDecisionRequest | AgentPlanRequest;
71
+ /**
72
+ * One durable checkpoint on the step path: the machine's current snapshot,
73
+ * the executable actions that produced it, the pending
74
+ * {@link AgentStepRequest}s (text/decision work still to resolve), and
75
+ * whether the machine has reached a final state. This is the
76
+ * per-model-call-checkpoint path for durable hosts (Workflows, Temporal,
77
+ * queues, …) — a peer of `runAgent`, not a lesser version of it. Produced by
78
+ * {@link initialAgentStep}/{@link transitionAgentStep}/{@link resolveAgentStep}.
79
+ */
80
+ interface AgentStep<TSnapshot extends AnyMachineSnapshot = AnyMachineSnapshot> {
81
+ snapshot: TSnapshot;
82
+ actions: readonly {
83
+ type?: string;
84
+ params?: unknown;
85
+ }[];
86
+ requests: AgentStepRequest[];
87
+ done: boolean;
88
+ }
89
+ /**
90
+ * Starts a machine and returns its first {@link AgentStep} — the step-path
91
+ * equivalent of `initialTransition` plus request discovery. Begins the
92
+ * durable/per-model-call-checkpoint loop: resolve each `step.requests` entry
93
+ * (via {@link executeAgentRequest} for `kind: 'text'`, or
94
+ * {@link resolveDecision} for `kind: 'decision'`), then advance with
95
+ * {@link resolveAgentStep} or {@link transitionAgentStep}.
96
+ */
97
+ declare function initialAgentStep<TMachine extends AnyActorLogic>(machine: TMachine, input?: unknown, options?: Partial<AgentExecutionOptions>): AgentStep<SnapshotFrom<TMachine>>;
98
+ /**
99
+ * Applies an externally-sent event (e.g. a decision's chosen event, or a
100
+ * human's reply) and returns the next {@link AgentStep}. Accepts **either**
101
+ * a raw snapshot **or** a prior `AgentStep` as the second argument —
102
+ * `.snapshot` is unwrapped automatically, so callers can thread the whole
103
+ * step object through without manually plucking the snapshot out.
104
+ */
105
+ declare function transitionAgentStep<TMachine extends AnyActorLogic>(machine: TMachine, snapshotOrStep: SnapshotFrom<TMachine> | AgentStep<SnapshotFrom<TMachine>>, event: EventFromLogic<TMachine>, options?: Partial<AgentExecutionOptions>): AgentStep<SnapshotFrom<TMachine>>;
106
+ /**
107
+ * Applies a resolved text request's output (a `kind: 'text'`
108
+ * {@link AgentRequest} — not a decision) as a done event and returns the
109
+ * next {@link AgentStep}. For decisions, resolve with `resolveDecision`
110
+ * (which returns a {@link ChosenEvent}) and apply it with
111
+ * {@link transitionAgentStep} instead — a decision has no output value of
112
+ * its own to feed here.
113
+ */
114
+ 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>>;
115
+ /**
116
+ * Snapshot in, requests out: scans executable actions for spawned agent
117
+ * invokes and lowers each into an {@link AgentStepRequest}, pre-filled with
118
+ * the machine's registered `setupAgent` schemas/actorSources (so callers
119
+ * don't pass them by hand each call) — merged with any `options` passed here,
120
+ * which take precedence. The step path's public discovery primitive;
121
+ * `initialAgentStep`/`transitionAgentStep`/`resolveAgentStep` call it
122
+ * internally to populate `AgentStep.requests`.
123
+ */
124
+ declare function getAgentRequests(machine: AnyActorLogic, actions: readonly {
125
+ type?: string;
126
+ params?: unknown;
127
+ }[], snapshot?: AnyMachineSnapshot, options?: Pick<AgentRequestOptions, "eventToolName"> & Partial<AgentExecutionOptions>): AgentStepRequest[];
128
+ /**
129
+ * Resolves one **text** {@link AgentRequest} against a host's
130
+ * {@link AgentRequestExecutors} — merges the request's tools, dispatches to
131
+ * `generateText`/`streamText` per `request.mode`, and validates the result
132
+ * against `request.input.outputSchema` if present. **Text-only**: passing a
133
+ * `kind: 'decision'` request throws, directing the caller to
134
+ * `resolveDecision(request, executors.decide, ...)` instead. By default
135
+ * returns the normalized output; pass `{ verbose: true }` to also get the
136
+ * raw executor result (tool calls, usage, finish reason — needed for
137
+ * observability and event-sourced replay).
138
+ */
139
+ declare function executeAgentRequest(request: AgentRequest, executors: Partial<AgentRequestExecutors>): Promise<unknown>;
140
+ declare function executeAgentRequest(request: AgentRequest, executors: Partial<AgentRequestExecutors>, options: {
141
+ verbose: true;
142
+ }): Promise<{
143
+ output: unknown;
144
+ raw: unknown;
145
+ }>;
146
+ /**
147
+ * Options for {@link resolveAgentRequests}.
148
+ */
149
+ interface ResolveAgentRequestsOptions extends Partial<AgentExecutionOptions> {
150
+ /** Retries per decision, passed to `resolveDecision`. Default `2`. */
151
+ maxRetries?: number;
152
+ }
153
+ /**
154
+ * Resolves the current step's pending requests and returns the next
155
+ * {@link AgentStep} — one iteration of the durable step loop, collapsing the
156
+ * manual `request.kind` dispatch a host would otherwise write by hand.
157
+ *
158
+ * For each pending request, in order: a `kind: 'text'` request is run with
159
+ * {@link executeAgentRequest} then fed back via {@link resolveAgentStep}; a
160
+ * `kind: 'decision'` request is resolved with `resolveDecision` (wiring
161
+ * `canTake` to `step.snapshot.can` so guard-rejected choices retry) then
162
+ * applied with {@link transitionAgentStep}. The **current** step is re-read
163
+ * after each application — the machine may advance and its `requests` change —
164
+ * so this always resolves against the live step, never a stale list.
165
+ *
166
+ * A `kind: 'plan'` request (`agent.plan`) is resolved natively too: one plan
167
+ * step per call. It resolves a single decision from `request.events` (wiring
168
+ * `canTake` to `step.snapshot.can`, exempting the reserved `agent.plan.done`
169
+ * move and `stopOn` events), then either applies the chosen machine event and
170
+ * lets the next step re-surface the plan, or completes the plan (feeding its
171
+ * `{ steps, stopped }` output back) on the done move / a `stopOn` event / an
172
+ * exhausted budget / no legal events. The plan's applied trail is carried in
173
+ * the invoke child's snapshot, so persisting the step between calls resumes the
174
+ * plan identically.
175
+ *
176
+ * Missing the executor a request needs throws a clear error
177
+ * (`generateText`/`streamText` for text, `decide` for decisions and plans).
178
+ *
179
+ * A complete durable host is two lines:
180
+ *
181
+ * ```ts
182
+ * let step = initialAgentStep(machine, input);
183
+ * while (!step.done) step = await resolveAgentRequests(machine, step, executors);
184
+ * ```
185
+ *
186
+ * All pending **text** requests of a step are resolved in parallel
187
+ * (`Promise.all`) — parallel statechart regions are genuinely concurrent, so
188
+ * their model calls run concurrently — then their outputs apply in
189
+ * **request-array order** (deterministic for durable replay regardless of which
190
+ * call finishes first). Decisions and plans stay **one at a time**: applying
191
+ * either changes the set of legal candidates for what follows, so they cannot be
192
+ * resolved against a stale snapshot. A host that instead wants strictly
193
+ * sequential text resolution loops the manual per-request helpers
194
+ * ({@link executeAgentRequest} + {@link resolveAgentStep}) one at a time.
195
+ */
196
+ declare function resolveAgentRequests<TMachine extends AnyActorLogic>(machine: TMachine, step: AgentStep<SnapshotFrom<TMachine>>, executors: Partial<AgentRequestExecutors>, options?: ResolveAgentRequestsOptions): Promise<AgentStep<SnapshotFrom<TMachine>>>;
197
+ //#endregion
198
+ export { ResolveAgentRequestsOptions as a, initialAgentStep as c, transitionAgentStep as d, AgentStepRequest as i, resolveAgentRequests as l, AgentRequest as n, executeAgentRequest as o, AgentStep as r, getAgentRequests as s, AgentPlanRequest as t, resolveAgentStep as u };
package/dist/steps.cjs ADDED
@@ -0,0 +1,12 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_decision = require("./decision-D8wJrM8W.cjs");
3
+ const require_steps = require("./steps-CVe54GPP.cjs");
4
+ exports.PLAN_DONE_EVENT_TYPE = require_decision.PLAN_DONE_EVENT_TYPE;
5
+ exports.executeAgentRequest = require_steps.executeAgentRequest;
6
+ exports.getAgentRequests = require_steps.getAgentRequests;
7
+ exports.initialAgentStep = require_steps.initialAgentStep;
8
+ exports.renderDecisionAttempts = require_decision.renderDecisionAttempts;
9
+ exports.resolveAgentRequests = require_steps.resolveAgentRequests;
10
+ exports.resolveAgentStep = require_steps.resolveAgentStep;
11
+ exports.resolveDecision = require_decision.resolveDecision;
12
+ exports.transitionAgentStep = require_steps.transitionAgentStep;
@@ -0,0 +1,3 @@
1
+ import { B as ResolveDecisionOptions, H as resolveDecision, K as AgentRequestSource, L as DecisionLogicConfig, P as DecisionAttempt, R as PLAN_DONE_EVENT_TYPE, U as AgentEventDescriptor, V as renderDecisionAttempts, j as AgentDecisionRequest, k as AgentDecisionExecutor } from "./text-logic-Ckhr2kKC.cjs";
2
+ import { a as ResolveAgentRequestsOptions, c as initialAgentStep, d as transitionAgentStep, i as AgentStepRequest, l as resolveAgentRequests, n as AgentRequest, o as executeAgentRequest, r as AgentStep, s as getAgentRequests, t as AgentPlanRequest, u as resolveAgentStep } from "./steps-MjnQI4aB.cjs";
3
+ export { type AgentDecisionExecutor, type AgentDecisionRequest, type AgentEventDescriptor, type AgentPlanRequest, type AgentRequest, type AgentRequestSource, type AgentStep, type AgentStepRequest, type DecisionAttempt, type DecisionLogicConfig, PLAN_DONE_EVENT_TYPE, type ResolveAgentRequestsOptions, type ResolveDecisionOptions, executeAgentRequest, getAgentRequests, initialAgentStep, renderDecisionAttempts, resolveAgentRequests, resolveAgentStep, resolveDecision, transitionAgentStep };
@@ -0,0 +1,3 @@
1
+ import { B as ResolveDecisionOptions, H as resolveDecision, K as AgentRequestSource, L as DecisionLogicConfig, P as DecisionAttempt, R as PLAN_DONE_EVENT_TYPE, U as AgentEventDescriptor, V as renderDecisionAttempts, j as AgentDecisionRequest, k as AgentDecisionExecutor } from "./text-logic-CaKqgX4Y.mjs";
2
+ import { a as ResolveAgentRequestsOptions, c as initialAgentStep, d as transitionAgentStep, i as AgentStepRequest, l as resolveAgentRequests, n as AgentRequest, o as executeAgentRequest, r as AgentStep, s as getAgentRequests, t as AgentPlanRequest, u as resolveAgentStep } from "./steps-BALp1eZo.mjs";
3
+ export { type AgentDecisionExecutor, type AgentDecisionRequest, type AgentEventDescriptor, type AgentPlanRequest, type AgentRequest, type AgentRequestSource, type AgentStep, type AgentStepRequest, type DecisionAttempt, type DecisionLogicConfig, PLAN_DONE_EVENT_TYPE, type ResolveAgentRequestsOptions, type ResolveDecisionOptions, executeAgentRequest, getAgentRequests, initialAgentStep, renderDecisionAttempts, resolveAgentRequests, resolveAgentStep, resolveDecision, transitionAgentStep };
package/dist/steps.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import { l as renderDecisionAttempts, n as PLAN_DONE_EVENT_TYPE, u as resolveDecision } from "./decision-C3k4ve51.mjs";
2
+ import { a as resolveAgentRequests, i as initialAgentStep, n as getAgentRequests, o as resolveAgentStep, s as transitionAgentStep, t as executeAgentRequest } from "./steps-CkyyyuHd.mjs";
3
+ export { PLAN_DONE_EVENT_TYPE, executeAgentRequest, getAgentRequests, initialAgentStep, renderDecisionAttempts, resolveAgentRequests, resolveAgentStep, resolveDecision, transitionAgentStep };