@statelyai/agent 2.0.0-alpha.6 → 2.0.0-alpha.8

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.
@@ -1,5 +1,5 @@
1
- import { A as userInputActor, B as getAgentMessages, C as createTextLogic, D as isTextLogic, F as isUnboundPlaceholder, H as getJsonSchemaSync, I as machineSuspensionPredicates, L as missingActor, M as executorBoundLogics, N as getMachineSuspensionPredicate, O as normalizeGeneratorResult, P as getRegisteredAgentExecutionOptions, R as assistantMessage, S as builtinTextActors, U as getMachineStructuralHash, X as validateSchemaSync, Y as userMessage, _ as INTERPRET_SOURCE, a as createPlanActor, c as isPlanLogic, f as getAcceptedEvents, g as DECIDE_ACTOR, h as sanitizeEventToolName, i as createDecideActor, j as agentExecutionOptions, n as PLAN_DONE_EVENT_TYPE, o as initialPlanLedger, r as advancePlanLedger, s as isDecisionLogic, t as DecisionExhaustedError, u as resolveDecision, v as PLAN_ACTOR, w as executeAgentTextRequest, y as USER_INPUT_ACTOR, z as findNonSerializableContextPaths } from "./decision-D1654JdD.mjs";
2
- import { createActor, createAsyncLogic, getNextTransitions, initialTransition, setup, transition } from "xstate";
1
+ import { $ as validateSchemaSync, B as missingActor, C as createTextLogic, D as isTextLogic, F as getMachineSuspensionPredicate, H as findNonSerializableContextPaths, I as getRegisteredAgentExecutionOptions, K as getMachineStructuralHash, M as userInputActor, N as agentExecutionOptions, O as normalizeGeneratorResult, P as executorBoundLogics, Q as userMessage, R as isUnboundPlaceholder, S as builtinTextActors, U as getAgentMessages, V as assistantMessage, _ as INTERPRET_SOURCE, a as createPlanActor, c as isPlanLogic, f as getAcceptedEvents, g as DECIDE_ACTOR, h as sanitizeEventToolName, i as createDecideActor, n as PLAN_DONE_EVENT_TYPE, o as initialPlanLedger, r as advancePlanLedger, s as isDecisionLogic, t as DecisionExhaustedError, u as resolveDecision, v as PLAN_ACTOR, y as USER_INPUT_ACTOR, z as machineSuspensionPredicates } from "./decision-CQdrKc8k.mjs";
2
+ import { createActor, createAsyncLogic, getNextTransitions, setup } from "xstate";
3
3
  //#region src/messages.ts
4
4
  function addMessages(resolve) {
5
5
  return (args) => {
@@ -260,6 +260,16 @@ function setupAgentFromConfig(config, options) {
260
260
  }
261
261
  //#endregion
262
262
  //#region src/setup-agent.ts
263
+ const emptyEventSchema = { "~standard": {
264
+ version: 1,
265
+ vendor: "statelyai-agent",
266
+ validate(value) {
267
+ return value !== null && typeof value === "object" && Object.keys(value).length === 0 ? { value: {} } : { issues: [{ message: "Expected an empty event payload" }] };
268
+ }
269
+ } };
270
+ function normalizeEventSchemas(events) {
271
+ return Object.fromEntries(Object.entries(events).map(([type, schema]) => [type, schema && typeof schema === "object" && "~standard" in schema ? schema : emptyEventSchema]));
272
+ }
263
273
  /**
264
274
  * Builds a machine's {@link AgentSchemaPack} from a partial schema
265
275
  * declaration — only `context` is required; `events`/`input`/`output`/`meta`
@@ -271,13 +281,50 @@ function setupAgentFromConfig(config, options) {
271
281
  function createAgentSchemas(schemas) {
272
282
  return {
273
283
  context: schemas.context,
274
- events: schemas.events ?? {},
284
+ events: normalizeEventSchemas(schemas.events ?? {}),
275
285
  input: schemas.input,
276
286
  output: schemas.output,
277
287
  meta: schemas.meta,
278
288
  emitted: schemas.emitted
279
289
  };
280
290
  }
291
+ function mergeContextSchema(base, fields) {
292
+ return { "~standard": {
293
+ version: 1,
294
+ vendor: "statelyai-agent",
295
+ validate(value) {
296
+ const baseResult = base["~standard"].validate(value);
297
+ if (baseResult instanceof Promise) throw new Error("setupAgent: async context schemas are not supported.");
298
+ if (baseResult.issues) return baseResult;
299
+ const merged = { ...baseResult.value };
300
+ const issues = [];
301
+ for (const [key, fieldSchema] of Object.entries(fields)) {
302
+ const fieldResult = fieldSchema["~standard"].validate(value[key]);
303
+ if (fieldResult instanceof Promise) throw new Error("setupAgent: async context schemas are not supported.");
304
+ if (fieldResult.issues) issues.push(...fieldResult.issues.map((issue) => ({
305
+ ...issue,
306
+ path: [key, ...issue.path ?? []]
307
+ })));
308
+ else merged[key] = fieldResult.value;
309
+ }
310
+ return issues.length > 0 ? { issues } : { value: merged };
311
+ }
312
+ } };
313
+ }
314
+ function resolveAgentStateSchemas(contextSchema, states) {
315
+ return Object.fromEntries(Object.entries(states).map(([key, state]) => {
316
+ if (!state || typeof state !== "object") return [key, state];
317
+ const children = "states" in state && state.states ? resolveAgentStateSchemas(contextSchema, state.states) : void 0;
318
+ if ("context" in state && state.context) return [key, {
319
+ schemas: { context: mergeContextSchema(contextSchema, state.context) },
320
+ ...children ? { states: children } : {}
321
+ }];
322
+ return [key, children ? {
323
+ ...state,
324
+ states: children
325
+ } : state];
326
+ }));
327
+ }
281
328
  /**
282
329
  * Schema-first `setup(...)` for agent machines — the standard entry point
283
330
  * for authoring a machine (the blueprint) that this library then runs (via
@@ -358,7 +405,12 @@ function createRequestActors(requests) {
358
405
  }));
359
406
  }
360
407
  function normalizeAgentSchemas(config) {
361
- return "schemas" in config ? config.schemas : createAgentSchemas(config);
408
+ if ("schemas" in config && config.schemas) return config.schemas;
409
+ const loose = config;
410
+ return createAgentSchemas({
411
+ ...loose,
412
+ context: loose.context
413
+ });
362
414
  }
363
415
  function normalizeAgentRequestInput(requests) {
364
416
  return requests ?? {};
@@ -418,7 +470,7 @@ function createAgentSetupConfig(schemas, actorSources, config) {
418
470
  meta: schemas.meta,
419
471
  ...schemas.emitted && Object.keys(schemas.emitted).length > 0 ? { emitted: schemas.emitted } : {}
420
472
  },
421
- ...config.states ? { states: config.states } : {},
473
+ ...config.states ? { states: resolveAgentStateSchemas(schemas.context, config.states) } : {},
422
474
  actorSources,
423
475
  actions: config.actions,
424
476
  guards: config.guards,
@@ -431,11 +483,12 @@ function createSetupAgent(config) {
431
483
  const actorSources = createAgentActorSources(config.actorSources, requestActors);
432
484
  const base = setup(createAgentSetupConfig(schemas, actorSources, config));
433
485
  const createBaseMachine = base.createMachine.bind(base);
486
+ const models = config.models ?? {};
434
487
  const machineOptions = {
435
488
  schemas,
436
- actorSources
489
+ actorSources,
490
+ models
437
491
  };
438
- const models = config.models ?? {};
439
492
  return Object.assign(base, {
440
493
  createMachine(machineConfig) {
441
494
  const machine = createBaseMachine(withRootOutputFromSingleFinal(machineConfig));
@@ -455,370 +508,6 @@ function createSetupAgent(config) {
455
508
  });
456
509
  }
457
510
  //#endregion
458
- //#region src/steps.ts
459
- /**
460
- * The step path: durable, per-model-call-checkpoint hosting of an agent
461
- * machine. Public vocabulary — `initialAgentStep`, `transitionAgentStep`,
462
- * `resolveAgentStep`, `getAgentRequests`, `executeAgentRequest`,
463
- * `resolveAgentRequests`.
464
- * @module
465
- */
466
- /**
467
- * Scans a set of executable actions (as returned by xstate's `transition`/
468
- * `initialTransition`) for spawned `TextLogic`/`DecisionLogic` invokes and
469
- * lowers each into an {@link AgentStepRequest}. The hand-passed-schemas
470
- * implementation detail behind the public {@link getAgentRequests} — it needs
471
- * `schemas`/`actorSources` passed explicitly, whereas `getAgentRequests`
472
- * pre-fills them from the machine's registered `setupAgent` options.
473
- * `options.snapshot` is required to resolve a decision's candidate events
474
- * (intersecting declared `allowedEvents` with what's currently legal) — omit
475
- * it and decision requests report an empty `events` list.
476
- *
477
- * @internal
478
- */
479
- function getAgentRequestsWith(actions, options = {}) {
480
- return [...actions.flatMap((action) => {
481
- if (action.type !== "xstate.spawnChild" && action.type !== "@xstate.start") return [];
482
- const params = action.type === "@xstate.start" ? action : action.params;
483
- if (!params || typeof params.src !== "string") return [];
484
- if (typeof params.id !== "string" || params.id.length === 0) throw new Error(`Agent invoke '${params.src}' must define a durable string id.`);
485
- const registeredLogic = isTextLogic(action.logic) || isDecisionLogic(action.logic) ? action.logic : options.actorSources?.[params.src];
486
- if (isDecisionLogic(registeredLogic)) {
487
- const decisionRequest = registeredLogic.request(params.input);
488
- const allowedEventTypes = registeredLogic.allowedEventTypes?.(params.input);
489
- const events = options.snapshot ? getAcceptedEvents(options.snapshot, {
490
- events: options.events,
491
- schemas: options.schemas,
492
- eventTypes: allowedEventTypes,
493
- eventToolName: options.eventToolName
494
- }) : [];
495
- return [{
496
- ...decisionRequest,
497
- id: params.id,
498
- events
499
- }];
500
- }
501
- const textLogic = isTextLogic(registeredLogic) ? registeredLogic : void 0;
502
- const input = textLogic ? textLogic.request(params.input) : void 0;
503
- if (!input) return [];
504
- return [{
505
- kind: "text",
506
- id: params.id,
507
- src: params.src,
508
- ...textLogic ? { mode: textLogic.mode } : {},
509
- input,
510
- tools: input.tools ?? {},
511
- events: []
512
- }];
513
- }), ...getActivePlanRequests(options)];
514
- }
515
- /**
516
- * Scans the live snapshot's children for active `agent.plan` (plan-logic)
517
- * invokes and lowers each into an {@link AgentPlanRequest} — the re-surfacing
518
- * half of plan discovery. Reads the applied-event trail and remaining budget
519
- * from the child's own ledger `context` ({@link PlanLedgerContext}), recomputes
520
- * the currently-legal candidates (∩ declared `allowedEvents`) plus the reserved
521
- * `agent.plan.done` move, and takes `stepsRemaining` from the ledger (falling
522
- * back to `maxSteps - applied.length` for a snapshot with no context yet).
523
- * Returns `[]` when no snapshot is available (candidates need a live snapshot).
524
- *
525
- * @internal
526
- */
527
- function getActivePlanRequests(options) {
528
- const snapshot = options.snapshot;
529
- if (!snapshot) return [];
530
- const children = snapshot.children;
531
- if (!children) return [];
532
- const requests = [];
533
- for (const [id, child] of Object.entries(children)) {
534
- const ref = child;
535
- if (typeof ref?.getSnapshot !== "function") continue;
536
- const src = typeof ref.src === "string" ? ref.src : void 0;
537
- const logic = (src ? options.actorSources?.[src] : void 0) ?? ref.logic;
538
- if (!isPlanLogic(logic)) continue;
539
- const childSnapshot = ref.getSnapshot();
540
- if (childSnapshot?.status !== "active") continue;
541
- const input = childSnapshot.input ?? {};
542
- const maxSteps = input.maxSteps ?? 8;
543
- const ledger = childSnapshot.context ?? {};
544
- const applied = ledger.applied ?? [];
545
- const stepsRemaining = ledger.stepsRemaining ?? maxSteps - applied.length;
546
- const machineEvents = getAcceptedEvents(snapshot, {
547
- events: options.events,
548
- schemas: options.schemas,
549
- eventTypes: logic.allowedEventTypes(input) ?? void 0,
550
- eventToolName: options.eventToolName
551
- });
552
- const events = machineEvents.some((event) => event.type === "agent.plan.done") ? machineEvents : [...machineEvents, {
553
- type: PLAN_DONE_EVENT_TYPE,
554
- toolName: sanitizeEventToolName(PLAN_DONE_EVENT_TYPE)
555
- }];
556
- requests.push({
557
- kind: "plan",
558
- id,
559
- src: src ?? "",
560
- input,
561
- events,
562
- applied,
563
- stepsRemaining: Math.max(0, stepsRemaining)
564
- });
565
- }
566
- return requests;
567
- }
568
- /**
569
- * Builds the synthetic `xstate.done.actor.<id>` event xstate's `transition()`
570
- * expects to resolve a spawned invoke — the event {@link resolveAgentStep}
571
- * applies internally.
572
- *
573
- * @internal
574
- */
575
- function doneEvent(request, output) {
576
- return {
577
- type: `xstate.done.actor.${typeof request === "string" ? request : request.id}`,
578
- output
579
- };
580
- }
581
- /**
582
- * Applies a request's `output` as a done event via `transition(...)`,
583
- * returning the raw `[snapshot, actions]` tuple. Lower-level than
584
- * {@link resolveAgentStep} — that helper wraps this and also runs
585
- * {@link getAgentRequests} to produce the next {@link AgentStep}.
586
- *
587
- * @internal
588
- */
589
- function transitionResult(logic, snapshot, request, output) {
590
- const event = doneEvent(request, output);
591
- const result = transition(logic, snapshot, event);
592
- applyFinalStateOutput(logic, result[0], event);
593
- return result;
594
- }
595
- /**
596
- * Starts a machine and returns its first {@link AgentStep} — the step-path
597
- * equivalent of `initialTransition` plus request discovery. Begins the
598
- * durable/per-model-call-checkpoint loop: resolve each `step.requests` entry
599
- * (via {@link executeAgentRequest} for `kind: 'text'`, or
600
- * {@link resolveDecision} for `kind: 'decision'`), then advance with
601
- * {@link resolveAgentStep} or {@link transitionAgentStep}.
602
- */
603
- function initialAgentStep(machine, input, options) {
604
- const [snapshot, actions] = initialTransition(machine, input);
605
- return createAgentStep(machine, snapshot, actions, getRegisteredAgentExecutionOptions(machine, options));
606
- }
607
- /**
608
- * Applies an externally-sent event (e.g. a decision's chosen event, or a
609
- * human's reply) and returns the next {@link AgentStep}. Accepts **either**
610
- * a raw snapshot **or** a prior `AgentStep` as the second argument —
611
- * `.snapshot` is unwrapped automatically, so callers can thread the whole
612
- * step object through without manually plucking the snapshot out.
613
- */
614
- function transitionAgentStep(machine, snapshotOrStep, event, options) {
615
- const [nextSnapshot, actions] = transition(machine, isAgentStep(snapshotOrStep) ? snapshotOrStep.snapshot : snapshotOrStep, event);
616
- return createAgentStep(machine, nextSnapshot, actions, getRegisteredAgentExecutionOptions(machine, options));
617
- }
618
- /**
619
- * Applies a resolved text request's output (a `kind: 'text'`
620
- * {@link AgentRequest} — not a decision) as a done event and returns the
621
- * next {@link AgentStep}. For decisions, resolve with `resolveDecision`
622
- * (which returns a {@link ChosenEvent}) and apply it with
623
- * {@link transitionAgentStep} instead — a decision has no output value of
624
- * its own to feed here.
625
- */
626
- function resolveAgentStep(machine, step, request, output, options) {
627
- const [snapshot, actions] = transitionResult(machine, step.snapshot, request, output);
628
- return createAgentStep(machine, snapshot, actions, getRegisteredAgentExecutionOptions(machine, options));
629
- }
630
- /**
631
- * Snapshot in, requests out: scans executable actions for spawned agent
632
- * invokes and lowers each into an {@link AgentStepRequest}, pre-filled with
633
- * the machine's registered `setupAgent` schemas/actorSources (so callers
634
- * don't pass them by hand each call) — merged with any `options` passed here,
635
- * which take precedence. The step path's public discovery primitive;
636
- * `initialAgentStep`/`transitionAgentStep`/`resolveAgentStep` call it
637
- * internally to populate `AgentStep.requests`.
638
- */
639
- function getAgentRequests(machine, actions, snapshot, options = {}) {
640
- return getAgentRequestsWith(actions, {
641
- ...getRegisteredAgentExecutionOptions(machine, options),
642
- ...options,
643
- snapshot
644
- });
645
- }
646
- async function executeAgentRequest(request, executors, options) {
647
- if (request.kind === "decision") throw new Error("executeAgentRequest(...) is text-only. Resolve a 'decision' request with resolveDecision(request, executors.decide, ...) instead.");
648
- assertTextExecutor(request, executors);
649
- const { output, raw } = await executeAgentTextRequest(request.mode ?? "generate", request.id, request.input, executors, request.tools);
650
- const normalizedOutput = request.input.outputSchema ? validateSchemaSync(request.input.outputSchema, output) : output;
651
- return options?.verbose ? {
652
- output: normalizedOutput,
653
- raw
654
- } : normalizedOutput;
655
- }
656
- /**
657
- * Resolves the current step's pending requests and returns the next
658
- * {@link AgentStep} — one iteration of the durable step loop, collapsing the
659
- * manual `request.kind` dispatch a host would otherwise write by hand.
660
- *
661
- * For each pending request, in order: a `kind: 'text'` request is run with
662
- * {@link executeAgentRequest} then fed back via {@link resolveAgentStep}; a
663
- * `kind: 'decision'` request is resolved with `resolveDecision` (wiring
664
- * `canTake` to `step.snapshot.can` so guard-rejected choices retry) then
665
- * applied with {@link transitionAgentStep}. The **current** step is re-read
666
- * after each application — the machine may advance and its `requests` change —
667
- * so this always resolves against the live step, never a stale list.
668
- *
669
- * A `kind: 'plan'` request (`agent.plan`) is resolved natively too: one plan
670
- * step per call. It resolves a single decision from `request.events` (wiring
671
- * `canTake` to `step.snapshot.can`, exempting the reserved `agent.plan.done`
672
- * move and `stopOn` events), then either applies the chosen machine event and
673
- * lets the next step re-surface the plan, or completes the plan (feeding its
674
- * `{ steps, stopped }` output back) on the done move / a `stopOn` event / an
675
- * exhausted budget / no legal events. The plan's applied trail is carried in
676
- * the invoke child's snapshot, so persisting the step between calls resumes the
677
- * plan identically.
678
- *
679
- * Missing the executor a request needs throws a clear error
680
- * (`generateText`/`streamText` for text, `decide` for decisions and plans).
681
- *
682
- * A complete durable host is two lines:
683
- *
684
- * ```ts
685
- * let step = initialAgentStep(machine, input);
686
- * while (!step.done) step = await resolveAgentRequests(machine, step, executors);
687
- * ```
688
- *
689
- * All pending **text** requests of a step are resolved in parallel
690
- * (`Promise.all`) — parallel statechart regions are genuinely concurrent, so
691
- * their model calls run concurrently — then their outputs apply in
692
- * **request-array order** (deterministic for durable replay regardless of which
693
- * call finishes first). Decisions and plans stay **one at a time**: applying
694
- * either changes the set of legal candidates for what follows, so they cannot be
695
- * resolved against a stale snapshot. A host that instead wants strictly
696
- * sequential text resolution loops the manual per-request helpers
697
- * ({@link executeAgentRequest} + {@link resolveAgentStep}) one at a time.
698
- */
699
- async function resolveAgentRequests(machine, step, executors, options) {
700
- const [request] = step.requests;
701
- if (!request) return step;
702
- if (request.kind === "decision") {
703
- if (!executors.decide) throw new Error(`this step's decision request '${request.id}' needs a 'decide' executor but none was provided.`);
704
- return transitionAgentStep(machine, step, await resolveDecision(request, executors.decide, {
705
- canTake: (event) => step.snapshot.can(event),
706
- maxRetries: options?.maxRetries
707
- }), options);
708
- }
709
- if (request.kind === "plan") return resolvePlanRequest(machine, step, request, executors, options);
710
- const textRequests = step.requests.filter((candidate) => candidate.kind === "text");
711
- for (const textRequest of textRequests) assertTextExecutor(textRequest, executors);
712
- const outputs = await Promise.all(textRequests.map((textRequest) => executeAgentRequest(textRequest, executors)));
713
- let next = step;
714
- for (let index = 0; index < textRequests.length; index++) next = resolveAgentStep(machine, next, textRequests[index], outputs[index], options);
715
- return next;
716
- }
717
- function assertTextExecutor(request, executors) {
718
- const mode = request.mode ?? "generate";
719
- const kind = mode === "stream" ? "streamText" : "generateText";
720
- if (!(mode === "stream" ? executors.streamText : executors.generateText)) throw new Error(`this step's text request '${request.src}' needs a '${kind}' executor but none was provided.`);
721
- }
722
- async function resolvePlanRequest(machine, step, request, executors, options) {
723
- if (!executors.decide) throw new Error(`this step's plan request '${request.src}' needs a 'decide' executor but none was provided.`);
724
- const stopOn = new Set(request.input.stopOn ?? []);
725
- if (request.stepsRemaining <= 0) return completePlan(machine, step, request.id, request.applied, "max-steps", options);
726
- if (request.events.filter((event) => event.type !== "agent.plan.done").length === 0) return completePlan(machine, step, request.id, request.applied, "no-legal-events", options);
727
- const chosen = await resolveDecision(planStepDecisionRequest(request), executors.decide, {
728
- maxRetries: options?.maxRetries,
729
- canTake: (event) => {
730
- if (event.type === "agent.plan.done" || stopOn.has(event.type)) return true;
731
- return step.snapshot.can(event);
732
- }
733
- });
734
- if (chosen.type === "agent.plan.done") return completePlan(machine, step, request.id, request.applied, "done", options);
735
- const applied = [...request.applied, chosen];
736
- advancePlanChildLedger(step.snapshot, request.id, {
737
- type: "plan.applied",
738
- event: chosen
739
- });
740
- const next = transitionAgentStep(machine, step, chosen, options);
741
- if (stopOn.has(chosen.type)) {
742
- if (isPlanActive(next.snapshot, request.id)) return completePlan(machine, next, request.id, applied, "stop-event", options);
743
- }
744
- return next;
745
- }
746
- function completePlan(machine, step, id, steps, stopped, options) {
747
- return resolveAgentStep(machine, step, { id }, {
748
- steps,
749
- stopped
750
- }, options);
751
- }
752
- function planStepDecisionRequest(request) {
753
- const { input, applied, events, id } = request;
754
- const trail = applied.length === 0 ? "" : `\n\nEvents already applied in this plan, in order:\n${applied.map((step) => JSON.stringify(step)).join("\n")}\nContinue from here; do not repeat applied events.`;
755
- const doneHint = `\n\nWhen the request is fully handled (or no action is needed), choose '${PLAN_DONE_EVENT_TYPE}'.`;
756
- return {
757
- kind: "decision",
758
- id: `${id}[${applied.length}]`,
759
- model: input.model,
760
- system: input.system,
761
- prompt: `${input.prompt ?? ""}${trail}${doneHint}`,
762
- messages: input.messages,
763
- events,
764
- attempts: [],
765
- temperature: input.temperature,
766
- maxOutputTokens: input.maxOutputTokens,
767
- topP: input.topP,
768
- topK: input.topK,
769
- seed: input.seed,
770
- stopSequences: input.stopSequences,
771
- metadata: input.metadata
772
- };
773
- }
774
- function advancePlanChildLedger(snapshot, id, event) {
775
- const child = snapshot.children?.[id];
776
- const childSnapshot = child?.getSnapshot?.();
777
- if (!isPlanLogic(child?.logic) || !childSnapshot || typeof childSnapshot !== "object") return;
778
- Object.assign(childSnapshot, advancePlanLedger(child.logic, childSnapshot, event));
779
- }
780
- function isPlanActive(snapshot, id) {
781
- return (snapshot.children?.[id])?.getSnapshot?.()?.status === "active";
782
- }
783
- function createAgentStep(machine, snapshot, actions, options) {
784
- applyFinalStateOutput(machine, snapshot);
785
- return {
786
- snapshot,
787
- actions,
788
- requests: getAgentRequestsWith(actions, {
789
- ...options,
790
- snapshot
791
- }),
792
- done: snapshot.status === "done"
793
- };
794
- }
795
- function resolveStateValueConfig(config, value) {
796
- if (typeof value === "string") return config.states?.[value];
797
- if (!value || typeof value !== "object") return;
798
- for (const [key, childValue] of Object.entries(value)) {
799
- const childConfig = config.states?.[key];
800
- if (!childConfig) continue;
801
- if (childConfig.type === "final") return childConfig;
802
- const nested = resolveStateValueConfig(childConfig, childValue);
803
- if (nested) return nested;
804
- }
805
- }
806
- function applyFinalStateOutput(logic, snapshot, event) {
807
- const machineSnapshot = snapshot;
808
- if (machineSnapshot.status !== "done" || machineSnapshot.output !== void 0 || !("config" in logic)) return;
809
- const config = logic.config;
810
- if (!config) return;
811
- const output = resolveStateValueConfig(config, machineSnapshot.value)?.output;
812
- if (output === void 0) return;
813
- machineSnapshot.output = typeof output === "function" ? output({
814
- context: machineSnapshot.context,
815
- event
816
- }) : output;
817
- }
818
- function isAgentStep(value) {
819
- return !!value && typeof value === "object" && "snapshot" in value && "actions" in value && "requests" in value;
820
- }
821
- //#endregion
822
511
  //#region src/internal/state-request-pass.ts
823
512
  async function runTextPhase(stateRequest, baseMessages, deps) {
824
513
  const { model, system } = stateRequest;
@@ -1839,611 +1528,4 @@ function collectPendingUserInputs(snapshot) {
1839
1528
  return pending;
1840
1529
  }
1841
1530
  //#endregion
1842
- //#region src/verify.ts
1843
- const DECIDE_SRC = "agent.decide";
1844
- const PLAN_SRC = "agent.plan";
1845
- function normalizeInvokes(invoke) {
1846
- if (invoke === void 0 || invoke === null) return [];
1847
- return Array.isArray(invoke) ? invoke : [invoke];
1848
- }
1849
- function buildStateIndex(rootConfig) {
1850
- const index = /* @__PURE__ */ new Map();
1851
- const walk = (states, parentPath) => {
1852
- for (const [name, config] of Object.entries(states ?? {})) {
1853
- const path = parentPath ? `${parentPath}.${name}` : name;
1854
- const hasChildren = !!config.states && Object.keys(config.states).length > 0;
1855
- index.set(path, {
1856
- path,
1857
- name,
1858
- config,
1859
- parentPath,
1860
- type: config.type,
1861
- isFinal: config.type === "final",
1862
- isParallel: config.type === "parallel",
1863
- isCompound: hasChildren && config.type !== "parallel",
1864
- invokes: normalizeInvokes(config.invoke)
1865
- });
1866
- if (hasChildren) walk(config.states, path);
1867
- }
1868
- };
1869
- walk(rootConfig.states, "");
1870
- return index;
1871
- }
1872
- function childrenOf(index, parentPath) {
1873
- const out = [];
1874
- for (const node of index.values()) if (node.parentPath === parentPath) out.push(node);
1875
- return out;
1876
- }
1877
- function collectTransitionTargets(value, fromNode, index, out) {
1878
- if (value === void 0 || value === null) return;
1879
- if (Array.isArray(value)) {
1880
- for (const item of value) collectTransitionTargets(item, fromNode, index, out);
1881
- return;
1882
- }
1883
- if (typeof value === "function") {
1884
- out.opaque = true;
1885
- return;
1886
- }
1887
- if (typeof value === "string") {
1888
- resolveTargetString(value, fromNode, index, out);
1889
- return;
1890
- }
1891
- if (typeof value === "object") {
1892
- const target = value.target;
1893
- if (target !== void 0) collectTransitionTargets(target, fromNode, index, out);
1894
- }
1895
- }
1896
- function resolveTargetString(target, fromNode, index, out) {
1897
- if (target.startsWith("#")) {
1898
- out.opaque = true;
1899
- return;
1900
- }
1901
- const resolved = target.startsWith(".") ? `${fromNode.path}.${target.slice(1)}` : fromNode.parentPath ? `${fromNode.parentPath}.${target}` : target;
1902
- if (index.has(resolved)) out.targets.push(resolved);
1903
- else out.opaque = true;
1904
- }
1905
- function outgoingTargets(node, index) {
1906
- const out = {
1907
- targets: [],
1908
- opaque: false
1909
- };
1910
- const { config } = node;
1911
- for (const value of Object.values(config.on ?? {})) collectTransitionTargets(value, node, index, out);
1912
- collectTransitionTargets(config.always, node, index, out);
1913
- collectTransitionTargets(config.choice, node, index, out);
1914
- for (const value of Object.values(config.after ?? {})) collectTransitionTargets(value, node, index, out);
1915
- collectTransitionTargets(config.onDone, node, index, out);
1916
- for (const invoke of node.invokes) {
1917
- collectTransitionTargets(invoke.onDone, node, index, out);
1918
- collectTransitionTargets(invoke.onError, node, index, out);
1919
- }
1920
- return out;
1921
- }
1922
- function computeReachable(rootConfig, index) {
1923
- const reachable = /* @__PURE__ */ new Set();
1924
- const queue = [];
1925
- const markAncestors = (path) => {
1926
- let parent = index.get(path)?.parentPath ?? "";
1927
- while (parent) {
1928
- reachable.add(parent);
1929
- parent = index.get(parent)?.parentPath ?? "";
1930
- }
1931
- };
1932
- const enter = (path) => {
1933
- if (reachable.has(path)) return;
1934
- const node = index.get(path);
1935
- if (!node) return;
1936
- reachable.add(path);
1937
- queue.push(path);
1938
- markAncestors(path);
1939
- if (node.isParallel) for (const child of childrenOf(index, path)) enter(child.path);
1940
- else if (node.isCompound && node.config.initial) enter(`${path}.${node.config.initial}`);
1941
- };
1942
- if (rootConfig.type === "parallel") for (const child of childrenOf(index, "")) enter(child.path);
1943
- else if (rootConfig.initial) enter(rootConfig.initial);
1944
- while (queue.length > 0) {
1945
- const node = index.get(queue.shift());
1946
- if (!node) continue;
1947
- const { targets, opaque } = outgoingTargets(node, index);
1948
- for (const target of targets) enter(target);
1949
- if (opaque) for (const sibling of childrenOf(index, node.parentPath)) enter(sibling.path);
1950
- }
1951
- return reachable;
1952
- }
1953
- function ancestorChain(node, index) {
1954
- const chain = [];
1955
- let parent = node.parentPath;
1956
- while (parent) {
1957
- const parentNode = index.get(parent);
1958
- if (!parentNode) break;
1959
- chain.push(parentNode);
1960
- parent = parentNode.parentPath;
1961
- }
1962
- return chain;
1963
- }
1964
- function hasNonEmptyOn(config) {
1965
- return !!config.on && Object.keys(config.on).length > 0;
1966
- }
1967
- function decisionKindOf(src, actorSources) {
1968
- if (typeof src === "string") {
1969
- if (src === DECIDE_SRC) return "decision";
1970
- if (src === PLAN_SRC) return "plan";
1971
- const logic = actorSources[src];
1972
- if (isDecisionLogic(logic)) return "decision";
1973
- if (isPlanLogic(logic)) return "plan";
1974
- return;
1975
- }
1976
- if (isDecisionLogic(src)) return "decision";
1977
- if (isPlanLogic(src)) return "plan";
1978
- }
1979
- function isAgentLogicNeedingBinding(src) {
1980
- return (isTextLogic(src) || isDecisionLogic(src) || isPlanLogic(src)) && !executorBoundLogics.has(src);
1981
- }
1982
- function schemaExposesJson(schema) {
1983
- if (!schema) return false;
1984
- try {
1985
- return getJsonSchemaSync(schema) !== void 0;
1986
- } catch {
1987
- return false;
1988
- }
1989
- }
1990
- function isDeclaredOutputSchema(schema) {
1991
- if (!schema) return false;
1992
- let json;
1993
- try {
1994
- json = getJsonSchemaSync(schema);
1995
- } catch {
1996
- return false;
1997
- }
1998
- if (!json) return false;
1999
- const properties = json.properties;
2000
- const required = json.required;
2001
- return json.type === "object" && !!properties && Object.keys(properties).length > 0 || Array.isArray(required) && required.length > 0;
2002
- }
2003
- function checkUnreachableStates(ctx) {
2004
- const out = [];
2005
- for (const node of ctx.index.values()) if (!ctx.reachable.has(node.path)) out.push({
2006
- code: "unreachable-state",
2007
- severity: "error",
2008
- path: node.path,
2009
- message: `State '${node.path}' is unreachable: no transition, always, onDone, or onError target (from any reachable state) leads to it. Remove it or add a transition.`
2010
- });
2011
- return out;
2012
- }
2013
- function checkDecideWithoutEvents(ctx) {
2014
- const out = [];
2015
- for (const node of ctx.index.values()) for (const invoke of node.invokes) {
2016
- const kind = decisionKindOf(invoke.src, ctx.actorSources);
2017
- if (!kind) continue;
2018
- const selfHandles = hasNonEmptyOn(node.config);
2019
- const ancestorHandles = ancestorChain(node, ctx.index).some((ancestor) => hasNonEmptyOn(ancestor.config));
2020
- const invokeObserves = invoke.onDone !== void 0;
2021
- if (selfHandles || ancestorHandles || invokeObserves) continue;
2022
- const srcName = typeof invoke.src === "string" ? invoke.src : "(inline logic)";
2023
- out.push({
2024
- code: "decide-without-events",
2025
- severity: "error",
2026
- path: node.path,
2027
- message: `State '${node.path}' invokes ${kind} source '${srcName}', but neither it nor any ancestor handles any event (no 'on:'), so the ${kind}'s chosen event can never be delivered. Add an 'on:' handler for the candidate events.`
2028
- });
2029
- }
2030
- return out;
2031
- }
2032
- function checkUnserializableContext(ctx) {
2033
- const contextSchema = ctx.schemas?.context;
2034
- if (!contextSchema) return [];
2035
- if (schemaExposesJson(contextSchema)) return [];
2036
- return [{
2037
- code: "unserializable-context",
2038
- severity: "warning",
2039
- path: "context",
2040
- message: "The context schema does not expose a JSON schema (e.g. a `z.custom` without a `jsonSchema` extension, such as a messages array), so its fields cannot be statically checked for JSON persist/resume round-tripping. This is expected for message transcripts; verify any other custom-typed context is JSON-serializable."
2041
- }];
2042
- }
2043
- function checkDirectObjectSrc(ctx) {
2044
- const out = [];
2045
- for (const node of ctx.index.values()) for (const invoke of node.invokes) {
2046
- const src = invoke.src;
2047
- if (typeof src === "string" || !src || typeof src !== "object") continue;
2048
- if (!isAgentLogicNeedingBinding(src)) continue;
2049
- out.push({
2050
- code: "direct-object-src",
2051
- severity: "warning",
2052
- path: node.path,
2053
- message: `State '${node.path}' invokes a direct-object agent logic. Direct-object invoke srcs cannot be rebound by runAgent, so they inherit no host executors — call '.withExecutor(...)' on the logic, or register it as a string-keyed actor source (machine.provide({ actorSources: { name: logic } })) and invoke it by name.`
2054
- });
2055
- }
2056
- return out;
2057
- }
2058
- function checkFinalWithoutOutput(ctx) {
2059
- if (!isDeclaredOutputSchema(ctx.schemas?.output)) return [];
2060
- if (ctx.config.output !== void 0) return [];
2061
- const out = [];
2062
- for (const node of ctx.index.values()) {
2063
- if (node.parentPath !== "" || !node.isFinal) continue;
2064
- if (node.config.output === void 0) out.push({
2065
- code: "final-without-output",
2066
- severity: "error",
2067
- path: node.path,
2068
- message: `The machine declares an output schema, but top-level final state '${node.path}' has no 'output'. Its snapshot output will be undefined and fail the schema. Add an 'output' to this final state (or a root 'output').`
2069
- });
2070
- }
2071
- return out;
2072
- }
2073
- function outputFnReadsEvent(fn) {
2074
- return /\bevent\s*(?:\.|\?\.|\[)/.test(fn.toString());
2075
- }
2076
- function checkFinalOutputReadsEvent(ctx) {
2077
- const out = [];
2078
- for (const node of ctx.index.values()) {
2079
- if (node.parentPath !== "" || !node.isFinal) continue;
2080
- const output = node.config.output;
2081
- if (typeof output !== "function") continue;
2082
- if (!outputFnReadsEvent(output)) continue;
2083
- out.push({
2084
- code: "final-output-reads-event",
2085
- severity: "warning",
2086
- path: node.path,
2087
- message: `Final state '${node.path}' has an 'output' function that reads 'event'. Final-state 'output' functions are evaluated more than once with different events (the entering event, then the machine-done computation) under current xstate behavior, so 'event' is unreliable here. Read 'context' only; capture what you need from the entering event into context in the transition that targets this state. (This guard can relax if xstate guarantees a stable entering event across evaluations.)`
2088
- });
2089
- }
2090
- return out;
2091
- }
2092
- function checkMissingFinal(ctx) {
2093
- for (const node of ctx.index.values()) if (node.isFinal && ctx.reachable.has(node.path)) return [];
2094
- return [{
2095
- code: "missing-final",
2096
- severity: "warning",
2097
- path: "(root)",
2098
- message: "The machine has no reachable final state, so a run can never settle 'done' (only idle/looping). This is legal for agents that only idle, but verify it is intended."
2099
- }];
2100
- }
2101
- const LINT_CHECKS = [
2102
- checkUnreachableStates,
2103
- checkDecideWithoutEvents,
2104
- checkUnserializableContext,
2105
- checkDirectObjectSrc,
2106
- checkFinalWithoutOutput,
2107
- checkFinalOutputReadsEvent,
2108
- checkMissingFinal
2109
- ];
2110
- /**
2111
- * Runs static structural checks over a built agent machine and returns the
2112
- * findings ({@link AgentLintDiagnostic}[], empty when clean). Works for
2113
- * TS-authored (`setupAgent(...).createMachine(...)`) and
2114
- * `setupAgent.fromConfig(...)`-compiled machines alike, reading `machine.config`
2115
- * plus the schemas/actor sources the library already retains per machine.
2116
- *
2117
- * No model calls, no API keys — a coding agent that emits an agent machine can
2118
- * call this to catch dead states, undeliverable decisions, un-rebindable
2119
- * invoke srcs, and output-contract gaps before ever running it.
2120
- *
2121
- * @example
2122
- * ```ts
2123
- * const errors = lintAgentMachine(machine).filter((d) => d.severity === 'error');
2124
- * if (errors.length) throw new Error(errors.map((e) => `${e.path}: ${e.message}`).join('\n'));
2125
- * ```
2126
- */
2127
- function lintAgentMachine(machine, options = {}) {
2128
- const config = machine.config ?? {};
2129
- const index = buildStateIndex(config);
2130
- const reachable = computeReachable(config, index);
2131
- const registered = getRegisteredAgentExecutionOptions(machine);
2132
- const ctx = {
2133
- machine,
2134
- config,
2135
- index,
2136
- reachable,
2137
- schemas: registered.schemas,
2138
- actorSources: registered.actorSources ?? machine.implementations?.actorSources ?? {}
2139
- };
2140
- const disabled = new Set(options.disable ?? []);
2141
- return LINT_CHECKS.flatMap((check) => check(ctx)).filter((d) => !disabled.has(d.code));
2142
- }
2143
- function pendingInvokes(step) {
2144
- const out = [];
2145
- for (const action of step.actions) {
2146
- const type = action.type;
2147
- if (type !== "xstate.spawnChild" && type !== "@xstate.start") continue;
2148
- const params = type === "@xstate.start" ? action : action.params ?? {};
2149
- if (typeof params.src === "string" && typeof params.id === "string") out.push({
2150
- id: params.id,
2151
- src: params.src
2152
- });
2153
- }
2154
- return out;
2155
- }
2156
- function takeFromQueue(channel, src) {
2157
- const queue = channel?.[src];
2158
- if (queue && queue.length > 0) return {
2159
- found: true,
2160
- value: queue.shift()
2161
- };
2162
- return { found: false };
2163
- }
2164
- /**
2165
- * Deterministically plays a machine through, resolving each request from a
2166
- * {@link SimulationScript} instead of a model — no API keys, no model calls.
2167
- * Runs on the pure step path ({@link initialAgentStep} etc.), so it exercises
2168
- * the real transition logic. Returns the terminal `status`, final `snapshot`,
2169
- * and a `trail` of every step taken.
2170
- *
2171
- * Throws a descriptive error when the script runs dry mid-request, naming the
2172
- * pending request's kind, src, and id so the missing scripted response is
2173
- * obvious.
2174
- *
2175
- * @example
2176
- * ```ts
2177
- * const { status, snapshot } = simulateAgent(machine, {
2178
- * input: { topic: 'state machines' },
2179
- * script: { decisions: { 'agent.decide': [{ type: 'END' }] } },
2180
- * });
2181
- * ```
2182
- */
2183
- async function simulateAgent(machine, options) {
2184
- const maxSteps = options.maxSteps ?? 100;
2185
- const script = {
2186
- text: { ...options.script.text },
2187
- decisions: mapValues(options.script.decisions ?? {}, (arr) => [...arr]),
2188
- userInput: mapValues(options.script.userInput ?? {}, (arr) => [...arr])
2189
- };
2190
- let step = initialAgentStep(machine, options.input);
2191
- const trail = [];
2192
- for (let i = 0; i < maxSteps; i++) {
2193
- if (step.done) return {
2194
- status: "done",
2195
- snapshot: step.snapshot,
2196
- trail
2197
- };
2198
- const request = step.requests[0];
2199
- if (request) {
2200
- if (request.kind === "decision") {
2201
- const decisionSrc = new Map(pendingInvokes(step).map((invoke) => [invoke.id, invoke.src])).get(request.id) ?? request.id;
2202
- const taken = takeFromQueue(script.decisions, decisionSrc);
2203
- if (!taken.found) throw scriptDryError("decision", decisionSrc, request.id, request);
2204
- step = transitionAgentStep(machine, step, taken.value);
2205
- trail.push({
2206
- state: step.snapshot.value,
2207
- appliedEvent: taken.value
2208
- });
2209
- continue;
2210
- }
2211
- if (request.kind === "plan") {
2212
- const taken = takeFromQueue(script.decisions, request.src);
2213
- if (!taken.found) throw scriptDryError("decision", request.src, request.id, request);
2214
- const event = taken.value;
2215
- step = await resolveAgentRequests(machine, step, { decide: async () => ({ event }) });
2216
- trail.push({
2217
- state: step.snapshot.value,
2218
- appliedEvent: taken.value
2219
- });
2220
- continue;
2221
- }
2222
- const taken = takeFromQueue(script.text, request.src);
2223
- if (!taken.found) throw scriptDryError("text", request.src, request.id);
2224
- step = resolveAgentStep(machine, step, request, taken.value);
2225
- trail.push({
2226
- state: step.snapshot.value,
2227
- resolvedRequest: {
2228
- kind: "text",
2229
- src: request.src,
2230
- id: request.id
2231
- }
2232
- });
2233
- continue;
2234
- }
2235
- const [invoke] = pendingInvokes(step);
2236
- if (invoke) {
2237
- const taken = takeFromQueue(script.userInput, invoke.src);
2238
- if (!taken.found) throw scriptDryError("userInput", invoke.src, invoke.id);
2239
- step = resolveAgentStep(machine, step, invoke.id, taken.value);
2240
- trail.push({
2241
- state: step.snapshot.value,
2242
- resolvedRequest: {
2243
- kind: "userInput",
2244
- src: invoke.src,
2245
- id: invoke.id
2246
- }
2247
- });
2248
- continue;
2249
- }
2250
- return {
2251
- status: "idle",
2252
- snapshot: step.snapshot,
2253
- trail
2254
- };
2255
- }
2256
- return {
2257
- status: "exhausted",
2258
- snapshot: step.snapshot,
2259
- trail
2260
- };
2261
- }
2262
- function mapValues(obj, fn) {
2263
- return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, fn(value)]));
2264
- }
2265
- function scriptDryError(kind, src, id, request) {
2266
- const events = request?.kind === "decision" ? ` Candidate events: ${request.events.map((e) => e.type).join(", ") || "(none)"}.` : "";
2267
- return /* @__PURE__ */ new Error(`simulateAgent: script ran dry on a pending ${kind} request for src '${src}' (id '${id}'). Add a '${kind}' entry for '${src}' to the script.${events}`);
2268
- }
2269
- async function explore(machine, options, stopWhen) {
2270
- const maxDepth = options.maxDepth ?? 8;
2271
- const maxPaths = options.maxPaths ?? 200;
2272
- const textOutputs = options.textOutputs ?? {};
2273
- const reachedStates = /* @__PURE__ */ new Set();
2274
- const reachedValues = [];
2275
- const terminals = [];
2276
- const unexplored = [];
2277
- let prunedByGuard = 0;
2278
- let pathsExplored = 0;
2279
- let hitPathCap = false;
2280
- let witness;
2281
- const recordState = (snapshot) => {
2282
- const key = JSON.stringify(snapshot.value);
2283
- if (!reachedStates.has(key)) {
2284
- reachedStates.add(key);
2285
- reachedValues.push(snapshot.value);
2286
- }
2287
- };
2288
- const initial = initialAgentStep(machine, options.input);
2289
- recordState(initial.snapshot);
2290
- if (stopWhen?.(initial.snapshot)) witness = [];
2291
- const advance = (step) => {
2292
- let current = step;
2293
- for (let i = 0; i < 1e3; i++) {
2294
- if (current.done) return { step: current };
2295
- const request = current.requests[0];
2296
- if (request && request.kind === "text") {
2297
- if (!(request.src in textOutputs)) return {
2298
- step: current,
2299
- blockedSrc: request.src
2300
- };
2301
- current = resolveAgentStep(machine, current, request, textOutputs[request.src]);
2302
- recordState(current.snapshot);
2303
- continue;
2304
- }
2305
- if (request && (request.kind === "decision" || request.kind === "plan")) return { step: current };
2306
- const [invoke] = pendingInvokes(current);
2307
- if (invoke) {
2308
- if (!(invoke.src in textOutputs)) return {
2309
- step: current,
2310
- blockedSrc: invoke.src
2311
- };
2312
- current = resolveAgentStep(machine, current, invoke.id, textOutputs[invoke.src]);
2313
- recordState(current.snapshot);
2314
- continue;
2315
- }
2316
- return { step: current };
2317
- }
2318
- return { step: current };
2319
- };
2320
- const visit = async (step, path, depth) => {
2321
- if (witness !== void 0) return;
2322
- if (pathsExplored >= maxPaths) {
2323
- hitPathCap = true;
2324
- return;
2325
- }
2326
- const { step: settled, blockedSrc } = advance(step);
2327
- if (stopWhen?.(settled.snapshot)) {
2328
- witness = path;
2329
- return;
2330
- }
2331
- if (blockedSrc) {
2332
- pathsExplored++;
2333
- terminals.push({
2334
- status: "needs-output",
2335
- path,
2336
- state: settled.snapshot.value,
2337
- missingSrc: blockedSrc
2338
- });
2339
- unexplored.push(`needs-output: no canned output for src '${blockedSrc}' at path [${path.map((e) => e.type).join(", ")}]`);
2340
- return;
2341
- }
2342
- if (settled.done) {
2343
- pathsExplored++;
2344
- terminals.push({
2345
- status: "done",
2346
- path,
2347
- state: settled.snapshot.value
2348
- });
2349
- return;
2350
- }
2351
- const request = settled.requests[0];
2352
- const isPlan = request?.kind === "plan";
2353
- const branchEvents = request?.kind === "decision" || request?.kind === "plan" ? request.events.map((descriptor) => ({ type: descriptor.type })) : getAcceptedEvents(settled.snapshot).map((descriptor) => ({ type: descriptor.type }));
2354
- if (branchEvents.length === 0) {
2355
- pathsExplored++;
2356
- terminals.push({
2357
- status: "idle",
2358
- path,
2359
- state: settled.snapshot.value
2360
- });
2361
- return;
2362
- }
2363
- if (depth >= maxDepth) {
2364
- pathsExplored++;
2365
- terminals.push({
2366
- status: "max-depth",
2367
- path,
2368
- state: settled.snapshot.value
2369
- });
2370
- unexplored.push(`max-depth: stopped at path [${path.map((e) => e.type).join(", ")}]`);
2371
- return;
2372
- }
2373
- for (const event of branchEvents) {
2374
- if (witness !== void 0 || pathsExplored >= maxPaths) {
2375
- if (pathsExplored >= maxPaths) hitPathCap = true;
2376
- return;
2377
- }
2378
- if (!(isPlan && event.type === "agent.plan.done") && !settled.snapshot.can(event)) {
2379
- prunedByGuard++;
2380
- continue;
2381
- }
2382
- const next = isPlan ? await resolveAgentRequests(machine, settled, { decide: async () => ({ event }) }) : transitionAgentStep(machine, settled, event);
2383
- recordState(next.snapshot);
2384
- await visit(next, [...path, event], depth + 1);
2385
- }
2386
- };
2387
- if (witness === void 0) await visit(initial, [], 0);
2388
- return {
2389
- report: {
2390
- reachedStates: reachedValues,
2391
- terminals,
2392
- prunedByGuard,
2393
- unexplored,
2394
- pathsExplored,
2395
- hitPathCap
2396
- },
2397
- witness
2398
- };
2399
- }
2400
- /**
2401
- * Enumerates a machine's decision and external-event branches to a bounded
2402
- * depth, model-free, and reports which states are reached and how each path
2403
- * terminates. At each decision request it forks one branch per candidate event
2404
- * (guard-rejected candidates are counted in `prunedByGuard`, not explored); at
2405
- * an idle wait it forks per externally-accepted event. A `agent.plan` request
2406
- * forks the same way — one branch per candidate, including the reserved
2407
- * `agent.plan.done` move — advancing each branch through the real plan protocol
2408
- * (`resolveAgentRequests`), so a plan can consume several depth units. Text/`userInput` invokes
2409
- * are resolved from `textOutputs` (a by-src canned-output map) — a missing src
2410
- * halts that branch with a `needs-output` terminal rather than throwing.
2411
- *
2412
- * Combinatorics are bounded by `maxDepth` (default 8) and `maxPaths` (default
2413
- * 200, reported via `hitPathCap`).
2414
- *
2415
- * @example
2416
- * ```ts
2417
- * const report = await explorePaths(refundMachine, { input: { request: 'x', amount: 5000 } });
2418
- * // report.terminals → both 'refunded' and 'denied'; report.prunedByGuard → 1
2419
- * ```
2420
- */
2421
- async function explorePaths(machine, options = {}) {
2422
- return (await explore(machine, options)).report;
2423
- }
2424
- /**
2425
- * Answers "can the machine reach `statePath`?" by exploring its branches (a
2426
- * thin wrapper over {@link explorePaths}). Returns `{ canReach: true, witness }`
2427
- * with the event sequence that reaches it, or `{ canReach: false }`.
2428
- *
2429
- * @example
2430
- * ```ts
2431
- * const { canReach, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
2432
- * // canReach → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
2433
- * ```
2434
- */
2435
- async function canReach(machine, statePath, options = {}) {
2436
- const { witness } = await explore(machine, options, (snapshot) => {
2437
- try {
2438
- return snapshot.matches(statePath);
2439
- } catch {
2440
- return false;
2441
- }
2442
- });
2443
- return witness !== void 0 ? {
2444
- canReach: true,
2445
- witness
2446
- } : { canReach: false };
2447
- }
2448
- //#endregion
2449
- export { createAgentSchemas as _, AgentIdleError as a, messagesSchema as b, inspectTransitions as c, executeAgentRequest as d, getAgentRequests as f, transitionAgentStep as g, resolveAgentStep as h, simulateAgent as i, runAgent as l, resolveAgentRequests as m, explorePaths as n, IllegalResumeEventError as o, initialAgentStep as p, lintAgentMachine as r, SnapshotVersionMismatchError as s, canReach as t, runAgentToCompletion as u, setupAgent as v, appendMessages as y };
1531
+ export { runAgent as a, setupAgent as c, inspectTransitions as i, appendMessages as l, IllegalResumeEventError as n, runAgentToCompletion as o, SnapshotVersionMismatchError as r, createAgentSchemas as s, AgentIdleError as t, messagesSchema as u };