@statelyai/agent 2.0.0-alpha.34 → 2.0.0-alpha.36

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 (130) hide show
  1. package/CHANGELOG.md +124 -0
  2. package/dist/act-B9hLQls6.mjs +19 -0
  3. package/dist/act-CrX0JwWY.cjs +42 -0
  4. package/dist/ai-sdk.cjs +63 -7
  5. package/dist/ai-sdk.d.cts +13 -3
  6. package/dist/ai-sdk.d.mts +13 -3
  7. package/dist/ai-sdk.mjs +63 -7
  8. package/dist/{decision-BEsATcr1.cjs → decision-CMeuNZ1g.cjs} +262 -4
  9. package/dist/{decision-COkJNjOW.mjs → decision-m5hGmHpF.mjs} +239 -5
  10. package/dist/decision-object-B5zGSPFp.d.mts +15 -0
  11. package/dist/decision-object-DBcLWVvv.d.cts +15 -0
  12. package/dist/{run-agent-s5D32w99.cjs → effects-B23bFZEs.cjs} +948 -102
  13. package/dist/{run-agent-Ct_GZw_f.mjs → effects-CuOUNYtZ.mjs} +914 -104
  14. package/dist/{event-log-C7jeH0y8.mjs → event-log-DkVlk3Rh.mjs} +30 -15
  15. package/dist/{event-log-BWSSLUff.cjs → event-log-Dkc-yIYu.cjs} +41 -14
  16. package/dist/{event-log-store-BzXehP7R.d.cts → event-log-store-BBS8so8a.d.mts} +2 -2
  17. package/dist/{event-log-store-W49TCJXi.mjs → event-log-store-Brx9tOHt.mjs} +1 -1
  18. package/dist/{event-log-store-CleWpsp5.cjs → event-log-store-Cl-YWDnq.cjs} +1 -1
  19. package/dist/{event-log-store-CWjN6lmM.d.mts → event-log-store-bc4ICGcS.d.cts} +2 -2
  20. package/dist/index.cjs +660 -286
  21. package/dist/index.d.cts +168 -9
  22. package/dist/index.d.mts +168 -9
  23. package/dist/index.mjs +639 -271
  24. package/dist/internal-C3Lqu538.d.cts +43 -0
  25. package/dist/internal-DUcdhk-i.d.mts +43 -0
  26. package/dist/log.cjs +2 -2
  27. package/dist/log.d.cts +1 -1
  28. package/dist/log.d.mts +1 -1
  29. package/dist/log.mjs +2 -2
  30. package/dist/machines.cjs +457 -41
  31. package/dist/machines.d.cts +114 -43
  32. package/dist/machines.d.mts +114 -43
  33. package/dist/machines.mjs +457 -42
  34. package/dist/{model-source-DmhTMK39.cjs → model-source-B4WQ8Idp.cjs} +1 -1
  35. package/dist/{model-source-CK3F4YuU.mjs → model-source-kjGwqAV8.mjs} +1 -1
  36. package/dist/openai.cjs +149 -36
  37. package/dist/openai.d.cts +28 -10
  38. package/dist/openai.d.mts +28 -10
  39. package/dist/openai.mjs +149 -36
  40. package/dist/otel.d.cts +1 -1
  41. package/dist/otel.d.mts +1 -1
  42. package/dist/{run-agent-BGdx5913.d.mts → run-agent-BcQ-9NRT.d.cts} +91 -9
  43. package/dist/{run-agent-B1-Eqviq.d.cts → run-agent-C86drZtN.d.mts} +91 -9
  44. package/dist/{setup-agent-05uw4dPZ.mjs → setup-agent-BDmNr6PC.mjs} +9 -3
  45. package/dist/{setup-agent-BtfeFfF6.d.cts → setup-agent-BIKcbVXV.d.mts} +4 -4
  46. package/dist/{setup-agent-CXEBURdo.cjs → setup-agent-CmEToB8y.cjs} +9 -3
  47. package/dist/{setup-agent-C6nqzv_X.d.mts → setup-agent-jlo4vtaZ.d.cts} +4 -4
  48. package/dist/tanstack-ai.cjs +62 -4
  49. package/dist/tanstack-ai.d.cts +18 -6
  50. package/dist/tanstack-ai.d.mts +18 -6
  51. package/dist/tanstack-ai.mjs +62 -4
  52. package/dist/testing.cjs +536 -67
  53. package/dist/testing.d.cts +197 -180
  54. package/dist/testing.d.mts +197 -180
  55. package/dist/testing.mjs +532 -67
  56. package/dist/{text-logic-CV_4KGr6.d.cts → text-logic-BqxalgMr.d.mts} +87 -4
  57. package/dist/{text-logic-Ckh-rJFV.d.mts → text-logic-CSf9bqpP.d.cts} +87 -4
  58. package/dist/{types-Dp5_Ru4R.d.cts → types-DQUOOaZO.d.cts} +1 -1
  59. package/dist/{types-Dp5_Ru4R.d.mts → types-DQUOOaZO.d.mts} +1 -1
  60. package/dist/{usage-BDiJKyv9.d.cts → usage-DoP0Oi84.d.mts} +1 -1
  61. package/dist/{usage-DOoVUGVq.d.mts → usage-HtnrUsl9.d.cts} +1 -1
  62. package/dist/utils-7lSa4H-i.d.cts +403 -0
  63. package/dist/utils-CBbKw2fM.d.mts +403 -0
  64. package/dist/validate.cjs +44 -12
  65. package/dist/validate.d.cts +6 -6
  66. package/dist/validate.d.mts +6 -6
  67. package/dist/validate.mjs +44 -12
  68. package/dist/verify-Bink-Drw.cjs +2304 -0
  69. package/dist/{verify-BQpE8hUz.d.cts → verify-Buh8XSUr.d.mts} +208 -14
  70. package/dist/{verify-CqeuEmIk.d.mts → verify-CciG8UP-.d.cts} +208 -14
  71. package/dist/verify-Dpz1u5Pe.mjs +2251 -0
  72. package/dist/with-model-calls-B_WLmOSl.cjs +248 -0
  73. package/dist/with-model-calls-BkOwdroS.mjs +213 -0
  74. package/docs/act.md +102 -0
  75. package/docs/advanced.md +105 -0
  76. package/docs/any-stack.md +62 -0
  77. package/docs/choosing-a-run-mode.md +55 -0
  78. package/docs/debugging.md +29 -0
  79. package/docs/decisions.md +473 -0
  80. package/docs/environment-and-policy.md +188 -0
  81. package/docs/evals.md +509 -0
  82. package/docs/event-log.md +311 -0
  83. package/docs/from-a-loop.md +528 -0
  84. package/docs/generate-machines.md +110 -0
  85. package/docs/hosts.md +414 -0
  86. package/docs/human-in-the-loop.md +177 -0
  87. package/docs/index.md +48 -0
  88. package/docs/judgments.md +281 -0
  89. package/docs/langgraph-comparison.md +198 -0
  90. package/docs/machines-as-data.md +454 -0
  91. package/docs/machines-presets.md +198 -0
  92. package/docs/machines.md +497 -0
  93. package/docs/messages.md +67 -0
  94. package/docs/meta.json +52 -0
  95. package/docs/models-and-providers.md +268 -0
  96. package/docs/multi-agent.md +68 -0
  97. package/docs/observability.md +109 -0
  98. package/docs/patterns.md +31 -0
  99. package/docs/persistence.md +136 -0
  100. package/docs/quickstart.md +121 -0
  101. package/docs/roadmap.md +22 -0
  102. package/docs/scope.md +75 -0
  103. package/docs/statechart-policy-examples.md +69 -0
  104. package/docs/steps.md +54 -0
  105. package/docs/strangler-fig.md +323 -0
  106. package/docs/text-requests.md +250 -0
  107. package/docs/thinking-in-state-machines.md +324 -0
  108. package/docs/tools.md +249 -0
  109. package/docs/upgrading.md +37 -0
  110. package/docs/usage-and-budgets.md +516 -0
  111. package/docs/validate-and-repair.md +253 -0
  112. package/docs/verify.md +487 -0
  113. package/docs/xstate-4-and-5-apps.md +161 -0
  114. package/llms.txt +53 -0
  115. package/package.json +10 -3
  116. package/readme.md +30 -15
  117. package/skills/add-evals/SKILL.md +3 -1
  118. package/skills/add-traces/SKILL.md +6 -1
  119. package/skills/build-machine/SKILL.md +81 -0
  120. package/skills/generate-machine/SKILL.md +1 -1
  121. package/skills/graph-engineering/SKILL.md +13 -3
  122. package/skills/improve-machine/SKILL.md +21 -2
  123. package/skills/loop-to-machine/SKILL.md +147 -190
  124. package/skills/loop-to-machine/reference.md +260 -0
  125. package/dist/utils-BnXdWih3.d.mts +0 -108
  126. package/dist/utils-ebVpCYoF.d.cts +0 -108
  127. package/dist/verify-Bpahmr34.mjs +0 -1241
  128. package/dist/verify-DCLZa9R0.cjs +0 -1288
  129. package/dist/with-model-calls-BXYdBdcu.cjs +0 -45
  130. package/dist/with-model-calls-Bv4V4EHC.mjs +0 -34
@@ -1,4 +1,4 @@
1
- const require_event_log = require("./event-log-BWSSLUff.cjs");
1
+ const require_event_log = require("./event-log-Dkc-yIYu.cjs");
2
2
  let xstate = require("xstate");
3
3
  //#region src/events.ts
4
4
  /**
@@ -167,6 +167,230 @@ function getHumanEventTypes(snapshot) {
167
167
  }
168
168
  const humanEventTypesBySnapshot = /* @__PURE__ */ new WeakMap();
169
169
  //#endregion
170
+ //#region src/decision-strategy.ts
171
+ /** Above this many candidate events, `'auto'` groups them (when two groups or more exist). */
172
+ const GROUPED_EVENT_THRESHOLD = 24;
173
+ /** The most payloads a finite payload schema may enumerate to be filled by a closed choice. */
174
+ const MAX_FINITE_PAYLOADS = 32;
175
+ /** The strategy `'auto'` resolves to for this request. @internal */
176
+ function resolveDecisionStrategy(request) {
177
+ const strategy = request.strategy ?? "auto";
178
+ if (strategy !== "auto") return strategy;
179
+ if (request.fillModel !== void 0) return "pick-then-fill";
180
+ if (candidateTypes(request).length > 24 && decisionGroups(request).length >= 2) return "grouped";
181
+ return "direct";
182
+ }
183
+ /**
184
+ * Every payload a JSON Schema allows, when each required field is finite (an
185
+ * `enum`, a `const`, a boolean, or a union of those) and they number at most
186
+ * {@link MAX_FINITE_PAYLOADS}. Optional fields are left out when finite; an
187
+ * optional open field makes the schema open. `undefined` when open. @internal
188
+ */
189
+ function enumerateFinitePayloads(jsonSchema) {
190
+ if (!jsonSchema) return void 0;
191
+ const union = jsonSchema.anyOf ?? jsonSchema.oneOf;
192
+ if (Array.isArray(union) && union.length > 0) {
193
+ const variants = union.map((variant) => require_event_log.isRecord(variant) ? enumerateFinitePayloads(variant) : void 0);
194
+ if (variants.some((variant) => variant === void 0)) return void 0;
195
+ const payloads = variants.flatMap((variant) => variant ?? []);
196
+ return payloads.length <= 32 ? payloads : void 0;
197
+ }
198
+ if (jsonSchema.allOf !== void 0 || jsonSchema.type !== void 0 && jsonSchema.type !== "object" || jsonSchema.type !== "object" && !require_event_log.isRecord(jsonSchema.properties)) return;
199
+ const properties = require_event_log.isRecord(jsonSchema.properties) ? jsonSchema.properties : {};
200
+ const required = new Set(Array.isArray(jsonSchema.required) ? jsonSchema.required : []);
201
+ let payloads = [{}];
202
+ for (const [key, property] of Object.entries(properties)) {
203
+ const values = finiteValues(property);
204
+ if (values === void 0) return void 0;
205
+ if (!required.has(key)) continue;
206
+ if (payloads.length * values.length > 32) return void 0;
207
+ payloads = payloads.flatMap((payload) => values.map((value) => ({
208
+ ...payload,
209
+ [key]: value
210
+ })));
211
+ }
212
+ return payloads;
213
+ }
214
+ function finiteValues(schema) {
215
+ if (!require_event_log.isRecord(schema)) return void 0;
216
+ if ("const" in schema) return [schema.const];
217
+ if (Array.isArray(schema.enum)) return schema.enum;
218
+ if (schema.type === "boolean") return [true, false];
219
+ const union = schema.anyOf ?? schema.oneOf;
220
+ if (Array.isArray(union) && union.length > 0) {
221
+ const values = union.map(finiteValues);
222
+ return values.every((value) => value !== void 0) ? values.flat() : void 0;
223
+ }
224
+ }
225
+ /**
226
+ * Whether an event's payload needs an open fill (a `fillModel`): it has a
227
+ * schema with fields, and they are not finite. @internal
228
+ */
229
+ function payloadNeedsFillModel(jsonSchema) {
230
+ if (!jsonSchema) return false;
231
+ return enumerateFinitePayloads(jsonSchema) === void 0;
232
+ }
233
+ function candidateTypes(request) {
234
+ const types = request.options ? request.options.map((option) => option.event.type) : request.events.map((event) => event.type);
235
+ return [...new Set(types)];
236
+ }
237
+ /**
238
+ * The non-empty groups over the request's candidate types: the explicit
239
+ * `groups` (members not among the candidates dropped), then every remaining
240
+ * type grouped by its prefix before the first `.`. @internal
241
+ */
242
+ function decisionGroups(request) {
243
+ const types = candidateTypes(request);
244
+ const groups = /* @__PURE__ */ new Map();
245
+ const grouped = /* @__PURE__ */ new Set();
246
+ for (const [name, members] of Object.entries(request.groups ?? {})) {
247
+ const present = types.filter((type) => members.includes(type) && !grouped.has(type));
248
+ for (const type of present) grouped.add(type);
249
+ if (present.length) groups.set(name, present);
250
+ }
251
+ for (const type of types) {
252
+ if (grouped.has(type)) continue;
253
+ const name = type.includes(".") ? type.slice(0, type.indexOf(".")) : type;
254
+ groups.set(name, [...groups.get(name) ?? [], type]);
255
+ }
256
+ return [...groups].map(([name, members]) => ({
257
+ name,
258
+ types: members
259
+ }));
260
+ }
261
+ function subInfo(info, role) {
262
+ return {
263
+ ...info,
264
+ ...info?.callKey !== void 0 ? { callKey: `${info.callKey}.${role}` } : {}
265
+ };
266
+ }
267
+ function choiceRequest(request, choices) {
268
+ const { withheld: _withheld, ...rest } = request;
269
+ return {
270
+ ...rest,
271
+ events: choices.map(({ name }) => ({
272
+ type: name,
273
+ toolName: sanitizeEventToolName(name)
274
+ })),
275
+ options: choices.map(({ name, description }) => ({
276
+ event: { type: name },
277
+ ...description !== void 0 ? { description } : {}
278
+ }))
279
+ };
280
+ }
281
+ function narrowRequest(request, types) {
282
+ return {
283
+ ...request,
284
+ events: request.events.filter((event) => types.includes(event.type)),
285
+ ...request.options ? { options: request.options.filter((option) => types.includes(option.event.type)) } : {}
286
+ };
287
+ }
288
+ /**
289
+ * Wraps a decide executor so one call answers the request with its strategy
290
+ * (see {@link DecisionStrategy}): it makes the strategy's sub-calls and returns
291
+ * ONE `{ event }` or `{ rejected }`, which `resolveDecision` validates and
292
+ * retries like any answer. Every sub-call gets the request's `attempts`, and
293
+ * `info.callKey` suffixed with `.pick`, `.group`, or `.fill`. `'direct'`
294
+ * returns `executors.decide` itself. @internal
295
+ */
296
+ function withDecisionStrategy(request, executors) {
297
+ const strategy = resolveDecisionStrategy(request);
298
+ if (strategy === "direct") return executors.decide;
299
+ return strategy === "grouped" ? groupedDecide(executors) : pickThenFillDecide(executors);
300
+ }
301
+ function groupedDecide({ decide }) {
302
+ return async (request, info) => {
303
+ const groups = decisionGroups(request);
304
+ if (groups.length < 2) return decide(request, info);
305
+ const picked = await decide(choiceRequest(request, groups.map(({ name, types }) => ({
306
+ name,
307
+ description: `One of: ${types.join(", ")}`
308
+ }))), subInfo(info, "group"));
309
+ if (picked.rejected) return picked;
310
+ const group = groups.find(({ name }) => name === picked.event.type);
311
+ if (!group) return { rejected: {
312
+ failure: "unknown-event",
313
+ reason: `'${picked.event.type}' is not a group: ${groups.map(({ name }) => name).join(", ")}.`
314
+ } };
315
+ return decide(narrowRequest(request, group.types), subInfo(info, "pick"));
316
+ };
317
+ }
318
+ function pickThenFillDecide(executors) {
319
+ return async (request, info) => {
320
+ const types = candidateTypes(request);
321
+ const descriptions = new Map((request.options ?? []).filter((option) => Object.keys(option.event).length === 1 && option.description).map((option) => [option.event.type, option.description]));
322
+ let type;
323
+ if (types.length === 1) type = types[0];
324
+ else {
325
+ const picked = await executors.decide(choiceRequest(request, types.map((name) => ({
326
+ name,
327
+ description: descriptions.get(name)
328
+ }))), subInfo(info, "pick"));
329
+ if (picked.rejected) return picked;
330
+ if (!types.includes(picked.event.type)) return { rejected: {
331
+ failure: "unknown-event",
332
+ reason: `'${picked.event.type}' is not among the currently allowed events: ${types.join(", ")}.`,
333
+ event: picked.event
334
+ } };
335
+ type = picked.event.type;
336
+ }
337
+ return fill(request, type, executors, info);
338
+ };
339
+ }
340
+ async function fill(request, type, { decide, generateText }, info) {
341
+ const narrowed = narrowRequest(request, [type]);
342
+ const descriptor = narrowed.events[0];
343
+ let options = narrowed.options;
344
+ if (!options) {
345
+ const payloads = descriptor?.inputSchema ? enumerateFinitePayloads(require_event_log.getJsonSchemaSync(descriptor.inputSchema)) : [{}];
346
+ if (payloads) options = payloads.map((payload) => ({ event: {
347
+ ...payload,
348
+ type
349
+ } }));
350
+ }
351
+ if (options) {
352
+ if (options.length === 1) return { event: options[0].event };
353
+ return decide({
354
+ ...narrowed,
355
+ options
356
+ }, subInfo(info, "fill"));
357
+ }
358
+ return fillWithModel(narrowed, descriptor, generateText, info);
359
+ }
360
+ async function fillWithModel(request, descriptor, generateText, info) {
361
+ if (request.fillModel === void 0) throw new require_event_log.AgentError("missing-fill-model", `Decision '${request.name}' uses strategy 'pick-then-fill', but '${descriptor.type}' has open payload fields and no \`fillModel\` is set to fill them. Set \`fillModel\`, enumerate the payloads with \`payloads\`, or use strategy 'direct'.`);
362
+ if (!generateText) throw new require_event_log.AgentError("missing-fill-executor", `Decision '${request.name}' fills '${descriptor.type}' with fillModel '${request.fillModel}', which needs a 'generateText' executor; none was provided.`);
363
+ const instruction = `You chose '${descriptor.type}'. Write its payload.`;
364
+ const feedback = request.attempts.map((attempt) => require_event_log.userMessage(`Your previous choice failed: ${attempt.reason}`));
365
+ const payload = (await generateText({
366
+ name: request.name,
367
+ ...request.input !== void 0 ? { input: request.input } : {},
368
+ model: request.fillModel,
369
+ ...request.system !== void 0 ? { system: request.system } : {},
370
+ ...request.messages ? { messages: [
371
+ ...request.messages,
372
+ ...feedback,
373
+ require_event_log.userMessage(instruction)
374
+ ] } : { prompt: [
375
+ request.prompt,
376
+ ...feedback.map((message) => message.content),
377
+ instruction
378
+ ].filter((part) => part !== void 0).join("\n\n") },
379
+ outputSchema: descriptor.inputSchema,
380
+ tools: {},
381
+ ...request.metadata !== void 0 ? { metadata: request.metadata } : {}
382
+ }, subInfo(info, "fill"))).result;
383
+ if (!require_event_log.isRecord(payload)) return { rejected: {
384
+ failure: "invalid-payload",
385
+ reason: `'${descriptor.type}' payload must be an object; got ${JSON.stringify(payload)}.`,
386
+ event: { type: descriptor.type }
387
+ } };
388
+ return { event: {
389
+ ...payload,
390
+ type: descriptor.type
391
+ } };
392
+ }
393
+ //#endregion
170
394
  //#region src/decision.ts
171
395
  function optionsFromPayloads(eventTypes, payloads) {
172
396
  return eventTypes.filter((type) => !isEventPattern(type)).flatMap((type) => (payloads[type] ?? [{}]).map((payload) => ({ event: {
@@ -231,6 +455,9 @@ function decideRequestFromInput(input) {
231
455
  toolName: sanitizeEventToolName(type)
232
456
  })),
233
457
  ...input.payloads ? { options: optionsFromPayloads(allowedEventTypes, input.payloads) } : {},
458
+ ...input.strategy !== void 0 ? { strategy: input.strategy } : {},
459
+ ...input.fillModel !== void 0 ? { fillModel: input.fillModel } : {},
460
+ ...input.groups !== void 0 ? { groups: input.groups } : {},
234
461
  attempts: [],
235
462
  temperature: input.temperature,
236
463
  maxOutputTokens: input.maxOutputTokens,
@@ -315,6 +542,9 @@ function createDecisionLogic(config, execute) {
315
542
  type,
316
543
  toolName: sanitizeEventToolName(type)
317
544
  })),
545
+ ...config.strategy !== void 0 ? { strategy: config.strategy } : {},
546
+ ...config.fillModel !== void 0 ? { fillModel: config.fillModel } : {},
547
+ ...config.groups !== void 0 ? { groups: config.groups } : {},
318
548
  attempts: [],
319
549
  temperature: require_event_log.resolveTextLogicValue(config.temperature, args),
320
550
  maxOutputTokens: require_event_log.resolveTextLogicValue(config.maxOutputTokens, args),
@@ -466,8 +696,11 @@ function renderDecisionAttempts(request) {
466
696
  * ```
467
697
  */
468
698
  async function resolveDecision(request, executors, options = {}) {
469
- const executor = executors?.decide;
470
- if (typeof executor !== "function") throw new require_event_log.AgentError("missing-decide-executor", "resolveDecision(request, executors, ...) takes the EXECUTOR SET (the same object executeAgentRequest takes), and this one has no 'decide' function. Build one with createAiSdkExecutors({ models }), or pass { decide }.");
699
+ if (typeof executors?.decide !== "function") throw new require_event_log.AgentError("missing-decide-executor", "resolveDecision(request, executors, ...) takes the EXECUTOR SET (the same object executeAgentRequest takes), and this one has no 'decide' function. Build one with createAiSdkExecutors({ models }), or pass { decide }.");
700
+ const executor = withDecisionStrategy(request, {
701
+ decide: executors.decide,
702
+ ...executors.generateText ? { generateText: executors.generateText } : {}
703
+ });
471
704
  const maxRetries = options.maxRetries ?? 2;
472
705
  const attempts = [];
473
706
  const eventsByType = new Map(request.events.map((event) => [event.type, event]));
@@ -484,7 +717,8 @@ async function resolveDecision(request, executors, options = {}) {
484
717
  attempts: [...attempts]
485
718
  }, {
486
719
  ...options.signal !== void 0 ? { signal: options.signal } : {},
487
- ...request.id ? { requestId: request.id } : {}
720
+ ...request.id ? { requestId: request.id } : {},
721
+ ...options.callKey !== void 0 ? { callKey: `${options.callKey}.${attempt}` } : {}
488
722
  });
489
723
  const rejected = result?.rejected;
490
724
  if (rejected !== void 0) {
@@ -558,6 +792,18 @@ Object.defineProperty(exports, "AgentInvalidEventPayloadError", {
558
792
  return AgentInvalidEventPayloadError;
559
793
  }
560
794
  });
795
+ Object.defineProperty(exports, "GROUPED_EVENT_THRESHOLD", {
796
+ enumerable: true,
797
+ get: function() {
798
+ return GROUPED_EVENT_THRESHOLD;
799
+ }
800
+ });
801
+ Object.defineProperty(exports, "MAX_FINITE_PAYLOADS", {
802
+ enumerable: true,
803
+ get: function() {
804
+ return MAX_FINITE_PAYLOADS;
805
+ }
806
+ });
561
807
  Object.defineProperty(exports, "acceptedDecisionOptions", {
562
808
  enumerable: true,
563
809
  get: function() {
@@ -618,12 +864,24 @@ Object.defineProperty(exports, "parseAgentEvent", {
618
864
  return parseAgentEvent;
619
865
  }
620
866
  });
867
+ Object.defineProperty(exports, "payloadNeedsFillModel", {
868
+ enumerable: true,
869
+ get: function() {
870
+ return payloadNeedsFillModel;
871
+ }
872
+ });
621
873
  Object.defineProperty(exports, "renderDecisionAttempts", {
622
874
  enumerable: true,
623
875
  get: function() {
624
876
  return renderDecisionAttempts;
625
877
  }
626
878
  });
879
+ Object.defineProperty(exports, "resolveAllowedEventTypes", {
880
+ enumerable: true,
881
+ get: function() {
882
+ return resolveAllowedEventTypes;
883
+ }
884
+ });
627
885
  Object.defineProperty(exports, "resolveDecision", {
628
886
  enumerable: true,
629
887
  get: function() {
@@ -1,4 +1,4 @@
1
- import { E as DECIDE_ACTOR, U as executorBoundLogics, V as resolveTextLogicValue, W as getAgentExecutionOptions, ct as validateSchemaSync, d as canonicalEventJson, ft as isRecord, pt as AgentError, st as userMessage } from "./event-log-C7jeH0y8.mjs";
1
+ import { G as executorBoundLogics, K as getAgentExecutionOptions, O as DECIDE_ACTOR, U as resolveTextLogicValue, d as canonicalEventJson, et as getJsonSchemaSync, ht as AgentError, lt as userMessage, mt as isRecord, ut as validateSchemaSync } from "./event-log-DkVlk3Rh.mjs";
2
2
  import { createAsyncLogic, getNextTransitions } from "xstate";
3
3
  //#region src/events.ts
4
4
  /**
@@ -167,6 +167,230 @@ function getHumanEventTypes(snapshot) {
167
167
  }
168
168
  const humanEventTypesBySnapshot = /* @__PURE__ */ new WeakMap();
169
169
  //#endregion
170
+ //#region src/decision-strategy.ts
171
+ /** Above this many candidate events, `'auto'` groups them (when two groups or more exist). */
172
+ const GROUPED_EVENT_THRESHOLD = 24;
173
+ /** The most payloads a finite payload schema may enumerate to be filled by a closed choice. */
174
+ const MAX_FINITE_PAYLOADS = 32;
175
+ /** The strategy `'auto'` resolves to for this request. @internal */
176
+ function resolveDecisionStrategy(request) {
177
+ const strategy = request.strategy ?? "auto";
178
+ if (strategy !== "auto") return strategy;
179
+ if (request.fillModel !== void 0) return "pick-then-fill";
180
+ if (candidateTypes(request).length > 24 && decisionGroups(request).length >= 2) return "grouped";
181
+ return "direct";
182
+ }
183
+ /**
184
+ * Every payload a JSON Schema allows, when each required field is finite (an
185
+ * `enum`, a `const`, a boolean, or a union of those) and they number at most
186
+ * {@link MAX_FINITE_PAYLOADS}. Optional fields are left out when finite; an
187
+ * optional open field makes the schema open. `undefined` when open. @internal
188
+ */
189
+ function enumerateFinitePayloads(jsonSchema) {
190
+ if (!jsonSchema) return void 0;
191
+ const union = jsonSchema.anyOf ?? jsonSchema.oneOf;
192
+ if (Array.isArray(union) && union.length > 0) {
193
+ const variants = union.map((variant) => isRecord(variant) ? enumerateFinitePayloads(variant) : void 0);
194
+ if (variants.some((variant) => variant === void 0)) return void 0;
195
+ const payloads = variants.flatMap((variant) => variant ?? []);
196
+ return payloads.length <= 32 ? payloads : void 0;
197
+ }
198
+ if (jsonSchema.allOf !== void 0 || jsonSchema.type !== void 0 && jsonSchema.type !== "object" || jsonSchema.type !== "object" && !isRecord(jsonSchema.properties)) return;
199
+ const properties = isRecord(jsonSchema.properties) ? jsonSchema.properties : {};
200
+ const required = new Set(Array.isArray(jsonSchema.required) ? jsonSchema.required : []);
201
+ let payloads = [{}];
202
+ for (const [key, property] of Object.entries(properties)) {
203
+ const values = finiteValues(property);
204
+ if (values === void 0) return void 0;
205
+ if (!required.has(key)) continue;
206
+ if (payloads.length * values.length > 32) return void 0;
207
+ payloads = payloads.flatMap((payload) => values.map((value) => ({
208
+ ...payload,
209
+ [key]: value
210
+ })));
211
+ }
212
+ return payloads;
213
+ }
214
+ function finiteValues(schema) {
215
+ if (!isRecord(schema)) return void 0;
216
+ if ("const" in schema) return [schema.const];
217
+ if (Array.isArray(schema.enum)) return schema.enum;
218
+ if (schema.type === "boolean") return [true, false];
219
+ const union = schema.anyOf ?? schema.oneOf;
220
+ if (Array.isArray(union) && union.length > 0) {
221
+ const values = union.map(finiteValues);
222
+ return values.every((value) => value !== void 0) ? values.flat() : void 0;
223
+ }
224
+ }
225
+ /**
226
+ * Whether an event's payload needs an open fill (a `fillModel`): it has a
227
+ * schema with fields, and they are not finite. @internal
228
+ */
229
+ function payloadNeedsFillModel(jsonSchema) {
230
+ if (!jsonSchema) return false;
231
+ return enumerateFinitePayloads(jsonSchema) === void 0;
232
+ }
233
+ function candidateTypes(request) {
234
+ const types = request.options ? request.options.map((option) => option.event.type) : request.events.map((event) => event.type);
235
+ return [...new Set(types)];
236
+ }
237
+ /**
238
+ * The non-empty groups over the request's candidate types: the explicit
239
+ * `groups` (members not among the candidates dropped), then every remaining
240
+ * type grouped by its prefix before the first `.`. @internal
241
+ */
242
+ function decisionGroups(request) {
243
+ const types = candidateTypes(request);
244
+ const groups = /* @__PURE__ */ new Map();
245
+ const grouped = /* @__PURE__ */ new Set();
246
+ for (const [name, members] of Object.entries(request.groups ?? {})) {
247
+ const present = types.filter((type) => members.includes(type) && !grouped.has(type));
248
+ for (const type of present) grouped.add(type);
249
+ if (present.length) groups.set(name, present);
250
+ }
251
+ for (const type of types) {
252
+ if (grouped.has(type)) continue;
253
+ const name = type.includes(".") ? type.slice(0, type.indexOf(".")) : type;
254
+ groups.set(name, [...groups.get(name) ?? [], type]);
255
+ }
256
+ return [...groups].map(([name, members]) => ({
257
+ name,
258
+ types: members
259
+ }));
260
+ }
261
+ function subInfo(info, role) {
262
+ return {
263
+ ...info,
264
+ ...info?.callKey !== void 0 ? { callKey: `${info.callKey}.${role}` } : {}
265
+ };
266
+ }
267
+ function choiceRequest(request, choices) {
268
+ const { withheld: _withheld, ...rest } = request;
269
+ return {
270
+ ...rest,
271
+ events: choices.map(({ name }) => ({
272
+ type: name,
273
+ toolName: sanitizeEventToolName(name)
274
+ })),
275
+ options: choices.map(({ name, description }) => ({
276
+ event: { type: name },
277
+ ...description !== void 0 ? { description } : {}
278
+ }))
279
+ };
280
+ }
281
+ function narrowRequest(request, types) {
282
+ return {
283
+ ...request,
284
+ events: request.events.filter((event) => types.includes(event.type)),
285
+ ...request.options ? { options: request.options.filter((option) => types.includes(option.event.type)) } : {}
286
+ };
287
+ }
288
+ /**
289
+ * Wraps a decide executor so one call answers the request with its strategy
290
+ * (see {@link DecisionStrategy}): it makes the strategy's sub-calls and returns
291
+ * ONE `{ event }` or `{ rejected }`, which `resolveDecision` validates and
292
+ * retries like any answer. Every sub-call gets the request's `attempts`, and
293
+ * `info.callKey` suffixed with `.pick`, `.group`, or `.fill`. `'direct'`
294
+ * returns `executors.decide` itself. @internal
295
+ */
296
+ function withDecisionStrategy(request, executors) {
297
+ const strategy = resolveDecisionStrategy(request);
298
+ if (strategy === "direct") return executors.decide;
299
+ return strategy === "grouped" ? groupedDecide(executors) : pickThenFillDecide(executors);
300
+ }
301
+ function groupedDecide({ decide }) {
302
+ return async (request, info) => {
303
+ const groups = decisionGroups(request);
304
+ if (groups.length < 2) return decide(request, info);
305
+ const picked = await decide(choiceRequest(request, groups.map(({ name, types }) => ({
306
+ name,
307
+ description: `One of: ${types.join(", ")}`
308
+ }))), subInfo(info, "group"));
309
+ if (picked.rejected) return picked;
310
+ const group = groups.find(({ name }) => name === picked.event.type);
311
+ if (!group) return { rejected: {
312
+ failure: "unknown-event",
313
+ reason: `'${picked.event.type}' is not a group: ${groups.map(({ name }) => name).join(", ")}.`
314
+ } };
315
+ return decide(narrowRequest(request, group.types), subInfo(info, "pick"));
316
+ };
317
+ }
318
+ function pickThenFillDecide(executors) {
319
+ return async (request, info) => {
320
+ const types = candidateTypes(request);
321
+ const descriptions = new Map((request.options ?? []).filter((option) => Object.keys(option.event).length === 1 && option.description).map((option) => [option.event.type, option.description]));
322
+ let type;
323
+ if (types.length === 1) type = types[0];
324
+ else {
325
+ const picked = await executors.decide(choiceRequest(request, types.map((name) => ({
326
+ name,
327
+ description: descriptions.get(name)
328
+ }))), subInfo(info, "pick"));
329
+ if (picked.rejected) return picked;
330
+ if (!types.includes(picked.event.type)) return { rejected: {
331
+ failure: "unknown-event",
332
+ reason: `'${picked.event.type}' is not among the currently allowed events: ${types.join(", ")}.`,
333
+ event: picked.event
334
+ } };
335
+ type = picked.event.type;
336
+ }
337
+ return fill(request, type, executors, info);
338
+ };
339
+ }
340
+ async function fill(request, type, { decide, generateText }, info) {
341
+ const narrowed = narrowRequest(request, [type]);
342
+ const descriptor = narrowed.events[0];
343
+ let options = narrowed.options;
344
+ if (!options) {
345
+ const payloads = descriptor?.inputSchema ? enumerateFinitePayloads(getJsonSchemaSync(descriptor.inputSchema)) : [{}];
346
+ if (payloads) options = payloads.map((payload) => ({ event: {
347
+ ...payload,
348
+ type
349
+ } }));
350
+ }
351
+ if (options) {
352
+ if (options.length === 1) return { event: options[0].event };
353
+ return decide({
354
+ ...narrowed,
355
+ options
356
+ }, subInfo(info, "fill"));
357
+ }
358
+ return fillWithModel(narrowed, descriptor, generateText, info);
359
+ }
360
+ async function fillWithModel(request, descriptor, generateText, info) {
361
+ if (request.fillModel === void 0) throw new AgentError("missing-fill-model", `Decision '${request.name}' uses strategy 'pick-then-fill', but '${descriptor.type}' has open payload fields and no \`fillModel\` is set to fill them. Set \`fillModel\`, enumerate the payloads with \`payloads\`, or use strategy 'direct'.`);
362
+ if (!generateText) throw new AgentError("missing-fill-executor", `Decision '${request.name}' fills '${descriptor.type}' with fillModel '${request.fillModel}', which needs a 'generateText' executor; none was provided.`);
363
+ const instruction = `You chose '${descriptor.type}'. Write its payload.`;
364
+ const feedback = request.attempts.map((attempt) => userMessage(`Your previous choice failed: ${attempt.reason}`));
365
+ const payload = (await generateText({
366
+ name: request.name,
367
+ ...request.input !== void 0 ? { input: request.input } : {},
368
+ model: request.fillModel,
369
+ ...request.system !== void 0 ? { system: request.system } : {},
370
+ ...request.messages ? { messages: [
371
+ ...request.messages,
372
+ ...feedback,
373
+ userMessage(instruction)
374
+ ] } : { prompt: [
375
+ request.prompt,
376
+ ...feedback.map((message) => message.content),
377
+ instruction
378
+ ].filter((part) => part !== void 0).join("\n\n") },
379
+ outputSchema: descriptor.inputSchema,
380
+ tools: {},
381
+ ...request.metadata !== void 0 ? { metadata: request.metadata } : {}
382
+ }, subInfo(info, "fill"))).result;
383
+ if (!isRecord(payload)) return { rejected: {
384
+ failure: "invalid-payload",
385
+ reason: `'${descriptor.type}' payload must be an object; got ${JSON.stringify(payload)}.`,
386
+ event: { type: descriptor.type }
387
+ } };
388
+ return { event: {
389
+ ...payload,
390
+ type: descriptor.type
391
+ } };
392
+ }
393
+ //#endregion
170
394
  //#region src/decision.ts
171
395
  function optionsFromPayloads(eventTypes, payloads) {
172
396
  return eventTypes.filter((type) => !isEventPattern(type)).flatMap((type) => (payloads[type] ?? [{}]).map((payload) => ({ event: {
@@ -231,6 +455,9 @@ function decideRequestFromInput(input) {
231
455
  toolName: sanitizeEventToolName(type)
232
456
  })),
233
457
  ...input.payloads ? { options: optionsFromPayloads(allowedEventTypes, input.payloads) } : {},
458
+ ...input.strategy !== void 0 ? { strategy: input.strategy } : {},
459
+ ...input.fillModel !== void 0 ? { fillModel: input.fillModel } : {},
460
+ ...input.groups !== void 0 ? { groups: input.groups } : {},
234
461
  attempts: [],
235
462
  temperature: input.temperature,
236
463
  maxOutputTokens: input.maxOutputTokens,
@@ -315,6 +542,9 @@ function createDecisionLogic(config, execute) {
315
542
  type,
316
543
  toolName: sanitizeEventToolName(type)
317
544
  })),
545
+ ...config.strategy !== void 0 ? { strategy: config.strategy } : {},
546
+ ...config.fillModel !== void 0 ? { fillModel: config.fillModel } : {},
547
+ ...config.groups !== void 0 ? { groups: config.groups } : {},
318
548
  attempts: [],
319
549
  temperature: resolveTextLogicValue(config.temperature, args),
320
550
  maxOutputTokens: resolveTextLogicValue(config.maxOutputTokens, args),
@@ -466,8 +696,11 @@ function renderDecisionAttempts(request) {
466
696
  * ```
467
697
  */
468
698
  async function resolveDecision(request, executors, options = {}) {
469
- const executor = executors?.decide;
470
- if (typeof executor !== "function") throw new AgentError("missing-decide-executor", "resolveDecision(request, executors, ...) takes the EXECUTOR SET (the same object executeAgentRequest takes), and this one has no 'decide' function. Build one with createAiSdkExecutors({ models }), or pass { decide }.");
699
+ if (typeof executors?.decide !== "function") throw new AgentError("missing-decide-executor", "resolveDecision(request, executors, ...) takes the EXECUTOR SET (the same object executeAgentRequest takes), and this one has no 'decide' function. Build one with createAiSdkExecutors({ models }), or pass { decide }.");
700
+ const executor = withDecisionStrategy(request, {
701
+ decide: executors.decide,
702
+ ...executors.generateText ? { generateText: executors.generateText } : {}
703
+ });
471
704
  const maxRetries = options.maxRetries ?? 2;
472
705
  const attempts = [];
473
706
  const eventsByType = new Map(request.events.map((event) => [event.type, event]));
@@ -484,7 +717,8 @@ async function resolveDecision(request, executors, options = {}) {
484
717
  attempts: [...attempts]
485
718
  }, {
486
719
  ...options.signal !== void 0 ? { signal: options.signal } : {},
487
- ...request.id ? { requestId: request.id } : {}
720
+ ...request.id ? { requestId: request.id } : {},
721
+ ...options.callKey !== void 0 ? { callKey: `${options.callKey}.${attempt}` } : {}
488
722
  });
489
723
  const rejected = result?.rejected;
490
724
  if (rejected !== void 0) {
@@ -546,4 +780,4 @@ async function resolveDecision(request, executors, options = {}) {
546
780
  throw new AgentDecisionExhaustedError(attempts);
547
781
  }
548
782
  //#endregion
549
- export { createDecisionRequest as a, renderDecisionAttempts as c, getAcceptedEvents as d, getHumanEventTypes as f, createDecisionLogic as i, resolveDecision as l, parseAgentEvent as m, acceptedDecisionOptions as n, decisionOptionIds as o, isEventPattern as p, createDecideActor as r, isDecisionLogic as s, AgentDecisionExhaustedError as t, AgentInvalidEventPayloadError as u };
783
+ export { isEventPattern as _, createDecisionRequest as a, renderDecisionAttempts as c, GROUPED_EVENT_THRESHOLD as d, MAX_FINITE_PAYLOADS as f, getHumanEventTypes as g, getAcceptedEvents as h, createDecisionLogic as i, resolveAllowedEventTypes as l, AgentInvalidEventPayloadError as m, acceptedDecisionOptions as n, decisionOptionIds as o, payloadNeedsFillModel as p, createDecideActor as r, isDecisionLogic as s, AgentDecisionExhaustedError as t, resolveDecision as u, parseAgentEvent as v };
@@ -0,0 +1,15 @@
1
+ import { L as AgentDecisionRequest } from "./text-logic-BqxalgMr.mjs";
2
+ //#region src/internal/decision-object.d.ts
3
+ /**
4
+ * How a decide executor asks a language model for its one event:
5
+ * - `'object'` (default for compatible payloads): ONE structured-output object, `{ event: { type, ...payload } }`
6
+ * (or `{ choice: id }` for a closed choice). Exactly one answer by construction.
7
+ * - `'tool'`: one tool per candidate event under a forced tool choice. Parallel
8
+ * calls are turned off where the provider allows it, and an answer that still
9
+ * calls more than one tool is rejected and retried.
10
+ */
11
+ type DecisionMode = "object" | "tool";
12
+ /** A host's `decideMode` option: one mode, or one per request. @internal */
13
+ type DecisionModeOption = DecisionMode | ((request: AgentDecisionRequest) => DecisionMode | undefined);
14
+ //#endregion
15
+ export { DecisionModeOption as n, DecisionMode as t };
@@ -0,0 +1,15 @@
1
+ import { L as AgentDecisionRequest } from "./text-logic-CSf9bqpP.cjs";
2
+ //#region src/internal/decision-object.d.ts
3
+ /**
4
+ * How a decide executor asks a language model for its one event:
5
+ * - `'object'` (default for compatible payloads): ONE structured-output object, `{ event: { type, ...payload } }`
6
+ * (or `{ choice: id }` for a closed choice). Exactly one answer by construction.
7
+ * - `'tool'`: one tool per candidate event under a forced tool choice. Parallel
8
+ * calls are turned off where the provider allows it, and an answer that still
9
+ * calls more than one tool is rejected and retried.
10
+ */
11
+ type DecisionMode = "object" | "tool";
12
+ /** A host's `decideMode` option: one mode, or one per request. @internal */
13
+ type DecisionModeOption = DecisionMode | ((request: AgentDecisionRequest) => DecisionMode | undefined);
14
+ //#endregion
15
+ export { DecisionModeOption as n, DecisionMode as t };