@statelyai/agent 2.0.0-alpha.29 → 2.0.0-alpha.31

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 (69) hide show
  1. package/CHANGELOG.md +1733 -0
  2. package/dist/ai-sdk.cjs +9 -9
  3. package/dist/ai-sdk.d.cts +5 -5
  4. package/dist/ai-sdk.d.mts +5 -5
  5. package/dist/ai-sdk.mjs +4 -4
  6. package/dist/{decision-Bl_rKQnU.mjs → decision-DqO018Tp.mjs} +23 -10
  7. package/dist/{decision-oevZnkBe.cjs → decision-Iys2hzg3.cjs} +31 -18
  8. package/dist/{event-log-Dtb16p1p.cjs → event-log-Bdww2l1D.cjs} +104 -25
  9. package/dist/{event-log-GPZO9p7_.mjs → event-log-DE430ZCa.mjs} +87 -26
  10. package/dist/{event-log-store-bCdskPNS.cjs → event-log-store-BWMLi6oh.cjs} +1 -1
  11. package/dist/{event-log-store-yalq8C77.mjs → event-log-store-CCWdTPEP.mjs} +1 -1
  12. package/dist/{event-log-store-CN9ygggF.d.cts → event-log-store-DTf_OzB-.d.cts} +1 -1
  13. package/dist/{event-log-store-DS836wch.d.mts → event-log-store-RziIobdW.d.mts} +1 -1
  14. package/dist/index.cjs +136 -23
  15. package/dist/index.d.cts +58 -11
  16. package/dist/index.d.mts +58 -11
  17. package/dist/index.mjs +133 -21
  18. package/dist/log.cjs +2 -2
  19. package/dist/log.d.cts +1 -1
  20. package/dist/log.d.mts +1 -1
  21. package/dist/log.mjs +2 -2
  22. package/dist/machines.cjs +1 -1
  23. package/dist/machines.mjs +1 -1
  24. package/dist/{model-source-C7FFP2Sj.mjs → model-source-CXsSZPq0.mjs} +1 -2
  25. package/dist/{model-source-DjJPjGSP.cjs → model-source-DQ7KgJaT.cjs} +4 -5
  26. package/dist/openai.cjs +3 -3
  27. package/dist/openai.d.cts +2 -2
  28. package/dist/openai.d.mts +2 -2
  29. package/dist/openai.mjs +3 -3
  30. package/dist/otel.d.cts +1 -1
  31. package/dist/otel.d.mts +1 -1
  32. package/dist/{run-agent-C9ubX8Tx.d.cts → run-agent-B5opVUxx.d.cts} +25 -6
  33. package/dist/{run-agent-CxSyZmIE.d.mts → run-agent-D4MwS5GY.d.mts} +25 -6
  34. package/dist/{run-agent-CuQT1xSS.mjs → run-agent-DWZ1uyBJ.mjs} +100 -37
  35. package/dist/{run-agent-cToZ3K42.cjs → run-agent-tmk58M0x.cjs} +100 -37
  36. package/dist/{setup-agent-DniLvDu7.mjs → setup-agent-BaffhCcM.mjs} +38 -3
  37. package/dist/{setup-agent-tsc3vm5I.d.mts → setup-agent-CPyg2ic7.d.mts} +11 -3
  38. package/dist/{setup-agent-DTF3NQg3.cjs → setup-agent-D0L8Anl_.cjs} +38 -3
  39. package/dist/{setup-agent-DlbgwsIJ.d.cts → setup-agent-yFFVXf5s.d.cts} +11 -3
  40. package/dist/tanstack-ai.cjs +3 -3
  41. package/dist/tanstack-ai.d.cts +2 -2
  42. package/dist/tanstack-ai.d.mts +2 -2
  43. package/dist/tanstack-ai.mjs +3 -3
  44. package/dist/testing.cjs +176 -26
  45. package/dist/testing.d.cts +128 -10
  46. package/dist/testing.d.mts +128 -10
  47. package/dist/testing.mjs +168 -20
  48. package/dist/{text-logic-BDbGjYMh.d.mts → text-logic-BwdrDpO9.d.mts} +6 -2
  49. package/dist/{text-logic-9fv1i9aK.d.cts → text-logic-j9hShB7d.d.cts} +6 -2
  50. package/dist/{usage-D8UphgEA.d.mts → usage-BYqv7VBw.d.cts} +1 -1
  51. package/dist/{usage-R1NTmLxY.d.cts → usage-Bl4nK8D-.d.mts} +1 -1
  52. package/dist/validate.cjs +3 -3
  53. package/dist/validate.d.cts +2 -2
  54. package/dist/validate.d.mts +2 -2
  55. package/dist/validate.mjs +3 -3
  56. package/dist/{verify-B5qGC5WN.mjs → verify-BH5e0XLK.mjs} +55 -5
  57. package/dist/{verify-DYH_2VzU.d.cts → verify-CPKDPMwY.d.cts} +14 -6
  58. package/dist/{verify-Cqghu4gz.cjs → verify-CS_xxvVU.cjs} +57 -7
  59. package/dist/{verify-CBuYIpsa.d.mts → verify-tkymWz6X.d.mts} +14 -6
  60. package/package.json +34 -4
  61. package/readme.md +72 -42
  62. package/skills/add-evals/SKILL.md +144 -0
  63. package/skills/add-traces/SKILL.md +147 -0
  64. package/skills/generate-machine/SKILL.md +6 -6
  65. package/skills/graph-engineering/SKILL.md +33 -0
  66. package/skills/improve-machine/SKILL.md +73 -21
  67. package/skills/improve-machine/reference.md +12 -7
  68. package/skills/loop-to-machine/SKILL.md +210 -0
  69. package/skills/loop-to-machine/policy.md +154 -0
package/dist/index.d.cts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { C as UserMessage, S as ToolResultPart, _ as StandardSchemaV1, a as AgentToolDescriptor, b as ToolCallPart, c as AllowedEvents, d as EventUnion, f as FilePart, h as InferOutput, i as AgentToolChoice, l as AssistantMessage, m as InferInput, n as AgentMessage, o as AgentToolExecute, p as ImagePart, r as AgentTool, s as AgentTools, u as ChosenEvent, v as SystemMessage, x as ToolMessage, y as TextPart } from "./types-Dp5_Ru4R.cjs";
2
- import { $ as AgentTruncatedError, A as AgentDecisionExhaustedError, B as createDecisionLogic, C as getAgentOutputMode, D as parseProviderOutput, E as parseOutput, F as CreateDecisionRequestOptions, G as AgentInvalidEventPayloadError, H as renderDecisionAttempts, I as DecisionAttempt, J as AgentSchemas, K as AgentRequestOptions, L as DecisionLogic, M as AgentDecisionOption, N as AgentDecisionRequest, O as providerOutputSchema, P as AgentExecutorDecisionRequest, Q as AgentError, R as DecisionLogicConfig, S as createTextLogic, T as getCallUsage, U as resolveDecision, V as createDecisionRequest, W as AgentEventDescriptor, X as getAcceptedEvents, Y as EventFromSnapshot, Z as parseAgentEvent, _ as TextLogic, a as AgentModelRef, b as TextLogicExecutor, c as AgentRequestExecutorInfo, f as AgentTextRequest, g as ProviderStructuredOutput, j as AgentDecisionInput, k as AgentDecisionExecutor, l as AgentRequestExecutorResult, m as AgentUsage, n as AgentExecutorTextRequest, o as AgentOutputMode, p as AgentTextResult, q as AgentRequestSource, r as AgentFinishReason, s as AgentRequestExecutor, t as AgentCallUsage, u as AgentRequestExecutors, v as TextLogicConfig, w as getCallFinishReason, x as bindRequestExecutor, y as TextLogicExecuteArgs, z as ResolveDecisionOptions } from "./text-logic-9fv1i9aK.cjs";
3
- import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-R1NTmLxY.cjs";
4
- import { C as AgentInteractionEventMeta, D as getInteraction, E as eventFromInteraction, O as interactionMetaSchema, S as AgentInteractionEvent, T as GetInteractionOptions, _ as FromConfigResult, a as WithAgentUsageEvent, b as AgentInteractionChoice, c as setupAgent, d as AgentWorkflowConfig, f as AgentWorkflowInvokeConfig, g as FromConfigOptions, h as AgentWorkflowTransitionConfig, i as WithAgentEvents, l as AgentWorkflowActionConfig, m as AgentWorkflowStateConfig, n as AgentSchemaPack, o as createAgentSchemas, p as AgentWorkflowRequestConfig, r as AgentUsageEventPayload, s as getAgentSchemas, t as AgentDefaultMeta, u as AgentWorkflowActorConfig, v as SchemaCompiler, w as AgentInteractionMeta, x as AgentInteractionDescriptor, y as AgentInteraction } from "./setup-agent-DlbgwsIJ.cjs";
5
- import { C as runAgent, D as AgentRequest, E as traceTransitions, O as AgentStepRequest, S as isAgentIdle, T as serializeTraceEvent, _ as AgentTransitionHandler, a as AgentRunErrorCause, b as createAgentRuntime, c as AgentRunOptions, d as AgentRuntime, f as AgentRuntimeOptions, g as AgentTraceEvent, h as AgentTimerScheduler, i as AgentMaxModelCallsExceededError, l as AgentRunResult, m as AgentTimerEvent, n as AgentEffects, o as AgentRunInit, p as AgentSnapshotDivergedError, r as AgentInputFrom, s as AgentRunMeta, t as AGENT_TRACE_SCHEMA_VERSION, u as AgentRunStart, v as InspectedActorRef, w as runToQuiescence, x as inspectTransitions, y as JsonSerializableTraceEvent } from "./run-agent-C9ubX8Tx.cjs";
6
- import { c as AgentLogEntry, d as AgentMachineVersionMismatchError, n as AgentEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-CN9ygggF.cjs";
2
+ import { $ as AgentTruncatedError, A as AgentDecisionExhaustedError, B as createDecisionLogic, C as getAgentOutputMode, D as parseProviderOutput, E as parseOutput, F as CreateDecisionRequestOptions, G as AgentInvalidEventPayloadError, H as renderDecisionAttempts, I as DecisionAttempt, J as AgentSchemas, K as AgentRequestOptions, L as DecisionLogic, M as AgentDecisionOption, N as AgentDecisionRequest, O as providerOutputSchema, P as AgentExecutorDecisionRequest, Q as AgentError, R as DecisionLogicConfig, S as createTextLogic, T as getCallUsage, U as resolveDecision, V as createDecisionRequest, W as AgentEventDescriptor, X as getAcceptedEvents, Y as EventFromSnapshot, Z as parseAgentEvent, _ as TextLogic, a as AgentModelRef, b as TextLogicExecutor, c as AgentRequestExecutorInfo, f as AgentTextRequest, g as ProviderStructuredOutput, j as AgentDecisionInput, k as AgentDecisionExecutor, l as AgentRequestExecutorResult, m as AgentUsage, n as AgentExecutorTextRequest, o as AgentOutputMode, p as AgentTextResult, q as AgentRequestSource, r as AgentFinishReason, s as AgentRequestExecutor, t as AgentCallUsage, u as AgentRequestExecutors, v as TextLogicConfig, w as getCallFinishReason, x as bindRequestExecutor, y as TextLogicExecuteArgs, z as ResolveDecisionOptions } from "./text-logic-j9hShB7d.cjs";
3
+ import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-BYqv7VBw.cjs";
4
+ import { C as AgentInteractionEventMeta, D as getInteraction, E as eventFromInteraction, O as interactionMetaSchema, S as AgentInteractionEvent, T as GetInteractionOptions, _ as FromConfigResult, a as WithAgentUsageEvent, b as AgentInteractionChoice, c as setupAgent, d as AgentWorkflowConfig, f as AgentWorkflowInvokeConfig, g as FromConfigOptions, h as AgentWorkflowTransitionConfig, i as WithAgentEvents, l as AgentWorkflowActionConfig, m as AgentWorkflowStateConfig, n as AgentSchemaPack, o as createAgentSchemas, p as AgentWorkflowRequestConfig, r as AgentUsageEventPayload, s as getAgentSchemas, t as AgentDefaultMeta, u as AgentWorkflowActorConfig, v as SchemaCompiler, w as AgentInteractionMeta, x as AgentInteractionDescriptor, y as AgentInteraction } from "./setup-agent-yFFVXf5s.cjs";
5
+ import { C as runAgent, D as AgentRequest, E as traceTransitions, O as AgentStepRequest, S as isAgentIdle, T as serializeTraceEvent, _ as AgentTransitionHandler, a as AgentRunErrorCause, b as createAgentRuntime, c as AgentRunOptions, d as AgentRuntime, f as AgentRuntimeOptions, g as AgentTraceEvent, h as AgentTimerScheduler, i as AgentMaxModelCallsExceededError, l as AgentRunResult, m as AgentTimerEvent, n as AgentEffects, o as AgentRunInit, p as AgentSnapshotDivergedError, r as AgentInputFrom, s as AgentRunMeta, t as AGENT_TRACE_SCHEMA_VERSION, u as AgentRunStart, v as InspectedActorRef, w as runToQuiescence, x as inspectTransitions, y as JsonSerializableTraceEvent } from "./run-agent-B5opVUxx.cjs";
6
+ import { c as AgentLogEntry, d as AgentMachineVersionMismatchError, n as AgentEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-DTf_OzB-.cjs";
7
7
  import { 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, u as systemMessage } from "./utils-ebVpCYoF.cjs";
8
8
  import { AnyActorLogic, AnyMachineSnapshot, AnyStateMachine, ContextFrom, DoneActorEvent, EventFromLogic, InputFrom, OutputFrom, SnapshotFrom, StateValueFrom } from "xstate";
9
9
  //#region src/type-helpers.d.ts
@@ -84,9 +84,10 @@ interface DescribeMachineOptions {
84
84
  * label and description (`*` marks the active ones when `snapshot` is given),
85
85
  * and under it every transition leaving it, one per line: `on EVENT`,
86
86
  * `always`, `after <delay>`, invoke `done`/`error`, and `choice` branches,
87
- * each with its guard (`if …`), where it goes (`→ review`), and what it sets
88
- * in context (`sets draft, attempts`). An `Events` section lists the
89
- * machine's event schemas with their descriptions and fields.
87
+ * each with `(human)` when its `meta.actor` is `"human"`, its guard (`if …`),
88
+ * where it goes (`→ review`), and what it sets in context (`sets draft,
89
+ * attempts`). An `Events` section lists the machine's event schemas with their
90
+ * descriptions and fields.
90
91
  *
91
92
  * A transition written as a function shows the targets its source names
92
93
  * (`→ review (conditional)` when it may decline or pick among several),
@@ -143,7 +144,9 @@ interface DecideNextResult<TEvent = ChosenEvent> {
143
144
  /**
144
145
  * The candidates the snapshot rejected: every `allowedEvents` type × payload,
145
146
  * built the same way as the offered options, where `snapshot.can(event)` was
146
- * false. Never offered to the model. Filled when nothing is offered too.
147
+ * false or the state handles the type through a transition tagged
148
+ * `meta: { actor: "human" }`. Never offered to the model. Filled when
149
+ * nothing is offered too.
147
150
  */
148
151
  withheld: ChosenEvent[];
149
152
  }
@@ -151,7 +154,8 @@ interface DecideNextResult<TEvent = ChosenEvent> {
151
154
  * Asks a model to choose the next event for ANY XState snapshot, including a
152
155
  * machine built with plain `createMachine`/`setup` that knows nothing about AI.
153
156
  * The candidates are the `allowedEvents` an active state handles, one option per
154
- * payload, kept only where `snapshot.can(event)` is true; the rest come back as
157
+ * payload, kept only where `snapshot.can(event)` is true and no transition
158
+ * tagged `meta: { actor: "human" }` handles the type; the rest come back as
155
159
  * `withheld`. Each option is
156
160
  * described from the transition's `description`, else the event schema's,
157
161
  * plus (with `lookahead`) what it changes. The chosen event must equal one
@@ -185,6 +189,49 @@ interface DecideNextResult<TEvent = ChosenEvent> {
185
189
  */
186
190
  export declare function decideNext<TSnapshot extends AnyMachineSnapshot>(snapshot: TSnapshot, options: DecideNextOptions<TSnapshot>): Promise<DecideNextResult<EventFromSnapshot<TSnapshot>>>;
187
191
  //#endregion
192
+ //#region src/policy-decider.d.ts
193
+ /** Options for {@link createPolicyDecider}: everything {@link runAgent} takes for the policy run, except how the run opens. */
194
+ interface PolicyDeciderOptions<TPolicy extends AnyStateMachine> extends Omit<AgentRunOptions<TPolicy>, "input" | "event" | "attempts" | "snapshot" | "events" | "onIdle" | "signal" | "threadId"> {
195
+ /**
196
+ * The `store` thread for one decision's policy run. Every decision, and every
197
+ * retry of one, needs its own thread: a thread that already has entries is
198
+ * resumed, so a shared one would return an earlier decision's choice. Default
199
+ * with a `store`: `policy:${info.callKey}:${hash}`, where `hash` is the
200
+ * SHA-256 of the policy input's canonical JSON. The call key is unique per call and attempt and stays the
201
+ * same when a crashed run re-issues the call; the hash keeps a fork that asks
202
+ * something else at the same call site off the parent's thread. Required
203
+ * with a `store` when the decider is called without a `callKey`.
204
+ */
205
+ threadId?: (request: AgentExecutorDecisionRequest, info?: AgentRequestExecutorInfo) => string;
206
+ /**
207
+ * Builds the policy's input from the decision request. Default:
208
+ * `{ facts: request.metadata?.facts, options, system: request.system, prompt: request.prompt }`,
209
+ * where `options` are the offered events (`request.options[].event`). The
210
+ * policy's input schema validates it.
211
+ */
212
+ input?: (request: AgentExecutorDecisionRequest) => InputFrom<TPolicy>;
213
+ }
214
+ /**
215
+ * Runs a policy machine as a decide executor: each decision request starts one
216
+ * run of `policy`, and its output is the chosen event. The policy can answer
217
+ * with a rule (a `choice` over the facts, no model call) and invoke
218
+ * `agent.decide` for the rest, answered by `options.executors`.
219
+ *
220
+ * The environment still judges the event: one it does not accept is retried
221
+ * like any other decider's choice. The policy's input must be JSON (it opens
222
+ * the policy run's event log): the default drops keys whose value is
223
+ * `undefined`, and any other value that is not JSON throws before the run. The policy's token usage is reported on the
224
+ * result, and left out when the policy made no model call. A run that does not
225
+ * end `done` with an event throws `AgentError` with code `policy-not-done`.
226
+ *
227
+ * @example
228
+ * ```ts no-check
229
+ * const decide = createPolicyDecider(policyMachine, { executors: modelExecutors });
230
+ * await runAgent(deskMachine, { input, executors: { ...modelExecutors, decide } });
231
+ * ```
232
+ */
233
+ export declare function createPolicyDecider<TPolicy extends AnyStateMachine>(policy: TPolicy, options?: PolicyDeciderOptions<TPolicy>): AgentDecisionExecutor;
234
+ //#endregion
188
235
  //#region src/provide-executors.d.ts
189
236
  /** Options for {@link provideExecutors}. */
190
237
  interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMachine> {
@@ -253,4 +300,4 @@ interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMac
253
300
  */
254
301
  export declare function provideExecutors<TMachine extends AnyStateMachine>(machine: TMachine, executors: AgentRequestExecutors, options?: ProvideExecutorsOptions<TMachine>): TMachine;
255
302
  //#endregion
256
- export { AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, type AgentCallUsage, type AgentDecisionExecutor, AgentDecisionExhaustedError, type AgentDecisionInput, type AgentDecisionOption, type AgentDecisionRequest, type AgentDefaultMeta, type AgentEffects, AgentError, type AgentEventDescriptor, AgentEventLogConflictError, type AgentEventLogStore, type AgentExecutorDecisionRequest, type AgentExecutorTextRequest, type AgentFinishReason, type AgentInputFrom, type AgentInteraction, type AgentInteractionChoice, type AgentInteractionDescriptor, type AgentInteractionEvent, type AgentInteractionEventMeta, type AgentInteractionMeta, AgentInvalidEventPayloadError, type AgentLogEntry, AgentMachineVersionMismatchError, AgentMaxModelCallsExceededError, type AgentMessage, type AgentModelRef, type AgentOutputMode, type AgentRequest, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, 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 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 AllowedEvents, type AssistantMessage, type ChosenEvent, type ContextOf, type CreateDecisionRequestOptions, type DecisionAttempt, type DecisionLogic, type DecisionLogicConfig, type DoneActorEventOf, type EventOf, type FilePart, type FromConfigOptions, type FromConfigResult, type GetInteractionOptions, type ImagePart, type InferInput, type InferOutput, type InputOf, type InspectedActorRef, type JsonSerializableTraceEvent, type MetaOf, type OutputOf, type ProvideExecutorsOptions, type ProviderStructuredOutput, type RequestNamesOf, type ResolveDecisionOptions, type SchemaCompiler, type SnapshotOf, type StandardSchemaV1, type StateValueOf, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultPart, type UserMessage, type WithAgentEvents, type WithAgentUsageEvent, assistantMessage, bindRequestExecutor, 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 };
303
+ export { AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, type AgentCallUsage, type AgentDecisionExecutor, AgentDecisionExhaustedError, type AgentDecisionInput, type AgentDecisionOption, type AgentDecisionRequest, type AgentDefaultMeta, type AgentEffects, AgentError, type AgentEventDescriptor, AgentEventLogConflictError, type AgentEventLogStore, type AgentExecutorDecisionRequest, type AgentExecutorTextRequest, type AgentFinishReason, type AgentInputFrom, type AgentInteraction, type AgentInteractionChoice, type AgentInteractionDescriptor, type AgentInteractionEvent, type AgentInteractionEventMeta, type AgentInteractionMeta, AgentInvalidEventPayloadError, type AgentLogEntry, AgentMachineVersionMismatchError, AgentMaxModelCallsExceededError, type AgentMessage, type AgentModelRef, type AgentOutputMode, type AgentRequest, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, 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 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 AllowedEvents, type AssistantMessage, type ChosenEvent, type ContextOf, type CreateDecisionRequestOptions, type DecisionAttempt, type DecisionLogic, type DecisionLogicConfig, type DoneActorEventOf, type EventOf, type FilePart, type FromConfigOptions, type FromConfigResult, type GetInteractionOptions, type ImagePart, type InferInput, type InferOutput, type InputOf, type InspectedActorRef, type JsonSerializableTraceEvent, type MetaOf, type OutputOf, type PolicyDeciderOptions, type ProvideExecutorsOptions, type ProviderStructuredOutput, type RequestNamesOf, type ResolveDecisionOptions, type SchemaCompiler, type SnapshotOf, type StandardSchemaV1, type StateValueOf, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultPart, type UserMessage, type WithAgentEvents, type WithAgentUsageEvent, assistantMessage, bindRequestExecutor, 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 };
package/dist/index.d.mts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { C as UserMessage, S as ToolResultPart, _ as StandardSchemaV1, a as AgentToolDescriptor, b as ToolCallPart, c as AllowedEvents, d as EventUnion, f as FilePart, h as InferOutput, i as AgentToolChoice, l as AssistantMessage, m as InferInput, n as AgentMessage, o as AgentToolExecute, p as ImagePart, r as AgentTool, s as AgentTools, u as ChosenEvent, v as SystemMessage, x as ToolMessage, y as TextPart } from "./types-Dp5_Ru4R.mjs";
2
- import { $ as AgentTruncatedError, A as AgentDecisionExhaustedError, B as createDecisionLogic, C as getAgentOutputMode, D as parseProviderOutput, E as parseOutput, F as CreateDecisionRequestOptions, G as AgentInvalidEventPayloadError, H as renderDecisionAttempts, I as DecisionAttempt, J as AgentSchemas, K as AgentRequestOptions, L as DecisionLogic, M as AgentDecisionOption, N as AgentDecisionRequest, O as providerOutputSchema, P as AgentExecutorDecisionRequest, Q as AgentError, R as DecisionLogicConfig, S as createTextLogic, T as getCallUsage, U as resolveDecision, V as createDecisionRequest, W as AgentEventDescriptor, X as getAcceptedEvents, Y as EventFromSnapshot, Z as parseAgentEvent, _ as TextLogic, a as AgentModelRef, b as TextLogicExecutor, c as AgentRequestExecutorInfo, f as AgentTextRequest, g as ProviderStructuredOutput, j as AgentDecisionInput, k as AgentDecisionExecutor, l as AgentRequestExecutorResult, m as AgentUsage, n as AgentExecutorTextRequest, o as AgentOutputMode, p as AgentTextResult, q as AgentRequestSource, r as AgentFinishReason, s as AgentRequestExecutor, t as AgentCallUsage, u as AgentRequestExecutors, v as TextLogicConfig, w as getCallFinishReason, x as bindRequestExecutor, y as TextLogicExecuteArgs, z as ResolveDecisionOptions } from "./text-logic-BDbGjYMh.mjs";
3
- import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-D8UphgEA.mjs";
4
- import { C as AgentInteractionEventMeta, D as getInteraction, E as eventFromInteraction, O as interactionMetaSchema, S as AgentInteractionEvent, T as GetInteractionOptions, _ as FromConfigResult, a as WithAgentUsageEvent, b as AgentInteractionChoice, c as setupAgent, d as AgentWorkflowConfig, f as AgentWorkflowInvokeConfig, g as FromConfigOptions, h as AgentWorkflowTransitionConfig, i as WithAgentEvents, l as AgentWorkflowActionConfig, m as AgentWorkflowStateConfig, n as AgentSchemaPack, o as createAgentSchemas, p as AgentWorkflowRequestConfig, r as AgentUsageEventPayload, s as getAgentSchemas, t as AgentDefaultMeta, u as AgentWorkflowActorConfig, v as SchemaCompiler, w as AgentInteractionMeta, x as AgentInteractionDescriptor, y as AgentInteraction } from "./setup-agent-tsc3vm5I.mjs";
5
- import { C as runAgent, D as AgentRequest, E as traceTransitions, O as AgentStepRequest, S as isAgentIdle, T as serializeTraceEvent, _ as AgentTransitionHandler, a as AgentRunErrorCause, b as createAgentRuntime, c as AgentRunOptions, d as AgentRuntime, f as AgentRuntimeOptions, g as AgentTraceEvent, h as AgentTimerScheduler, i as AgentMaxModelCallsExceededError, l as AgentRunResult, m as AgentTimerEvent, n as AgentEffects, o as AgentRunInit, p as AgentSnapshotDivergedError, r as AgentInputFrom, s as AgentRunMeta, t as AGENT_TRACE_SCHEMA_VERSION, u as AgentRunStart, v as InspectedActorRef, w as runToQuiescence, x as inspectTransitions, y as JsonSerializableTraceEvent } from "./run-agent-CxSyZmIE.mjs";
6
- import { c as AgentLogEntry, d as AgentMachineVersionMismatchError, n as AgentEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-DS836wch.mjs";
2
+ import { $ as AgentTruncatedError, A as AgentDecisionExhaustedError, B as createDecisionLogic, C as getAgentOutputMode, D as parseProviderOutput, E as parseOutput, F as CreateDecisionRequestOptions, G as AgentInvalidEventPayloadError, H as renderDecisionAttempts, I as DecisionAttempt, J as AgentSchemas, K as AgentRequestOptions, L as DecisionLogic, M as AgentDecisionOption, N as AgentDecisionRequest, O as providerOutputSchema, P as AgentExecutorDecisionRequest, Q as AgentError, R as DecisionLogicConfig, S as createTextLogic, T as getCallUsage, U as resolveDecision, V as createDecisionRequest, W as AgentEventDescriptor, X as getAcceptedEvents, Y as EventFromSnapshot, Z as parseAgentEvent, _ as TextLogic, a as AgentModelRef, b as TextLogicExecutor, c as AgentRequestExecutorInfo, f as AgentTextRequest, g as ProviderStructuredOutput, j as AgentDecisionInput, k as AgentDecisionExecutor, l as AgentRequestExecutorResult, m as AgentUsage, n as AgentExecutorTextRequest, o as AgentOutputMode, p as AgentTextResult, q as AgentRequestSource, r as AgentFinishReason, s as AgentRequestExecutor, t as AgentCallUsage, u as AgentRequestExecutors, v as TextLogicConfig, w as getCallFinishReason, x as bindRequestExecutor, y as TextLogicExecuteArgs, z as ResolveDecisionOptions } from "./text-logic-BwdrDpO9.mjs";
3
+ import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-Bl4nK8D-.mjs";
4
+ import { C as AgentInteractionEventMeta, D as getInteraction, E as eventFromInteraction, O as interactionMetaSchema, S as AgentInteractionEvent, T as GetInteractionOptions, _ as FromConfigResult, a as WithAgentUsageEvent, b as AgentInteractionChoice, c as setupAgent, d as AgentWorkflowConfig, f as AgentWorkflowInvokeConfig, g as FromConfigOptions, h as AgentWorkflowTransitionConfig, i as WithAgentEvents, l as AgentWorkflowActionConfig, m as AgentWorkflowStateConfig, n as AgentSchemaPack, o as createAgentSchemas, p as AgentWorkflowRequestConfig, r as AgentUsageEventPayload, s as getAgentSchemas, t as AgentDefaultMeta, u as AgentWorkflowActorConfig, v as SchemaCompiler, w as AgentInteractionMeta, x as AgentInteractionDescriptor, y as AgentInteraction } from "./setup-agent-CPyg2ic7.mjs";
5
+ import { C as runAgent, D as AgentRequest, E as traceTransitions, O as AgentStepRequest, S as isAgentIdle, T as serializeTraceEvent, _ as AgentTransitionHandler, a as AgentRunErrorCause, b as createAgentRuntime, c as AgentRunOptions, d as AgentRuntime, f as AgentRuntimeOptions, g as AgentTraceEvent, h as AgentTimerScheduler, i as AgentMaxModelCallsExceededError, l as AgentRunResult, m as AgentTimerEvent, n as AgentEffects, o as AgentRunInit, p as AgentSnapshotDivergedError, r as AgentInputFrom, s as AgentRunMeta, t as AGENT_TRACE_SCHEMA_VERSION, u as AgentRunStart, v as InspectedActorRef, w as runToQuiescence, x as inspectTransitions, y as JsonSerializableTraceEvent } from "./run-agent-D4MwS5GY.mjs";
6
+ import { c as AgentLogEntry, d as AgentMachineVersionMismatchError, n as AgentEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-RziIobdW.mjs";
7
7
  import { 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, u as systemMessage } from "./utils-BnXdWih3.mjs";
8
8
  import { AnyActorLogic, AnyMachineSnapshot, AnyStateMachine, ContextFrom, DoneActorEvent, EventFromLogic, InputFrom, OutputFrom, SnapshotFrom, StateValueFrom } from "xstate";
9
9
  //#region src/type-helpers.d.ts
@@ -84,9 +84,10 @@ interface DescribeMachineOptions {
84
84
  * label and description (`*` marks the active ones when `snapshot` is given),
85
85
  * and under it every transition leaving it, one per line: `on EVENT`,
86
86
  * `always`, `after <delay>`, invoke `done`/`error`, and `choice` branches,
87
- * each with its guard (`if …`), where it goes (`→ review`), and what it sets
88
- * in context (`sets draft, attempts`). An `Events` section lists the
89
- * machine's event schemas with their descriptions and fields.
87
+ * each with `(human)` when its `meta.actor` is `"human"`, its guard (`if …`),
88
+ * where it goes (`→ review`), and what it sets in context (`sets draft,
89
+ * attempts`). An `Events` section lists the machine's event schemas with their
90
+ * descriptions and fields.
90
91
  *
91
92
  * A transition written as a function shows the targets its source names
92
93
  * (`→ review (conditional)` when it may decline or pick among several),
@@ -143,7 +144,9 @@ interface DecideNextResult<TEvent = ChosenEvent> {
143
144
  /**
144
145
  * The candidates the snapshot rejected: every `allowedEvents` type × payload,
145
146
  * built the same way as the offered options, where `snapshot.can(event)` was
146
- * false. Never offered to the model. Filled when nothing is offered too.
147
+ * false or the state handles the type through a transition tagged
148
+ * `meta: { actor: "human" }`. Never offered to the model. Filled when
149
+ * nothing is offered too.
147
150
  */
148
151
  withheld: ChosenEvent[];
149
152
  }
@@ -151,7 +154,8 @@ interface DecideNextResult<TEvent = ChosenEvent> {
151
154
  * Asks a model to choose the next event for ANY XState snapshot, including a
152
155
  * machine built with plain `createMachine`/`setup` that knows nothing about AI.
153
156
  * The candidates are the `allowedEvents` an active state handles, one option per
154
- * payload, kept only where `snapshot.can(event)` is true; the rest come back as
157
+ * payload, kept only where `snapshot.can(event)` is true and no transition
158
+ * tagged `meta: { actor: "human" }` handles the type; the rest come back as
155
159
  * `withheld`. Each option is
156
160
  * described from the transition's `description`, else the event schema's,
157
161
  * plus (with `lookahead`) what it changes. The chosen event must equal one
@@ -185,6 +189,49 @@ interface DecideNextResult<TEvent = ChosenEvent> {
185
189
  */
186
190
  export declare function decideNext<TSnapshot extends AnyMachineSnapshot>(snapshot: TSnapshot, options: DecideNextOptions<TSnapshot>): Promise<DecideNextResult<EventFromSnapshot<TSnapshot>>>;
187
191
  //#endregion
192
+ //#region src/policy-decider.d.ts
193
+ /** Options for {@link createPolicyDecider}: everything {@link runAgent} takes for the policy run, except how the run opens. */
194
+ interface PolicyDeciderOptions<TPolicy extends AnyStateMachine> extends Omit<AgentRunOptions<TPolicy>, "input" | "event" | "attempts" | "snapshot" | "events" | "onIdle" | "signal" | "threadId"> {
195
+ /**
196
+ * The `store` thread for one decision's policy run. Every decision, and every
197
+ * retry of one, needs its own thread: a thread that already has entries is
198
+ * resumed, so a shared one would return an earlier decision's choice. Default
199
+ * with a `store`: `policy:${info.callKey}:${hash}`, where `hash` is the
200
+ * SHA-256 of the policy input's canonical JSON. The call key is unique per call and attempt and stays the
201
+ * same when a crashed run re-issues the call; the hash keeps a fork that asks
202
+ * something else at the same call site off the parent's thread. Required
203
+ * with a `store` when the decider is called without a `callKey`.
204
+ */
205
+ threadId?: (request: AgentExecutorDecisionRequest, info?: AgentRequestExecutorInfo) => string;
206
+ /**
207
+ * Builds the policy's input from the decision request. Default:
208
+ * `{ facts: request.metadata?.facts, options, system: request.system, prompt: request.prompt }`,
209
+ * where `options` are the offered events (`request.options[].event`). The
210
+ * policy's input schema validates it.
211
+ */
212
+ input?: (request: AgentExecutorDecisionRequest) => InputFrom<TPolicy>;
213
+ }
214
+ /**
215
+ * Runs a policy machine as a decide executor: each decision request starts one
216
+ * run of `policy`, and its output is the chosen event. The policy can answer
217
+ * with a rule (a `choice` over the facts, no model call) and invoke
218
+ * `agent.decide` for the rest, answered by `options.executors`.
219
+ *
220
+ * The environment still judges the event: one it does not accept is retried
221
+ * like any other decider's choice. The policy's input must be JSON (it opens
222
+ * the policy run's event log): the default drops keys whose value is
223
+ * `undefined`, and any other value that is not JSON throws before the run. The policy's token usage is reported on the
224
+ * result, and left out when the policy made no model call. A run that does not
225
+ * end `done` with an event throws `AgentError` with code `policy-not-done`.
226
+ *
227
+ * @example
228
+ * ```ts no-check
229
+ * const decide = createPolicyDecider(policyMachine, { executors: modelExecutors });
230
+ * await runAgent(deskMachine, { input, executors: { ...modelExecutors, decide } });
231
+ * ```
232
+ */
233
+ export declare function createPolicyDecider<TPolicy extends AnyStateMachine>(policy: TPolicy, options?: PolicyDeciderOptions<TPolicy>): AgentDecisionExecutor;
234
+ //#endregion
188
235
  //#region src/provide-executors.d.ts
189
236
  /** Options for {@link provideExecutors}. */
190
237
  interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMachine> {
@@ -253,4 +300,4 @@ interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMac
253
300
  */
254
301
  export declare function provideExecutors<TMachine extends AnyStateMachine>(machine: TMachine, executors: AgentRequestExecutors, options?: ProvideExecutorsOptions<TMachine>): TMachine;
255
302
  //#endregion
256
- export { AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, type AgentCallUsage, type AgentDecisionExecutor, AgentDecisionExhaustedError, type AgentDecisionInput, type AgentDecisionOption, type AgentDecisionRequest, type AgentDefaultMeta, type AgentEffects, AgentError, type AgentEventDescriptor, AgentEventLogConflictError, type AgentEventLogStore, type AgentExecutorDecisionRequest, type AgentExecutorTextRequest, type AgentFinishReason, type AgentInputFrom, type AgentInteraction, type AgentInteractionChoice, type AgentInteractionDescriptor, type AgentInteractionEvent, type AgentInteractionEventMeta, type AgentInteractionMeta, AgentInvalidEventPayloadError, type AgentLogEntry, AgentMachineVersionMismatchError, AgentMaxModelCallsExceededError, type AgentMessage, type AgentModelRef, type AgentOutputMode, type AgentRequest, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, 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 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 AllowedEvents, type AssistantMessage, type ChosenEvent, type ContextOf, type CreateDecisionRequestOptions, type DecisionAttempt, type DecisionLogic, type DecisionLogicConfig, type DoneActorEventOf, type EventOf, type FilePart, type FromConfigOptions, type FromConfigResult, type GetInteractionOptions, type ImagePart, type InferInput, type InferOutput, type InputOf, type InspectedActorRef, type JsonSerializableTraceEvent, type MetaOf, type OutputOf, type ProvideExecutorsOptions, type ProviderStructuredOutput, type RequestNamesOf, type ResolveDecisionOptions, type SchemaCompiler, type SnapshotOf, type StandardSchemaV1, type StateValueOf, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultPart, type UserMessage, type WithAgentEvents, type WithAgentUsageEvent, assistantMessage, bindRequestExecutor, 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 };
303
+ export { AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, type AgentCallUsage, type AgentDecisionExecutor, AgentDecisionExhaustedError, type AgentDecisionInput, type AgentDecisionOption, type AgentDecisionRequest, type AgentDefaultMeta, type AgentEffects, AgentError, type AgentEventDescriptor, AgentEventLogConflictError, type AgentEventLogStore, type AgentExecutorDecisionRequest, type AgentExecutorTextRequest, type AgentFinishReason, type AgentInputFrom, type AgentInteraction, type AgentInteractionChoice, type AgentInteractionDescriptor, type AgentInteractionEvent, type AgentInteractionEventMeta, type AgentInteractionMeta, AgentInvalidEventPayloadError, type AgentLogEntry, AgentMachineVersionMismatchError, AgentMaxModelCallsExceededError, type AgentMessage, type AgentModelRef, type AgentOutputMode, type AgentRequest, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, 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 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 AllowedEvents, type AssistantMessage, type ChosenEvent, type ContextOf, type CreateDecisionRequestOptions, type DecisionAttempt, type DecisionLogic, type DecisionLogicConfig, type DoneActorEventOf, type EventOf, type FilePart, type FromConfigOptions, type FromConfigResult, type GetInteractionOptions, type ImagePart, type InferInput, type InferOutput, type InputOf, type InspectedActorRef, type JsonSerializableTraceEvent, type MetaOf, type OutputOf, type PolicyDeciderOptions, type ProvideExecutorsOptions, type ProviderStructuredOutput, type RequestNamesOf, type ResolveDecisionOptions, type SchemaCompiler, type SnapshotOf, type StandardSchemaV1, type StateValueOf, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultPart, type UserMessage, type WithAgentEvents, type WithAgentUsageEvent, assistantMessage, bindRequestExecutor, 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 };
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- import { $ as getStateMeta, A as createTextLogic, C as AGENT_USAGE_EVENT_TYPE, H as getAgentExecutionOptions, I as parseOutput, L as parseProviderOutput, M as getCallFinishReason, N as getCallUsage, O as bindRequestExecutor, P as isTextLogic, Q as getMessageText, R as providerOutputSchema, V as executorBoundLogics, X as getJsonSchemaSync, Y as getJsonSchema, Z as getMachineStructuralHash, at as userMessage, ct as AgentTruncatedError, et as getStatePath, i as AgentMachineVersionMismatchError, it as toolMessage, j as getAgentOutputMode, q as assistantMessage, rt as systemMessage, st as AgentError, tt as isStandardSchema, u as canonicalEventJson } from "./event-log-GPZO9p7_.mjs";
2
- import { a as createDecisionRequest, c as renderDecisionAttempts, d as getAcceptedEvents, f as isEventPattern, i as createDecisionLogic, l as resolveDecision, m as isRecord, p as parseAgentEvent, s as isDecisionLogic, t as AgentDecisionExhaustedError, u as AgentInvalidEventPayloadError } from "./decision-Bl_rKQnU.mjs";
3
- import { n as getAgentSchemas, r as setupAgent, t as createAgentSchemas } from "./setup-agent-DniLvDu7.mjs";
4
- import { t as AgentEventLogConflictError } from "./event-log-store-yalq8C77.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-CuQT1xSS.mjs";
1
+ import { $ as getStateMeta, A as createTextLogic, C as AGENT_USAGE_EVENT_TYPE, H as getAgentExecutionOptions, I as parseOutput, L as parseProviderOutput, M as getCallFinishReason, N as getCallUsage, O as bindRequestExecutor, P as isTextLogic, Q as getMessageText, R as providerOutputSchema, V as executorBoundLogics, X as getJsonSchemaSync, Y as getJsonSchema, Z as getMachineStructuralHash, at as userMessage, dt as AgentTruncatedError, et as getStatePath, i as AgentMachineVersionMismatchError, it as toolMessage, j as getAgentOutputMode, l as assertJsonSerializable, lt as isRecord, q as assistantMessage, rt as systemMessage, tt as isStandardSchema, u as canonicalEventJson, ut as AgentError } from "./event-log-DE430ZCa.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-DqO018Tp.mjs";
3
+ import { n as getAgentSchemas, r as setupAgent, t as createAgentSchemas } from "./setup-agent-BaffhCcM.mjs";
4
+ import { t as AgentEventLogConflictError } from "./event-log-store-CCWdTPEP.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-DWZ1uyBJ.mjs";
6
6
  import { getNextTransitions, machineToJSON, transition } from "xstate";
7
7
  //#region src/messages.ts
8
8
  const KNOWN_PART_TYPES = /* @__PURE__ */ new Set([
@@ -167,7 +167,8 @@ function validateChoice(value, path) {
167
167
  * reads: an object whose optional `interaction` declares a `label` (a string
168
168
  * with `{context.path}` interpolation, or a function of the context), an
169
169
  * `events` map of choices, payload `choices` (an array, or a context path to
170
- * one), and a `textEvent` (a type, or `{ type, field }`) for free-text answers. This is
170
+ * one), and a `textEvent` (a type, or `{ type, field }`) for free-text answers; and
171
+ * an optional `actor: "human"`, which tags a transition as sent by a person. This is
171
172
  * the default `meta` type `setupAgent` gives a machine; pass it to
172
173
  * `createAgentSchemas({ meta: interactionMetaSchema })` only when building a
173
174
  * schema pack by hand.
@@ -177,6 +178,8 @@ const interactionMetaSchema = { "~standard": {
177
178
  vendor: "statelyai-agent",
178
179
  validate(value) {
179
180
  if (!value || typeof value !== "object" || Array.isArray(value)) return { issues: [{ message: "Expected a state meta object" }] };
181
+ const actor = value["actor"];
182
+ if (actor !== void 0 && actor !== "human") return { issues: [issue("Expected \"human\"", ["actor"])] };
180
183
  const interaction = value["interaction"];
181
184
  if (interaction === void 0) return { value };
182
185
  if (!interaction || typeof interaction !== "object" || Array.isArray(interaction)) return { issues: [issue("Expected an interaction descriptor object", ["interaction"])] };
@@ -451,13 +454,44 @@ function guardText(guard) {
451
454
  if (isObject(decoded) && typeof decoded.type === "string") return decoded.type.startsWith("__fromConfigGuard") ? "guarded" : decoded.type;
452
455
  return "guarded";
453
456
  }
454
- /** True when a transition function's source has a path that returns no transition, so it may not be taken. */
455
- const mayDecline = (code) => /\bundefined\b|\bnull\b|\breturn\s*;|\bif\s*\(|\s\?\s|&&/.test(code);
457
+ /**
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
+ }
456
490
  /**
457
491
  * Where a transition written as a function goes: every string literal after a
458
492
  * `target:` that names a real state node, `(conditional)` when it may decline
459
493
  * or pick among several, `(stays)` when its source has no `target`, `?` when
460
- * it names none that resolves.
494
+ * it names none that resolves or returns a helper call's result.
461
495
  */
462
496
  function targetsInSource(source, code, choice) {
463
497
  const found = /* @__PURE__ */ new Set();
@@ -470,14 +504,15 @@ function targetsInSource(source, code, choice) {
470
504
  const conditional = names.length > 1 || !choice && mayDecline(code);
471
505
  return `${names.join(", ")}${conditional ? " (conditional)" : ""}`;
472
506
  }
473
- return /\btarget\s*:/.test(code) ? "?" : "(stays)";
507
+ return /\btarget\s*:/.test(code) || returnsCall(code) ? "?" : "(stays)";
474
508
  }
475
- /** One transition, as a line: `on GO if context.ready → review; sets draft — description`. */
509
+ /** One transition, as a line: `on GO (human) if context.ready → review; sets draft — description`. */
476
510
  function transitionLine(source, head, transition, options = {}) {
477
511
  const code = codeOf(transition);
478
512
  let to;
479
513
  let guard;
480
514
  let description;
515
+ let human = false;
481
516
  let sets;
482
517
  if (typeof transition === "string") {
483
518
  const node = resolveTarget(source, transition);
@@ -494,12 +529,13 @@ function transitionLine(source, head, transition, options = {}) {
494
529
  }).join(", ") : "(stays)";
495
530
  guard = guardText(transition[options.guardKey ?? "guard"]);
496
531
  description = typeof transition.description === "string" ? transition.description : void 0;
532
+ human = isObject(transition.meta) && transition.meta.actor === "human";
497
533
  sets = contextKeys(transition, void 0);
498
534
  } else {
499
535
  to = "?";
500
536
  sets = [];
501
537
  }
502
- return `${head}${guard ? ` if ${guard}` : ""} → ${to}${sets.length ? `; sets ${sets.join(", ")}` : ""}${description ? ` — ${oneLine(description)}` : ""}`;
538
+ return `${head}${human ? " (human)" : ""}${guard ? ` if ${guard}` : ""} → ${to}${sets.length ? `; sets ${sets.join(", ")}` : ""}${description ? ` — ${oneLine(description)}` : ""}`;
503
539
  }
504
540
  function formatMs(ms) {
505
541
  if (ms < 1e3) return `${ms}ms`;
@@ -546,7 +582,7 @@ function stateLine(node, json) {
546
582
  else if (node.type === "compound" && typeof json.initial === "string") marker = ` (initial: ${json.initial})`;
547
583
  const tags = node.tags.length ? ` [tags: ${node.tags.join(", ")}]` : "";
548
584
  const interaction = node.meta?.interaction;
549
- const label = typeof interaction?.label === "string" ? ` [interaction: "${oneLine(interaction.label)}"]` : "";
585
+ const label = !interaction ? "" : typeof interaction.label === "string" ? ` [interaction: "${oneLine(interaction.label)}"]` : typeof interaction.label === "function" ? " [interaction: computed label]" : " [interaction]";
550
586
  const description = node.description ? ` — ${oneLine(node.description)}` : "";
551
587
  return `${node.key}${marker}${tags}${label}${description}`;
552
588
  }
@@ -583,9 +619,10 @@ function eventLines(machine) {
583
619
  * label and description (`*` marks the active ones when `snapshot` is given),
584
620
  * and under it every transition leaving it, one per line: `on EVENT`,
585
621
  * `always`, `after <delay>`, invoke `done`/`error`, and `choice` branches,
586
- * each with its guard (`if …`), where it goes (`→ review`), and what it sets
587
- * in context (`sets draft, attempts`). An `Events` section lists the
588
- * machine's event schemas with their descriptions and fields.
622
+ * each with `(human)` when its `meta.actor` is `"human"`, its guard (`if …`),
623
+ * where it goes (`→ review`), and what it sets in context (`sets draft,
624
+ * attempts`). An `Events` section lists the machine's event schemas with their
625
+ * descriptions and fields.
589
626
  *
590
627
  * A transition written as a function shows the targets its source names
591
628
  * (`→ review (conditional)` when it may decline or pick among several),
@@ -629,7 +666,8 @@ function describeMachine(machine, options = {}) {
629
666
  * Asks a model to choose the next event for ANY XState snapshot, including a
630
667
  * machine built with plain `createMachine`/`setup` that knows nothing about AI.
631
668
  * The candidates are the `allowedEvents` an active state handles, one option per
632
- * payload, kept only where `snapshot.can(event)` is true; the rest come back as
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
633
671
  * `withheld`. Each option is
634
672
  * described from the transition's `description`, else the event schema's,
635
673
  * plus (with `lookahead`) what it changes. The chosen event must equal one
@@ -664,19 +702,21 @@ function describeMachine(machine, options = {}) {
664
702
  async function decideNext(snapshot, options) {
665
703
  const patterns = typeof options.allowedEvents === "string" ? [options.allowedEvents] : options.allowedEvents;
666
704
  const schemas = snapshot.machine.schemas?.events;
667
- const events = getAcceptedEvents(snapshot, {
705
+ const candidates = getAcceptedEvents(snapshot, {
668
706
  events: schemas,
669
707
  eventTypes: patterns
670
708
  }).filter((event) => !isEventPattern(event.type));
709
+ const humanEventTypes = getHumanEventTypes(snapshot);
710
+ const events = candidates.filter((event) => !humanEventTypes.has(event.type));
671
711
  const payloads = options.payloads?.(snapshot) ?? {};
672
712
  const accepted = [];
673
713
  const withheld = [];
674
- for (const { type } of events) for (const payload of payloads[type] ?? [{}]) {
714
+ for (const { type } of candidates) for (const payload of payloads[type] ?? [{}]) {
675
715
  const event = {
676
716
  ...payload,
677
717
  type
678
718
  };
679
- (safeCan(snapshot, event) ? accepted : withheld).push(event);
719
+ (!humanEventTypes.has(type) && safeCan(snapshot, event) ? accepted : withheld).push(event);
680
720
  }
681
721
  const offered = accepted.map((event) => ({
682
722
  event,
@@ -766,6 +806,78 @@ function short(value, max = 60) {
766
806
  return text.length > max ? `${text.slice(0, max - 1)}…` : text;
767
807
  }
768
808
  //#endregion
809
+ //#region src/policy-decider.ts
810
+ /**
811
+ * Runs a policy machine as a decide executor: each decision request starts one
812
+ * run of `policy`, and its output is the chosen event. The policy can answer
813
+ * with a rule (a `choice` over the facts, no model call) and invoke
814
+ * `agent.decide` for the rest, answered by `options.executors`.
815
+ *
816
+ * The environment still judges the event: one it does not accept is retried
817
+ * like any other decider's choice. The policy's input must be JSON (it opens
818
+ * the policy run's event log): the default drops keys whose value is
819
+ * `undefined`, and any other value that is not JSON throws before the run. The policy's token usage is reported on the
820
+ * result, and left out when the policy made no model call. A run that does not
821
+ * end `done` with an event throws `AgentError` with code `policy-not-done`.
822
+ *
823
+ * @example
824
+ * ```ts no-check
825
+ * const decide = createPolicyDecider(policyMachine, { executors: modelExecutors });
826
+ * await runAgent(deskMachine, { input, executors: { ...modelExecutors, decide } });
827
+ * ```
828
+ */
829
+ function createPolicyDecider(policy, options = {}) {
830
+ const { input = defaultInput, threadId, ...runOptions } = options;
831
+ const id = policy.config.id ?? policy.id;
832
+ return async (request, info) => {
833
+ const policyInput = input(request);
834
+ assertJsonSerializable(policyInput, "policy input");
835
+ const thread = runOptions.store === void 0 ? void 0 : await policyThread(request, policyInput, info);
836
+ const result = await runAgent(policy, {
837
+ ...runOptions,
838
+ input: policyInput,
839
+ ...thread === void 0 ? {} : { threadId: thread },
840
+ ...info?.signal ? { signal: info.signal } : {}
841
+ });
842
+ if (result.status !== "done") {
843
+ const why = result.status === "error" ? `: ${String(result.error)}` : "";
844
+ throw new AgentError("policy-not-done", `policy '${id}' settled '${result.status}'${why}`, { cause: result.status === "error" ? result.error : void 0 });
845
+ }
846
+ const event = result.output;
847
+ if (!isRecord(event) || typeof event.type !== "string") throw new AgentError("policy-not-done", `policy '${id}' output is not an event: ${JSON.stringify(event)}`);
848
+ const { modelCalls, ...usage } = result.usage;
849
+ return {
850
+ event,
851
+ ...modelCalls > 0 ? { usage } : {}
852
+ };
853
+ };
854
+ async function policyThread(request, policyInput, info) {
855
+ if (threadId) return threadId(request, info);
856
+ if (info?.callKey) return `policy:${info.callKey}:${await sha256(canonicalEventJson(policyInput))}`;
857
+ 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`);
858
+ }
859
+ }
860
+ function defaultInput(request) {
861
+ const facts = request.metadata?.facts;
862
+ return withoutUndefinedKeys({
863
+ facts,
864
+ options: (request.options ?? []).map((option) => option.event),
865
+ system: request.system,
866
+ prompt: request.prompt
867
+ });
868
+ }
869
+ /** A copy of `value` with every object key whose value is `undefined` removed, at any depth. */
870
+ function withoutUndefinedKeys(value) {
871
+ if (Array.isArray(value)) return value.map(withoutUndefinedKeys);
872
+ if (!isRecord(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return value;
873
+ return Object.fromEntries(Object.entries(value).filter(([, child]) => child !== void 0).map(([key, child]) => [key, withoutUndefinedKeys(child)]));
874
+ }
875
+ /** Hex SHA-256 of `text`, with Web Crypto (Node, browsers, workers). */
876
+ async function sha256(text) {
877
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
878
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
879
+ }
880
+ //#endregion
769
881
  //#region src/provide-executors.ts
770
882
  /**
771
883
  * Binds a machine's agent actor sources to a set of host `executors` in one
@@ -879,4 +991,4 @@ function missingExecutorError(src, kind, executor) {
879
991
  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.`);
880
992
  }
881
993
  //#endregion
882
- export { AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, AgentDecisionExhaustedError, AgentError, AgentEventLogConflictError, AgentInvalidEventPayloadError, AgentMachineVersionMismatchError, AgentMaxModelCallsExceededError, AgentSnapshotDivergedError, AgentTruncatedError, assistantMessage, bindRequestExecutor, createAgentRuntime, createAgentSchemas, createDecisionLogic, createDecisionRequest, 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 };
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 };
package/dist/log.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_event_log = require("./event-log-Dtb16p1p.cjs");
3
- const require_event_log_store = require("./event-log-store-bCdskPNS.cjs");
2
+ const require_event_log = require("./event-log-Bdww2l1D.cjs");
3
+ const require_event_log_store = require("./event-log-store-BWMLi6oh.cjs");
4
4
  //#region src/event-log-store-conformance.ts
5
5
  /**
6
6
  * The runner-agnostic conformance suite for {@link AgentEventLogStore}
package/dist/log.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as rebindActorSession, C as createReplayEntry, D as getSnapshotStateHash, E as getLogExecutionId, M as replay, N as validateReplayEntries, O as getUsageFromEvents, S as assertJsonSerializable, T as getDecisionAttempts, _ as NonSerializableAgentEventError, a as AGENT_INIT_EVENT_TYPE, b as agentCallOccurrence, c as AgentLogEntry, d as AgentMachineVersionMismatchError, f as AgentPersistedSnapshot, g as LogRecorder, h as JsonValue, i as AGENT_EVENT_SCHEMA_VERSION, j as recordLog, k as initEntry, l as AgentLogInit, m as CreateReplayEntryOptions, n as AgentEventLogStore, o as AgentEventLogError, p as AgentReplayDivergenceError, r as createInMemoryEventLogStore, s as AgentInitEvent, t as AgentEventLogConflictError, u as AgentLogVerification, v as ReplayOptions, w as forkEventLog, x as assertAgentLogEntry, y as ReplayResult } from "./event-log-store-CN9ygggF.cjs";
1
+ import { A as rebindActorSession, C as createReplayEntry, D as getSnapshotStateHash, E as getLogExecutionId, M as replay, N as validateReplayEntries, O as getUsageFromEvents, S as assertJsonSerializable, T as getDecisionAttempts, _ as NonSerializableAgentEventError, a as AGENT_INIT_EVENT_TYPE, b as agentCallOccurrence, c as AgentLogEntry, d as AgentMachineVersionMismatchError, f as AgentPersistedSnapshot, g as LogRecorder, h as JsonValue, i as AGENT_EVENT_SCHEMA_VERSION, j as recordLog, k as initEntry, l as AgentLogInit, m as CreateReplayEntryOptions, n as AgentEventLogStore, o as AgentEventLogError, p as AgentReplayDivergenceError, r as createInMemoryEventLogStore, s as AgentInitEvent, t as AgentEventLogConflictError, u as AgentLogVerification, v as ReplayOptions, w as forkEventLog, x as assertAgentLogEntry, y as ReplayResult } from "./event-log-store-DTf_OzB-.cjs";
2
2
  //#region src/event-log-store-conformance.d.ts
3
3
  /** Produces a fresh, empty store for one case. */
4
4
  type CreateStore = () => Promise<AgentEventLogStore> | AgentEventLogStore;
package/dist/log.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as rebindActorSession, C as createReplayEntry, D as getSnapshotStateHash, E as getLogExecutionId, M as replay, N as validateReplayEntries, O as getUsageFromEvents, S as assertJsonSerializable, T as getDecisionAttempts, _ as NonSerializableAgentEventError, a as AGENT_INIT_EVENT_TYPE, b as agentCallOccurrence, c as AgentLogEntry, d as AgentMachineVersionMismatchError, f as AgentPersistedSnapshot, g as LogRecorder, h as JsonValue, i as AGENT_EVENT_SCHEMA_VERSION, j as recordLog, k as initEntry, l as AgentLogInit, m as CreateReplayEntryOptions, n as AgentEventLogStore, o as AgentEventLogError, p as AgentReplayDivergenceError, r as createInMemoryEventLogStore, s as AgentInitEvent, t as AgentEventLogConflictError, u as AgentLogVerification, v as ReplayOptions, w as forkEventLog, x as assertAgentLogEntry, y as ReplayResult } from "./event-log-store-DS836wch.mjs";
1
+ import { A as rebindActorSession, C as createReplayEntry, D as getSnapshotStateHash, E as getLogExecutionId, M as replay, N as validateReplayEntries, O as getUsageFromEvents, S as assertJsonSerializable, T as getDecisionAttempts, _ as NonSerializableAgentEventError, a as AGENT_INIT_EVENT_TYPE, b as agentCallOccurrence, c as AgentLogEntry, d as AgentMachineVersionMismatchError, f as AgentPersistedSnapshot, g as LogRecorder, h as JsonValue, i as AGENT_EVENT_SCHEMA_VERSION, j as recordLog, k as initEntry, l as AgentLogInit, m as CreateReplayEntryOptions, n as AgentEventLogStore, o as AgentEventLogError, p as AgentReplayDivergenceError, r as createInMemoryEventLogStore, s as AgentInitEvent, t as AgentEventLogConflictError, u as AgentLogVerification, v as ReplayOptions, w as forkEventLog, x as assertAgentLogEntry, y as ReplayResult } from "./event-log-store-RziIobdW.mjs";
2
2
  //#region src/event-log-store-conformance.d.ts
3
3
  /** Produces a fresh, empty store for one case. */
4
4
  type CreateStore = () => Promise<AgentEventLogStore> | AgentEventLogStore;
package/dist/log.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { S as validateReplayEntries, _ as getUsageFromEvents, a as AgentReplayDivergenceError, b as recordLog, c as assertAgentLogEntry, d as createReplayEntry, g as getSnapshotStateHash, h as getLogExecutionId, i as AgentMachineVersionMismatchError, l as assertJsonSerializable, m as getDecisionAttempts, n as AGENT_INIT_EVENT_TYPE, o as NonSerializableAgentEventError, p as forkEventLog, r as AgentEventLogError, s as agentCallOccurrence, t as AGENT_EVENT_SCHEMA_VERSION, v as initEntry, x as replay, y as rebindActorSession } from "./event-log-GPZO9p7_.mjs";
2
- import { n as createInMemoryEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-yalq8C77.mjs";
1
+ import { S as validateReplayEntries, _ as getUsageFromEvents, a as AgentReplayDivergenceError, b as recordLog, c as assertAgentLogEntry, d as createReplayEntry, g as getSnapshotStateHash, h as getLogExecutionId, i as AgentMachineVersionMismatchError, l as assertJsonSerializable, m as getDecisionAttempts, n as AGENT_INIT_EVENT_TYPE, o as NonSerializableAgentEventError, p as forkEventLog, r as AgentEventLogError, s as agentCallOccurrence, t as AGENT_EVENT_SCHEMA_VERSION, v as initEntry, x as replay, y as rebindActorSession } from "./event-log-DE430ZCa.mjs";
2
+ import { n as createInMemoryEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-CCWdTPEP.mjs";
3
3
  //#region src/event-log-store-conformance.ts
4
4
  /**
5
5
  * The runner-agnostic conformance suite for {@link AgentEventLogStore}
package/dist/machines.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_setup_agent = require("./setup-agent-DTF3NQg3.cjs");
2
+ const require_setup_agent = require("./setup-agent-D0L8Anl_.cjs");
3
3
  //#region src/machines/internal.ts
4
4
  /** The builtin inline text request every preset lowers a request entry to. */
5
5
  const GENERATE_TEXT_SRC = "agent.generateText";
package/dist/machines.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { r as setupAgent } from "./setup-agent-DniLvDu7.mjs";
1
+ import { r as setupAgent } from "./setup-agent-BaffhCcM.mjs";
2
2
  //#region src/machines/internal.ts
3
3
  /** The builtin inline text request every preset lowers a request entry to. */
4
4
  const GENERATE_TEXT_SRC = "agent.generateText";
@@ -1,5 +1,4 @@
1
- import { H as getAgentExecutionOptions } from "./event-log-GPZO9p7_.mjs";
2
- import { m as isRecord } from "./decision-Bl_rKQnU.mjs";
1
+ import { H as getAgentExecutionOptions, lt as isRecord } from "./event-log-DE430ZCa.mjs";
3
2
  //#region src/internal/model-source.ts
4
3
  function hasEntries(value) {
5
4
  return isRecord(value) && Object.keys(value).length > 0;
@@ -1,8 +1,7 @@
1
- const require_event_log = require("./event-log-Dtb16p1p.cjs");
2
- const require_decision = require("./decision-oevZnkBe.cjs");
1
+ const require_event_log = require("./event-log-Bdww2l1D.cjs");
3
2
  //#region src/internal/model-source.ts
4
3
  function hasEntries(value) {
5
- return require_decision.isRecord(value) && Object.keys(value).length > 0;
4
+ return require_event_log.isRecord(value) && Object.keys(value).length > 0;
6
5
  }
7
6
  function isMachineLike(value) {
8
7
  return "config" in value && typeof value.transition === "function";
@@ -25,13 +24,13 @@ function describeValue(value) {
25
24
  * model values are. Throws, naming what it got, for anything else. @internal
26
25
  */
27
26
  function resolveModelSource(adapter, source) {
28
- if (require_decision.isRecord(source)) {
27
+ if (require_event_log.isRecord(source)) {
29
28
  if (typeof source.createMachine === "function") {
30
29
  if (hasEntries(source.models)) return { models: source.models };
31
30
  } else if (isMachineLike(source)) {
32
31
  const models = require_event_log.getAgentExecutionOptions(source)?.models;
33
32
  if (hasEntries(models)) return { models };
34
- } else if (require_decision.isRecord(source.models) || typeof source.resolveModel === "function") return source;
33
+ } else if (require_event_log.isRecord(source.models) || typeof source.resolveModel === "function") return source;
35
34
  }
36
35
  throw new TypeError(`${adapter}: expected { models }, { resolveModel }, a setupAgent(...) result with models, or a machine from its createMachine; got ${describeValue(source)}.`);
37
36
  }