@statelyai/agent 2.0.0-alpha.10 → 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 (45) hide show
  1. package/dist/adapter.cjs +15 -0
  2. package/dist/adapter.d.cts +4 -0
  3. package/dist/adapter.d.mts +4 -0
  4. package/dist/adapter.mjs +2 -0
  5. package/dist/ai-sdk.cjs +66 -102
  6. package/dist/ai-sdk.d.cts +5 -115
  7. package/dist/ai-sdk.d.mts +5 -115
  8. package/dist/ai-sdk.mjs +64 -91
  9. package/dist/decision-C3k4ve51.mjs +227 -0
  10. package/dist/decision-D8wJrM8W.cjs +286 -0
  11. package/dist/{decision-b-lkcs4L.cjs → events-CRQj3VtP.cjs} +10 -295
  12. package/dist/{decision-CQdrKc8k.mjs → events-JiVPYrct.mjs} +10 -229
  13. package/dist/index.cjs +2521 -52
  14. package/dist/index.d.cts +1029 -9
  15. package/dist/index.d.mts +1029 -9
  16. package/dist/index.mjs +2493 -4
  17. package/dist/openai-compat.cjs +23 -33
  18. package/dist/openai-compat.d.cts +3 -42
  19. package/dist/openai-compat.d.mts +3 -42
  20. package/dist/openai-compat.mjs +20 -24
  21. package/dist/steps-BALp1eZo.d.mts +198 -0
  22. package/dist/steps-CVe54GPP.cjs +420 -0
  23. package/dist/steps-CkyyyuHd.mjs +379 -0
  24. package/dist/steps-MjnQI4aB.d.cts +198 -0
  25. package/dist/steps.cjs +12 -0
  26. package/dist/steps.d.cts +3 -0
  27. package/dist/steps.d.mts +3 -0
  28. package/dist/steps.mjs +3 -0
  29. package/dist/{text-logic-C7WJpCIc.d.mts → text-logic-CaKqgX4Y.d.mts} +8 -8
  30. package/dist/{text-logic-CZjyACzQ.d.cts → text-logic-Ckhr2kKC.d.cts} +8 -8
  31. package/package.json +27 -4
  32. package/readme.md +18 -8
  33. package/schemas/agent-workflow.json +4 -5
  34. package/dist/cli.cjs +0 -64
  35. package/dist/cli.d.cts +0 -1
  36. package/dist/cli.d.mts +0 -1
  37. package/dist/cli.mjs +0 -65
  38. package/dist/run-agent-BFMkuI1F.cjs +0 -1599
  39. package/dist/run-agent-BVMd--1l.d.cts +0 -1103
  40. package/dist/run-agent-BoAOq_0Z.mjs +0 -1540
  41. package/dist/run-agent-DzYJb3CK.d.mts +0 -1103
  42. package/dist/src-D-77Ha5p.cjs +0 -1087
  43. package/dist/src-DUeIFjv-.mjs +0 -1016
  44. /package/dist/{utils-Dri7aeEG.d.cts → utils-BYqT_Dyv.d.cts} +0 -0
  45. /package/dist/{utils-Y6GDRGGE.d.mts → utils-Do5wIJrh.d.mts} +0 -0
package/dist/ai-sdk.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { a as runAgent$1, c as setupAgent } from "./run-agent-BoAOq_0Z.mjs";
2
- import { J as isStandardSchema, L as getRegisteredAgentModels, T as getAgentOutputMode, l as renderDecisionAttempts, x as buildEnvelopeSchema } from "./decision-CQdrKc8k.mjs";
1
+ import { L as isStandardSchema, d as buildEnvelopeSchema, h as getAgentOutputMode } from "./events-JiVPYrct.mjs";
2
+ import { l as renderDecisionAttempts } from "./decision-C3k4ve51.mjs";
3
3
  import { NoObjectGeneratedError, Output, generateText, stepCountIs, streamText, tool } from "ai";
4
- //#region src/ai-sdk/index.ts
4
+ //#region src/ai-sdk/mappers.ts
5
5
  /**
6
6
  * Maps an {@link AgentTools} map onto AI SDK `tool()` definitions. A tool that
7
7
  * already carries its own Standard Schema `inputSchema` — an AI SDK
@@ -10,8 +10,7 @@ import { NoObjectGeneratedError, Output, generateText, stepCountIs, streamText,
10
10
  * every extra property (`providerOptions`, `toModelOutput`, …) survives. A bare
11
11
  * `AgentToolExecute` function becomes a tool with an unconstrained input schema;
12
12
  * a minimal descriptor with no readable schema is converted with a permissive
13
- * fallback. Used internally by {@link toAiSdkCallSettings}; exported for callers
14
- * building AI SDK calls by hand outside `createAiSdkExecutors`.
13
+ * fallback. Used by {@link toAiSdkCallSettings}.
15
14
  */
16
15
  function toAiSdkTools(tools) {
17
16
  const entries = [];
@@ -44,9 +43,6 @@ function toAiSdkTools(tools) {
44
43
  }
45
44
  return Object.fromEntries(entries);
46
45
  }
47
- function maxStepsSetting(request) {
48
- return typeof request.metadata?.maxSteps === "number" ? { stopWhen: stepCountIs(request.metadata.maxSteps) } : {};
49
- }
50
46
  const unknownSchema = { "~standard": {
51
47
  version: 1,
52
48
  vendor: "statelyai-agent",
@@ -54,35 +50,6 @@ const unknownSchema = { "~standard": {
54
50
  jsonSchema: { input: () => ({}) }
55
51
  } };
56
52
  /**
57
- * Identity helper for a `models` map whose value is exported. Returns the map
58
- * unchanged, but types it as {@link AiSdkModelMap}`<keyof T & string>` — a
59
- * portable, nameable type — so an exported `const models = defineModels({...})`
60
- * needs no `Record<'a' | 'b', LanguageModel>` annotation and never triggers
61
- * TS2742 ("inferred type cannot be named without a reference to …"). The exact
62
- * ref keys survive, so `createAiSdkExecutors({ models })` and
63
- * `setupAgent({ models })` still infer/autocomplete them.
64
- *
65
- * @example
66
- * ```ts
67
- * export const models = defineModels({
68
- * quick: openai('gpt-5.4-mini'),
69
- * deep: openai('gpt-5.4'),
70
- * });
71
- * // typeof models === AiSdkModelMap<'quick' | 'deep'>
72
- * ```
73
- */
74
- function defineModels(models) {
75
- return models;
76
- }
77
- function resolveAiSdkModel(options, modelRef) {
78
- if (options.resolveModel) return options.resolveModel(modelRef);
79
- const models = options.models;
80
- if (!models) throw new Error(`createAiSdkExecutors: no model resolver configured for '${modelRef}'.`);
81
- const model = models[modelRef];
82
- if (!model) throw new Error(`createAiSdkExecutors: unknown model '${modelRef}'.`);
83
- return model;
84
- }
85
- /**
86
53
  * AI SDK request-mapping settings shared by `generateText`/`streamText`.
87
54
  * `AgentTextRequest.messages` (`AgentMessage[]`) and AI SDK's `ModelMessage[]`
88
55
  * are structurally compatible by design (§1 of .scratch/p0-design.md) — the cast
@@ -147,6 +114,65 @@ function extractFirstJsonValue(text) {
147
114
  }
148
115
  }
149
116
  }
117
+ /** One AI SDK `tool()` per candidate event — the "tool-per-event +
118
+ * toolChoice: 'required'" recipe from .scratch/p0-design.md §2.6. */
119
+ function toAiSdkEventTools(events) {
120
+ return Object.fromEntries(events.map((event) => [event.toolName, tool({
121
+ description: `Choose the '${event.type}' move.`,
122
+ inputSchema: event.inputSchema ? event.inputSchema : unknownSchema
123
+ })]));
124
+ }
125
+ /**
126
+ * Messages for a decision request, with prior failed `attempts` (§2.6)
127
+ * rendered as appended user messages (via core's {@link renderDecisionAttempts})
128
+ * so retries converge. Core never rewrites prompts — this is adapter business.
129
+ */
130
+ function toDecisionMessages(request) {
131
+ if (!request.messages && request.attempts.length === 0) return;
132
+ const messages = [...request.messages ?? (request.prompt !== void 0 ? [{
133
+ role: "user",
134
+ content: request.prompt
135
+ }] : [])];
136
+ for (const attempt of renderDecisionAttempts(request)) messages.push({
137
+ role: "user",
138
+ content: attempt.content
139
+ });
140
+ return messages;
141
+ }
142
+ //#endregion
143
+ //#region src/ai-sdk/index.ts
144
+ function maxStepsSetting(request) {
145
+ return typeof request.metadata?.maxSteps === "number" ? { stopWhen: stepCountIs(request.metadata.maxSteps) } : {};
146
+ }
147
+ /**
148
+ * Identity helper for a `models` map whose value is exported. Returns the map
149
+ * unchanged, but types it as {@link AiSdkModelMap}`<keyof T & string>` — a
150
+ * portable, nameable type — so an exported `const models = defineModels({...})`
151
+ * needs no `Record<'a' | 'b', LanguageModel>` annotation and never triggers
152
+ * TS2742 ("inferred type cannot be named without a reference to …"). The exact
153
+ * ref keys survive, so `createAiSdkExecutors({ models })` and
154
+ * `setupAgent({ models })` still infer/autocomplete them.
155
+ *
156
+ * @example
157
+ * ```ts
158
+ * export const models = defineModels({
159
+ * quick: openai('gpt-5.4-mini'),
160
+ * deep: openai('gpt-5.4'),
161
+ * });
162
+ * // typeof models === AiSdkModelMap<'quick' | 'deep'>
163
+ * ```
164
+ */
165
+ function defineModels(models) {
166
+ return models;
167
+ }
168
+ function resolveAiSdkModel(options, modelRef) {
169
+ if (options.resolveModel) return options.resolveModel(modelRef);
170
+ const models = options.models;
171
+ if (!models) throw new Error(`createAiSdkExecutors: no model resolver configured for '${modelRef}'.`);
172
+ const model = models[modelRef];
173
+ if (!model) throw new Error(`createAiSdkExecutors: unknown model '${modelRef}'.`);
174
+ return model;
175
+ }
150
176
  function withJsonRepair(output) {
151
177
  return {
152
178
  ...output,
@@ -274,58 +300,5 @@ function createAiSdkExecutors(options) {
274
300
  decide
275
301
  };
276
302
  }
277
- /** AI SDK host for a machine authored with `setupAgent({ models })`. */
278
- function runAgent(machine, options) {
279
- const models = getRegisteredAgentModels(machine);
280
- if (!models || Object.keys(models).length === 0) throw new Error("AI SDK runAgent: machine has no models. Pass `models` to setupAgent, or use core runAgent with explicit executors.");
281
- return runAgent$1(machine, {
282
- ...options,
283
- executors: createAiSdkExecutors({ models })
284
- });
285
- }
286
- function createAgent(config) {
287
- const { model, models: configuredModels, schemas, ...machineConfig } = config;
288
- const models = configuredModels ?? { default: model };
289
- const executors = createAiSdkExecutors({ models });
290
- const machine = setupAgent({
291
- ...schemas,
292
- models
293
- }).createMachine(machineConfig);
294
- return {
295
- machine,
296
- run(runInput, options = {}) {
297
- return runAgent$1(machine, {
298
- ...options,
299
- input: runInput,
300
- executors
301
- });
302
- }
303
- };
304
- }
305
- /** One AI SDK `tool()` per candidate event — the "tool-per-event +
306
- * toolChoice: 'required'" recipe from .scratch/p0-design.md §2.6. */
307
- function toAiSdkEventTools(events) {
308
- return Object.fromEntries(events.map((event) => [event.toolName, tool({
309
- description: `Choose the '${event.type}' move.`,
310
- inputSchema: event.inputSchema ? event.inputSchema : unknownSchema
311
- })]));
312
- }
313
- /**
314
- * Messages for a decision request, with prior failed `attempts` (§2.6)
315
- * rendered as appended user messages (via core's {@link renderDecisionAttempts})
316
- * so retries converge. Core never rewrites prompts — this is adapter business.
317
- */
318
- function toDecisionMessages(request) {
319
- if (!request.messages && request.attempts.length === 0) return;
320
- const messages = [...request.messages ?? (request.prompt !== void 0 ? [{
321
- role: "user",
322
- content: request.prompt
323
- }] : [])];
324
- for (const attempt of renderDecisionAttempts(request)) messages.push({
325
- role: "user",
326
- content: attempt.content
327
- });
328
- return messages;
329
- }
330
303
  //#endregion
331
- export { createAgent, createAiSdkExecutors, defineModels, extractFirstJsonValue, isStructuredOutputRequest, runAgent, toAiSdkCallSettings, toAiSdkEventTools, toAiSdkToolChoice, toAiSdkTools, toDecisionMessages };
304
+ export { createAiSdkExecutors, defineModels };
@@ -0,0 +1,227 @@
1
+ import { H as validateSchemaSync, V as userMessage, a as sanitizeEventToolName, n as isEventPattern, o as DECIDE_ACTOR } from "./events-JiVPYrct.mjs";
2
+ import { createAsyncLogic, createLogic } from "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) => !isEventPattern(type)).map((type) => ({
14
+ type,
15
+ toolName: 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 = createAsyncLogic({ run: async ({ input, signal }) => {
29
+ if (!execute) throw new Error(`'${DECIDE_ACTOR}' has no host execution. Provide an implementation with machine.provide({ actorSources: { '${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(`'${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(isEventPattern)) throw new Error(`'${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 = 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) => 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
+ ...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
+ export { createPlanActor as a, isPlanLogic as c, createDecideActor as i, renderDecisionAttempts as l, PLAN_DONE_EVENT_TYPE as n, initialPlanLedger as o, advancePlanLedger as r, isDecisionLogic as s, DecisionExhaustedError as t, resolveDecision as u };