@statelyai/agent 2.0.0-alpha.35 → 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 +111 -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 +399 -20
  53. package/dist/testing.d.cts +196 -255
  54. package/dist/testing.d.mts +196 -255
  55. package/dist/testing.mjs +395 -20
  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 -192
  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
package/dist/index.cjs CHANGED
@@ -1,10 +1,12 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_event_log = require("./event-log-BWSSLUff.cjs");
3
- const require_decision = require("./decision-BEsATcr1.cjs");
4
- const require_setup_agent = require("./setup-agent-CXEBURdo.cjs");
5
- const require_event_log_store = require("./event-log-store-CleWpsp5.cjs");
6
- const require_run_agent = require("./run-agent-s5D32w99.cjs");
2
+ const require_event_log = require("./event-log-Dkc-yIYu.cjs");
3
+ const require_decision = require("./decision-CMeuNZ1g.cjs");
4
+ const require_act = require("./act-CrX0JwWY.cjs");
5
+ const require_setup_agent = require("./setup-agent-CmEToB8y.cjs");
6
+ const require_effects = require("./effects-B23bFZEs.cjs");
7
+ const require_event_log_store = require("./event-log-store-Cl-YWDnq.cjs");
7
8
  let xstate = require("xstate");
9
+ let acorn = require("acorn");
8
10
  //#region src/messages.ts
9
11
  const KNOWN_PART_TYPES = /* @__PURE__ */ new Set([
10
12
  "text",
@@ -330,6 +332,268 @@ function eventFromInteraction(snapshot, choice) {
330
332
  return require_decision.parseAgentEvent(snapshot, event, { events: eventSchemasOf(snapshot) });
331
333
  }
332
334
  //#endregion
335
+ //#region src/internal/transition-source.ts
336
+ /**
337
+ * Reads a transition function's source (`String(fn)`, already JavaScript) with
338
+ * a real parser, so what it returns is read from its syntax tree: every path
339
+ * through ternaries, `&&`/`||`, early returns and local constants.
340
+ *
341
+ * @module
342
+ */
343
+ const isNode = (value) => typeof value === "object" && value !== null && typeof value.type === "string";
344
+ const FUNCTION_TYPES = /* @__PURE__ */ new Set([
345
+ "ArrowFunctionExpression",
346
+ "FunctionExpression",
347
+ "FunctionDeclaration"
348
+ ]);
349
+ /** The function in `code`: an arrow, a function expression, or a method (`GO({ context }) { … }`). */
350
+ function parseFunction(code) {
351
+ for (const text of [`(${code})`, `({${code}})`]) {
352
+ let program;
353
+ try {
354
+ program = (0, acorn.parse)(text, { ecmaVersion: "latest" });
355
+ } catch {
356
+ continue;
357
+ }
358
+ let expression = program.body?.[0]?.expression;
359
+ if (expression?.type === "ObjectExpression") expression = expression.properties?.[0]?.value;
360
+ if (expression && FUNCTION_TYPES.has(expression.type)) return {
361
+ fn: expression,
362
+ text
363
+ };
364
+ }
365
+ }
366
+ /** Calls `visit` on every node under `node`, without entering nested functions unless `deep`. */
367
+ function walk(node, visit, deep = false) {
368
+ for (const [key, value] of Object.entries(node)) {
369
+ if (key === "start" || key === "end") continue;
370
+ for (const child of Array.isArray(value) ? value : [value]) {
371
+ if (!isNode(child)) continue;
372
+ visit(child);
373
+ if (deep || !FUNCTION_TYPES.has(child.type)) walk(child, visit, deep);
374
+ }
375
+ }
376
+ }
377
+ const DECLINE = Symbol("decline");
378
+ const UNKNOWN = Symbol("unknown");
379
+ function scopeOf(fn, text) {
380
+ const declared = /* @__PURE__ */ new Map();
381
+ const assigned = /* @__PURE__ */ new Set();
382
+ walk(fn.body, (node) => {
383
+ if (node.type === "VariableDeclarator" && node.id.type === "Identifier") declared.set(node.id.name, declared.has(node.id.name) ? null : node.init ?? null);
384
+ });
385
+ walk(fn.body, (node) => {
386
+ if (node.type === "AssignmentExpression") {
387
+ const name = rootName(node.left);
388
+ if (name) assigned.add(name);
389
+ } else if (node.type === "UpdateExpression") {
390
+ const name = rootName(node.argument);
391
+ if (name) assigned.add(name);
392
+ } else if (node.type === "UnaryExpression" && node.operator === "delete") {
393
+ const name = rootName(node.argument);
394
+ if (name) assigned.add(name);
395
+ } else if (node.type === "CallExpression") {
396
+ for (const argument of node.arguments) if (argument.type === "Identifier") assigned.add(argument.name);
397
+ const name = node.callee.type === "MemberExpression" ? rootName(node.callee.object) : void 0;
398
+ if (name) assigned.add(name);
399
+ }
400
+ }, true);
401
+ const constants = /* @__PURE__ */ new Map();
402
+ for (const [name, init] of declared) if (init && !assigned.has(name)) constants.set(name, init);
403
+ const kept = /* @__PURE__ */ new Set(["context"]);
404
+ const param = fn.params?.[0];
405
+ const binding = param?.type === "AssignmentPattern" ? param.left : param;
406
+ if (binding?.type === "Identifier") kept.add(`${binding.name}.context`);
407
+ if (binding?.type === "ObjectPattern") for (const property of binding.properties) {
408
+ if (property.type !== "Property" || keyName(property) !== "context") continue;
409
+ const value = property.value.type === "AssignmentPattern" ? property.value.left : property.value;
410
+ if (value.type === "Identifier") kept.add(value.name);
411
+ }
412
+ return {
413
+ text,
414
+ constants,
415
+ kept
416
+ };
417
+ }
418
+ /** The variable a reference starts from: `t` in `t`, `t.target`, `t[k].x`. */
419
+ function rootName(node) {
420
+ let current = node;
421
+ while (current.type === "MemberExpression") current = current.object;
422
+ return current.type === "Identifier" ? current.name : void 0;
423
+ }
424
+ const keyName = (property) => property.computed ? void 0 : property.key.type === "Identifier" ? property.key.name : typeof property.key.value === "string" ? property.key.value : void 0;
425
+ const sourceOf = (scope, node) => scope.text.slice(node.start, node.end).replace(/\s+/g, " ");
426
+ /** Every value `node` can evaluate to, through ternaries, `&&`/`||`/`??` and local constants. */
427
+ function values(node, scope, depth = 0) {
428
+ if (depth > 20) return [UNKNOWN];
429
+ switch (node.type) {
430
+ case "ConditionalExpression": return [...values(node.consequent, scope, depth + 1), ...values(node.alternate, scope, depth + 1)];
431
+ case "LogicalExpression": return node.operator === "&&" ? [DECLINE, ...values(node.right, scope, depth + 1)] : [...values(node.left, scope, depth + 1), ...values(node.right, scope, depth + 1)];
432
+ case "SequenceExpression": return values(node.expressions.at(-1), scope, depth + 1);
433
+ case "Literal": return node.value === null ? [DECLINE] : [node];
434
+ case "UnaryExpression": return node.operator === "void" ? [DECLINE] : [UNKNOWN];
435
+ case "Identifier": {
436
+ if (node.name === "undefined") return [DECLINE];
437
+ const init = scope.constants.get(node.name);
438
+ return init ? values(init, scope, depth + 1) : [UNKNOWN];
439
+ }
440
+ case "ObjectExpression":
441
+ case "TemplateLiteral": return [node];
442
+ default: return [UNKNOWN];
443
+ }
444
+ }
445
+ /** Every value the function returns, including `undefined` when its body can fall through. */
446
+ function returnedValues(fn, scope) {
447
+ if (fn.body.type !== "BlockStatement") return values(fn.body, scope);
448
+ const returned = [];
449
+ walk(fn.body, (node) => {
450
+ if (node.type !== "ReturnStatement") return;
451
+ if (node.argument) returned.push(...values(node.argument, scope));
452
+ else returned.push(DECLINE);
453
+ });
454
+ if (completes(fn.body)) returned.push(DECLINE);
455
+ return returned;
456
+ }
457
+ /** True when control can run past the end of `node` (so the function may return nothing). */
458
+ function completes(node) {
459
+ if (!node) return true;
460
+ switch (node.type) {
461
+ case "ReturnStatement":
462
+ case "ThrowStatement": return false;
463
+ case "BlockStatement": return node.body.every(completes);
464
+ case "IfStatement": return !node.alternate || completes(node.consequent) || completes(node.alternate);
465
+ case "TryStatement":
466
+ if (node.finalizer && !completes(node.finalizer)) return false;
467
+ return completes(node.block) || (node.handler ? completes(node.handler.body) : false);
468
+ case "SwitchStatement":
469
+ if (!node.cases.some((c) => c.test === null)) return true;
470
+ if (breaksOut(node)) return true;
471
+ return (node.cases.at(-1)?.consequent ?? []).every(completes);
472
+ default: return true;
473
+ }
474
+ }
475
+ /** True when a `break` inside this switch (not in a nested loop or switch) leaves it. */
476
+ function breaksOut(node) {
477
+ let found = false;
478
+ const visit = (child) => {
479
+ if (found || FUNCTION_TYPES.has(child.type)) return;
480
+ if (child.type === "BreakStatement" && !child.label) {
481
+ found = true;
482
+ return;
483
+ }
484
+ if (/^(For|ForIn|ForOf|While|DoWhile|Switch)Statement$/.test(child.type)) return;
485
+ for (const [key, value] of Object.entries(child)) {
486
+ if (key === "start" || key === "end") continue;
487
+ for (const item of Array.isArray(value) ? value : [value]) if (isNode(item)) visit(item);
488
+ }
489
+ };
490
+ for (const c of node.cases) for (const statement of c.consequent) visit(statement);
491
+ return found;
492
+ }
493
+ /** The literal string a node holds, if it is one: `"done"`, `` `done` ``. */
494
+ function literalString(node) {
495
+ if (node.type === "Literal" && typeof node.value === "string") return node.value;
496
+ if (node.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0]?.value.cooked ?? void 0;
497
+ }
498
+ /** The keys an object sets: its own, plus `…name` for a spread of anything but the current context. */
499
+ function objectKeys(node, scope, keys, depth = 0) {
500
+ for (const value of values(node, scope, depth)) {
501
+ if (value === DECLINE) continue;
502
+ if (value === UNKNOWN || value.type !== "ObjectExpression") {
503
+ const text = value === UNKNOWN ? sourceOf(scope, node) : sourceOf(scope, value);
504
+ if (!scope.kept.has(text)) keys.add(`…${text}`);
505
+ continue;
506
+ }
507
+ for (const property of value.properties) {
508
+ if (property.type === "SpreadElement") {
509
+ const text = sourceOf(scope, property.argument);
510
+ if (!scope.kept.has(text)) keys.add(`…${text}`);
511
+ continue;
512
+ }
513
+ keys.add(keyName(property) ?? `[${sourceOf(scope, property.key)}]`);
514
+ }
515
+ }
516
+ }
517
+ /**
518
+ * The expression an object literal's `target` ends up as, with later
519
+ * properties and spreads overriding earlier ones: `undefined` when it sets
520
+ * none, `UNKNOWN` when a spread that cannot be read may set it.
521
+ */
522
+ function targetOf(object, scope, depth = 0) {
523
+ let target;
524
+ for (const property of object.properties) {
525
+ if (property.type === "Property") {
526
+ if (keyName(property) === "target") target = property.value;
527
+ continue;
528
+ }
529
+ const spread = depth < 20 ? values(property.argument, scope, depth + 1) : [UNKNOWN];
530
+ if (spread.length !== 1) {
531
+ target = UNKNOWN;
532
+ continue;
533
+ }
534
+ const only = spread[0];
535
+ if (only === DECLINE) continue;
536
+ if (only === UNKNOWN || only.type !== "ObjectExpression") target = UNKNOWN;
537
+ else target = targetOf(only, scope, depth + 1) ?? target;
538
+ }
539
+ return target;
540
+ }
541
+ /**
542
+ * Reads a transition function: where each of its return paths goes and what
543
+ * context it sets. `undefined` when the source does not parse.
544
+ */
545
+ function readTransitionSource(code) {
546
+ const parsed = parseFunction(code);
547
+ if (!parsed) return void 0;
548
+ const scope = scopeOf(parsed.fn, parsed.text);
549
+ const result = {
550
+ targets: [],
551
+ unknown: false,
552
+ stays: false,
553
+ declines: false,
554
+ context: []
555
+ };
556
+ const targets = /* @__PURE__ */ new Set();
557
+ const context = /* @__PURE__ */ new Set();
558
+ for (const value of returnedValues(parsed.fn, scope)) {
559
+ if (value === DECLINE) {
560
+ result.declines = true;
561
+ continue;
562
+ }
563
+ if (value === UNKNOWN || value.type !== "ObjectExpression") {
564
+ result.unknown = true;
565
+ continue;
566
+ }
567
+ const target = targetOf(value, scope);
568
+ if (target === void 0) result.stays = true;
569
+ else if (target === UNKNOWN) result.unknown = true;
570
+ else for (const option of values(target, scope)) {
571
+ const literal = option === DECLINE || option === UNKNOWN ? void 0 : literalString(option);
572
+ if (literal !== void 0) targets.add(literal);
573
+ else if (option === DECLINE) result.stays = true;
574
+ else result.unknown = true;
575
+ }
576
+ const patch = value.properties.find((property) => property.type === "Property" && keyName(property) === "context");
577
+ if (patch) objectKeys(patch.value, scope, context);
578
+ }
579
+ result.targets = [...targets];
580
+ result.context = [...context];
581
+ return result;
582
+ }
583
+ /** The keys a context function (`({ context }) => ({ … })`) returns. `undefined` when it does not parse. */
584
+ function readContextSource(code) {
585
+ const parsed = parseFunction(code);
586
+ if (!parsed) return void 0;
587
+ const scope = scopeOf(parsed.fn, parsed.text);
588
+ const keys = /* @__PURE__ */ new Set();
589
+ for (const value of returnedValues(parsed.fn, scope)) {
590
+ if (value === DECLINE) continue;
591
+ if (value === UNKNOWN) keys.add("…");
592
+ else objectKeys(value, scope, keys);
593
+ }
594
+ return [...keys];
595
+ }
596
+ //#endregion
333
597
  //#region src/describe-machine.ts
334
598
  /**
335
599
  * A machine, described in plain text for a model to read: the prompt for a
@@ -347,8 +611,12 @@ const toList = (value) => value === void 0 ? [] : Array.isArray(value) ? value :
347
611
  const oneLine = (text) => text.replace(/\s+/g, " ").trim();
348
612
  /** The source of a function as serialized (`{ "@code" }`) or as a live function. */
349
613
  function codeOf(value) {
350
- if (typeof value === "function") return String(value);
351
- if (isObject(value) && typeof value["@code"] === "string") return value["@code"];
614
+ const code = typeof value === "function" ? String(value) : isObject(value) && typeof value["@code"] === "string" ? value["@code"] : void 0;
615
+ return code === void 0 ? void 0 : unbundle(code);
616
+ }
617
+ /** Source as written: vite SSR's named-import rewrites (`(0, __vite_ssr_import_3__.f)`) undone; a default import's `.default` stays, as bare `default` would not parse. */
618
+ function unbundle(code) {
619
+ return code.replace(/\(0,\s*__vite_ssr_import_\d+__\.(?!default\b)([\w$]+)\)/g, "$1").replace(/__vite_ssr_import_\d+__\.(?!default\b)/g, "");
352
620
  }
353
621
  /** The decoded value of a fromConfig `{ "@expr": "<json>" }` slot, or the value itself. */
354
622
  function decodeExpr(value) {
@@ -373,72 +641,14 @@ function resolveTarget(source, target) {
373
641
  }
374
642
  /** A target as said from where the transition starts: a sibling by key, else its path below the machine. */
375
643
  const nameOf = (source, target) => target.parent === source.parent ? target.key : target.path.join(".");
376
- /**
377
- * The keys of the object literal whose `{` is at `open` in `text`, at its top
378
- * level: `a`, `b` for `{ a: 1, b, ...c }`, and `…c` for a spread, whose keys
379
- * cannot be read. Strings, templates and nested brackets are skipped over.
380
- */
381
- function objectKeys(text, open) {
382
- const keys = [];
383
- let depth = 0;
384
- let expectKey = false;
385
- for (let i = open; i < text.length; i++) {
386
- const c = text[i];
387
- if (c === "\"" || c === "'" || c === "`") {
388
- const end = text.indexOf(c, i + 1);
389
- if (end < 0) break;
390
- i = end;
391
- continue;
392
- }
393
- if (c === "{" || c === "(" || c === "[") {
394
- depth++;
395
- if (depth === 1) expectKey = true;
396
- continue;
397
- }
398
- if (c === "}" || c === ")" || c === "]") {
399
- if (--depth === 0) break;
400
- continue;
401
- }
402
- if (depth !== 1) continue;
403
- if (c === ",") {
404
- expectKey = true;
405
- continue;
406
- }
407
- if (expectKey && !/\s/.test(c)) {
408
- expectKey = false;
409
- if (text.startsWith("...", i)) {
410
- const spread = /^\.\.\.\s*([\w$.]+)(\()?/.exec(text.slice(i));
411
- keys.push(`…${spread?.[1] ?? ""}${spread?.[2] ? "()" : ""}`);
412
- continue;
413
- }
414
- const key = /^[A-Za-z_$][\w$]*/.exec(text.slice(i))?.[0];
415
- if (key) {
416
- keys.push(key);
417
- i += key.length - 1;
418
- }
419
- }
420
- }
421
- return keys;
422
- }
423
- /** Every key of each object literal that follows a match of `at` in `code`; `…name` when what follows is not a literal. */
424
- function keysInSource(code, at, keys) {
425
- for (const match of code.matchAll(at)) {
426
- const open = match.index + match[0].length - 1;
427
- if (code[open] === "{") for (const key of objectKeys(code, open)) keys.add(key);
428
- else {
429
- const from = /^[\w$.]+(\()?/.exec(code.slice(open));
430
- keys.add(from ? `…${from[0]}${from[1] ? ")" : ""}` : "…");
431
- }
432
- }
433
- }
434
- /** What a transition sets in context: a declarative patch's keys, or each `context: { … }` in a function's source. */
644
+ /** What a transition sets in context: a declarative patch's keys, or each returned `context` in a function's source. */
435
645
  function contextKeys(transition, code) {
436
646
  const keys = /* @__PURE__ */ new Set();
437
- if (code) keysInSource(code, /\bcontext\s*:\s*[^\s]/g, keys);
647
+ if (code) for (const key of readTransitionSource(code)?.context ?? []) keys.add(key);
438
648
  if (transition) {
439
649
  const context = decodeExpr(transition.context);
440
650
  const contextCode = codeOf(context);
441
- if (contextCode) keysInSource(contextCode, /=>\s*\(\s*\{|\breturn\s*\{/g, keys);
651
+ if (contextCode) for (const key of readContextSource(contextCode) ?? ["…"]) keys.add(key);
442
652
  else if (isObject(context)) for (const key of Object.keys(context)) keys.add(key);
443
653
  for (const action of toList(transition.actions)) if (isObject(action) && action.type === "@xstate.assign") {
444
654
  const assigned = decodeExpr(action.context);
@@ -456,56 +666,25 @@ function guardText(guard) {
456
666
  return "guarded";
457
667
  }
458
668
  /**
459
- * True when a transition function's source has a path that returns no
460
- * transition, so it may not be taken. Matches minified source too: `void 0`
461
- * for `undefined`, and a ternary `?` with no spaces (but not `?.` or `??`).
462
- * String and template literals are blanked first, so their text never counts.
463
- */
464
- const mayDecline = (code) => /\bundefined\b|\bnull\b|\bvoid 0\b|\breturn\s*;|\bif\s*\(|(?<!\?)\?(?![.?])|&&/.test(code.replace(/(["'`])(?:\\.|(?!\1)[^\\])*\1/g, "\"\""));
465
- /**
466
- * True when the function returns a call's result (`=> next(ctx)`, `return
467
- * pick(x)`), so its target is not in its own source. Reads only the
468
- * function's own returned expressions, not those of callbacks nested in it.
469
- */
470
- function returnsCall(code) {
471
- const text = code.replace(/(["'`])(?:\\.|(?!\1)[^\\])*\1/g, "\"\"");
472
- const startsWithCall = (at) => /^[\s(]*[A-Za-z_$][\w$.]*\s*\(/.test(text.slice(at));
473
- let parens = 0;
474
- let body = -1;
475
- for (let i = 0; i < text.length && body < 0; i++) {
476
- const char = text[i];
477
- if (char === "(") parens++;
478
- else if (char === ")") parens--;
479
- else if (parens === 0 && char === "=" && text[i + 1] === ">") body = i + 2;
480
- else if (parens === 0 && char === "{") body = i;
481
- }
482
- if (body < 0) return false;
483
- while (/\s/.test(text[body] ?? "")) body++;
484
- if (text[body] !== "{") return startsWithCall(body);
485
- let depth = 0;
486
- for (let i = body; i < text.length; i++) if (text[i] === "{") depth++;
487
- else if (text[i] === "}" && --depth === 0) return false;
488
- else if (depth === 1 && text.startsWith("return", i) && !/[\w$]/.test(text[i - 1] ?? "") && !/[\w$]/.test(text[i + 6] ?? "") && startsWithCall(i + 6)) return true;
489
- return false;
490
- }
491
- /**
492
- * Where a transition written as a function goes: every string literal after a
493
- * `target:` that names a real state node, `(conditional)` when it may decline
494
- * or pick among several, `(stays)` when its source has no `target`, `?` when
495
- * it names none that resolves or returns a helper call's result.
669
+ * Where a transition written as a function goes, read from its return paths:
670
+ * each literal target (`x ?` when it names no state node), `?` for one the
671
+ * source does not spell out (a variable's value, a helper call's result),
672
+ * `(conditional)` when it may decline, stay, or pick among several, and
673
+ * `(stays)` when no path names a target.
496
674
  */
497
675
  function targetsInSource(source, code, choice) {
498
- const found = /* @__PURE__ */ new Set();
499
- for (const [, expression] of code.matchAll(/\btarget\s*:\s*(\[[^\]]*\]|[^,}\n]+)/g)) for (const [, , literal] of expression.matchAll(/(['"`])([^'"`$]+)\1/g)) {
500
- const node = resolveTarget(source, literal);
501
- if (node) found.add(node);
502
- }
503
- const names = [...found].map((node) => nameOf(source, node));
504
- if (names.length) {
505
- const conditional = names.length > 1 || !choice && mayDecline(code);
506
- return `${names.join(", ")}${conditional ? " (conditional)" : ""}`;
507
- }
508
- return /\btarget\s*:/.test(code) || returnsCall(code) ? "?" : "(stays)";
676
+ const read = readTransitionSource(code);
677
+ if (!read) return "?";
678
+ const names = read.targets.map((target) => {
679
+ const node = resolveTarget(source, target);
680
+ return node ? nameOf(source, node) : `${target} ?`;
681
+ });
682
+ const parts = [...new Set(names)];
683
+ if (read.unknown) parts.push("?");
684
+ if (!parts.length) return "(stays)";
685
+ if (parts.length === 1 && read.unknown) return "?";
686
+ const conditional = parts.length > 1 || !choice && (read.declines || read.stays);
687
+ return `${parts.join(", ")}${conditional ? " (conditional)" : ""}`;
509
688
  }
510
689
  /** One transition, as a line: `on GO (human) if context.ready → review; sets draft — description`. */
511
690
  function transitionLine(source, head, transition, options = {}) {
@@ -548,12 +727,28 @@ function delayText(key, delays) {
548
727
  const delay = delays[key];
549
728
  return typeof delay === "number" ? `${key} (${formatMs(delay)})` : key;
550
729
  }
730
+ /** A transition function's source (or a config transition's context function), dedented, at `pad`. */
731
+ function sourceLines(transition, pad) {
732
+ const code = codeOf(transition) ?? (isObject(transition) ? codeOf(decodeExpr(transition.context)) : void 0);
733
+ if (!code) return [];
734
+ const [first = "", ...rest] = code.split("\n");
735
+ const indent = Math.min(...rest.filter((line) => line.trim()).map((line) => /^\s*/.exec(line)[0].length));
736
+ return [first, ...rest.map((line) => line.slice(Number.isFinite(indent) ? indent : 0))].filter((line) => line.trim()).map((line) => `${pad} | ${line.trimEnd()}`);
737
+ }
551
738
  /** Every transition leaving one state node, as lines at `pad`. */
552
- function transitionLines(node, json, delays, pad) {
739
+ function transitionLines(node, json, delays, pad, source) {
553
740
  const lines = [];
741
+ const line = (head, transition, options) => {
742
+ lines.push(`${pad}${transitionLine(node, head, transition, options)}`);
743
+ if (source) lines.push(...sourceLines(transition, pad));
744
+ };
554
745
  const push = (head, value) => {
555
- for (const transition of toList(value)) lines.push(`${pad}${transitionLine(node, head, transition)}`);
746
+ for (const transition of toList(value)) line(head, transition);
556
747
  };
748
+ if (source) for (const key of ["entry", "exit"]) for (const action of toList(json[key])) {
749
+ const code = sourceLines(action, pad);
750
+ if (code.length) lines.push(`${pad}${key}`, ...code);
751
+ }
557
752
  for (const [event, value] of Object.entries(isObject(json.on) ? json.on : {})) push(event === "xstate.done.state" ? "onDone" : `on ${event}`, value);
558
753
  push("onDone", json.onDone);
559
754
  push("always", json.always);
@@ -568,10 +763,10 @@ function transitionLines(node, json, delays, pad) {
568
763
  }
569
764
  if (json.choice !== void 0) toList(json.choice).forEach((branch, index) => {
570
765
  const head = isObject(branch) && branch.when !== void 0 || index === 0 ? "choice" : "choice else";
571
- lines.push(`${pad}${transitionLine(node, head, branch, {
766
+ line(head, branch, {
572
767
  guardKey: "when",
573
768
  choice: true
574
- })}`);
769
+ });
575
770
  });
576
771
  return lines;
577
772
  }
@@ -628,7 +823,11 @@ function eventLines(machine) {
628
823
  * A transition written as a function shows the targets its source names
629
824
  * (`→ review (conditional)` when it may decline or pick among several),
630
825
  * `(stays)` when its source has no `target`, or `→ ?` when no target can be
631
- * read. A `setupAgent.fromConfig(...)` machine is read from its config, so
826
+ * read (a variable's value, a helper call's result). Function sources are
827
+ * parsed, so every return path counts: ternaries, `&&`/`||`, early returns and
828
+ * local constants. With `source: true`, each function is printed under its
829
+ * line, along with entry and exit actions; pass `helpers` to print the
830
+ * functions they call by name. A `setupAgent.fromConfig(...)` machine is read from its config, so
632
831
  * its targets, guards and context patches are always known.
633
832
  *
634
833
  * @example
@@ -640,10 +839,11 @@ function describeMachine(machine, options = {}) {
640
839
  const json = (0, xstate.machineToJSON)(machine);
641
840
  const delays = isObject(json.delays) ? json.delays : {};
642
841
  const active = new Set(options.snapshot?.nodes.map((node) => node.id) ?? []);
842
+ const source = options.source ?? false;
643
843
  const root = machine.root;
644
844
  const lines = [`Machine ${machine.id}`];
645
845
  if (root.description) lines.push(`Goal: ${root.description.trim()}`);
646
- const rootTransitions = transitionLines(root, json, delays, " ");
846
+ const rootTransitions = transitionLines(root, json, delays, " ", source);
647
847
  if (rootTransitions.length) lines.push("Any state:", ...rootTransitions);
648
848
  const initial = typeof json.initial === "string" ? ` (initial: ${json.initial})` : "";
649
849
  lines.push(`States${initial}${options.snapshot ? " (* = current)" : ""}:`);
@@ -651,7 +851,7 @@ function describeMachine(machine, options = {}) {
651
851
  const pad = " ".repeat(depth);
652
852
  const mark = active.has(node.id) ? `${pad.slice(2)}* ` : pad;
653
853
  lines.push(`${mark}${stateLine(node, nodeJson)}`);
654
- lines.push(...transitionLines(node, nodeJson, delays, `${pad} `));
854
+ lines.push(...transitionLines(node, nodeJson, delays, `${pad} `, source));
655
855
  const childJson = isObject(nodeJson.states) ? nodeJson.states : {};
656
856
  for (const [key, child] of Object.entries(node.states)) walk(child, isObject(childJson[key]) ? childJson[key] : {}, depth + 1);
657
857
  };
@@ -659,152 +859,12 @@ function describeMachine(machine, options = {}) {
659
859
  for (const [key, child] of Object.entries(root.states)) walk(child, isObject(rootStates[key]) ? rootStates[key] : {}, 1);
660
860
  const events = eventLines(machine);
661
861
  if (events.length) lines.push("Events:", ...events);
662
- return lines.join("\n");
663
- }
664
- //#endregion
665
- //#region src/decide-next.ts
666
- /**
667
- * Asks a model to choose the next event for ANY XState snapshot, including a
668
- * machine built with plain `createMachine`/`setup` that knows nothing about AI.
669
- * The candidates are the `allowedEvents` an active state handles, one option per
670
- * payload, kept only where `snapshot.can(event)` is true and no transition
671
- * tagged `meta: { actor: "human" }` handles the type; the rest come back as
672
- * `withheld`. Each option is
673
- * described from the transition's `description`, else the event schema's,
674
- * plus (with `lookahead`) what it changes. The chosen event must equal one
675
- * offered option; anything else is retried.
676
- *
677
- * It never sends. The host sends the event, re-checking `can` first, because
678
- * the actor may have moved while the model was thinking. With no options it
679
- * returns `{ event: null }` without calling the executor. Exhausting retries
680
- * throws `AgentDecisionExhaustedError`.
681
- *
682
- * @example
683
- * ```ts no-check
684
- * let busy = false;
685
- * actor.subscribe(async (snapshot) => {
686
- * if (busy || !snapshot.matches('reviewing')) return;
687
- * busy = true;
688
- * try {
689
- * const { event } = await decideNext(snapshot, {
690
- * decide,
691
- * model: 'quick',
692
- * allowedEvents: 'desk.*',
693
- * payloads: (s) => ({ 'desk.refund': [{ amount: s.context.requested }] }),
694
- * lookahead: true,
695
- * });
696
- * if (event && actor.getSnapshot().can(event)) actor.send(event);
697
- * } finally {
698
- * busy = false;
699
- * }
700
- * });
701
- * ```
702
- */
703
- async function decideNext(snapshot, options) {
704
- const patterns = typeof options.allowedEvents === "string" ? [options.allowedEvents] : options.allowedEvents;
705
- const schemas = snapshot.machine.schemas?.events;
706
- const candidates = require_decision.getAcceptedEvents(snapshot, {
707
- events: schemas,
708
- eventTypes: patterns
709
- }).filter((event) => !require_decision.isEventPattern(event.type));
710
- const humanEventTypes = require_decision.getHumanEventTypes(snapshot);
711
- const events = candidates.filter((event) => !humanEventTypes.has(event.type));
712
- const payloads = options.payloads?.(snapshot) ?? {};
713
- const accepted = [];
714
- const withheld = [];
715
- for (const { type } of candidates) for (const payload of payloads[type] ?? [{}]) {
716
- const event = {
717
- ...payload,
718
- type
719
- };
720
- (!humanEventTypes.has(type) && safeCan(snapshot, event) ? accepted : withheld).push(event);
721
- }
722
- const offered = accepted.map((event) => ({
723
- event,
724
- description: describeOption(snapshot, event, schemas?.[event.type], options.lookahead)
725
- }));
726
- const request = require_decision.createDecisionRequest({
727
- name: options.name ?? "decideNext",
728
- model: options.model,
729
- system: options.system,
730
- prompt: options.prompt,
731
- input: {
732
- value: snapshot.value,
733
- context: snapshot.context
734
- },
735
- events,
736
- options: offered,
737
- withheld
738
- });
739
- if (offered.length === 0) return {
740
- event: null,
741
- attempts: [],
742
- request,
743
- withheld
744
- };
745
- let attempts = [];
746
- return {
747
- event: await require_decision.resolveDecision(request, { decide: (attemptRequest, info) => {
748
- attempts = attemptRequest.attempts;
749
- return options.decide(attemptRequest, info);
750
- } }, {
751
- maxRetries: options.maxRetries,
752
- signal: options.signal,
753
- canTake: (chosen) => safeCan(snapshot, chosen)
754
- }),
755
- attempts,
756
- request,
757
- withheld
758
- };
759
- }
760
- function safeCan(snapshot, event) {
761
- try {
762
- return snapshot.can(event);
763
- } catch {
764
- return false;
765
- }
766
- }
767
- function describeOption(snapshot, event, schema, lookahead) {
768
- const what = (0, xstate.getNextTransitions)(snapshot).find((candidate) => candidate.eventType === event.type && candidate.description)?.description ?? schemaDescription(schema) ?? event.type;
769
- const fields = Object.entries(event).filter(([key]) => key !== "type").map(([key, value]) => `${key}: ${short(value)}`);
770
- const base = fields.length ? `${what} (${fields.join("; ")})` : what;
771
- const effect = lookahead ? describeEffect(snapshot, event, lookahead === true ? void 0 : lookahead) : void 0;
772
- return effect ? `${base}. Then: ${effect}` : base;
773
- }
774
- function schemaDescription(schema) {
775
- if (!schema) return void 0;
776
- const direct = schema.description;
777
- if (typeof direct === "string") return direct;
778
- try {
779
- const json = schema["~standard"].jsonSchema?.input?.({ target: "draft-2020-12" });
780
- return require_event_log.isRecord(json) && typeof json.description === "string" ? json.description : void 0;
781
- } catch {
782
- return;
783
- }
784
- }
785
- function describeEffect(snapshot, event, keys) {
786
- const maxLength = 120;
787
- let next;
788
- try {
789
- [next] = (0, xstate.transition)(snapshot.machine, snapshot, event);
790
- } catch {
791
- return;
792
- }
793
- const changes = [];
794
- if (require_event_log.canonicalEventJson(snapshot.value) !== require_event_log.canonicalEventJson(next.value)) changes.push(`state: ${short(snapshot.value, maxLength)} → ${short(next.value, maxLength)}`);
795
- const before = require_event_log.isRecord(snapshot.context) ? snapshot.context : {};
796
- const after = require_event_log.isRecord(next.context) ? next.context : {};
797
- for (const key of keys ?? /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])) if (require_event_log.canonicalEventJson(before[key]) !== require_event_log.canonicalEventJson(after[key])) changes.push(`${key}: ${short(before[key], maxLength)} → ${short(after[key], maxLength)}`);
798
- return changes.length ? changes.join("; ") : "nothing changes";
799
- }
800
- function short(value, max = 60) {
801
- let text;
802
- try {
803
- text = value === void 0 ? "(none)" : JSON.stringify(value) ?? String(value);
804
- } catch {
805
- text = String(value);
862
+ const helpers = Object.entries(options.helpers ?? {});
863
+ if (helpers.length) {
864
+ lines.push("Helpers:");
865
+ for (const [name, helper] of helpers) lines.push(` ${name}`, ...sourceLines(helper, " "));
806
866
  }
807
- return text.length > max ? `${text.slice(0, max - 1)}…` : text;
867
+ return lines.join("\n");
808
868
  }
809
869
  //#endregion
810
870
  //#region src/policy-decider.ts
@@ -834,7 +894,7 @@ function createPolicyDecider(policy, options = {}) {
834
894
  const policyInput = input(request);
835
895
  require_event_log.assertJsonSerializable(policyInput, "policy input");
836
896
  const thread = runOptions.store === void 0 ? void 0 : await policyThread(request, policyInput, info);
837
- const result = await require_run_agent.runAgent(policy, {
897
+ const result = await require_effects.runAgent(policy, {
838
898
  ...runOptions,
839
899
  input: policyInput,
840
900
  ...thread === void 0 ? {} : { threadId: thread },
@@ -879,6 +939,308 @@ async function sha256(text) {
879
939
  return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
880
940
  }
881
941
  //#endregion
942
+ //#region src/wrap-workflow.ts
943
+ /**
944
+ * `wrapWorkflow` — step 0 of a strangler-fig retrofit: an existing async
945
+ * workflow, unchanged, as an agent machine.
946
+ * @module
947
+ */
948
+ /** A schema that only carries a type: values pass through unchecked. */
949
+ function typeOnly() {
950
+ return { "~standard": {
951
+ version: 1,
952
+ vendor: "statelyai-agent",
953
+ validate: (value) => ({ value })
954
+ } };
955
+ }
956
+ /**
957
+ * Wraps each effect so its call and settlement reach the machine as events.
958
+ * Once `signal` aborts, an effect throws its reason instead of running, so a
959
+ * workflow that ignores its signal stops spending calls.
960
+ */
961
+ function observeEffects(effects, send, signal, redact = (_name, _part, value) => value) {
962
+ let calls = 0;
963
+ return require_effects.mapEffects(effects, (name, effect) => async (...args) => {
964
+ signal.throwIfAborted();
965
+ const call = calls++;
966
+ send({
967
+ type: "effect.call",
968
+ name,
969
+ call,
970
+ args: require_effects.toJsonValue(redact(name, "args", args)) ?? []
971
+ });
972
+ const done = (result) => send({
973
+ type: "effect.done",
974
+ name,
975
+ call,
976
+ result: require_effects.toJsonValue(redact(name, "result", result)) ?? null
977
+ });
978
+ const failed = (error) => send({
979
+ type: "effect.error",
980
+ name,
981
+ call,
982
+ error: require_effects.toJsonValue(redact(name, "error", error)) ?? null
983
+ });
984
+ let result;
985
+ try {
986
+ result = await effect(...args);
987
+ } catch (error) {
988
+ failed(error);
989
+ throw error;
990
+ }
991
+ if (require_effects.isAsyncIterable(result)) return observeStream(result, done, failed);
992
+ done(result);
993
+ return result;
994
+ });
995
+ }
996
+ /**
997
+ * A stream that settles its effect once read: `done` with the chunks read
998
+ * (`{ chunks, returned }` when a generator returned a value) when iteration
999
+ * ends or the reader stops early, `failed` if it throws. Reading through
1000
+ * `for await`, `[Symbol.asyncIterator]().next()`, or a generator's own
1001
+ * `next()` is observed alike; anything else reaches the original stream,
1002
+ * bound to it.
1003
+ */
1004
+ function observeStream(stream, done, failed) {
1005
+ const chunks = [];
1006
+ let settled = false;
1007
+ const settle = (outcome) => {
1008
+ if (settled) return;
1009
+ settled = true;
1010
+ if ("error" in outcome) failed(outcome.error);
1011
+ else done(outcome.returned === void 0 ? chunks : {
1012
+ chunks,
1013
+ returned: outcome.returned
1014
+ });
1015
+ };
1016
+ const observe = (source) => {
1017
+ const step = async (run) => {
1018
+ try {
1019
+ const next = await run();
1020
+ if (next.done) settle({ returned: next.value });
1021
+ else chunks.push(next.value);
1022
+ return next;
1023
+ } catch (error) {
1024
+ settle({ error });
1025
+ throw error;
1026
+ }
1027
+ };
1028
+ return {
1029
+ next: (...args) => step(() => source.next(...args)),
1030
+ return: async (value) => {
1031
+ let result;
1032
+ try {
1033
+ result = source.return ? await source.return(value) : {
1034
+ done: true,
1035
+ value
1036
+ };
1037
+ } catch (error) {
1038
+ settle({ error });
1039
+ throw error;
1040
+ }
1041
+ if (result.done) settle({});
1042
+ else chunks.push(result.value);
1043
+ return result;
1044
+ },
1045
+ ...source.throw && { throw: (error) => step(() => source.throw(error)) }
1046
+ };
1047
+ };
1048
+ const self = typeof stream.next === "function" ? observe(stream) : void 0;
1049
+ const iterate = () => {
1050
+ try {
1051
+ const iterator = stream[Symbol.asyncIterator]();
1052
+ return self && iterator === stream ? self : observe(iterator);
1053
+ } catch (error) {
1054
+ settle({ error });
1055
+ throw error;
1056
+ }
1057
+ };
1058
+ return new Proxy(stream, { get(target, property) {
1059
+ if (property === Symbol.asyncIterator) return iterate;
1060
+ if (self && (property === "next" || property === "return" || property === "throw")) return self[property];
1061
+ const value = Reflect.get(target, property, target);
1062
+ return typeof value === "function" ? value.bind(target) : value;
1063
+ } });
1064
+ }
1065
+ /**
1066
+ * A deep copy the workflow owns: machine context is frozen in XState's dev
1067
+ * build, and legacy code mutates its input. Only plain data is copied:
1068
+ * `structuredClone` would turn a class instance into a plain object, so a
1069
+ * value holding one (or anything it cannot copy) passes as is.
1070
+ */
1071
+ function ownCopy(value) {
1072
+ const hidden = { found: false };
1073
+ if (!isPlainData(value, /* @__PURE__ */ new WeakSet(), hidden)) return value;
1074
+ if (hidden.found) return contextCopy(value);
1075
+ try {
1076
+ return structuredClone(value);
1077
+ } catch {
1078
+ return value;
1079
+ }
1080
+ }
1081
+ /**
1082
+ * The input as machine context holds it: plain objects and arrays copied, so
1083
+ * XState's dev build, which deep-freezes them in context, never freezes the
1084
+ * caller's own. Everything else (class instances, functions, Maps) is shared,
1085
+ * and XState leaves those unfrozen.
1086
+ */
1087
+ /** Each context copy of an input, to the input it was copied from. */
1088
+ const copiedFrom = /* @__PURE__ */ new WeakMap();
1089
+ function contextCopy(value, seen = /* @__PURE__ */ new Map()) {
1090
+ if (value === null || typeof value !== "object") return value;
1091
+ if (seen.has(value)) return seen.get(value);
1092
+ const proto = Object.getPrototypeOf(value);
1093
+ const isArray = Array.isArray(value);
1094
+ if (!isArray && proto !== Object.prototype && proto !== null) return value;
1095
+ const copy = isArray ? [] : Object.create(proto);
1096
+ seen.set(value, copy);
1097
+ for (const key of Reflect.ownKeys(value)) {
1098
+ if (isArray && key === "length") continue;
1099
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
1100
+ if ("value" in descriptor) descriptor.value = contextCopy(descriptor.value, seen);
1101
+ Object.defineProperty(copy, key, descriptor);
1102
+ }
1103
+ if (isArray) copy.length = value.length;
1104
+ return copy;
1105
+ }
1106
+ /** The input's context copy, remembered so the workflow gets the input itself back. */
1107
+ function inputCopy(input) {
1108
+ const copy = contextCopy(input);
1109
+ if (copy !== input && typeof copy === "object" && copy !== null) copiedFrom.set(copy, input);
1110
+ return copy;
1111
+ }
1112
+ function isBuiltinView(value) {
1113
+ const proto = Object.getPrototypeOf(value);
1114
+ if (proto === DataView.prototype) return true;
1115
+ const tag = value[Symbol.toStringTag];
1116
+ const ctor = tag ? globalThis[tag] : void 0;
1117
+ return typeof ctor === "function" && proto === ctor.prototype;
1118
+ }
1119
+ function isPlainData(value, seen, hidden) {
1120
+ if (typeof value === "function") return false;
1121
+ if (value === null || typeof value !== "object") return true;
1122
+ if (seen.has(value)) return true;
1123
+ seen.add(value);
1124
+ if (value instanceof Date || value instanceof RegExp) return true;
1125
+ if (ArrayBuffer.isView(value)) return isBuiltinView(value);
1126
+ if (value instanceof Map || value instanceof Set) return [...value.entries()].every((entry) => entry.every((v) => isPlainData(v, seen, hidden)));
1127
+ const proto = Object.getPrototypeOf(value);
1128
+ if (proto !== Object.prototype && proto !== Array.prototype && proto !== null) return false;
1129
+ if (Reflect.ownKeys(value).length - Object.keys(value).length !== (Array.isArray(value) ? 1 : 0)) hidden.found = true;
1130
+ return Reflect.ownKeys(value).every((key) => {
1131
+ if (Array.isArray(value) && key === "length") return true;
1132
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
1133
+ return !("value" in descriptor) || isPlainData(descriptor.value, seen, hidden);
1134
+ });
1135
+ }
1136
+ function workflowLogic(run, effects, runSignal, redact) {
1137
+ return (0, xstate.createAsyncLogic)({ run: async ({ input: contextInput, self, signal }) => {
1138
+ const input = typeof contextInput === "object" && contextInput !== null && copiedFrom.has(contextInput) ? copiedFrom.get(contextInput) : contextInput;
1139
+ const parent = self._parent;
1140
+ const combined = runSignal ? AbortSignal.any([runSignal, signal]) : signal;
1141
+ return run(ownCopy(input), observeEffects(effects, (event) => parent?.send(event), combined, redact), { signal: combined });
1142
+ } });
1143
+ }
1144
+ function createWrappedMachine(id, version, workflow) {
1145
+ return require_setup_agent.setupAgent({
1146
+ actors: { workflow },
1147
+ context: typeOnly(),
1148
+ input: typeOnly(),
1149
+ output: typeOnly(),
1150
+ events: {
1151
+ "effect.call": typeOnly(),
1152
+ "effect.done": typeOnly(),
1153
+ "effect.error": typeOnly()
1154
+ }
1155
+ }).createMachine({
1156
+ id,
1157
+ version,
1158
+ context: ({ input }) => ({
1159
+ input: inputCopy(input),
1160
+ calls: 0,
1161
+ failures: 0
1162
+ }),
1163
+ initial: "running",
1164
+ states: {
1165
+ running: {
1166
+ description: "The wrapped workflow runs as one black-box actor.",
1167
+ invoke: {
1168
+ src: "workflow",
1169
+ input: ({ context }) => context.input,
1170
+ onDone: ({ output }) => ({
1171
+ target: "done",
1172
+ context: { output }
1173
+ })
1174
+ },
1175
+ on: {
1176
+ "effect.call": ({ context }) => ({ context: { calls: context.calls + 1 } }),
1177
+ "effect.done": () => ({}),
1178
+ "effect.error": ({ context }) => ({ context: { failures: context.failures + 1 } })
1179
+ }
1180
+ },
1181
+ done: {
1182
+ type: "final",
1183
+ output: ({ context }) => context.output
1184
+ }
1185
+ }
1186
+ });
1187
+ }
1188
+ /**
1189
+ * Wraps an existing async workflow, unchanged, as an agent machine: step 0 of
1190
+ * a strangler-fig retrofit. Pass every side effect it makes as `effects`; each
1191
+ * call becomes an `effect.call` event, then `effect.done` or `effect.error`, so
1192
+ * it shows up in transitions, traces, the event log and the inspector.
1193
+ *
1194
+ * What it buys today: inspection and traces of a workflow nobody rewrote, a
1195
+ * recorded baseline (`run(input, { recorder })`, or `checkParity` from
1196
+ * `@statelyai/agent/testing`), `signal` to abort it, and a seam to carve
1197
+ * phases out of, one at a time.
1198
+ *
1199
+ * What it does not: the workflow is a black box. The machine has one state
1200
+ * for all of it, so there is no resume in the middle of the function (a
1201
+ * resumed run starts it again), and `canReach` or `explorePaths` prove nothing
1202
+ * about what happens inside. Those arrive per phase, as phases move into
1203
+ * states. Effect arguments and results are journaled JSON-safe; values that
1204
+ * are not JSON lose what JSON cannot hold.
1205
+ *
1206
+ * @example
1207
+ * ```ts
1208
+ * const support = wrapWorkflow({
1209
+ * id: "support",
1210
+ * effects: { generate, lookupOrder, issueRefund },
1211
+ * run: (input: Ticket, effects) => legacyRunTicket(input, effects),
1212
+ * });
1213
+ * const reply = await support.run(ticket); // what legacyRunTicket returned
1214
+ * ```
1215
+ */
1216
+ function wrapWorkflow(config) {
1217
+ const machine = createWrappedMachine(config.id, config.version ?? "1", workflowLogic(config.run, config.effects, void 0, config.redact));
1218
+ return {
1219
+ machine,
1220
+ async run(input, options = {}) {
1221
+ const { effects: overrides, recorder, ...runOptions } = options;
1222
+ let effects = {
1223
+ ...require_effects.mapEffects(config.effects, (_name, effect) => effect),
1224
+ ...overrides ? require_effects.mapEffects(overrides, (_name, effect) => effect) : {}
1225
+ };
1226
+ if (recorder) effects = require_effects.mapEffects(effects, (name, effect) => recorder.fn(name, effect));
1227
+ const { signal: _signal, ...agentOptions } = runOptions;
1228
+ const result = await require_effects.runAgent(machine, {
1229
+ ...agentOptions,
1230
+ input,
1231
+ actors: { workflow: workflowLogic(config.run, effects, options.signal, config.redact) }
1232
+ });
1233
+ if (result.status === "done") {
1234
+ const output = result.output;
1235
+ recorder?.output(output);
1236
+ return output;
1237
+ }
1238
+ if (result.status === "error") throw result.error;
1239
+ throw new require_event_log.AgentError("workflow-idle", `wrapWorkflow '${config.id}': the run settled idle, which a wrapped workflow never should.`);
1240
+ }
1241
+ };
1242
+ }
1243
+ //#endregion
882
1244
  //#region src/provide-executors.ts
883
1245
  /**
884
1246
  * Binds a machine's agent actor sources to a set of host `executors` in one
@@ -900,6 +1262,8 @@ async function sha256(text) {
900
1262
  * - decision / `agent.decide` source → `executors.decide` (snapshot-driven
901
1263
  * candidate events, guard `canTake`, and auto-delivery of the chosen event,
902
1264
  * mirroring `createAgentRuntime` but without its model-call counting)
1265
+ * - `agent.act` → `executors.generateText` (accepted events as tools, each
1266
+ * call sent to the invoking actor)
903
1267
  *
904
1268
  * Pass `options.onTrace` to observe request-level trace events (identical in
905
1269
  * shape to `createAgentRuntime`'s); pair it with {@link traceTransitions} on the actor's
@@ -929,11 +1293,11 @@ function provideExecutors(machine, executors, options = {}) {
929
1293
  const provided = options.actors ? withActors(machine, options.actors) : machine;
930
1294
  const effectiveSources = provided.sources.actors;
931
1295
  const wrappedSources = {};
932
- const invokedSrcs = require_run_agent.getConfiguredInvokeSrcs(provided);
1296
+ const invokedSrcs = require_effects.getConfiguredInvokeSrcs(provided);
933
1297
  for (const [key, logic] of Object.entries(effectiveSources)) {
934
- if (require_run_agent.isStateMachineLogic(logic)) {
1298
+ if (require_effects.isStateMachineLogic(logic)) {
935
1299
  if (invokedSrcs.has(key)) assertChildBindable(logic, executors, key, /* @__PURE__ */ new Set([provided]));
936
- const rebound = require_run_agent.bindChildMachineForProvide(logic, executors, bindOptions, /* @__PURE__ */ new Set([provided]));
1300
+ const rebound = require_effects.bindChildMachineForProvide(logic, executors, bindOptions, /* @__PURE__ */ new Set([provided]));
937
1301
  if (rebound !== logic) wrappedSources[key] = rebound;
938
1302
  continue;
939
1303
  }
@@ -941,7 +1305,7 @@ function provideExecutors(machine, executors, options = {}) {
941
1305
  if (!requirement) continue;
942
1306
  const binding = {
943
1307
  ...requirement,
944
- bind: () => require_decision.isDecisionLogic(logic) ? require_run_agent.bindDecisionForProvide(provided, logic, executors, bindOptions) : require_run_agent.bindTextForProvide(provided, logic, executors, bindOptions)
1308
+ bind: () => require_act.isActLogic(logic) ? require_effects.bindActForProvide(provided, executors, bindOptions) : require_decision.isDecisionLogic(logic) ? require_effects.bindDecisionForProvide(provided, logic, executors, bindOptions) : require_effects.bindTextForProvide(provided, logic, executors, bindOptions)
945
1309
  };
946
1310
  if (require_event_log.executorBoundLogics.has(logic)) continue;
947
1311
  if (!executors[binding.executorKey]) {
@@ -954,6 +1318,10 @@ function provideExecutors(machine, executors, options = {}) {
954
1318
  }
955
1319
  /** The executor slot + label an agent logic needs, or `undefined` for a non-agent actor. */
956
1320
  function executorRequirementOf(logic) {
1321
+ if (require_act.isActLogic(logic)) return {
1322
+ executorKey: "generateText",
1323
+ kind: "text"
1324
+ };
957
1325
  if (require_decision.isDecisionLogic(logic)) return {
958
1326
  executorKey: "decide",
959
1327
  kind: "decision"
@@ -976,10 +1344,10 @@ function assertChildBindable(childMachine, executors, path, visited) {
976
1344
  if (visited.has(childMachine)) return;
977
1345
  const nextVisited = /* @__PURE__ */ new Set([...visited, childMachine]);
978
1346
  const sources = childMachine.sources.actors;
979
- for (const src of require_run_agent.getConfiguredInvokeSrcs(childMachine)) {
1347
+ for (const src of require_effects.getConfiguredInvokeSrcs(childMachine)) {
980
1348
  const logic = sources[src];
981
1349
  if (!logic) continue;
982
- if (require_run_agent.isStateMachineLogic(logic)) {
1350
+ if (require_effects.isStateMachineLogic(logic)) {
983
1351
  assertChildBindable(logic, executors, `${path} > ${src}`, nextVisited);
984
1352
  continue;
985
1353
  }
@@ -992,25 +1360,30 @@ function missingExecutorError(src, kind, executor) {
992
1360
  return /* @__PURE__ */ new Error(`provideExecutors: actor source '${src}' is a ${kind} source but no '${executor}' executor was provided. Add it to the executors object, or bind the source with its own executor (logic.withExecutor(...)) before calling provideExecutors.`);
993
1361
  }
994
1362
  //#endregion
995
- exports.AGENT_TRACE_SCHEMA_VERSION = require_run_agent.AGENT_TRACE_SCHEMA_VERSION;
1363
+ exports.ACT_STATE_EXITED = require_act.ACT_STATE_EXITED;
1364
+ exports.AGENT_TRACE_SCHEMA_VERSION = require_effects.AGENT_TRACE_SCHEMA_VERSION;
996
1365
  exports.AGENT_USAGE_EVENT_TYPE = require_event_log.AGENT_USAGE_EVENT_TYPE;
997
1366
  exports.AgentDecisionExhaustedError = require_decision.AgentDecisionExhaustedError;
998
1367
  exports.AgentError = require_event_log.AgentError;
999
1368
  exports.AgentEventLogConflictError = require_event_log_store.AgentEventLogConflictError;
1000
1369
  exports.AgentInvalidEventPayloadError = require_decision.AgentInvalidEventPayloadError;
1001
1370
  exports.AgentMachineVersionMismatchError = require_event_log.AgentMachineVersionMismatchError;
1002
- exports.AgentMaxModelCallsExceededError = require_run_agent.AgentMaxModelCallsExceededError;
1003
- exports.AgentSnapshotDivergedError = require_run_agent.AgentSnapshotDivergedError;
1371
+ exports.AgentMaxModelCallsExceededError = require_effects.AgentMaxModelCallsExceededError;
1372
+ exports.AgentSnapshotDivergedError = require_effects.AgentSnapshotDivergedError;
1004
1373
  exports.AgentTruncatedError = require_event_log.AgentTruncatedError;
1374
+ exports.DEFAULT_ACT_MAX_STEPS = require_act.DEFAULT_ACT_MAX_STEPS;
1375
+ exports.GROUPED_EVENT_THRESHOLD = require_decision.GROUPED_EVENT_THRESHOLD;
1376
+ exports.MAX_FINITE_PAYLOADS = require_decision.MAX_FINITE_PAYLOADS;
1005
1377
  exports.assistantMessage = require_event_log.assistantMessage;
1006
1378
  exports.bindRequestExecutor = require_event_log.bindRequestExecutor;
1007
- exports.createAgentRuntime = require_run_agent.createAgentRuntime;
1379
+ exports.createAgentInbox = require_effects.createAgentInbox;
1380
+ exports.createAgentRuntime = require_effects.createAgentRuntime;
1008
1381
  exports.createAgentSchemas = require_setup_agent.createAgentSchemas;
1009
1382
  exports.createDecisionLogic = require_decision.createDecisionLogic;
1010
1383
  exports.createDecisionRequest = require_decision.createDecisionRequest;
1011
1384
  exports.createPolicyDecider = createPolicyDecider;
1012
1385
  exports.createTextLogic = require_event_log.createTextLogic;
1013
- exports.decideNext = decideNext;
1386
+ exports.decideNext = require_effects.decideNext;
1014
1387
  exports.describeMachine = describeMachine;
1015
1388
  exports.eventFromInteraction = eventFromInteraction;
1016
1389
  exports.getAcceptedEvents = require_decision.getAcceptedEvents;
@@ -1025,9 +1398,9 @@ exports.getMachineStructuralHash = require_event_log.getMachineStructuralHash;
1025
1398
  exports.getMessageText = require_event_log.getMessageText;
1026
1399
  exports.getStateMeta = require_event_log.getStateMeta;
1027
1400
  exports.getStatePath = require_event_log.getStatePath;
1028
- exports.inspectTransitions = require_run_agent.inspectTransitions;
1401
+ exports.inspectTransitions = require_effects.inspectTransitions;
1029
1402
  exports.interactionMetaSchema = interactionMetaSchema;
1030
- exports.isAgentIdle = require_run_agent.isAgentIdle;
1403
+ exports.isAgentIdle = require_effects.isAgentIdle;
1031
1404
  exports.isAgentMessages = isAgentMessages;
1032
1405
  exports.isStandardSchema = require_event_log.isStandardSchema;
1033
1406
  exports.messagesSchema = messagesSchema;
@@ -1038,9 +1411,9 @@ exports.provideExecutors = provideExecutors;
1038
1411
  exports.providerOutputSchema = require_event_log.providerOutputSchema;
1039
1412
  exports.renderDecisionAttempts = require_decision.renderDecisionAttempts;
1040
1413
  exports.resolveDecision = require_decision.resolveDecision;
1041
- exports.runAgent = require_run_agent.runAgent;
1042
- exports.runToQuiescence = require_run_agent.runToQuiescence;
1043
- exports.serializeTraceEvent = require_run_agent.serializeTraceEvent;
1414
+ exports.runAgent = require_effects.runAgent;
1415
+ exports.runToQuiescence = require_effects.runToQuiescence;
1416
+ exports.serializeTraceEvent = require_effects.serializeTraceEvent;
1044
1417
  Object.defineProperty(exports, "setupAgent", {
1045
1418
  enumerable: true,
1046
1419
  get: function() {
@@ -1049,5 +1422,6 @@ Object.defineProperty(exports, "setupAgent", {
1049
1422
  });
1050
1423
  exports.systemMessage = require_event_log.systemMessage;
1051
1424
  exports.toolMessage = require_event_log.toolMessage;
1052
- exports.traceTransitions = require_run_agent.traceTransitions;
1425
+ exports.traceTransitions = require_effects.traceTransitions;
1053
1426
  exports.userMessage = require_event_log.userMessage;
1427
+ exports.wrapWorkflow = wrapWorkflow;