@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,286 @@
1
+ const require_events = require("./events-CRQj3VtP.cjs");
2
+ let xstate = require("xstate");
3
+ //#region src/decision.ts
4
+ function decideRequestFromInput(input) {
5
+ const allowedEventTypes = resolveAllowedEventTypes(input.allowedEvents, input) ?? [];
6
+ return {
7
+ kind: "decision",
8
+ id: "",
9
+ model: input.model,
10
+ system: input.system,
11
+ prompt: input.prompt,
12
+ messages: input.messages,
13
+ events: allowedEventTypes.filter((type) => !require_events.isEventPattern(type)).map((type) => ({
14
+ type,
15
+ toolName: require_events.sanitizeEventToolName(type)
16
+ })),
17
+ attempts: [],
18
+ temperature: input.temperature,
19
+ maxOutputTokens: input.maxOutputTokens,
20
+ topP: input.topP,
21
+ topK: input.topK,
22
+ seed: input.seed,
23
+ stopSequences: input.stopSequences,
24
+ metadata: input.metadata
25
+ };
26
+ }
27
+ function decideActorWithExecutor(execute) {
28
+ const logic = (0, xstate.createAsyncLogic)({ run: async ({ input, signal }) => {
29
+ if (!execute) throw new Error(`'${require_events.DECIDE_ACTOR}' has no host execution. Provide an implementation with machine.provide({ actorSources: { '${require_events.DECIDE_ACTOR}': ... } }) or resolve the returned agent request with resolveDecision(...).`);
30
+ const resolvedEventTypes = resolveAllowedEventTypes(input.allowedEvents, input);
31
+ if (resolvedEventTypes === void 0) throw new Error(`'${require_events.DECIDE_ACTOR}' input has omitted \`allowedEvents\`, which means "all currently-legal events" — but that requires a snapshot-aware host (runAgent or the step path) to resolve. Under a bare createActor(...), declare \`allowedEvents\` explicitly to use this actor here.`);
32
+ if (resolvedEventTypes.some(require_events.isEventPattern)) throw new Error(`'${require_events.DECIDE_ACTOR}' input uses wildcard \`allowedEvents\` patterns, which expand against the live snapshot — that requires a snapshot-aware host (runAgent or the step path). Under a bare createActor(...), list event types explicitly.`);
33
+ return resolveDecision(decideRequestFromInput(input), execute, {
34
+ maxRetries: input.maxRetries ?? 2,
35
+ signal
36
+ });
37
+ } });
38
+ return Object.assign(logic, {
39
+ kind: "statelyai.decisionLogic",
40
+ maxRetries: 2,
41
+ request: decideRequestFromInput,
42
+ allowedEventTypes: (input) => resolveAllowedEventTypes(input.allowedEvents, input),
43
+ withExecutor: (nextExecute) => decideActorWithExecutor(nextExecute)
44
+ });
45
+ }
46
+ function createDecideActor() {
47
+ return decideActorWithExecutor();
48
+ }
49
+ /**
50
+ * Reserved event type the `agent.plan` builtin adds to every step's
51
+ * candidates as the explicit "no further action needed" move. Choosing it
52
+ * ends the plan (`stopped: 'done'`); it is never sent to the machine, so
53
+ * machines need no no-op sentinel event of their own.
54
+ */
55
+ const PLAN_DONE_EVENT_TYPE = "agent.plan.done";
56
+ function createPlanActor() {
57
+ const logic = (0, xstate.createLogic)({
58
+ context: ({ input }) => ({
59
+ applied: [],
60
+ stepsRemaining: input.maxSteps ?? 8,
61
+ stopped: null
62
+ }),
63
+ run: ({ context, event }) => event.type === "plan.applied" ? { context: {
64
+ ...context,
65
+ applied: [...context.applied, event.event],
66
+ stepsRemaining: context.stepsRemaining - 1
67
+ } } : event.type === "plan.ended" ? {
68
+ context: {
69
+ ...context,
70
+ stopped: event.stopped
71
+ },
72
+ status: "done",
73
+ output: {
74
+ steps: context.applied,
75
+ stopped: event.stopped
76
+ }
77
+ } : void 0
78
+ });
79
+ return Object.assign(logic, {
80
+ kind: "statelyai.planLogic",
81
+ maxRetries: 2,
82
+ request: decideRequestFromInput,
83
+ allowedEventTypes: (input) => resolveAllowedEventTypes(input.allowedEvents, input)
84
+ });
85
+ }
86
+ const PLAN_LEDGER_SCOPE = { emit: () => {} };
87
+ /**
88
+ * Builds a fresh plan ledger snapshot from resolved plan input — the shared
89
+ * starting point for BOTH hosts (the step path reads the invoke child's own
90
+ * initial snapshot; runAgent seeds a local ledger with this). @internal
91
+ */
92
+ function initialPlanLedger(logic, input) {
93
+ return logic.getInitialSnapshot(PLAN_LEDGER_SCOPE, input);
94
+ }
95
+ /**
96
+ * Advances a plan ledger by one {@link PlanLedgerEvent}, returning the next
97
+ * snapshot (unwrapping `createLogic`'s `[snapshot, effects]` tuple). Pure — no
98
+ * mutation of the input snapshot. @internal
99
+ */
100
+ function advancePlanLedger(logic, snapshot, event) {
101
+ const result = logic.transition(snapshot, event, PLAN_LEDGER_SCOPE);
102
+ return Array.isArray(result) ? result[0] : result;
103
+ }
104
+ /** Type guard: true for the `agent.plan` builtin logic (checks the `kind` marker). @internal */
105
+ function isPlanLogic(logic) {
106
+ return !!logic && logic.kind === "statelyai.planLogic";
107
+ }
108
+ function resolveAllowedEventTypes(allowedEvents, input) {
109
+ if (allowedEvents === void 0) return;
110
+ const resolved = typeof allowedEvents === "function" ? allowedEvents({ input }) : allowedEvents;
111
+ return typeof resolved === "string" ? [resolved] : resolved;
112
+ }
113
+ /** Type guard: true for any actor logic built by createDecisionLogic/createDecideActor (checks the `kind` marker). @internal */
114
+ function isDecisionLogic(value) {
115
+ return !!value && typeof value === "object" && value.kind === "statelyai.decisionLogic" && typeof value.request === "function";
116
+ }
117
+ /**
118
+ * Thrown by {@link resolveDecision} when every attempt (up to
119
+ * `maxRetries + 1` of them) fails one of the three checks recorded in
120
+ * {@link DecisionAttempt.failure}. Carries the full `attempts` list for
121
+ * diagnostics; a machine typically routes this via the decision invoke's
122
+ * `onError`.
123
+ */
124
+ var DecisionExhaustedError = class extends Error {
125
+ attempts;
126
+ constructor(attempts) {
127
+ super(`Decision exhausted after ${attempts.length} attempt${attempts.length === 1 ? "" : "s"}: ` + attempts.map((attempt) => attempt.reason).join("; "));
128
+ this.name = "DecisionExhaustedError";
129
+ this.attempts = attempts;
130
+ }
131
+ };
132
+ /**
133
+ * Renders a decision request's prior failed `attempts` into feedback messages
134
+ * a host appends to the model call so retries converge — the transport-agnostic
135
+ * "your last choice failed because X, choose again from Y" logic every adapter
136
+ * and raw-SDK host repeats. Returns one `user`-role {@link AgentMessage} per
137
+ * attempt (empty when there are none); adapters map each onto their wire
138
+ * message shape (`attempt.content` is always a string). Core never rewrites the
139
+ * request itself — this only turns the recorded attempts into messages.
140
+ *
141
+ * @example
142
+ * ```ts
143
+ * const messages = [...baseMessages, ...renderDecisionAttempts(request)];
144
+ * ```
145
+ */
146
+ function renderDecisionAttempts(request) {
147
+ const types = request.events.map((event) => event.type).join(", ") || "(none)";
148
+ return request.attempts.map((attempt) => require_events.userMessage(`Your previous choice failed: ${attempt.reason}. Choose again from: ${types}`));
149
+ }
150
+ /**
151
+ * Validation + retry core for decisions. No provider mechanics — the
152
+ * `executor` is responsible for making the model choose an event; this
153
+ * function only validates the choice and retries on failure, up to
154
+ * `options.maxRetries` (default 2, i.e. up to 3 attempts total).
155
+ *
156
+ * Each attempt is checked in order and can fail one of three ways (recorded
157
+ * as a {@link DecisionAttempt}): `'unknown-event'` (the chosen `type` is not
158
+ * among `request.events`), `'invalid-payload'` (the payload fails that
159
+ * event's schema), or `'rejected-by-guard'` (passes both checks but
160
+ * `options.canTake` returns `false` — a type/payload-legal event the
161
+ * machine's guard rejects right now; omit `canTake` to skip this check).
162
+ * Every prior failed attempt for this call is fed back to the executor on
163
+ * the next attempt via `request.attempts`, so an adapter can render "your
164
+ * last choice failed because X — try again" into the next model call; core
165
+ * never rewrites the request itself. Exhausting all attempts throws
166
+ * {@link DecisionExhaustedError} with the full attempts list.
167
+ *
168
+ * @example
169
+ * ```ts
170
+ * const event = await resolveDecision(request, decide, {
171
+ * canTake: (e) => snapshot.can(e),
172
+ * });
173
+ * ```
174
+ */
175
+ async function resolveDecision(request, executor, options = {}) {
176
+ const maxRetries = options.maxRetries ?? 2;
177
+ const attempts = [];
178
+ const eventsByType = new Map(request.events.map((event) => [event.type, event]));
179
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
180
+ options.signal?.throwIfAborted();
181
+ const result = await executor({
182
+ ...request,
183
+ attempts: [...attempts],
184
+ signal: options.signal
185
+ });
186
+ if (!result || typeof result !== "object" || typeof result.event !== "object" || result.event === null || typeof result.event.type !== "string") throw new Error(`decide executor must return { event: { type: string, ... } }; got ${JSON.stringify(result)}. Wrap the chosen event: return { event: { type: 'SAFE' } }.`);
187
+ const { event } = result;
188
+ const descriptor = eventsByType.get(event.type);
189
+ if (!descriptor) {
190
+ attempts.push({
191
+ event,
192
+ failure: "unknown-event",
193
+ reason: `'${event.type}' is not among the currently allowed events: ${request.events.map((candidate) => candidate.type).join(", ") || "(none)"}.`
194
+ });
195
+ continue;
196
+ }
197
+ let validatedEvent = event;
198
+ if (descriptor.inputSchema) {
199
+ const { type, ...payload } = event;
200
+ try {
201
+ validatedEvent = {
202
+ ...require_events.validateSchemaSync(descriptor.inputSchema, payload),
203
+ type
204
+ };
205
+ } catch (error) {
206
+ attempts.push({
207
+ event,
208
+ failure: "invalid-payload",
209
+ reason: `'${event.type}' payload failed validation: ${error instanceof Error ? error.message : String(error)}`
210
+ });
211
+ continue;
212
+ }
213
+ }
214
+ if (options.canTake?.(validatedEvent) === false) {
215
+ attempts.push({
216
+ event: validatedEvent,
217
+ failure: "rejected-by-guard",
218
+ reason: `'${validatedEvent.type}' is not currently takeable (guard rejected it).`
219
+ });
220
+ continue;
221
+ }
222
+ return validatedEvent;
223
+ }
224
+ throw new DecisionExhaustedError(attempts);
225
+ }
226
+ //#endregion
227
+ Object.defineProperty(exports, "DecisionExhaustedError", {
228
+ enumerable: true,
229
+ get: function() {
230
+ return DecisionExhaustedError;
231
+ }
232
+ });
233
+ Object.defineProperty(exports, "PLAN_DONE_EVENT_TYPE", {
234
+ enumerable: true,
235
+ get: function() {
236
+ return PLAN_DONE_EVENT_TYPE;
237
+ }
238
+ });
239
+ Object.defineProperty(exports, "advancePlanLedger", {
240
+ enumerable: true,
241
+ get: function() {
242
+ return advancePlanLedger;
243
+ }
244
+ });
245
+ Object.defineProperty(exports, "createDecideActor", {
246
+ enumerable: true,
247
+ get: function() {
248
+ return createDecideActor;
249
+ }
250
+ });
251
+ Object.defineProperty(exports, "createPlanActor", {
252
+ enumerable: true,
253
+ get: function() {
254
+ return createPlanActor;
255
+ }
256
+ });
257
+ Object.defineProperty(exports, "initialPlanLedger", {
258
+ enumerable: true,
259
+ get: function() {
260
+ return initialPlanLedger;
261
+ }
262
+ });
263
+ Object.defineProperty(exports, "isDecisionLogic", {
264
+ enumerable: true,
265
+ get: function() {
266
+ return isDecisionLogic;
267
+ }
268
+ });
269
+ Object.defineProperty(exports, "isPlanLogic", {
270
+ enumerable: true,
271
+ get: function() {
272
+ return isPlanLogic;
273
+ }
274
+ });
275
+ Object.defineProperty(exports, "renderDecisionAttempts", {
276
+ enumerable: true,
277
+ get: function() {
278
+ return renderDecisionAttempts;
279
+ }
280
+ });
281
+ Object.defineProperty(exports, "resolveDecision", {
282
+ enumerable: true,
283
+ get: function() {
284
+ return resolveDecision;
285
+ }
286
+ });