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