@statelyai/agent 2.0.0-alpha.38 → 2.0.0-alpha.40

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 (137) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/dist/{act-CrX0JwWY.cjs → act-B0CVbmo4.cjs} +1 -1
  3. package/dist/{act-B9hLQls6.mjs → act-Bsz-hUfD.mjs} +1 -1
  4. package/dist/ai-sdk.cjs +4 -4
  5. package/dist/ai-sdk.d.cts +2 -3
  6. package/dist/ai-sdk.d.mts +2 -3
  7. package/dist/ai-sdk.mjs +4 -4
  8. package/dist/{decision-m5hGmHpF.mjs → decision-B41YBx5U.mjs} +1 -1
  9. package/dist/{decision-CMeuNZ1g.cjs → decision-D8bcIGXQ.cjs} +1 -1
  10. package/dist/{decision-object-DBcLWVvv.d.cts → decision-object-BB8XV5Ec.d.cts} +1 -1
  11. package/dist/{decision-object-B5zGSPFp.d.mts → decision-object-CH_sE694.d.mts} +1 -1
  12. package/dist/effects-B9IvUPVh.mjs +23 -0
  13. package/dist/effects-DrWcUGgc.cjs +34 -0
  14. package/dist/evals.cjs +810 -0
  15. package/dist/evals.d.cts +595 -0
  16. package/dist/evals.d.mts +595 -0
  17. package/dist/evals.mjs +801 -0
  18. package/dist/{event-log-DkVlk3Rh.mjs → event-log-CEq_bVXQ.mjs} +8 -4
  19. package/dist/{event-log-Dkc-yIYu.cjs → event-log-dSOnXHuG.cjs} +7 -15
  20. package/dist/{event-log-store-Brx9tOHt.mjs → event-log-store-DLAfNM34.mjs} +1 -1
  21. package/dist/{event-log-store-BBS8so8a.d.mts → event-log-store-DYun526m.d.mts} +15 -14
  22. package/dist/{event-log-store-Cl-YWDnq.cjs → event-log-store-Dey9ufA4.cjs} +1 -1
  23. package/dist/{event-log-store-bc4ICGcS.d.cts → event-log-store-aFXK6yZX.d.cts} +15 -14
  24. package/dist/index.cjs +142 -97
  25. package/dist/index.d.cts +97 -141
  26. package/dist/index.d.mts +97 -141
  27. package/dist/index.mjs +123 -74
  28. package/dist/internal-BzlpzSux.d.cts +14 -0
  29. package/dist/internal-BzlpzSux.d.mts +14 -0
  30. package/dist/log.cjs +2 -3
  31. package/dist/log.d.cts +2 -2
  32. package/dist/log.d.mts +2 -2
  33. package/dist/log.mjs +3 -3
  34. package/dist/machine-input-0YTPcnCm.mjs +27 -0
  35. package/dist/machine-input-DU3owLUr.cjs +32 -0
  36. package/dist/machines.cjs +1 -719
  37. package/dist/machines.d.cts +2 -424
  38. package/dist/machines.d.mts +2 -424
  39. package/dist/machines.mjs +2 -709
  40. package/dist/{model-source-kjGwqAV8.mjs → model-source-BrsLDvHL.mjs} +1 -1
  41. package/dist/{model-source-B4WQ8Idp.cjs → model-source-YpxjmWuX.cjs} +1 -1
  42. package/dist/openai.cjs +3 -3
  43. package/dist/openai.d.cts +2 -3
  44. package/dist/openai.d.mts +2 -3
  45. package/dist/openai.mjs +3 -3
  46. package/dist/otel.d.cts +1 -1
  47. package/dist/otel.d.mts +1 -1
  48. package/dist/policy.cjs +77 -0
  49. package/dist/policy.d.cts +143 -0
  50. package/dist/policy.d.mts +143 -0
  51. package/dist/policy.mjs +75 -0
  52. package/dist/{run-agent-DlPzBWj-.d.mts → run-agent-BO9RSb7i.d.cts} +33 -40
  53. package/dist/{run-agent-30mH2moE.d.cts → run-agent-BxkeuAYR.d.mts} +33 -40
  54. package/dist/{effects-DDseYtJk.cjs → run-agent-COdR9FpM.cjs} +175 -228
  55. package/dist/{effects-BT_cSY0j.mjs → run-agent-D3gW9wfd.mjs} +176 -211
  56. package/dist/{setup-agent-BDmNr6PC.mjs → setup-agent-CLm6QVGy.mjs} +3 -3
  57. package/dist/{setup-agent-BaNyz6Q3.d.cts → setup-agent-Cv8Hk3mX.d.cts} +12 -11
  58. package/dist/{setup-agent-C1CG_nfX.d.mts → setup-agent-DgFAhaPJ.d.mts} +12 -11
  59. package/dist/{setup-agent-CmEToB8y.cjs → setup-agent-Dv5VpuHe.cjs} +3 -3
  60. package/dist/tanstack-ai.cjs +4 -4
  61. package/dist/tanstack-ai.d.cts +2 -3
  62. package/dist/tanstack-ai.d.mts +2 -3
  63. package/dist/tanstack-ai.mjs +4 -4
  64. package/dist/testing.cjs +122 -996
  65. package/dist/testing.d.cts +36 -695
  66. package/dist/testing.d.mts +36 -695
  67. package/dist/testing.mjs +112 -977
  68. package/dist/{text-logic-BqxalgMr.d.mts → text-logic-x17uLBwA.d.cts} +238 -2
  69. package/dist/{text-logic-CSf9bqpP.d.cts → text-logic-x17uLBwA.d.mts} +238 -2
  70. package/dist/trajectory-BFjXaooB.d.cts +96 -0
  71. package/dist/trajectory-BFjXaooB.d.mts +96 -0
  72. package/dist/trajectory-BUXj_1Ue.mjs +152 -0
  73. package/dist/trajectory-CoZSv4wF.cjs +157 -0
  74. package/dist/{usage-Bm5nvpow.d.cts → usage-B4B-TQSV.d.mts} +1 -1
  75. package/dist/{usage-BnikdOca.d.mts → usage-DvGcoK6x.d.cts} +1 -1
  76. package/dist/{utils-7lSa4H-i.d.cts → utils-B8k-YPYI.d.mts} +23 -17
  77. package/dist/{utils-CBbKw2fM.d.mts → utils-DAclF-kw.d.cts} +23 -17
  78. package/dist/validate.cjs +4 -4
  79. package/dist/validate.d.cts +2 -2
  80. package/dist/validate.d.mts +2 -2
  81. package/dist/validate.mjs +4 -4
  82. package/dist/{verify-DJHfEfm6.d.cts → verify-CIu4mqIZ.d.mts} +56 -6
  83. package/dist/{verify-i9Hiwc5g.d.mts → verify-CTHlmBbh.d.cts} +56 -6
  84. package/dist/{verify-ChyX6jq0.mjs → verify-Cacz6XSk.mjs} +170 -46
  85. package/dist/{verify-CwlombbC.cjs → verify-D8UDqU4l.cjs} +170 -46
  86. package/dist/{with-model-calls-B_WLmOSl.cjs → with-model-calls-D50Ca6qW.cjs} +2 -2
  87. package/dist/{with-model-calls-BkOwdroS.mjs → with-model-calls-uY-KKliA.mjs} +2 -2
  88. package/docs/advanced.md +5 -5
  89. package/docs/choosing-a-run-mode.md +7 -7
  90. package/docs/debugging.md +6 -8
  91. package/docs/decisions.md +5 -4
  92. package/docs/environment-and-policy.md +1 -1
  93. package/docs/evals.md +57 -43
  94. package/docs/event-log.md +13 -15
  95. package/docs/from-a-loop.md +3 -3
  96. package/docs/generate-machines.md +4 -4
  97. package/docs/hosts.md +25 -30
  98. package/docs/human-in-the-loop.md +5 -8
  99. package/docs/index.md +4 -4
  100. package/docs/judgments.md +5 -7
  101. package/docs/langgraph-comparison.md +6 -6
  102. package/docs/machines-as-data.md +7 -12
  103. package/docs/machines-presets.md +17 -120
  104. package/docs/machines.md +13 -13
  105. package/docs/models-and-providers.md +19 -25
  106. package/docs/multi-agent.md +1 -1
  107. package/docs/observability.md +6 -8
  108. package/docs/persistence.md +10 -20
  109. package/docs/quickstart.md +3 -3
  110. package/docs/statechart-policy-examples.md +1 -1
  111. package/docs/steps.md +5 -6
  112. package/docs/strangler-fig.md +105 -33
  113. package/docs/text-requests.md +10 -12
  114. package/docs/thinking-in-state-machines.md +8 -8
  115. package/docs/tools.md +10 -12
  116. package/docs/upgrading.md +1 -1
  117. package/docs/usage-and-budgets.md +51 -56
  118. package/docs/validate-and-repair.md +9 -14
  119. package/docs/verify.md +54 -7
  120. package/docs/xstate-4-and-5-apps.md +19 -28
  121. package/llms.txt +1 -1
  122. package/package.json +31 -6
  123. package/readme.md +32 -24
  124. package/dist/internal-C3Lqu538.d.cts +0 -43
  125. package/dist/internal-DUcdhk-i.d.mts +0 -43
  126. package/dist/types-DQUOOaZO.d.cts +0 -238
  127. package/dist/types-DQUOOaZO.d.mts +0 -238
  128. package/skills/add-evals/SKILL.md +0 -152
  129. package/skills/add-traces/SKILL.md +0 -152
  130. package/skills/build-machine/SKILL.md +0 -84
  131. package/skills/generate-machine/SKILL.md +0 -335
  132. package/skills/graph-engineering/SKILL.md +0 -43
  133. package/skills/improve-machine/SKILL.md +0 -261
  134. package/skills/improve-machine/reference.md +0 -101
  135. package/skills/loop-to-machine/SKILL.md +0 -205
  136. package/skills/loop-to-machine/policy.md +0 -154
  137. package/skills/loop-to-machine/reference.md +0 -260
package/dist/index.d.mts CHANGED
@@ -1,11 +1,10 @@
1
- import { A as UserMessage, C as StandardSchemaV1, D as ToolMessage, E as ToolCallPart, O as ToolResultOutput, S as ProviderOptions, T as TextPart, _ as FilePart, a as AgentToolChoice, b as InferOutput, c as AgentToolSchema, d as AllowedEvents, f as AssistantMessage, g as EventUnion, h as EventPayload, i as AgentTool, j as WithAgentInputSchema, k as ToolResultPart, l as AgentTools, m as DataContent, n as AgentEventSchemaInputMap, o as AgentToolDescriptor, p as ChosenEvent, r as AgentMessage, s as AgentToolExecute, t as AgentEventSchemaInput, u as AllowedEventPattern, v as ImagePart, w as SystemMessage, x as NormalizedEventSchemas, y as InferInput } from "./types-DQUOOaZO.mjs";
2
- import { $ as AgentRequestOptions, A as AgentActInput, B as DecisionAttempt, C as getAgentOutputMode, D as parseProviderOutput, E as parseOutput, F as AgentDecisionOption, G as createDecisionRequest, H as DecisionLogicConfig, I as AgentDecisionRejection, J as DecisionStrategy, K as renderDecisionAttempts, L as AgentDecisionRequest, M as AgentDecisionExecutor, N as AgentDecisionExhaustedError, O as providerOutputSchema, P as AgentDecisionInput, Q as AgentInvalidEventPayloadError, R as AgentExecutorDecisionRequest, S as createTextLogic, T as getCallUsage, U as ResolveDecisionOptions, V as DecisionLogic, W as createDecisionLogic, X as MAX_FINITE_PAYLOADS, Y as GROUPED_EVENT_THRESHOLD, Z as AgentEventDescriptor, _ as TextLogic, a as AgentModelRef, at as AgentError, b as TextLogicExecutor, c as AgentRequestExecutorInfo, d as AgentRequestMode, et as AgentRequestSource, f as AgentTextRequest, g as ProviderStructuredOutput, h as BuiltinAgentActors, i as AgentModelMap, it as parseAgentEvent, j as DEFAULT_ACT_MAX_STEPS, k as ACT_STATE_EXITED, l as AgentRequestExecutorResult, m as AgentUsage, n as AgentExecutorTextRequest, nt as EventFromSnapshot, o as AgentOutputMode, ot as AgentTruncatedError, p as AgentTextResult, q as resolveDecision, r as AgentFinishReason, rt as getAcceptedEvents, s as AgentRequestExecutor, t as AgentCallUsage, tt as AgentSchemas, u as AgentRequestExecutors, v as TextLogicConfig, w as getCallFinishReason, x as bindRequestExecutor, y as TextLogicExecuteArgs, z as CreateDecisionRequestOptions } from "./text-logic-BqxalgMr.mjs";
3
- import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-BnikdOca.mjs";
4
- import { C as AgentInteractionEvent, D as eventFromInteraction, E as GetInteractionOptions, O as getInteraction, S as AgentInteractionDescriptor, T as AgentInteractionMeta, _ as FromConfigOptions, a as WithAgentEvents, b as AgentInteraction, c as getAgentSchemas, d as AgentWorkflowActorConfig, f as AgentWorkflowConfig, g as AgentWorkflowTransitionConfig, h as AgentWorkflowStateConfig, i as SetupAgentResult, k as interactionMetaSchema, l as setupAgent, m as AgentWorkflowRequestConfig, n as AgentSchemaPack, o as WithAgentUsageEvent, p as AgentWorkflowInvokeConfig, r as AgentUsageEventPayload, s as createAgentSchemas, t as AgentDefaultMeta, u as AgentWorkflowActionConfig, v as FromConfigResult, w as AgentInteractionEventMeta, x as AgentInteractionChoice, y as SchemaCompiler } from "./setup-agent-C1CG_nfX.mjs";
5
- import { A as AgentStepRequest, C as inspectTransitions, D as serializeTraceEvent, E as runToQuiescence, O as traceTransitions, S as createAgentRuntime, T as runAgent, _ as AgentTraceEvent, a as AgentMaxModelCallsExceededError, b as JsonSerializableTraceEvent, c as AgentRunMeta, d as AgentRunStart, f as AgentRuntime, g as AgentTimerScheduler, h as AgentTimerEvent, i as AgentInputFrom, k as AgentRequest, l as AgentRunOptions, m as AgentSnapshotDivergedError, n as AgentEffects, o as AgentRunErrorCause, p as AgentRuntimeOptions, r as AgentInbox, s as AgentRunInit, t as AGENT_TRACE_SCHEMA_VERSION, u as AgentRunResult, v as AgentTransitionHandler, w as isAgentIdle, x as createAgentInbox, y as InspectedActorRef } from "./run-agent-DlPzBWj-.mjs";
6
- import { c as AgentLogEntry, d as AgentMachineVersionMismatchError, h as JsonValue, n as AgentEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-BBS8so8a.mjs";
7
- import { n as PresetMachine } from "./internal-DUcdhk-i.mjs";
8
- import { M as Recorder, a as getMachineStructuralHash, c as getStatePath, d as toolMessage, f as userMessage, i as getJsonSchemaSync, l as isStandardSchema, n as assistantMessage, o as getMessageText, r as getJsonSchema, s as getStateMeta, t as MetaOfSnapshot, u as systemMessage } from "./utils-CBbKw2fM.mjs";
1
+ import { $ as AgentRequestOptions, A as AgentActInput, At as SystemMessage, B as DecisionAttempt, C as getAgentOutputMode, Ct as FilePart, D as parseProviderOutput, Dt as NormalizedEventSchemas, E as parseOutput, Et as InferOutput, F as AgentDecisionOption, Ft as ToolResultPart, G as createDecisionRequest, H as DecisionLogicConfig, I as AgentDecisionRejection, It as UserMessage, J as DecisionStrategy, K as renderDecisionAttempts, L as AgentDecisionRequest, Lt as WithAgentInputSchema, M as AgentDecisionExecutor, Mt as ToolCallPart, N as AgentDecisionExhaustedError, Nt as ToolMessage, O as providerOutputSchema, Ot as ProviderOptions, P as AgentDecisionInput, Pt as ToolResultOutput, Q as AgentInvalidEventPayloadError, R as AgentExecutorDecisionRequest, S as createTextLogic, St as EventUnion, T as getCallUsage, Tt as InferInput, U as ResolveDecisionOptions, V as DecisionLogic, W as createDecisionLogic, X as MAX_FINITE_PAYLOADS, Y as GROUPED_EVENT_THRESHOLD, Z as AgentEventDescriptor, _ as TextLogic, _t as AllowedEvents, a as AgentModelRef, at as AgentError, b as TextLogicExecutor, bt as DataContent, c as AgentRequestExecutorInfo, ct as AgentEventSchemaInputMap, d as AgentRequestMode, dt as AgentToolChoice, et as AgentRequestSource, f as AgentTextRequest, ft as AgentToolDescriptor, g as ProviderStructuredOutput, gt as AllowedEventPattern, h as BuiltinAgentActors, ht as AgentTools, i as AgentModelMap, it as parseAgentEvent, j as DEFAULT_ACT_MAX_STEPS, jt as TextPart, k as ACT_STATE_EXITED, kt as StandardSchemaV1, l as AgentRequestExecutorResult, lt as AgentMessage, m as AgentUsage, mt as AgentToolSchema, n as AgentExecutorTextRequest, nt as EventFromSnapshot, o as AgentOutputMode, ot as AgentTruncatedError, p as AgentTextResult, pt as AgentToolExecute, q as resolveDecision, r as AgentFinishReason, rt as getAcceptedEvents, s as AgentRequestExecutor, st as AgentEventSchemaInput, t as AgentCallUsage, tt as AgentSchemas, u as AgentRequestExecutors, ut as AgentTool, v as TextLogicConfig, vt as AssistantMessage, w as getCallFinishReason, wt as ImagePart, x as bindRequestExecutor, xt as EventPayload, y as TextLogicExecuteArgs, yt as ChosenEvent, z as CreateDecisionRequestOptions } from "./text-logic-x17uLBwA.mjs";
2
+ import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-B4B-TQSV.mjs";
3
+ import { C as AgentInteractionEvent, D as eventFromInteraction, E as GetInteractionOptions, O as getInteraction, S as AgentInteractionDescriptor, T as AgentInteractionMeta, _ as FromConfigOptions, a as WithAgentEvents, b as AgentInteraction, c as getAgentSchemas, d as AgentWorkflowActorConfig, f as AgentWorkflowConfig, g as AgentWorkflowTransitionConfig, h as AgentWorkflowStateConfig, i as SetupAgentResult, k as interactionMetaSchema, l as setupAgent, m as AgentWorkflowRequestConfig, n as AgentSchemaPack, o as WithAgentUsageEvent, p as AgentWorkflowInvokeConfig, r as AgentUsageEventPayload, s as createAgentSchemas, t as AgentDefaultMeta, u as AgentWorkflowActionConfig, v as FromConfigResult, w as AgentInteractionEventMeta, x as AgentInteractionChoice, y as SchemaCompiler } from "./setup-agent-DgFAhaPJ.mjs";
4
+ import { C as runAgent, D as AgentStepRequest, E as AgentRequest, S as isAgentIdle, T as traceTransitions, _ as AgentTraceEvent, a as AgentMaxModelCallsExceededError, b as createAgentInbox, c as AgentRunMeta, d as AgentRunStart, f as AgentRuntime, g as AgentTimerScheduler, h as AgentTimerEvent, i as AgentInputFrom, l as AgentRunOptions, m as AgentSnapshotDivergedError, n as AgentEffects, o as AgentRunErrorCause, p as AgentRuntimeOptions, r as AgentInbox, s as AgentRunInit, t as AGENT_TRACE_SCHEMA_VERSION, u as AgentRunResult, v as AgentTransitionHandler, w as serializeTraceEvent, x as createAgentRuntime, y as JsonSerializableTraceEvent } from "./run-agent-BxkeuAYR.mjs";
5
+ import { c as AgentLogEntry, d as AgentMachineVersionMismatchError, h as JsonValue, n as AgentEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-DYun526m.mjs";
6
+ import { t as PresetMachine } from "./internal-BzlpzSux.mjs";
7
+ import { a as getMessageText, b as RecordCallOptions, c as isStandardSchema, d as userMessage, i as getJsonSchemaSync, j as Recorder, l as systemMessage, n as assistantMessage, o as getStateMeta, r as getJsonSchema, s as getStatePath, t as MetaOfSnapshot, u as toolMessage } from "./utils-B8k-YPYI.mjs";
9
8
  import { AnyActorLogic, AnyMachineSnapshot, AnyStateMachine, ContextFrom, DoneActorEvent, EventFromLogic, InputFrom, OutputFrom, SnapshotFrom, StateValueFrom } from "xstate";
10
9
  //#region src/type-helpers.d.ts
11
10
  type SchemaAt<T, TKey extends PropertyKey> = T extends {
@@ -118,155 +117,103 @@ interface DescribeMachineOptions {
118
117
  */
119
118
  export declare function describeMachine(machine: AnyStateMachine, options?: DescribeMachineOptions): string;
120
119
  //#endregion
121
- //#region src/decide-next.d.ts
122
- /** Options for {@link decideNext}. */
123
- interface DecideNextOptions<TSnapshot extends AnyMachineSnapshot = AnyMachineSnapshot> {
124
- /** The decide executor that asks a model to pick one option. */
125
- decide: AgentDecisionExecutor;
126
- /** Model ref, passed through to the executor. */
127
- model: string;
128
- /** Event types the model may choose: exact types or wildcards (`'desk.*'`, `'*'`). */
129
- allowedEvents: string | readonly string[];
130
- /**
131
- * Concrete payloads per event type, without `type`. One option per payload.
132
- * A candidate type with no key is offered bare, as `{ type }`; an empty list
133
- * offers nothing for it. To withhold a type, give it `[]`:
134
- * `(s) => ({ "desk.refund": [{ amount: s.context.requested }], "desk.close": [] })`.
135
- */
136
- payloads?: (snapshot: TSnapshot) => Partial<Record<string, Record<string, unknown>[]>>;
137
- system?: string;
138
- prompt?: string;
139
- /** Semantic request name, for traces and scripted executors. Default `'decideNext'`. */
140
- name?: string;
141
- /**
142
- * Describe what each option changes: the state value and the changed
143
- * top-level context keys, computed with xstate's pure `transition()`.
144
- * An array limits which context keys are reported (a state value change is
145
- * always reported). Each reported value is cut to 120 characters.
146
- */
147
- lookahead?: boolean | readonly string[];
148
- /** Retries after a failed choice. Default `2`. */
149
- maxRetries?: number;
150
- signal?: AbortSignal;
151
- /** How the decision is split into model calls. Default `'auto'`; see {@link DecisionStrategy}. */
152
- strategy?: DecisionStrategy;
153
- /** Model ref that fills open payload fields under `'pick-then-fill'`. */
154
- fillModel?: string;
155
- /** Named groups of event types for `'grouped'`; the rest group by prefix before the first `.`. */
156
- groups?: Record<string, readonly string[]>;
157
- /** Fills open payload fields with `fillModel`. */
158
- generateText?: AgentRequestExecutor;
159
- }
160
- /** Result of {@link decideNext}. */
161
- interface DecideNextResult<TEvent = ChosenEvent> {
162
- /** The chosen event, or `null` when the snapshot accepts none of the options. */
163
- event: TEvent | null;
164
- /** Failed attempts before the choice landed. */
165
- attempts: DecisionAttempt[];
166
- /** The request built for the executor, with the offered `options` and the same `withheld`. */
167
- request: AgentDecisionRequest;
168
- /**
169
- * The candidates the snapshot rejected: every `allowedEvents` type × payload,
170
- * built the same way as the offered options, where `snapshot.can(event)` was
171
- * false or the state handles the type through a transition tagged
172
- * `meta: { actor: "human" }`. Never offered to the model. Filled when
173
- * nothing is offered too.
174
- */
175
- withheld: ChosenEvent[];
176
- }
120
+ //#region src/generator-bridge.d.ts
177
121
  /**
178
- * Asks a model to choose the next event for ANY XState snapshot, including a
179
- * machine built with plain `createMachine`/`setup` that knows nothing about AI.
180
- * The candidates are the `allowedEvents` an active state handles, one option per
181
- * payload, kept only where `snapshot.can(event)` is true and no transition
182
- * tagged `meta: { actor: "human" }` handles the type; the rest come back as
183
- * `withheld`. Each option is
184
- * described from the transition's `description`, else the event schema's,
185
- * plus (with `lookahead`) what it changes. The chosen event must equal one
186
- * offered option; anything else is retried.
187
- *
188
- * It never sends. The host sends the event, re-checking `can` first, because
189
- * the actor may have moved while the model was thinking. With no options it
190
- * returns `{ event: null }` without calling the executor. Exhausting retries
191
- * throws `AgentDecisionExhaustedError`.
192
- *
193
- * @example
194
- * ```ts no-check
195
- * let busy = false;
196
- * actor.subscribe(async (snapshot) => {
197
- * if (busy || !snapshot.matches('reviewing')) return;
198
- * busy = true;
199
- * try {
200
- * const { event } = await decideNext(snapshot, {
201
- * decide,
202
- * model: 'quick',
203
- * allowedEvents: 'desk.*',
204
- * payloads: (s) => ({ 'desk.refund': [{ amount: s.context.requested }] }),
205
- * lookahead: true,
206
- * });
207
- * if (event && actor.getSnapshot().can(event)) actor.send(event);
208
- * } finally {
209
- * busy = false;
210
- * }
211
- * });
212
- * ```
122
+ * `createGeneratorBridge`: an async generator's pull contract, across an
123
+ * actor boundary.
124
+ * @module
213
125
  */
214
- export declare function decideNext<TSnapshot extends AnyMachineSnapshot>(snapshot: TSnapshot, options: DecideNextOptions<TSnapshot>): Promise<DecideNextResult<EventFromSnapshot<TSnapshot>>>;
215
- //#endregion
216
- //#region src/policy-decider.d.ts
217
- /** Options for {@link createPolicyDecider}: everything {@link runAgent} takes for the policy run, except how the run opens. */
218
- interface PolicyDeciderOptions<TPolicy extends AnyStateMachine> extends Omit<AgentRunOptions<TPolicy>, "input" | "event" | "attempts" | "snapshot" | "events" | "onIdle" | "signal" | "threadId"> {
126
+ /** What {@link GeneratorBridge.forward} reports once the generator stops. */
127
+ type ForwardResult<TReturn> =
128
+ /**
129
+ * The generator returned. Also when the consumer stopped and then pulled a
130
+ * value yielded while unwinding: as with `yield*`, that resumes the
131
+ * generator, which then completes normally with `value`.
132
+ */
133
+ {
134
+ closed: false;
135
+ value: TReturn | undefined;
136
+ } |
137
+ /** The consumer stopped reading; `value` is what the generator returned while unwinding. */
138
+ {
139
+ closed: true;
140
+ value: TReturn | undefined;
141
+ };
142
+ /** The two ends of a {@link createGeneratorBridge} bridge. */
143
+ interface GeneratorBridge<T> {
144
+ /**
145
+ * Producer side, inside an actor: hands `value` to the consumer and waits
146
+ * until the consumer pulls again, as a generator suspended at `yield`
147
+ * does. Resolves `true` when the consumer pulled, `false` when it stopped
148
+ * (`.return()`, a `break`) or the run settled. Rejects with what the
149
+ * consumer passed to `.throw()`.
150
+ */
151
+ put(value: T): Promise<boolean>;
219
152
  /**
220
- * The `store` thread for one decision's policy run. Every decision, and every
221
- * retry of one, needs its own thread: a thread that already has entries is
222
- * resumed, so a shared one would return an earlier decision's choice. Default
223
- * with a `store`: `policy:${info.callKey}:${hash}`, where `hash` is the
224
- * SHA-256 of the policy input's canonical JSON. The call key is unique per
225
- * call and attempt and stays the same when a crashed run re-issues the call;
226
- * the hash keeps a machine that asks something else at the same call site
227
- * after a version bridge, which keeps the call key, off the earlier thread. Required
228
- * with a `store` when the decider is called without a `callKey`.
153
+ * Producer side: drives `generator` through {@link put}. A consumer's
154
+ * `.throw(error)` becomes `generator.throw(error)`; a consumer that stops
155
+ * gets `generator.return()`, so its `finally` blocks run before this
156
+ * resolves. Values the generator yields while unwinding still reach the
157
+ * consumer, as with `yield*`.
229
158
  */
230
- threadId?: (request: AgentExecutorDecisionRequest, info?: AgentRequestExecutorInfo) => string;
159
+ forward<TReturn>(generator: AsyncGenerator<T, TReturn, undefined>): Promise<ForwardResult<TReturn>>;
231
160
  /**
232
- * Builds the policy's input from the decision request. Default:
233
- * `{ facts: request.metadata?.facts, options, system: request.system, prompt: request.prompt }`,
234
- * where `options` are the offered events (`request.options[].event`). The
235
- * policy's input schema validates it.
161
+ * Consumer side: yields each value the producer puts until `settled`
162
+ * resolves, then returns what it resolved to. Pass the run:
163
+ * `const result = yield* bridge.stream(runAgent(machine, options))`. When
164
+ * the consumer stops, it waits for `settled` before it returns, so the
165
+ * producer has unwound by then, and returns what `settled` resolved to
166
+ * rather than the value passed to `.return()`. As with any `yield*`, a
167
+ * stopped consumer skips the code after it in the enclosing generator;
168
+ * cleanup that must run either way goes in a `finally`. A run that fails
169
+ * while a stopped consumer waits (a legacy `finally` that throws) throws
170
+ * its error from `.return()` instead. A consumer that pulls again after
171
+ * stopping (`.next()` on a value yielded while unwinding) resumes, as with
172
+ * `yield*`: the code after it runs and gets the run's result, failed or not.
236
173
  */
237
- input?: (request: AgentExecutorDecisionRequest) => InputFrom<TPolicy>;
174
+ stream<TSettled>(settled: PromiseLike<TSettled>): AsyncGenerator<T, TSettled, undefined>;
238
175
  }
239
176
  /**
240
- * Runs a policy machine as a decide executor: each decision request starts one
241
- * run of `policy`, and its output is the chosen event. The policy can answer
242
- * with a rule (a `choice` over the facts, no model call) and invoke
243
- * `agent.decide` for the rest, answered by `options.executors`.
177
+ * A backpressured hand-off between an actor and an async generator's
178
+ * consumer, for a loop whose public surface is an `AsyncGenerator`: the
179
+ * machine owns the loop head, each pass is an actor, and the events it
180
+ * yields still reach the consumer one pull at a time.
244
181
  *
245
- * The environment still judges the event: one it does not accept is retried
246
- * like any other decider's choice. The policy's input must be JSON (it opens
247
- * the policy run's event log): the default drops keys whose value is
248
- * `undefined`, and any other value that is not JSON throws before the run. The policy's token usage is reported on the
249
- * result, and left out when the policy made no model call. A run that does not
250
- * end `done` with an event throws `AgentError` with code `policy-not-done`.
182
+ * One bridge serves one run.
251
183
  *
252
184
  * @example
253
- * ```ts no-check
254
- * const decide = createPolicyDecider(policyMachine, { executors: modelExecutors });
255
- * await runAgent(deskMachine, { input, executors: { ...modelExecutors, decide } });
185
+ * ```ts
186
+ * async function* carvedLoop(input: Input): AsyncGenerator<Event, Result> {
187
+ * const bridge = createGeneratorBridge<Event>();
188
+ * const pass = createAsyncLogic({
189
+ * run: async () => {
190
+ * const step = await bridge.forward(legacyPass(input));
191
+ * return step.closed ? { kind: "closed" } : step.value;
192
+ * },
193
+ * });
194
+ * const result = yield* bridge.stream(runAgent(loopMachine, { input, actors: { pass } }));
195
+ * if (result.status === "error") throw result.error;
196
+ * return toResult(result);
197
+ * }
256
198
  * ```
257
199
  */
258
- export declare function createPolicyDecider<TPolicy extends AnyStateMachine>(policy: TPolicy, options?: PolicyDeciderOptions<TPolicy>): AgentDecisionExecutor;
200
+ export declare function createGeneratorBridge<T>(): GeneratorBridge<T>;
259
201
  //#endregion
260
202
  //#region src/wrap-workflow.d.ts
261
203
  /** The effects a wrapped workflow calls: async functions, by name. */
262
204
  type WorkflowEffects<TEffects> = { [K in keyof TEffects]: (...args: never[]) => PromiseLike<unknown>; };
263
205
  /** What a wrapped workflow's `run` gets besides its input and effects. */
264
- interface WorkflowRunContext {
206
+ interface WorkflowRunContext<TLive = undefined> {
265
207
  /** Aborted when the run is aborted or the machine stops the workflow. */
266
208
  signal: AbortSignal;
209
+ /**
210
+ * The live object this call passed as `live` (the instance a class-shaped
211
+ * loop runs on), so one wrapped workflow serves every instance.
212
+ */
213
+ live: TLive;
267
214
  }
268
215
  /** Options for {@link wrapWorkflow}. */
269
- interface WrapWorkflowConfig<TInput, TOutput, TEffects extends WorkflowEffects<TEffects>> {
216
+ interface WrapWorkflowConfig<TInput, TOutput, TEffects extends WorkflowEffects<TEffects>, TLive = undefined> {
270
217
  /** The machine id. */
271
218
  id: string;
272
219
  /** The machine version, for the event log. Default `"1"`. */
@@ -281,7 +228,7 @@ interface WrapWorkflowConfig<TInput, TOutput, TEffects extends WorkflowEffects<T
281
228
  * functions is passed as is. An effect that resolves to a stream (anything
282
229
  * `for await` reads) settles once the stream is read, with its chunks.
283
230
  */
284
- run: (input: TInput, effects: TEffects, context: WorkflowRunContext) => PromiseLike<TOutput>;
231
+ run: (input: TInput, effects: TEffects, context: WorkflowRunContext<TLive>) => PromiseLike<TOutput>;
285
232
  /**
286
233
  * Maps an effect's arguments, result, or error before it is journaled as an
287
234
  * event. Return a redacted value for secrets and private records: every
@@ -329,7 +276,7 @@ type WrappedWorkflowContext<TInput, TOutput> = {
329
276
  failures: number;
330
277
  };
331
278
  /** Options for {@link WrappedWorkflow.run}: `runAgent` options that fit a black box, plus fakes and a recorder. */
332
- interface WrappedWorkflowRunOptions<TEffects, TInput, TOutput> extends Pick<AgentRunOptions<WrappedWorkflowMachine<TInput, TOutput>>, "signal" | "inspect" | "onTransition" | "onTrace" | "onEvent" | "metadata" | "verification"> {
279
+ interface WrappedWorkflowRunOptions<TEffects, TInput, TOutput, TLive = undefined> extends Pick<AgentRunOptions<WrappedWorkflowMachine<TInput, TOutput>>, "signal" | "inspect" | "onTransition" | "onTrace" | "onEvent" | "metadata" | "verification"> {
333
280
  /** Replaces some effects for this run: fakes, stubs, replay wrappers. */
334
281
  effects?: Partial<TEffects>;
335
282
  /**
@@ -337,9 +284,16 @@ interface WrappedWorkflowRunOptions<TEffects, TInput, TOutput> extends Pick<Agen
337
284
  * result with `recorder.output`, so `recorder.recording` is a golden run.
338
285
  */
339
286
  recorder?: Recorder;
287
+ /**
288
+ * `recorder.fn` options per effect: `serialize` for a result that is not
289
+ * JSON, `revive` to rebuild it in replay, `redact` for arguments.
290
+ */
291
+ recordOptions?: { [K in keyof TEffects]?: RecordCallOptions; };
292
+ /** Passed to the workflow as `context.live`: this call's live object. */
293
+ live?: TLive;
340
294
  }
341
295
  /** The result of {@link wrapWorkflow}. */
342
- interface WrappedWorkflow<TInput, TOutput, TEffects> {
296
+ interface WrappedWorkflow<TInput, TOutput, TEffects, TLive = undefined> {
343
297
  /**
344
298
  * `running` invokes the workflow and counts its effect calls; `done` is
345
299
  * final with the workflow's result as output. A rejection is unhandled, so
@@ -354,7 +308,9 @@ interface WrappedWorkflow<TInput, TOutput, TEffects> {
354
308
  * workflow that returns an `aborted` result still returns it. Once it
355
309
  * aborts, an effect call throws `signal.reason` instead of running.
356
310
  */
357
- run(input: TInput, options?: WrappedWorkflowRunOptions<TEffects, TInput, TOutput>): Promise<TOutput>;
311
+ run(input: TInput, ...options: undefined extends TLive ? [options?: WrappedWorkflowRunOptions<TEffects, TInput, TOutput, TLive>] : [options: WrappedWorkflowRunOptions<TEffects, TInput, TOutput, TLive> & {
312
+ live: TLive;
313
+ }]): Promise<TOutput>;
358
314
  }
359
315
  /** The events a {@link wrapWorkflow} machine handles. */
360
316
  type WrappedWorkflowEvent = EffectCallEvent | EffectDoneEvent | EffectErrorEvent;
@@ -388,7 +344,7 @@ type WrappedWorkflowMachine<TInput, TOutput> = PresetMachine<WrappedWorkflowCont
388
344
  * const reply = await support.run(ticket); // what legacyRunTicket returned
389
345
  * ```
390
346
  */
391
- export declare function wrapWorkflow<TInput, TOutput, TEffects extends WorkflowEffects<TEffects>>(config: WrapWorkflowConfig<TInput, TOutput, TEffects>): WrappedWorkflow<TInput, TOutput, TEffects>;
347
+ export declare function wrapWorkflow<TInput, TOutput, TEffects extends WorkflowEffects<TEffects>, TLive = undefined>(config: WrapWorkflowConfig<TInput, TOutput, TEffects, TLive>): WrappedWorkflow<TInput, TOutput, TEffects, TLive>;
392
348
  //#endregion
393
349
  //#region src/provide-executors.d.ts
394
350
  /** Options for {@link provideExecutors}. */
@@ -460,4 +416,4 @@ interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMac
460
416
  */
461
417
  export declare function provideExecutors<TMachine extends AnyStateMachine>(machine: TMachine, executors: AgentRequestExecutors, options?: ProvideExecutorsOptions<TMachine>): TMachine;
462
418
  //#endregion
463
- export { ACT_STATE_EXITED, AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, type AgentActInput, type AgentCallUsage, type AgentDecisionExecutor, AgentDecisionExhaustedError, type AgentDecisionInput, type AgentDecisionOption, type AgentDecisionRejection, type AgentDecisionRequest, type AgentDefaultMeta, type AgentEffects, AgentError, type AgentEventDescriptor, AgentEventLogConflictError, type AgentEventLogStore, type AgentEventSchemaInput, type AgentEventSchemaInputMap, type AgentExecutorDecisionRequest, type AgentExecutorTextRequest, type AgentFinishReason, type AgentInbox, type AgentInputFrom, type AgentInteraction, type AgentInteractionChoice, type AgentInteractionDescriptor, type AgentInteractionEvent, type AgentInteractionEventMeta, type AgentInteractionMeta, AgentInvalidEventPayloadError, type AgentLogEntry, AgentMachineVersionMismatchError, AgentMaxModelCallsExceededError, type AgentMessage, type AgentModelMap, type AgentModelRef, type AgentOutputMode, type AgentRequest, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestMode, type AgentRequestOptions, type AgentRequestSource, type AgentRunErrorCause, type AgentRunInit, type AgentRunMeta, type AgentRunOptions, type AgentRunResult, type AgentRunStart, type AgentRuntime, type AgentRuntimeOptions, type AgentSchemaPack, type AgentSchemas, AgentSnapshotDivergedError, type AgentStepRequest, type AgentTextRequest, type AgentTextResult, type AgentTimerEvent, type AgentTimerScheduler, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentToolSchema, type AgentTools, type AgentTraceEvent, type AgentTransitionHandler, AgentTruncatedError, type AgentUsage, type AgentUsageEvent, type AgentUsageEventPayload, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AllowedEventPattern, type AllowedEvents, type AssistantMessage, type BuiltinAgentActors, type ChosenEvent, type ContextOf, type CreateDecisionRequestOptions, DEFAULT_ACT_MAX_STEPS, type DataContent, type DecideNextOptions, type DecideNextResult, type DecisionAttempt, type DecisionLogic, type DecisionLogicConfig, type DecisionStrategy, type DescribeMachineOptions, type DoneActorEventOf, type EffectCallEvent, type EffectDoneEvent, type EffectErrorEvent, type EventFromSnapshot, type EventOf, type EventPayload, type EventUnion, type FilePart, type FromConfigOptions, type FromConfigResult, GROUPED_EVENT_THRESHOLD, type GetInteractionOptions, type ImagePart, type InferInput, type InferOutput, type InputOf, type InspectedActorRef, type JsonSerializableTraceEvent, MAX_FINITE_PAYLOADS, type MetaOf, type MetaOfSnapshot, type NormalizedEventSchemas, type OutputOf, type PolicyDeciderOptions, type ProvideExecutorsOptions, type ProviderOptions, type ProviderStructuredOutput, type RequestNamesOf, type ResolveDecisionOptions, type SchemaCompiler, type SetupAgentResult, type SnapshotOf, type StandardSchemaV1, type StateValueOf, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultOutput, type ToolResultPart, type UserMessage, type WithAgentEvents, type WithAgentInputSchema, type WithAgentUsageEvent, type WorkflowEffects, type WorkflowRunContext, type WrapWorkflowConfig, type WrappedWorkflow, type WrappedWorkflowContext, type WrappedWorkflowEvent, type WrappedWorkflowMachine, type WrappedWorkflowRunOptions, assistantMessage, bindRequestExecutor, createAgentInbox, createAgentRuntime, createAgentSchemas, createDecisionLogic, createDecisionRequest, createTextLogic, eventFromInteraction, getAcceptedEvents, getAgentOutputMode, getAgentSchemas, getCallFinishReason, getCallUsage, getInteraction, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getMessageText, getStateMeta, getStatePath, inspectTransitions, interactionMetaSchema, isAgentIdle, isStandardSchema, parseAgentEvent, parseOutput, parseProviderOutput, providerOutputSchema, renderDecisionAttempts, resolveDecision, runAgent, runToQuiescence, serializeTraceEvent, setupAgent, systemMessage, toolMessage, traceTransitions, userMessage };
419
+ export { ACT_STATE_EXITED, AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, type AgentActInput, type AgentCallUsage, type AgentDecisionExecutor, AgentDecisionExhaustedError, type AgentDecisionInput, type AgentDecisionOption, type AgentDecisionRejection, type AgentDecisionRequest, type AgentDefaultMeta, type AgentEffects, AgentError, type AgentEventDescriptor, AgentEventLogConflictError, type AgentEventLogStore, type AgentEventSchemaInput, type AgentEventSchemaInputMap, type AgentExecutorDecisionRequest, type AgentExecutorTextRequest, type AgentFinishReason, type AgentInbox, type AgentInputFrom, type AgentInteraction, type AgentInteractionChoice, type AgentInteractionDescriptor, type AgentInteractionEvent, type AgentInteractionEventMeta, type AgentInteractionMeta, AgentInvalidEventPayloadError, type AgentLogEntry, AgentMachineVersionMismatchError, AgentMaxModelCallsExceededError, type AgentMessage, type AgentModelMap, type AgentModelRef, type AgentOutputMode, type AgentRequest, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestMode, type AgentRequestOptions, type AgentRequestSource, type AgentRunErrorCause, type AgentRunInit, type AgentRunMeta, type AgentRunOptions, type AgentRunResult, type AgentRunStart, type AgentRuntime, type AgentRuntimeOptions, type AgentSchemaPack, type AgentSchemas, AgentSnapshotDivergedError, type AgentStepRequest, type AgentTextRequest, type AgentTextResult, type AgentTimerEvent, type AgentTimerScheduler, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentToolSchema, type AgentTools, type AgentTraceEvent, type AgentTransitionHandler, AgentTruncatedError, type AgentUsage, type AgentUsageEvent, type AgentUsageEventPayload, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AllowedEventPattern, type AllowedEvents, type AssistantMessage, type BuiltinAgentActors, type ChosenEvent, type ContextOf, type CreateDecisionRequestOptions, DEFAULT_ACT_MAX_STEPS, type DataContent, type DecisionAttempt, type DecisionLogic, type DecisionLogicConfig, type DecisionStrategy, type DescribeMachineOptions, type DoneActorEventOf, type EffectCallEvent, type EffectDoneEvent, type EffectErrorEvent, type EventFromSnapshot, type EventOf, type EventPayload, type EventUnion, type FilePart, type ForwardResult, type FromConfigOptions, type FromConfigResult, GROUPED_EVENT_THRESHOLD, type GeneratorBridge, type GetInteractionOptions, type ImagePart, type InferInput, type InferOutput, type InputOf, type JsonSerializableTraceEvent, MAX_FINITE_PAYLOADS, type MetaOf, type MetaOfSnapshot, type NormalizedEventSchemas, type OutputOf, type ProvideExecutorsOptions, type ProviderOptions, type ProviderStructuredOutput, type RequestNamesOf, type ResolveDecisionOptions, type SchemaCompiler, type SetupAgentResult, type SnapshotOf, type StandardSchemaV1, type StateValueOf, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultOutput, type ToolResultPart, type UserMessage, type WithAgentEvents, type WithAgentInputSchema, type WithAgentUsageEvent, type WorkflowEffects, type WorkflowRunContext, type WrapWorkflowConfig, type WrappedWorkflow, type WrappedWorkflowContext, type WrappedWorkflowEvent, type WrappedWorkflowMachine, type WrappedWorkflowRunOptions, assistantMessage, bindRequestExecutor, createAgentInbox, createAgentRuntime, createAgentSchemas, createDecisionLogic, createDecisionRequest, createTextLogic, eventFromInteraction, getAcceptedEvents, getAgentOutputMode, getAgentSchemas, getCallFinishReason, getCallUsage, getInteraction, getJsonSchema, getJsonSchemaSync, getMessageText, getStateMeta, getStatePath, interactionMetaSchema, isAgentIdle, isStandardSchema, parseAgentEvent, parseOutput, parseProviderOutput, providerOutputSchema, renderDecisionAttempts, resolveDecision, runAgent, serializeTraceEvent, setupAgent, systemMessage, toolMessage, traceTransitions, userMessage };
package/dist/index.mjs CHANGED
@@ -1,9 +1,10 @@
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-BT_cSY0j.mjs";
6
- import { t as AgentEventLogConflictError } from "./event-log-store-Brx9tOHt.mjs";
1
+ import { $ as getJsonSchemaSync, A as bindRequestExecutor, B as parseProviderOutput, C as AGENT_USAGE_EVENT_TYPE, G as getAgentExecutionOptions, I as getCallUsage, L as isTextLogic, M as createTextLogic, N as getAgentOutputMode, P as getCallFinishReason, Q as getJsonSchema, V as providerOutputSchema, W as executorBoundLogics, X as assistantMessage, at as systemMessage, et as getMessageText, i as AgentMachineVersionMismatchError, mt as AgentTruncatedError, nt as getStatePath, ot as toolMessage, pt as AgentError, rt as isStandardSchema, st as userMessage, tt as getStateMeta, z as parseOutput } from "./event-log-CEq_bVXQ.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-B41YBx5U.mjs";
3
+ import { i as isActLogic, n as DEFAULT_ACT_MAX_STEPS, t as ACT_STATE_EXITED } from "./act-Bsz-hUfD.mjs";
4
+ import { n as getAgentSchemas, r as setupAgent, t as createAgentSchemas } from "./setup-agent-CLm6QVGy.mjs";
5
+ import { t as AgentEventLogConflictError } from "./event-log-store-DLAfNM34.mjs";
6
+ import { _ as traceTransitions, a as bindChildMachineForProvide, c as createAgentInbox, d as isAgentIdle, f as isStateMachineLogic, g as toJsonValue, h as serializeTraceEvent, i as bindActForProvide, l as createAgentRuntime, n as AgentMaxModelCallsExceededError, o as bindDecisionForProvide, p as runAgent, r as AgentSnapshotDivergedError, s as bindTextForProvide, t as AGENT_TRACE_SCHEMA_VERSION, u as getConfiguredInvokeSrcs } from "./run-agent-D3gW9wfd.mjs";
7
+ import { n as mapEffects, t as isAsyncIterable } from "./effects-B9IvUPVh.mjs";
7
8
  import { createAsyncLogic, machineToJSON } from "xstate";
8
9
  import { parse } from "acorn";
9
10
  //#region src/messages.ts
@@ -866,76 +867,120 @@ function describeMachine(machine, options = {}) {
866
867
  return lines.join("\n");
867
868
  }
868
869
  //#endregion
869
- //#region src/policy-decider.ts
870
+ //#region src/generator-bridge.ts
871
+ /** A `runAgent` result that settled with an error. */
872
+ function isFailedRun(value) {
873
+ return typeof value === "object" && value !== null && value.status === "error" && "error" in value;
874
+ }
870
875
  /**
871
- * Runs a policy machine as a decide executor: each decision request starts one
872
- * run of `policy`, and its output is the chosen event. The policy can answer
873
- * with a rule (a `choice` over the facts, no model call) and invoke
874
- * `agent.decide` for the rest, answered by `options.executors`.
876
+ * A backpressured hand-off between an actor and an async generator's
877
+ * consumer, for a loop whose public surface is an `AsyncGenerator`: the
878
+ * machine owns the loop head, each pass is an actor, and the events it
879
+ * yields still reach the consumer one pull at a time.
875
880
  *
876
- * The environment still judges the event: one it does not accept is retried
877
- * like any other decider's choice. The policy's input must be JSON (it opens
878
- * the policy run's event log): the default drops keys whose value is
879
- * `undefined`, and any other value that is not JSON throws before the run. The policy's token usage is reported on the
880
- * result, and left out when the policy made no model call. A run that does not
881
- * end `done` with an event throws `AgentError` with code `policy-not-done`.
881
+ * One bridge serves one run.
882
882
  *
883
883
  * @example
884
- * ```ts no-check
885
- * const decide = createPolicyDecider(policyMachine, { executors: modelExecutors });
886
- * await runAgent(deskMachine, { input, executors: { ...modelExecutors, decide } });
884
+ * ```ts
885
+ * async function* carvedLoop(input: Input): AsyncGenerator<Event, Result> {
886
+ * const bridge = createGeneratorBridge<Event>();
887
+ * const pass = createAsyncLogic({
888
+ * run: async () => {
889
+ * const step = await bridge.forward(legacyPass(input));
890
+ * return step.closed ? { kind: "closed" } : step.value;
891
+ * },
892
+ * });
893
+ * const result = yield* bridge.stream(runAgent(loopMachine, { input, actors: { pass } }));
894
+ * if (result.status === "error") throw result.error;
895
+ * return toResult(result);
896
+ * }
887
897
  * ```
888
898
  */
889
- function createPolicyDecider(policy, options = {}) {
890
- const { input = defaultInput, threadId, ...runOptions } = options;
891
- const id = policy.config.id ?? policy.id;
892
- return async (request, info) => {
893
- const policyInput = input(request);
894
- assertJsonSerializable(policyInput, "policy input");
895
- const thread = runOptions.store === void 0 ? void 0 : await policyThread(request, policyInput, info);
896
- const result = await runAgent(policy, {
897
- ...runOptions,
898
- input: policyInput,
899
- ...thread === void 0 ? {} : { threadId: thread },
900
- ...info?.signal ? { signal: info.signal } : {}
899
+ function createGeneratorBridge() {
900
+ const queue = [];
901
+ let wake;
902
+ let ended = false;
903
+ const notify = () => {
904
+ const resume = wake;
905
+ wake = void 0;
906
+ resume?.();
907
+ };
908
+ const put = (value) => {
909
+ if (ended) return Promise.resolve(false);
910
+ return new Promise((pulled, threw) => {
911
+ queue.push({
912
+ value,
913
+ pulled,
914
+ threw
915
+ });
916
+ notify();
901
917
  });
902
- if (result.status !== "done") {
903
- const why = result.status === "error" ? `: ${String(result.error)}` : "";
904
- throw new AgentError("policy-not-done", `policy '${id}' settled '${result.status}'${why}`, { cause: result.status === "error" ? result.error : void 0 });
918
+ };
919
+ return {
920
+ put,
921
+ async forward(generator) {
922
+ let closed = false;
923
+ let resumed = false;
924
+ let step = await generator.next();
925
+ while (!step.done) {
926
+ let pulled;
927
+ try {
928
+ pulled = await put(step.value);
929
+ } catch (error) {
930
+ step = await generator.throw(error);
931
+ continue;
932
+ }
933
+ const freshStop = !pulled && (!closed || resumed);
934
+ if (closed) resumed = pulled;
935
+ if (freshStop) {
936
+ closed = true;
937
+ step = await generator.return(void 0);
938
+ } else step = await generator.next();
939
+ }
940
+ return {
941
+ closed: closed && !resumed,
942
+ value: step.value
943
+ };
944
+ },
945
+ stream(settled) {
946
+ const end = () => {
947
+ ended = true;
948
+ for (const item of queue.splice(0)) item.pulled(false);
949
+ notify();
950
+ };
951
+ Promise.resolve(settled).then(end, end);
952
+ const next = async () => {
953
+ while (!queue.length && !ended) await new Promise((resolve) => wake = resolve);
954
+ return queue.shift();
955
+ };
956
+ const loop = async function* (stopped) {
957
+ while (true) {
958
+ const item = await next();
959
+ if (!item) {
960
+ const result = await settled;
961
+ if (stopped && isFailedRun(result)) throw result.error;
962
+ return result;
963
+ }
964
+ let resumed = false;
965
+ try {
966
+ yield item.value;
967
+ resumed = true;
968
+ stopped = false;
969
+ item.pulled(true);
970
+ } catch (error) {
971
+ resumed = true;
972
+ item.threw(error);
973
+ } finally {
974
+ if (!resumed) {
975
+ item.pulled(false);
976
+ return yield* loop(true);
977
+ }
978
+ }
979
+ }
980
+ };
981
+ return loop(false);
905
982
  }
906
- const event = result.output;
907
- if (!isRecord(event) || typeof event.type !== "string") throw new AgentError("policy-not-done", `policy '${id}' output is not an event: ${JSON.stringify(event)}`);
908
- const { modelCalls, ...usage } = result.usage;
909
- return {
910
- event,
911
- ...modelCalls > 0 ? { usage } : {}
912
- };
913
983
  };
914
- async function policyThread(request, policyInput, info) {
915
- if (threadId) return threadId(request, info);
916
- if (info?.callKey) return `policy:${info.callKey}:${await sha256(canonicalEventJson(policyInput))}`;
917
- throw new AgentError("missing-thread-id", `policy '${id}' has a store but no threadId, and the decision came with no callKey to derive one from`);
918
- }
919
- }
920
- function defaultInput(request) {
921
- const facts = request.metadata?.facts;
922
- return withoutUndefinedKeys({
923
- facts,
924
- options: (request.options ?? []).map((option) => option.event),
925
- system: request.system,
926
- prompt: request.prompt
927
- });
928
- }
929
- /** A copy of `value` with every object key whose value is `undefined` removed, at any depth. */
930
- function withoutUndefinedKeys(value) {
931
- if (Array.isArray(value)) return value.map(withoutUndefinedKeys);
932
- if (!isRecord(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return value;
933
- return Object.fromEntries(Object.entries(value).filter(([, child]) => child !== void 0).map(([key, child]) => [key, withoutUndefinedKeys(child)]));
934
- }
935
- /** Hex SHA-256 of `text`, with Web Crypto (Node, browsers, workers). */
936
- async function sha256(text) {
937
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
938
- return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
939
984
  }
940
985
  //#endregion
941
986
  //#region src/wrap-workflow.ts
@@ -1132,12 +1177,15 @@ function isPlainData(value, seen, hidden) {
1132
1177
  return !("value" in descriptor) || isPlainData(descriptor.value, seen, hidden);
1133
1178
  });
1134
1179
  }
1135
- function workflowLogic(run, effects, runSignal, redact) {
1180
+ function workflowLogic(run, effects, runSignal, redact, live) {
1136
1181
  return createAsyncLogic({ run: async ({ input: contextInput, self, signal }) => {
1137
1182
  const input = typeof contextInput === "object" && contextInput !== null && copiedFrom.has(contextInput) ? copiedFrom.get(contextInput) : contextInput;
1138
1183
  const parent = self._parent;
1139
1184
  const combined = runSignal ? AbortSignal.any([runSignal, signal]) : signal;
1140
- return run(ownCopy(input), observeEffects(effects, (event) => parent?.send(event), combined, redact), { signal: combined });
1185
+ return run(ownCopy(input), observeEffects(effects, (event) => parent?.send(event), combined, redact), {
1186
+ signal: combined,
1187
+ live
1188
+ });
1141
1189
  } });
1142
1190
  }
1143
1191
  function createWrappedMachine(id, version, workflow) {
@@ -1216,18 +1264,19 @@ function wrapWorkflow(config) {
1216
1264
  const machine = createWrappedMachine(config.id, config.version ?? "1", workflowLogic(config.run, config.effects, void 0, config.redact));
1217
1265
  return {
1218
1266
  machine,
1219
- async run(input, options = {}) {
1220
- const { effects: overrides, recorder, ...runOptions } = options;
1267
+ async run(input, ...args) {
1268
+ const options = args[0] ?? {};
1269
+ const { effects: overrides, recorder, recordOptions, live, ...runOptions } = options;
1221
1270
  let effects = {
1222
1271
  ...mapEffects(config.effects, (_name, effect) => effect),
1223
1272
  ...overrides ? mapEffects(overrides, (_name, effect) => effect) : {}
1224
1273
  };
1225
- if (recorder) effects = mapEffects(effects, (name, effect) => recorder.fn(name, effect));
1274
+ if (recorder) effects = mapEffects(effects, (name, effect) => recorder.fn(name, effect, recordOptions?.[name]));
1226
1275
  const { signal: _signal, ...agentOptions } = runOptions;
1227
1276
  const result = await runAgent(machine, {
1228
1277
  ...agentOptions,
1229
1278
  input,
1230
- actors: { workflow: workflowLogic(config.run, effects, options.signal, config.redact) }
1279
+ actors: { workflow: workflowLogic(config.run, effects, options.signal, config.redact, live) }
1231
1280
  });
1232
1281
  if (result.status === "done") {
1233
1282
  const output = result.output;
@@ -1359,4 +1408,4 @@ function missingExecutorError(src, kind, executor) {
1359
1408
  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.`);
1360
1409
  }
1361
1410
  //#endregion
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 };
1411
+ 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, createGeneratorBridge, createTextLogic, describeMachine, eventFromInteraction, getAcceptedEvents, getAgentOutputMode, getAgentSchemas, getCallFinishReason, getCallUsage, getInteraction, getJsonSchema, getJsonSchemaSync, getMessageText, getStateMeta, getStatePath, interactionMetaSchema, isAgentIdle, isAgentMessages, isStandardSchema, messagesSchema, parseAgentEvent, parseOutput, parseProviderOutput, provideExecutors, providerOutputSchema, renderDecisionAttempts, resolveDecision, runAgent, serializeTraceEvent, setupAgent, systemMessage, toolMessage, traceTransitions, userMessage, wrapWorkflow };
@@ -0,0 +1,14 @@
1
+ import { AnyActorRef, EventObject, MachineContext, MetaObject, StateMachine, StateSchema, StateValue } from "xstate";
2
+ //#region src/machines/internal.d.ts
3
+ /**
4
+ * The machine type a preset factory returns: its context, event union, input
5
+ * and output are all concrete, so callers get typed run input and
6
+ * output instead of `AnyStateMachine`. The remaining slots (children, state
7
+ * value/tags/config, source maps) are left permissive — a preset builds its
8
+ * states dynamically, so there is no literal state schema to infer.
9
+ *
10
+ * @internal
11
+ */
12
+ type PresetMachine<TContext extends MachineContext, TInput, TOutput, TEvent extends EventObject = EventObject> = StateMachine<TContext, TEvent, Record<string, AnyActorRef | undefined>, StateValue, string, TInput, TOutput, EventObject, MetaObject, StateSchema, any, any, any, any>;
13
+ //#endregion
14
+ export { PresetMachine as t };
@@ -0,0 +1,14 @@
1
+ import { AnyActorRef, EventObject, MachineContext, MetaObject, StateMachine, StateSchema, StateValue } from "xstate";
2
+ //#region src/machines/internal.d.ts
3
+ /**
4
+ * The machine type a preset factory returns: its context, event union, input
5
+ * and output are all concrete, so callers get typed run input and
6
+ * output instead of `AnyStateMachine`. The remaining slots (children, state
7
+ * value/tags/config, source maps) are left permissive — a preset builds its
8
+ * states dynamically, so there is no literal state schema to infer.
9
+ *
10
+ * @internal
11
+ */
12
+ type PresetMachine<TContext extends MachineContext, TInput, TOutput, TEvent extends EventObject = EventObject> = StateMachine<TContext, TEvent, Record<string, AnyActorRef | undefined>, StateValue, string, TInput, TOutput, EventObject, MetaObject, StateSchema, any, any, any, any>;
13
+ //#endregion
14
+ export { PresetMachine as t };