@statelyai/agent 2.0.0-alpha.39 → 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 (37) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/evals.cjs +1 -1
  3. package/dist/evals.d.cts +1 -1
  4. package/dist/evals.d.mts +1 -1
  5. package/dist/evals.mjs +1 -1
  6. package/dist/index.cjs +17 -10
  7. package/dist/index.d.cts +28 -11
  8. package/dist/index.d.mts +28 -11
  9. package/dist/index.mjs +17 -10
  10. package/dist/machine-input-0YTPcnCm.mjs +27 -0
  11. package/dist/machine-input-DU3owLUr.cjs +32 -0
  12. package/dist/otel.d.cts +1 -1
  13. package/dist/otel.d.mts +1 -1
  14. package/dist/policy.cjs +1 -1
  15. package/dist/policy.d.cts +1 -1
  16. package/dist/policy.d.mts +1 -1
  17. package/dist/policy.mjs +1 -1
  18. package/dist/{run-agent-Dq0oSFRm.d.cts → run-agent-BO9RSb7i.d.cts} +16 -7
  19. package/dist/{run-agent-DHlq87G7.d.mts → run-agent-BxkeuAYR.d.mts} +16 -7
  20. package/dist/{run-agent-De3xVFGw.cjs → run-agent-COdR9FpM.cjs} +26 -27
  21. package/dist/{run-agent-BE7DOWD6.mjs → run-agent-D3gW9wfd.mjs} +27 -28
  22. package/dist/testing.cjs +2 -2
  23. package/dist/testing.d.cts +2 -2
  24. package/dist/testing.d.mts +2 -2
  25. package/dist/testing.mjs +2 -2
  26. package/dist/validate.cjs +1 -1
  27. package/dist/validate.d.cts +1 -1
  28. package/dist/validate.d.mts +1 -1
  29. package/dist/validate.mjs +1 -1
  30. package/dist/{verify-H3Pr2gNw.d.mts → verify-CIu4mqIZ.d.mts} +15 -1
  31. package/dist/{verify-BM0sGmsf.d.cts → verify-CTHlmBbh.d.cts} +15 -1
  32. package/dist/{verify-CWlg3j7B.mjs → verify-Cacz6XSk.mjs} +19 -3
  33. package/dist/{verify-Dek6gHCS.cjs → verify-D8UDqU4l.cjs} +19 -3
  34. package/docs/hosts.md +5 -3
  35. package/docs/strangler-fig.md +36 -29
  36. package/docs/verify.md +3 -2
  37. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # @statelyai/agent
2
2
 
3
+ ## 2.0.0-alpha.40
4
+
5
+ ### Patch Changes
6
+
7
+ - [#247](https://github.com/statelyai/agent/pull/247) [`1f63610`](https://github.com/statelyai/agent/commit/1f636103210aa368580676e8ae88cdaf821523b1) Thanks [@davidkpiano](https://github.com/davidkpiano)! - - `createAgentInbox` and `runtime.send`: an event the host sends is handed out ahead of completions the run already holds. Before, a send landed only once the machine stopped when its actors settled in microtasks, so a pause sent before start or mid-run was never applied.
8
+ - `canReach` ordering targets check `reach` on the step that matched `after` too: what the trigger's own transition starts comes after it. Before, a turn started in the trigger's step was missed.
9
+ - `createGeneratorBridge`: a consumer that pulls a value yielded while unwinding resumes the pass, as `yield*` does. `forward` reports `closed: false` (its `value` is then `undefined`), and `stream` hands a failed run back instead of throwing it.
10
+
11
+ - [#251](https://github.com/statelyai/agent/pull/251) [`5f72ebd`](https://github.com/statelyai/agent/commit/5f72ebd8a657c7107ce941857977b59b0062d863) Thanks [@davidkpiano](https://github.com/davidkpiano)! - - `wrapWorkflow`: `run(input, { live })` passes a live object to the workflow as `context.live`, so one wrapped workflow serves every instance of a class-shaped loop. When the workflow types `live`, every `run` call must pass it.
12
+ - `abortWith.event` can be a function of `signal.reason`, so aborts with different reasons send different events.
13
+ - `runAgent({ onIdle: "inbox" })`: an idle state waits for the next inbox send. Needs `inbox`.
14
+
15
+ - [#250](https://github.com/statelyai/agent/pull/250) [`bb74c83`](https://github.com/statelyai/agent/commit/bb74c838e1d7140395be59b1f9e13f799dc8f3b2) Thanks [@davidkpiano](https://github.com/davidkpiano)! - `canReach`, `explorePaths`, and `simulateAgent` validate `input` against the machine's input schema, as `runAgent` does. Input the schema rejects throws `AgentError` with code `invalid-machine-input`, and the parsed value (defaults filled) seeds the search. Before, a misspelled input field could report `reachable: false, complete: true` for a start state no run can reach.
16
+
3
17
  ## 2.0.0-alpha.39
4
18
 
5
19
  ### Minor Changes
package/dist/evals.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_event_log = require("./event-log-dSOnXHuG.cjs");
3
- const require_verify = require("./verify-Dek6gHCS.cjs");
3
+ const require_verify = require("./verify-D8UDqU4l.cjs");
4
4
  const require_trajectory = require("./trajectory-CoZSv4wF.cjs");
5
5
  let xstate = require("xstate");
6
6
  //#region src/internal/trace-states.ts
package/dist/evals.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { R as AgentExecutorDecisionRequest } from "./text-logic-x17uLBwA.cjs";
2
- import { i as AgentPathReport } from "./verify-BM0sGmsf.cjs";
2
+ import { i as AgentPathReport } from "./verify-CTHlmBbh.cjs";
3
3
  import { i as TrajectoryItem } from "./trajectory-BFjXaooB.cjs";
4
4
  import { AnyStateMachine } from "xstate";
5
5
  //#region src/fold-traces.d.ts
package/dist/evals.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { R as AgentExecutorDecisionRequest } from "./text-logic-x17uLBwA.mjs";
2
- import { i as AgentPathReport } from "./verify-H3Pr2gNw.mjs";
2
+ import { i as AgentPathReport } from "./verify-CIu4mqIZ.mjs";
3
3
  import { i as TrajectoryItem } from "./trajectory-BFjXaooB.mjs";
4
4
  import { AnyStateMachine } from "xstate";
5
5
  //#region src/fold-traces.d.ts
package/dist/evals.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { d as canonicalEventJson, dt as isPlainObject, ft as isRecord, pt as AgentError, ut as isError } from "./event-log-CEq_bVXQ.mjs";
2
- import { o as isExplorationComplete } from "./verify-CWlg3j7B.mjs";
2
+ import { o as isExplorationComplete } from "./verify-Cacz6XSk.mjs";
3
3
  import { t as matchesTrajectory } from "./trajectory-BUXj_1Ue.mjs";
4
4
  import { getInitialMicrosteps, getMicrosteps } from "xstate";
5
5
  //#region src/internal/trace-states.ts
package/dist/index.cjs CHANGED
@@ -4,7 +4,7 @@ const require_decision = require("./decision-D8bcIGXQ.cjs");
4
4
  const require_act = require("./act-B0CVbmo4.cjs");
5
5
  const require_setup_agent = require("./setup-agent-Dv5VpuHe.cjs");
6
6
  const require_event_log_store = require("./event-log-store-Dey9ufA4.cjs");
7
- const require_run_agent = require("./run-agent-De3xVFGw.cjs");
7
+ const require_run_agent = require("./run-agent-COdR9FpM.cjs");
8
8
  const require_effects = require("./effects-DrWcUGgc.cjs");
9
9
  let xstate = require("xstate");
10
10
  let acorn = require("acorn");
@@ -921,6 +921,7 @@ function createGeneratorBridge() {
921
921
  put,
922
922
  async forward(generator) {
923
923
  let closed = false;
924
+ let resumed = false;
924
925
  let step = await generator.next();
925
926
  while (!step.done) {
926
927
  let pulled;
@@ -930,14 +931,15 @@ function createGeneratorBridge() {
930
931
  step = await generator.throw(error);
931
932
  continue;
932
933
  }
933
- if (pulled || closed) step = await generator.next();
934
- else {
934
+ const freshStop = !pulled && (!closed || resumed);
935
+ if (closed) resumed = pulled;
936
+ if (freshStop) {
935
937
  closed = true;
936
938
  step = await generator.return(void 0);
937
- }
939
+ } else step = await generator.next();
938
940
  }
939
941
  return {
940
- closed,
942
+ closed: closed && !resumed,
941
943
  value: step.value
942
944
  };
943
945
  },
@@ -964,6 +966,7 @@ function createGeneratorBridge() {
964
966
  try {
965
967
  yield item.value;
966
968
  resumed = true;
969
+ stopped = false;
967
970
  item.pulled(true);
968
971
  } catch (error) {
969
972
  resumed = true;
@@ -1175,12 +1178,15 @@ function isPlainData(value, seen, hidden) {
1175
1178
  return !("value" in descriptor) || isPlainData(descriptor.value, seen, hidden);
1176
1179
  });
1177
1180
  }
1178
- function workflowLogic(run, effects, runSignal, redact) {
1181
+ function workflowLogic(run, effects, runSignal, redact, live) {
1179
1182
  return (0, xstate.createAsyncLogic)({ run: async ({ input: contextInput, self, signal }) => {
1180
1183
  const input = typeof contextInput === "object" && contextInput !== null && copiedFrom.has(contextInput) ? copiedFrom.get(contextInput) : contextInput;
1181
1184
  const parent = self._parent;
1182
1185
  const combined = runSignal ? AbortSignal.any([runSignal, signal]) : signal;
1183
- return run(ownCopy(input), observeEffects(effects, (event) => parent?.send(event), combined, redact), { signal: combined });
1186
+ return run(ownCopy(input), observeEffects(effects, (event) => parent?.send(event), combined, redact), {
1187
+ signal: combined,
1188
+ live
1189
+ });
1184
1190
  } });
1185
1191
  }
1186
1192
  function createWrappedMachine(id, version, workflow) {
@@ -1259,8 +1265,9 @@ function wrapWorkflow(config) {
1259
1265
  const machine = createWrappedMachine(config.id, config.version ?? "1", workflowLogic(config.run, config.effects, void 0, config.redact));
1260
1266
  return {
1261
1267
  machine,
1262
- async run(input, options = {}) {
1263
- const { effects: overrides, recorder, recordOptions, ...runOptions } = options;
1268
+ async run(input, ...args) {
1269
+ const options = args[0] ?? {};
1270
+ const { effects: overrides, recorder, recordOptions, live, ...runOptions } = options;
1264
1271
  let effects = {
1265
1272
  ...require_effects.mapEffects(config.effects, (_name, effect) => effect),
1266
1273
  ...overrides ? require_effects.mapEffects(overrides, (_name, effect) => effect) : {}
@@ -1270,7 +1277,7 @@ function wrapWorkflow(config) {
1270
1277
  const result = await require_run_agent.runAgent(machine, {
1271
1278
  ...agentOptions,
1272
1279
  input,
1273
- actors: { workflow: workflowLogic(config.run, effects, options.signal, config.redact) }
1280
+ actors: { workflow: workflowLogic(config.run, effects, options.signal, config.redact, live) }
1274
1281
  });
1275
1282
  if (result.status === "done") {
1276
1283
  const output = result.output;
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
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.cjs";
2
2
  import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-DvGcoK6x.cjs";
3
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-Cv8Hk3mX.cjs";
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-Dq0oSFRm.cjs";
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-BO9RSb7i.cjs";
5
5
  import { c as AgentLogEntry, d as AgentMachineVersionMismatchError, h as JsonValue, n as AgentEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-aFXK6yZX.cjs";
6
6
  import { t as PresetMachine } from "./internal-BzlpzSux.cjs";
7
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-DAclF-kw.cjs";
@@ -124,9 +124,15 @@ export declare function describeMachine(machine: AnyStateMachine, options?: Desc
124
124
  * @module
125
125
  */
126
126
  /** What {@link GeneratorBridge.forward} reports once the generator stops. */
127
- type ForwardResult<TReturn> = {
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
+ {
128
134
  closed: false;
129
- value: TReturn;
135
+ value: TReturn | undefined;
130
136
  } |
131
137
  /** The consumer stopped reading; `value` is what the generator returned while unwinding. */
132
138
  {
@@ -161,7 +167,9 @@ interface GeneratorBridge<T> {
161
167
  * stopped consumer skips the code after it in the enclosing generator;
162
168
  * cleanup that must run either way goes in a `finally`. A run that fails
163
169
  * while a stopped consumer waits (a legacy `finally` that throws) throws
164
- * its error from `.return()` instead.
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.
165
173
  */
166
174
  stream<TSettled>(settled: PromiseLike<TSettled>): AsyncGenerator<T, TSettled, undefined>;
167
175
  }
@@ -195,12 +203,17 @@ export declare function createGeneratorBridge<T>(): GeneratorBridge<T>;
195
203
  /** The effects a wrapped workflow calls: async functions, by name. */
196
204
  type WorkflowEffects<TEffects> = { [K in keyof TEffects]: (...args: never[]) => PromiseLike<unknown>; };
197
205
  /** What a wrapped workflow's `run` gets besides its input and effects. */
198
- interface WorkflowRunContext {
206
+ interface WorkflowRunContext<TLive = undefined> {
199
207
  /** Aborted when the run is aborted or the machine stops the workflow. */
200
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;
201
214
  }
202
215
  /** Options for {@link wrapWorkflow}. */
203
- interface WrapWorkflowConfig<TInput, TOutput, TEffects extends WorkflowEffects<TEffects>> {
216
+ interface WrapWorkflowConfig<TInput, TOutput, TEffects extends WorkflowEffects<TEffects>, TLive = undefined> {
204
217
  /** The machine id. */
205
218
  id: string;
206
219
  /** The machine version, for the event log. Default `"1"`. */
@@ -215,7 +228,7 @@ interface WrapWorkflowConfig<TInput, TOutput, TEffects extends WorkflowEffects<T
215
228
  * functions is passed as is. An effect that resolves to a stream (anything
216
229
  * `for await` reads) settles once the stream is read, with its chunks.
217
230
  */
218
- run: (input: TInput, effects: TEffects, context: WorkflowRunContext) => PromiseLike<TOutput>;
231
+ run: (input: TInput, effects: TEffects, context: WorkflowRunContext<TLive>) => PromiseLike<TOutput>;
219
232
  /**
220
233
  * Maps an effect's arguments, result, or error before it is journaled as an
221
234
  * event. Return a redacted value for secrets and private records: every
@@ -263,7 +276,7 @@ type WrappedWorkflowContext<TInput, TOutput> = {
263
276
  failures: number;
264
277
  };
265
278
  /** Options for {@link WrappedWorkflow.run}: `runAgent` options that fit a black box, plus fakes and a recorder. */
266
- 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"> {
267
280
  /** Replaces some effects for this run: fakes, stubs, replay wrappers. */
268
281
  effects?: Partial<TEffects>;
269
282
  /**
@@ -276,9 +289,11 @@ interface WrappedWorkflowRunOptions<TEffects, TInput, TOutput> extends Pick<Agen
276
289
  * JSON, `revive` to rebuild it in replay, `redact` for arguments.
277
290
  */
278
291
  recordOptions?: { [K in keyof TEffects]?: RecordCallOptions; };
292
+ /** Passed to the workflow as `context.live`: this call's live object. */
293
+ live?: TLive;
279
294
  }
280
295
  /** The result of {@link wrapWorkflow}. */
281
- interface WrappedWorkflow<TInput, TOutput, TEffects> {
296
+ interface WrappedWorkflow<TInput, TOutput, TEffects, TLive = undefined> {
282
297
  /**
283
298
  * `running` invokes the workflow and counts its effect calls; `done` is
284
299
  * final with the workflow's result as output. A rejection is unhandled, so
@@ -293,7 +308,9 @@ interface WrappedWorkflow<TInput, TOutput, TEffects> {
293
308
  * workflow that returns an `aborted` result still returns it. Once it
294
309
  * aborts, an effect call throws `signal.reason` instead of running.
295
310
  */
296
- 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>;
297
314
  }
298
315
  /** The events a {@link wrapWorkflow} machine handles. */
299
316
  type WrappedWorkflowEvent = EffectCallEvent | EffectDoneEvent | EffectErrorEvent;
@@ -327,7 +344,7 @@ type WrappedWorkflowMachine<TInput, TOutput> = PresetMachine<WrappedWorkflowCont
327
344
  * const reply = await support.run(ticket); // what legacyRunTicket returned
328
345
  * ```
329
346
  */
330
- 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>;
331
348
  //#endregion
332
349
  //#region src/provide-executors.d.ts
333
350
  /** Options for {@link provideExecutors}. */
package/dist/index.d.mts CHANGED
@@ -1,7 +1,7 @@
1
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
2
  import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-B4B-TQSV.mjs";
3
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-DHlq87G7.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
5
  import { c as AgentLogEntry, d as AgentMachineVersionMismatchError, h as JsonValue, n as AgentEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-DYun526m.mjs";
6
6
  import { t as PresetMachine } from "./internal-BzlpzSux.mjs";
7
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";
@@ -124,9 +124,15 @@ export declare function describeMachine(machine: AnyStateMachine, options?: Desc
124
124
  * @module
125
125
  */
126
126
  /** What {@link GeneratorBridge.forward} reports once the generator stops. */
127
- type ForwardResult<TReturn> = {
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
+ {
128
134
  closed: false;
129
- value: TReturn;
135
+ value: TReturn | undefined;
130
136
  } |
131
137
  /** The consumer stopped reading; `value` is what the generator returned while unwinding. */
132
138
  {
@@ -161,7 +167,9 @@ interface GeneratorBridge<T> {
161
167
  * stopped consumer skips the code after it in the enclosing generator;
162
168
  * cleanup that must run either way goes in a `finally`. A run that fails
163
169
  * while a stopped consumer waits (a legacy `finally` that throws) throws
164
- * its error from `.return()` instead.
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.
165
173
  */
166
174
  stream<TSettled>(settled: PromiseLike<TSettled>): AsyncGenerator<T, TSettled, undefined>;
167
175
  }
@@ -195,12 +203,17 @@ export declare function createGeneratorBridge<T>(): GeneratorBridge<T>;
195
203
  /** The effects a wrapped workflow calls: async functions, by name. */
196
204
  type WorkflowEffects<TEffects> = { [K in keyof TEffects]: (...args: never[]) => PromiseLike<unknown>; };
197
205
  /** What a wrapped workflow's `run` gets besides its input and effects. */
198
- interface WorkflowRunContext {
206
+ interface WorkflowRunContext<TLive = undefined> {
199
207
  /** Aborted when the run is aborted or the machine stops the workflow. */
200
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;
201
214
  }
202
215
  /** Options for {@link wrapWorkflow}. */
203
- interface WrapWorkflowConfig<TInput, TOutput, TEffects extends WorkflowEffects<TEffects>> {
216
+ interface WrapWorkflowConfig<TInput, TOutput, TEffects extends WorkflowEffects<TEffects>, TLive = undefined> {
204
217
  /** The machine id. */
205
218
  id: string;
206
219
  /** The machine version, for the event log. Default `"1"`. */
@@ -215,7 +228,7 @@ interface WrapWorkflowConfig<TInput, TOutput, TEffects extends WorkflowEffects<T
215
228
  * functions is passed as is. An effect that resolves to a stream (anything
216
229
  * `for await` reads) settles once the stream is read, with its chunks.
217
230
  */
218
- run: (input: TInput, effects: TEffects, context: WorkflowRunContext) => PromiseLike<TOutput>;
231
+ run: (input: TInput, effects: TEffects, context: WorkflowRunContext<TLive>) => PromiseLike<TOutput>;
219
232
  /**
220
233
  * Maps an effect's arguments, result, or error before it is journaled as an
221
234
  * event. Return a redacted value for secrets and private records: every
@@ -263,7 +276,7 @@ type WrappedWorkflowContext<TInput, TOutput> = {
263
276
  failures: number;
264
277
  };
265
278
  /** Options for {@link WrappedWorkflow.run}: `runAgent` options that fit a black box, plus fakes and a recorder. */
266
- 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"> {
267
280
  /** Replaces some effects for this run: fakes, stubs, replay wrappers. */
268
281
  effects?: Partial<TEffects>;
269
282
  /**
@@ -276,9 +289,11 @@ interface WrappedWorkflowRunOptions<TEffects, TInput, TOutput> extends Pick<Agen
276
289
  * JSON, `revive` to rebuild it in replay, `redact` for arguments.
277
290
  */
278
291
  recordOptions?: { [K in keyof TEffects]?: RecordCallOptions; };
292
+ /** Passed to the workflow as `context.live`: this call's live object. */
293
+ live?: TLive;
279
294
  }
280
295
  /** The result of {@link wrapWorkflow}. */
281
- interface WrappedWorkflow<TInput, TOutput, TEffects> {
296
+ interface WrappedWorkflow<TInput, TOutput, TEffects, TLive = undefined> {
282
297
  /**
283
298
  * `running` invokes the workflow and counts its effect calls; `done` is
284
299
  * final with the workflow's result as output. A rejection is unhandled, so
@@ -293,7 +308,9 @@ interface WrappedWorkflow<TInput, TOutput, TEffects> {
293
308
  * workflow that returns an `aborted` result still returns it. Once it
294
309
  * aborts, an effect call throws `signal.reason` instead of running.
295
310
  */
296
- 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>;
297
314
  }
298
315
  /** The events a {@link wrapWorkflow} machine handles. */
299
316
  type WrappedWorkflowEvent = EffectCallEvent | EffectDoneEvent | EffectErrorEvent;
@@ -327,7 +344,7 @@ type WrappedWorkflowMachine<TInput, TOutput> = PresetMachine<WrappedWorkflowCont
327
344
  * const reply = await support.run(ticket); // what legacyRunTicket returned
328
345
  * ```
329
346
  */
330
- 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>;
331
348
  //#endregion
332
349
  //#region src/provide-executors.d.ts
333
350
  /** Options for {@link provideExecutors}. */
package/dist/index.mjs CHANGED
@@ -3,7 +3,7 @@ import { a as createDecisionRequest, c as renderDecisionAttempts, d as GROUPED_E
3
3
  import { i as isActLogic, n as DEFAULT_ACT_MAX_STEPS, t as ACT_STATE_EXITED } from "./act-Bsz-hUfD.mjs";
4
4
  import { n as getAgentSchemas, r as setupAgent, t as createAgentSchemas } from "./setup-agent-CLm6QVGy.mjs";
5
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-BE7DOWD6.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
7
  import { n as mapEffects, t as isAsyncIterable } from "./effects-B9IvUPVh.mjs";
8
8
  import { createAsyncLogic, machineToJSON } from "xstate";
9
9
  import { parse } from "acorn";
@@ -920,6 +920,7 @@ function createGeneratorBridge() {
920
920
  put,
921
921
  async forward(generator) {
922
922
  let closed = false;
923
+ let resumed = false;
923
924
  let step = await generator.next();
924
925
  while (!step.done) {
925
926
  let pulled;
@@ -929,14 +930,15 @@ function createGeneratorBridge() {
929
930
  step = await generator.throw(error);
930
931
  continue;
931
932
  }
932
- if (pulled || closed) step = await generator.next();
933
- else {
933
+ const freshStop = !pulled && (!closed || resumed);
934
+ if (closed) resumed = pulled;
935
+ if (freshStop) {
934
936
  closed = true;
935
937
  step = await generator.return(void 0);
936
- }
938
+ } else step = await generator.next();
937
939
  }
938
940
  return {
939
- closed,
941
+ closed: closed && !resumed,
940
942
  value: step.value
941
943
  };
942
944
  },
@@ -963,6 +965,7 @@ function createGeneratorBridge() {
963
965
  try {
964
966
  yield item.value;
965
967
  resumed = true;
968
+ stopped = false;
966
969
  item.pulled(true);
967
970
  } catch (error) {
968
971
  resumed = true;
@@ -1174,12 +1177,15 @@ function isPlainData(value, seen, hidden) {
1174
1177
  return !("value" in descriptor) || isPlainData(descriptor.value, seen, hidden);
1175
1178
  });
1176
1179
  }
1177
- function workflowLogic(run, effects, runSignal, redact) {
1180
+ function workflowLogic(run, effects, runSignal, redact, live) {
1178
1181
  return createAsyncLogic({ run: async ({ input: contextInput, self, signal }) => {
1179
1182
  const input = typeof contextInput === "object" && contextInput !== null && copiedFrom.has(contextInput) ? copiedFrom.get(contextInput) : contextInput;
1180
1183
  const parent = self._parent;
1181
1184
  const combined = runSignal ? AbortSignal.any([runSignal, signal]) : signal;
1182
- 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
+ });
1183
1189
  } });
1184
1190
  }
1185
1191
  function createWrappedMachine(id, version, workflow) {
@@ -1258,8 +1264,9 @@ function wrapWorkflow(config) {
1258
1264
  const machine = createWrappedMachine(config.id, config.version ?? "1", workflowLogic(config.run, config.effects, void 0, config.redact));
1259
1265
  return {
1260
1266
  machine,
1261
- async run(input, options = {}) {
1262
- const { effects: overrides, recorder, recordOptions, ...runOptions } = options;
1267
+ async run(input, ...args) {
1268
+ const options = args[0] ?? {};
1269
+ const { effects: overrides, recorder, recordOptions, live, ...runOptions } = options;
1263
1270
  let effects = {
1264
1271
  ...mapEffects(config.effects, (_name, effect) => effect),
1265
1272
  ...overrides ? mapEffects(overrides, (_name, effect) => effect) : {}
@@ -1269,7 +1276,7 @@ function wrapWorkflow(config) {
1269
1276
  const result = await runAgent(machine, {
1270
1277
  ...agentOptions,
1271
1278
  input,
1272
- actors: { workflow: workflowLogic(config.run, effects, options.signal, config.redact) }
1279
+ actors: { workflow: workflowLogic(config.run, effects, options.signal, config.redact, live) }
1273
1280
  });
1274
1281
  if (result.status === "done") {
1275
1282
  const output = result.output;
@@ -0,0 +1,27 @@
1
+ import { K as getRegisteredAgentExecutionOptions, ct as validateSchemaSync, pt as AgentError, rt as isStandardSchema } from "./event-log-CEq_bVXQ.mjs";
2
+ //#region src/internal/machine-input.ts
3
+ /**
4
+ * Validates `input` against the machine's registered input schema, returning
5
+ * the schema's output, so defaults are filled and transforms applied before
6
+ * the value reaches `createActor`, the replayable event log, or a search.
7
+ *
8
+ * Standard Schema only (no validation library is referenced), so this works for
9
+ * whatever the machine was declared with. Omitted input stays omitted rather
10
+ * than being validated as `{}`: "started with no input" keeps meaning what it
11
+ * has always meant, instead of newly failing schemas with required fields.
12
+ * `caller` names the public function in the error message.
13
+ *
14
+ * @internal
15
+ */
16
+ function resolveMachineInput(machine, input, caller) {
17
+ if (input === void 0) return input;
18
+ const schema = getRegisteredAgentExecutionOptions(machine).schemas?.input;
19
+ if (!isStandardSchema(schema)) return input;
20
+ try {
21
+ return validateSchemaSync(schema, input);
22
+ } catch (error) {
23
+ throw new AgentError("invalid-machine-input", `${caller}: machine input failed validation against the declared input schema: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
24
+ }
25
+ }
26
+ //#endregion
27
+ export { resolveMachineInput as t };
@@ -0,0 +1,32 @@
1
+ const require_event_log = require("./event-log-dSOnXHuG.cjs");
2
+ //#region src/internal/machine-input.ts
3
+ /**
4
+ * Validates `input` against the machine's registered input schema, returning
5
+ * the schema's output, so defaults are filled and transforms applied before
6
+ * the value reaches `createActor`, the replayable event log, or a search.
7
+ *
8
+ * Standard Schema only (no validation library is referenced), so this works for
9
+ * whatever the machine was declared with. Omitted input stays omitted rather
10
+ * than being validated as `{}`: "started with no input" keeps meaning what it
11
+ * has always meant, instead of newly failing schemas with required fields.
12
+ * `caller` names the public function in the error message.
13
+ *
14
+ * @internal
15
+ */
16
+ function resolveMachineInput(machine, input, caller) {
17
+ if (input === void 0) return input;
18
+ const schema = require_event_log.getRegisteredAgentExecutionOptions(machine).schemas?.input;
19
+ if (!require_event_log.isStandardSchema(schema)) return input;
20
+ try {
21
+ return require_event_log.validateSchemaSync(schema, input);
22
+ } catch (error) {
23
+ throw new require_event_log.AgentError("invalid-machine-input", `${caller}: machine input failed validation against the declared input schema: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
24
+ }
25
+ }
26
+ //#endregion
27
+ Object.defineProperty(exports, "resolveMachineInput", {
28
+ enumerable: true,
29
+ get: function() {
30
+ return resolveMachineInput;
31
+ }
32
+ });
package/dist/otel.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as AgentTraceEvent } from "./run-agent-Dq0oSFRm.cjs";
1
+ import { _ as AgentTraceEvent } from "./run-agent-BO9RSb7i.cjs";
2
2
  import { Attributes, Tracer, TracerProvider } from "@opentelemetry/api";
3
3
  //#region src/otel/index.d.ts
4
4
  /** Options for {@link createOtelTraceHandler}. */
package/dist/otel.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as AgentTraceEvent } from "./run-agent-DHlq87G7.mjs";
1
+ import { _ as AgentTraceEvent } from "./run-agent-BxkeuAYR.mjs";
2
2
  import { Attributes, Tracer, TracerProvider } from "@opentelemetry/api";
3
3
  //#region src/otel/index.d.ts
4
4
  /** Options for {@link createOtelTraceHandler}. */
package/dist/policy.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_event_log = require("./event-log-dSOnXHuG.cjs");
3
- const require_run_agent = require("./run-agent-De3xVFGw.cjs");
3
+ const require_run_agent = require("./run-agent-COdR9FpM.cjs");
4
4
  //#region src/policy-decider.ts
5
5
  /**
6
6
  * Runs a policy machine as a decide executor: each decision request starts one
package/dist/policy.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { B as DecisionAttempt, J as DecisionStrategy, L as AgentDecisionRequest, M as AgentDecisionExecutor, R as AgentExecutorDecisionRequest, c as AgentRequestExecutorInfo, nt as EventFromSnapshot, s as AgentRequestExecutor, yt as ChosenEvent } from "./text-logic-x17uLBwA.cjs";
2
- import { l as AgentRunOptions } from "./run-agent-Dq0oSFRm.cjs";
2
+ import { l as AgentRunOptions } from "./run-agent-BO9RSb7i.cjs";
3
3
  import { AnyMachineSnapshot, AnyStateMachine, InputFrom } from "xstate";
4
4
  //#region src/decide-next.d.ts
5
5
  /** Options for {@link decideNext}. */
package/dist/policy.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { B as DecisionAttempt, J as DecisionStrategy, L as AgentDecisionRequest, M as AgentDecisionExecutor, R as AgentExecutorDecisionRequest, c as AgentRequestExecutorInfo, nt as EventFromSnapshot, s as AgentRequestExecutor, yt as ChosenEvent } from "./text-logic-x17uLBwA.mjs";
2
- import { l as AgentRunOptions } from "./run-agent-DHlq87G7.mjs";
2
+ import { l as AgentRunOptions } from "./run-agent-BxkeuAYR.mjs";
3
3
  import { AnyMachineSnapshot, AnyStateMachine, InputFrom } from "xstate";
4
4
  //#region src/decide-next.d.ts
5
5
  /** Options for {@link decideNext}. */
package/dist/policy.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { d as canonicalEventJson, ft as isRecord, pt as AgentError, u as assertJsonSerializable } from "./event-log-CEq_bVXQ.mjs";
2
- import { p as runAgent, v as decideNext } from "./run-agent-BE7DOWD6.mjs";
2
+ import { p as runAgent, v as decideNext } from "./run-agent-D3gW9wfd.mjs";
3
3
  //#region src/policy-decider.ts
4
4
  /**
5
5
  * Runs a policy machine as a decide executor: each decision request starts one
@@ -369,9 +369,12 @@ interface AgentRuntimeOptions<TMachine extends AnyStateMachine> {
369
369
  * when the machine has no transition for `event`, when the loop never
370
370
  * applies it, when the machine settles still `active` after handling it,
371
371
  * or when `timeout` milliseconds pass while it is still working.
372
+ *
373
+ * `event` can be a function of `signal.reason`, so aborts with different
374
+ * reasons (a pause and a stop) send different events.
372
375
  */
373
376
  abortWith?: {
374
- event: EventFromLogic<TMachine>;
377
+ event: EventFromLogic<TMachine> | ((reason: unknown) => EventFromLogic<TMachine>);
375
378
  timeout?: number;
376
379
  };
377
380
  /** Where root `after` timers live. Default `"in-process"`. See {@link AgentTimerScheduler}. */
@@ -617,7 +620,8 @@ interface AgentRuntime<TMachine extends AnyStateMachine> {
617
620
  nextEvent(): Promise<EventFromLogic<TMachine> | undefined>;
618
621
  /**
619
622
  * Delivers a host event (a cancel, a user message, a host-owned timer) into
620
- * the run's mailbox, behind whatever already arrived. Asynchronous: `send`
623
+ * the run, behind earlier host sends and ahead of completions not yet handed
624
+ * out. Asynchronous: `send`
621
625
  * only enqueues; the machine moves when the host loop's next `nextEvent()`
622
626
  * hands the event out (a parked `nextEvent()` resolves with it) and the loop
623
627
  * calls `transition`. A host that needs the event applied before it returns
@@ -631,8 +635,9 @@ interface AgentRuntime<TMachine extends AnyStateMachine> {
631
635
  *
632
636
  * - Before `start`: queued; the first `nextEvent()` hands it out (after the
633
637
  * init event a host delivers itself). Returns `true`.
634
- * - While an effect, child or timer is in flight: queued in arrival order
635
- * with their completions. Returns `true`.
638
+ * - While an effect, child or timer is in flight: queued behind earlier
639
+ * host sends, and handed out before any completion the run holds, so
640
+ * actors that settle in microtasks cannot keep it waiting. Returns `true`.
636
641
  * - After the run stopped (cancelled, aborted, journal failure) or the
637
642
  * machine left `active` (done, error): dropped. Returns `false`.
638
643
  * - After `finish`: throws {@link AgentError} `runtime-finished`.
@@ -682,10 +687,13 @@ interface AgentRunOptions<TMachine extends AnyStateMachine> extends AgentRuntime
682
687
  * A host that cannot block for the answer (a request handler, a durable
683
688
  * object) leaves this out, stores `result.persist()`, and calls
684
689
  * {@link runAgent} again later with `{ snapshot, event }`.
690
+ *
691
+ * `"inbox"`: each idle state waits for the next `inbox.send` (a resume
692
+ * after a pause), with no answer of its own. Needs `inbox`.
685
693
  */
686
- onIdle?: (snapshot: SnapshotFrom<TMachine>, options: {
694
+ onIdle?: ((snapshot: SnapshotFrom<TMachine>, options: {
687
695
  signal: AbortSignal | undefined;
688
- }) => Promise<EventFromLogic<TMachine> | AgentTimerEvent>;
696
+ }) => Promise<EventFromLogic<TMachine> | AgentTimerEvent>) | "inbox";
689
697
  /**
690
698
  * A send handle for events pushed mid-run (a cancel, a user message), from
691
699
  * {@link createAgentInbox}. Each `inbox.send` goes to the current pass's
@@ -695,7 +703,8 @@ interface AgentRunOptions<TMachine extends AnyStateMachine> extends AgentRuntime
695
703
  * dropped). Without `onIdle`, the run returns at the first idle state
696
704
  * (an event that lands while that pass is finishing still resumes it), and
697
705
  * a `send` after `runAgent` returns gets `false`: a pause that waits for a
698
- * resume needs `onIdle` as well. One inbox serves one `runAgent` call.
706
+ * resume needs `onIdle` as well (`onIdle: "inbox"` when only the inbox
707
+ * answers). One inbox serves one `runAgent` call.
699
708
  */
700
709
  inbox?: AgentInbox<EventFromLogic<TMachine>>;
701
710
  }