@statelyai/agent 2.0.0-alpha.14 → 2.0.0-alpha.16

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 (35) hide show
  1. package/dist/ai-sdk.cjs +1 -1
  2. package/dist/ai-sdk.d.cts +2 -2
  3. package/dist/ai-sdk.d.mts +2 -2
  4. package/dist/ai-sdk.mjs +1 -1
  5. package/dist/{decision-C0cUKvNt.cjs → decision-Ba8qrT8r.cjs} +42 -28
  6. package/dist/{decision-D9Zi7Xi5.mjs → decision-Bt2HYYRo.mjs} +31 -23
  7. package/dist/{event-log-store-D7pWtIhb.mjs → event-log-store-B-1fcfkT.mjs} +149 -141
  8. package/dist/{event-log-store-BkUNtyOF.d.mts → event-log-store-BrC9Q1xW.d.mts} +14 -12
  9. package/dist/{event-log-store-CVd2eyRy.d.cts → event-log-store-CQJq8_v4.d.cts} +14 -12
  10. package/dist/{event-log-store-CNT_7F0V.cjs → event-log-store-yquOV1TX.cjs} +148 -140
  11. package/dist/index.cjs +520 -521
  12. package/dist/index.d.cts +128 -106
  13. package/dist/index.d.mts +128 -106
  14. package/dist/index.mjs +519 -520
  15. package/dist/machines.cjs +1 -1
  16. package/dist/machines.d.cts +1 -1
  17. package/dist/machines.d.mts +1 -1
  18. package/dist/machines.mjs +1 -1
  19. package/dist/otel.d.cts +1 -1
  20. package/dist/otel.d.mts +1 -1
  21. package/dist/{run-agent-BlqKwHIF.d.cts → run-agent-BxjGaVpL.d.cts} +72 -111
  22. package/dist/{run-agent-2MnlQTkB.d.mts → run-agent-COHoCgQd.d.mts} +72 -111
  23. package/dist/{setup-agent-CpK0ZRWV.cjs → setup-agent-BLU77gqr.cjs} +141 -172
  24. package/dist/{setup-agent-DeHRW-qX.mjs → setup-agent-SbiiSbAU.mjs} +136 -167
  25. package/dist/sqlite.cjs +1 -1
  26. package/dist/sqlite.d.cts +2 -2
  27. package/dist/sqlite.d.mts +2 -2
  28. package/dist/sqlite.mjs +1 -1
  29. package/dist/{text-logic-Jkilp1Ie.d.cts → text-logic-BFX5q7fM.d.cts} +26 -3
  30. package/dist/{text-logic-C5kbjaDz.d.mts → text-logic-DQW8_DWW.d.mts} +26 -3
  31. package/dist/{types-rMe7x6NR.d.cts → types-DYpK3QF4.d.mts} +35 -7
  32. package/dist/{types-9Bqg5rZB.d.mts → types-pJ5Hn8fv.d.cts} +35 -7
  33. package/package.json +28 -28
  34. package/readme.md +6 -19
  35. package/schemas/agent-workflow.json +1 -4
package/dist/machines.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_setup_agent = require("./setup-agent-CpK0ZRWV.cjs");
2
+ const require_setup_agent = require("./setup-agent-BLU77gqr.cjs");
3
3
  //#region src/machines/internal.ts
4
4
  /** The builtin inline text request every preset lowers a request entry to. */
5
5
  const GENERATE_TEXT_SRC = "agent.generateText";
@@ -1,4 +1,4 @@
1
- import { _ as StandardSchemaV1, c as AgentTools } from "./types-rMe7x6NR.cjs";
1
+ import { c as AgentTools, v as StandardSchemaV1 } from "./types-pJ5Hn8fv.cjs";
2
2
  import { AnyStateMachine } from "xstate";
3
3
 
4
4
  //#region src/machines/tool-loop.d.ts
@@ -1,4 +1,4 @@
1
- import { _ as StandardSchemaV1, c as AgentTools } from "./types-9Bqg5rZB.mjs";
1
+ import { c as AgentTools, v as StandardSchemaV1 } from "./types-DYpK3QF4.mjs";
2
2
  import { AnyStateMachine } from "xstate";
3
3
 
4
4
  //#region src/machines/tool-loop.d.ts
package/dist/machines.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { n as setupAgent } from "./setup-agent-DeHRW-qX.mjs";
1
+ import { n as setupAgent } from "./setup-agent-SbiiSbAU.mjs";
2
2
  //#region src/machines/internal.ts
3
3
  /** The builtin inline text request every preset lowers a request entry to. */
4
4
  const GENERATE_TEXT_SRC = "agent.generateText";
package/dist/otel.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { c as AgentTraceEvent } from "./run-agent-BlqKwHIF.cjs";
1
+ import { l as AgentTraceEvent } from "./run-agent-BxjGaVpL.cjs";
2
2
  import { Attributes, Tracer, TracerProvider } from "@opentelemetry/api";
3
3
 
4
4
  //#region src/otel/index.d.ts
package/dist/otel.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { c as AgentTraceEvent } from "./run-agent-2MnlQTkB.mjs";
1
+ import { l as AgentTraceEvent } from "./run-agent-COHoCgQd.mjs";
2
2
  import { Attributes, Tracer, TracerProvider } from "@opentelemetry/api";
3
3
 
4
4
  //#region src/otel/index.d.ts
@@ -1,7 +1,7 @@
1
- import { c as AgentTools, d as ChosenEvent, n as AgentMessage } from "./types-rMe7x6NR.cjs";
1
+ import { T as WithAgentInputSchema, c as AgentTools, d as ChosenEvent, h as InferInput, n as AgentMessage, v as StandardSchemaV1 } from "./types-pJ5Hn8fv.cjs";
2
2
  import { t as AgentError } from "./errors-BQRk9eiZ.cjs";
3
- import { B as AgentRequestOptions, M as AgentDecisionRequest, R as AgentEventDescriptor, V as AgentRequestSource, d as AgentTextRequest, f as AgentUsage, l as AgentRequestExecutors, p as AgentUserInput, t as AgentCallUsage, u as AgentRequestMode } from "./text-logic-Jkilp1Ie.cjs";
4
- import { i as AgentLogEntry, o as JsonValue } from "./event-log-store-CVd2eyRy.cjs";
3
+ import { H as AgentRequestSource, N as AgentDecisionRequest, V as AgentRequestOptions, d as AgentTextRequest, f as AgentUsage, l as AgentRequestExecutors, p as AgentUserInput, t as AgentCallUsage, u as AgentRequestMode, z as AgentEventDescriptor } from "./text-logic-BFX5q7fM.cjs";
4
+ import { i as AgentLogEntry, o as JsonValue } from "./event-log-store-CQJq8_v4.cjs";
5
5
  import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, ExecutableActionObject, InputFrom, InspectionEvent, OutputFrom, Snapshot, SnapshotFrom, createActor } from "xstate";
6
6
 
7
7
  //#region src/internal/registry.d.ts
@@ -111,24 +111,6 @@ interface AgentUsageEvent extends EventObject {
111
111
  /** The reporting text request's registered `name`, when it declared one. */
112
112
  name?: string;
113
113
  }
114
- /**
115
- * Reads a settled call's token usage off a RAW executor result — the same
116
- * normalization `runAgent` applies before it delivers
117
- * {@link AGENT_USAGE_EVENT_TYPE}. Returns `undefined` when the executor
118
- * reported none.
119
- *
120
- * The seam for the step-loop path, where the host holds the raw result itself:
121
- *
122
- * ```ts
123
- * const { output, raw } = await executeAgentRequest(effect, executors, { verbose: true });
124
- * const usage = getCallUsage(raw);
125
- * if (usage) append({ type: AGENT_USAGE_EVENT_TYPE, usage }); // journal + transition, like any event
126
- * append(effect.toDoneEvent(output));
127
- * ```
128
- *
129
- * See "Token usage on this path" in docs/steps.md for the full loop.
130
- */
131
- declare function getCallUsage(raw: unknown): AgentCallUsage | undefined;
132
114
  /** Options controlling the durable envelope created by {@link createReplayEntry}. */
133
115
  interface CreateReplayEntryOptions {
134
116
  /** Explicit machine version; defaults to the machine's structural hash. */
@@ -257,19 +239,6 @@ interface AgentEventLogDiff<TMachine extends AnyStateMachine> {
257
239
  stateChanges: AgentLogPatchOperation[];
258
240
  effectChanges: AgentEffectDiff;
259
241
  }
260
- /**
261
- * Folds a journal through `initialTransition`/`transition` WITHOUT executing
262
- * anything, then returns the final snapshot plus the still-owed effects
263
- * ({@link getAgentEffects} of the final frontier, occurrence counts taken from
264
- * the whole log). Crash recovery, fork resume, and time travel in one call.
265
- *
266
- * `entries` is a versioned {@link AgentLogEntry} array. A reserved
267
- * {@link initEntry} first envelope carries `{ type: '@agent.init', input }`,
268
- * so a complete log replays with no side-channel; when absent,
269
- * `options.input` is used instead.
270
- * Raised/internal events are never in the journal — replay re-derives them
271
- * deterministically from the machine's own logic.
272
- */
273
242
  declare function replay<TMachine extends AnyStateMachine>(machine: TMachine, entries: readonly AgentLogEntry[], options?: ReplayOptions): ReplayResult<TMachine>;
274
243
  /** Requires and checks every entry's recorded state/effect hashes. */
275
244
  declare function verifyReplay<TMachine extends AnyStateMachine>(machine: TMachine, entries: readonly AgentLogEntry[], options?: Omit<ReplayOptions, "verify">): ReplayResult<TMachine>;
@@ -299,13 +268,13 @@ type AgentStepRequest = AgentRequest | AgentDecisionRequest;
299
268
  * Resolves one **text** request against a host's {@link AgentRequestExecutors}
300
269
  * — merges the request's tools, dispatches to `generateText`/`streamText` per
301
270
  * `mode`, and validates the result against the request's `outputSchema` if
302
- * present. Accepts either a `kind: 'text'` `AgentEffect` (the thin-loop shape
303
- * from `getAgentEffects`) or a legacy {@link AgentRequest} envelope.
271
+ * present. Accepts either a `kind: 'text'` `AgentEffect` (the step-path shape
272
+ * from `getAgentEffects`) or an {@link AgentRequest} envelope.
304
273
  * **Text-only**: passing a `kind: 'decision'` request throws, directing the
305
- * caller to `resolveDecision(request, executors.decide, ...)` instead. By default
306
- * returns the normalized output; pass `{ verbose: true }` to also get the
307
- * raw executor result (tool calls, usage, finish reason — needed for
308
- * observability and event-sourced replay).
274
+ * caller to `resolveDecision(request, executors.decide, ...)` instead. Always
275
+ * returns both the normalized `output` and the `raw` executor result (tool
276
+ * calls, usage, finish reason — needed for observability and event-sourced
277
+ * replay).
309
278
  */
310
279
  /** A `kind: 'text'` `AgentEffect` (structural, to avoid an import cycle with effects.ts). */
311
280
  interface TextEffectLike {
@@ -314,10 +283,7 @@ interface TextEffectLike {
314
283
  request: AgentTextRequest;
315
284
  mode?: AgentRequestMode;
316
285
  }
317
- declare function executeAgentRequest(request: AgentRequest | TextEffectLike, executors: Partial<AgentRequestExecutors>): Promise<unknown>;
318
- declare function executeAgentRequest(request: AgentRequest | TextEffectLike, executors: Partial<AgentRequestExecutors>, options: {
319
- verbose: true;
320
- }): Promise<{
286
+ declare function executeAgentRequest(requestOrEffect: AgentRequest | TextEffectLike, executors: Partial<AgentRequestExecutors>): Promise<{
321
287
  output: unknown;
322
288
  raw: unknown;
323
289
  }>;
@@ -514,73 +480,36 @@ type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
514
480
  error: unknown;
515
481
  snapshot: SnapshotFrom<TMachine>;
516
482
  }));
483
+ /**
484
+ * Fields a JSON projection keeps VERBATIM: {@link TRACE_ENVELOPE_KEYS} (the
485
+ * envelope, the `type`/`status`/`cause` discriminants, and the payload fields
486
+ * that are already plain strings) plus `usage.dropped`'s `reason`, which is a
487
+ * string literal — sanitizing it is the identity, so it keeps its literal type.
488
+ * Every other payload field narrows to {@link JsonValue}. @internal
489
+ */
490
+ type TraceVerbatimKey = (typeof TRACE_ENVELOPE_KEYS)[number] | "reason";
491
+ /** One trace variant's JSON projection. Homomorphic, so `?` modifiers survive. @internal */
492
+ type JsonProjectedTraceVariant<TEvent> = { [K in keyof TEvent]: K extends TraceVerbatimKey ? TEvent[K] : JsonValue };
493
+ /**
494
+ * `raw` is written only when `includeRaw` was set, so it is optional on the
495
+ * JSON side even though the live trace always carries it. @internal
496
+ */
497
+ type WithOptionalRaw<T> = "raw" extends keyof T ? Omit<T, "raw"> & {
498
+ raw?: JsonValue;
499
+ } : T;
517
500
  /**
518
501
  * The JSON-safe projection of an {@link AgentTraceEvent} produced by
519
502
  * {@link serializeTraceEvent}: the envelope fields are unchanged, and every
520
503
  * payload field that can hold a live object (snapshots, machine events, request
521
504
  * objects, raw SDK results, errors) is narrowed to a {@link JsonValue}. Safe to
522
505
  * hand straight to `JSON.stringify` for a JSONL trace file.
506
+ *
507
+ * DERIVED from {@link AgentTraceEvent}, so a new trace variant cannot silently
508
+ * miss the JSON side. `src/serialize-trace-event.test.ts` pins the result to
509
+ * the shape this type had when it was hand-maintained.
523
510
  */
524
- type JsonSerializableTraceEvent = {
525
- schemaVersion: typeof AGENT_TRACE_SCHEMA_VERSION;
526
- runId: string;
527
- seq: number;
528
- timestamp: string;
529
- machineId: string;
530
- machineVersion: string;
531
- } & ({
532
- type: "run.start";
533
- input?: JsonValue;
534
- snapshot?: JsonValue;
535
- event?: JsonValue;
536
- } | {
537
- type: "request.start";
538
- request: JsonValue;
539
- } | {
540
- type: "request.end";
541
- request: JsonValue;
542
- output: JsonValue; /** Present only when `includeRaw` was set; the raw executor result, sanitized. */
543
- raw?: JsonValue;
544
- reasoning?: string; /** Present only when the executor reported it; plain numbers, passed through as-is. */
545
- usage?: JsonValue;
546
- } | {
547
- type: "request.error";
548
- request: JsonValue;
549
- error: JsonValue;
550
- } | {
551
- type: "stream.chunk";
552
- request: JsonValue;
553
- chunk: string;
554
- } | {
555
- type: "machine.transition";
556
- snapshot: JsonValue;
557
- event: JsonValue;
558
- eventId?: string;
559
- } | {
560
- type: "emit";
561
- event: JsonValue;
562
- } | {
563
- type: "usage.dropped";
564
- event: JsonValue;
565
- reason: "settled";
566
- } | {
567
- type: "run.end";
568
- status: "done";
569
- output: JsonValue;
570
- snapshot: JsonValue;
571
- } | {
572
- type: "run.end";
573
- status: "idle";
574
- snapshot: JsonValue;
575
- pendingUserInputs?: JsonValue;
576
- persistedSnapshot?: JsonValue;
577
- } | {
578
- type: "run.end";
579
- status: "error";
580
- cause: RunAgentErrorCause;
581
- error: JsonValue;
582
- snapshot: JsonValue;
583
- });
511
+ type JsonSerializableTraceEvent = AgentTraceEvent extends infer TEvent ? TEvent extends unknown ? WithOptionalRaw<JsonProjectedTraceVariant<TEvent>> : never : never;
512
+ declare const TRACE_ENVELOPE_KEYS: readonly ["schemaVersion", "runId", "seq", "timestamp", "machineId", "machineVersion", "type", "status", "cause", "eventId", "reasoning", "chunk"];
584
513
  /**
585
514
  * Projects an {@link AgentTraceEvent} into a guaranteed JSON-safe envelope —
586
515
  * the form the trace stream is actually sold for (one `JSON.stringify` per line
@@ -624,8 +553,15 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
624
553
  * kind, so e.g. a stream-only machine may pass `{ streamText }` alone.
625
554
  */
626
555
  executors?: Partial<AgentRequestExecutors>;
627
- /** Machine input, passed straight to `createActor(machine, { input })`. Omit when resuming via `snapshot`. */
628
- input?: InputFrom<TMachine>;
556
+ /**
557
+ * Machine input. Validated against the machine's declared input schema —
558
+ * defaults filled, transforms applied — before it reaches
559
+ * `createActor(machine, { input })` and the replayable event log; invalid
560
+ * input throws an {@link AgentError} with code `invalid-machine-input`.
561
+ * Typed as {@link AgentInputFrom}, so fields the schema defaults are optional
562
+ * here. Omit when resuming via `snapshot`.
563
+ */
564
+ input?: AgentInputFrom<TMachine>;
629
565
  /** A previously-settled run's `result.snapshot`, to resume from instead of starting fresh. Pair with `event` to deliver the event that unblocks the resumed idle state. */
630
566
  snapshot?: Snapshot<unknown>;
631
567
  /** An event to send immediately after starting/resuming the actor (e.g. the human's answer to an idle-state prompt). */
@@ -760,11 +696,21 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
760
696
  * with no extra wiring — read it with `getAgentMessages(snapshot)`.
761
697
  */
762
698
  messages?: AgentMessage[] | ((prior: AgentMessage[]) => AgentMessage[]);
763
- /** Fires for each streamed chunk of a `mode: 'stream'` text request, alongside the {@link AgentRequest} that produced it (parallel states can interleave multiple streams). Purely observational. */
699
+ /**
700
+ * Sugar over {@link onTrace}'s `stream.chunk` events: fires for each streamed
701
+ * chunk of a `mode: 'stream'` text request, alongside the {@link AgentRequest}
702
+ * that produced it (parallel states can interleave multiple streams). Purely
703
+ * observational.
704
+ */
764
705
  onChunk?: (chunk: string, info: {
765
706
  request: AgentRequest;
766
707
  }) => void;
767
- /** Fires once per resolved text/decision request with its normalized output and the raw executor result (tool calls, usage, …) — the seam for tracing/observability and event-sourced replay logging. */
708
+ /**
709
+ * Sugar over {@link onTrace}'s `request.end` events: fires once per resolved
710
+ * text/decision request with its normalized output and the raw executor
711
+ * result (tool calls, usage, …) — the seam for tracing/observability and
712
+ * event-sourced replay logging.
713
+ */
768
714
  onResult?: (request: AgentStepRequest, result: {
769
715
  output: unknown;
770
716
  raw: unknown;
@@ -779,8 +725,9 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
779
725
  /** Fires a single ordered stream of run/request/chunk/transition/emit/end events. Intended for eval traces, JSONL logs, and adapter-owned telemetry/exporters. */
780
726
  onTrace?: (event: AgentTraceEvent<TMachine>) => void;
781
727
  /**
782
- * Fires on every machine transition (snapshot + causing event). Pure
783
- * observation progress UIs, logging, tracing. Cannot send events.
728
+ * Sugar over {@link onTrace}'s `machine.transition` events: fires on every
729
+ * root-machine transition (snapshot + causing event). Pure observation
730
+ * progress UIs, logging, tracing. Cannot send events.
784
731
  */
785
732
  onTransition?: (snapshot: SnapshotFrom<TMachine>, event: EventFromLogic<TMachine>) => void;
786
733
  /**
@@ -901,6 +848,20 @@ type RunAgentResult<TMachine extends AnyStateMachine> = RunAgentOutcome<TMachine
901
848
  * - `'stopped'` — the actor was stopped externally (`status === 'stopped'`).
902
849
  */
903
850
  type RunAgentErrorCause = "aborted" | "max-model-calls" | "decision-exhausted" | "machine" | "stopped";
851
+ /**
852
+ * The machine input a run accepts, which is the schema's *pre*-validation side.
853
+ *
854
+ * XState's `schemas` are types only — it never validates, and it resolves
855
+ * `schemas.input` to one type shared by `createActor`'s `input` option and the
856
+ * `context: ({ input })` factory. A schema field declared with a default
857
+ * therefore reads as required at the call site even though the caller is meant
858
+ * to omit it. `setupAgent` brands the machine's input type with its own schema
859
+ * ({@link WithAgentInputSchema}), so this recovers the looser caller-facing
860
+ * side while the factory keeps seeing the validated one. Machines with no
861
+ * declared input schema — and machines reached through `.provide(...)`, which
862
+ * drops the brand — fall back to xstate's `InputFrom`.
863
+ */
864
+ type AgentInputFrom<TMachine extends AnyStateMachine> = InputFrom<TMachine> extends WithAgentInputSchema<infer TInputSchema> ? [TInputSchema] extends [StandardSchemaV1] ? InferInput<TInputSchema> : InputFrom<TMachine> : InputFrom<TMachine>;
904
865
  /**
905
866
  * Runs an agent machine to completion or idle: a `createActor` host that
906
867
  * binds `options`' host executors onto the machine's `agent.*`/`TextLogic`/
@@ -1061,4 +1022,4 @@ declare function inspectTransitions(handler: (snapshot: AnyMachineSnapshot, acto
1061
1022
  */
1062
1023
  declare function traceTransitions<TMachine extends AnyStateMachine = AnyStateMachine>(onTrace: (event: AgentTraceEvent<TMachine>) => void): (inspectionEvent: InspectionEvent) => void;
1063
1024
  //#endregion
1064
- export { AgentEffectDiff as A, createReplayEntry as B, AgentStateRequest as C, AGENT_INIT_EVENT_TYPE as D, executeAgentRequest as E, AgentUsageEvent as F, replay as G, getAgentEffects as H, CreateReplayEntryOptions as I, verifyReplay as K, GetAgentEffectsOptions as L, AgentLogPatchOperation as M, AgentReplayDivergenceError as N, AGENT_USAGE_EVENT_TYPE as O, AgentReplayMachineMismatchError as P, ReplayOptions as R, traceTransitions as S, AgentStepRequest as T, getCallUsage as U, diffEventLogs as V, initEntry as W, createAgentActor as _, AgentMessageInfo as a, runAgent as b, AgentTraceEvent as c, InspectedActorRef as d, JsonSerializableTraceEvent as f, RunAgentResult as g, RunAgentOptions as h, AgentIllegalResumeEventError as i, AgentEventLogDiff as j, AgentEffect as k, AgentUserInputExecutor as l, RunAgentErrorCause as m, AgentActorSession as n, AgentRunMeta as o, PendingUserInput as p, AgentIdleError as r, AgentSnapshotVersionMismatchError as s, AGENT_TRACE_SCHEMA_VERSION as t, GenerateResult as u, generateResult as v, AgentRequest as w, serializeTraceEvent as x, inspectTransitions as y, ReplayResult as z };
1025
+ export { AgentEffect as A, ReplayResult as B, traceTransitions as C, executeAgentRequest as D, AgentStepRequest as E, AgentReplayMachineMismatchError as F, replay as G, diffEventLogs as H, AgentUsageEvent as I, verifyReplay as K, CreateReplayEntryOptions as L, AgentEventLogDiff as M, AgentLogPatchOperation as N, AGENT_INIT_EVENT_TYPE as O, AgentReplayDivergenceError as P, GetAgentEffectsOptions as R, serializeTraceEvent as S, AgentRequest as T, getAgentEffects as U, createReplayEntry as V, initEntry as W, RunAgentResult as _, AgentInputFrom as a, inspectTransitions as b, AgentSnapshotVersionMismatchError as c, GenerateResult as d, InspectedActorRef as f, RunAgentOptions as g, RunAgentErrorCause as h, AgentIllegalResumeEventError as i, AgentEffectDiff as j, AGENT_USAGE_EVENT_TYPE as k, AgentTraceEvent as l, PendingUserInput as m, AgentActorSession as n, AgentMessageInfo as o, JsonSerializableTraceEvent as p, AgentIdleError as r, AgentRunMeta as s, AGENT_TRACE_SCHEMA_VERSION as t, AgentUserInputExecutor as u, createAgentActor as v, AgentStateRequest as w, runAgent as x, generateResult as y, ReplayOptions as z };
@@ -1,7 +1,7 @@
1
- import { c as AgentTools, d as ChosenEvent, n as AgentMessage } from "./types-9Bqg5rZB.mjs";
1
+ import { T as WithAgentInputSchema, c as AgentTools, d as ChosenEvent, h as InferInput, n as AgentMessage, v as StandardSchemaV1 } from "./types-DYpK3QF4.mjs";
2
2
  import { t as AgentError } from "./errors-C9rxnWbX.mjs";
3
- import { B as AgentRequestOptions, M as AgentDecisionRequest, R as AgentEventDescriptor, V as AgentRequestSource, d as AgentTextRequest, f as AgentUsage, l as AgentRequestExecutors, p as AgentUserInput, t as AgentCallUsage, u as AgentRequestMode } from "./text-logic-C5kbjaDz.mjs";
4
- import { i as AgentLogEntry, o as JsonValue } from "./event-log-store-BkUNtyOF.mjs";
3
+ import { H as AgentRequestSource, N as AgentDecisionRequest, V as AgentRequestOptions, d as AgentTextRequest, f as AgentUsage, l as AgentRequestExecutors, p as AgentUserInput, t as AgentCallUsage, u as AgentRequestMode, z as AgentEventDescriptor } from "./text-logic-DQW8_DWW.mjs";
4
+ import { i as AgentLogEntry, o as JsonValue } from "./event-log-store-BrC9Q1xW.mjs";
5
5
  import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, ExecutableActionObject, InputFrom, InspectionEvent, OutputFrom, Snapshot, SnapshotFrom, createActor } from "xstate";
6
6
 
7
7
  //#region src/internal/registry.d.ts
@@ -111,24 +111,6 @@ interface AgentUsageEvent extends EventObject {
111
111
  /** The reporting text request's registered `name`, when it declared one. */
112
112
  name?: string;
113
113
  }
114
- /**
115
- * Reads a settled call's token usage off a RAW executor result — the same
116
- * normalization `runAgent` applies before it delivers
117
- * {@link AGENT_USAGE_EVENT_TYPE}. Returns `undefined` when the executor
118
- * reported none.
119
- *
120
- * The seam for the step-loop path, where the host holds the raw result itself:
121
- *
122
- * ```ts
123
- * const { output, raw } = await executeAgentRequest(effect, executors, { verbose: true });
124
- * const usage = getCallUsage(raw);
125
- * if (usage) append({ type: AGENT_USAGE_EVENT_TYPE, usage }); // journal + transition, like any event
126
- * append(effect.toDoneEvent(output));
127
- * ```
128
- *
129
- * See "Token usage on this path" in docs/steps.md for the full loop.
130
- */
131
- declare function getCallUsage(raw: unknown): AgentCallUsage | undefined;
132
114
  /** Options controlling the durable envelope created by {@link createReplayEntry}. */
133
115
  interface CreateReplayEntryOptions {
134
116
  /** Explicit machine version; defaults to the machine's structural hash. */
@@ -257,19 +239,6 @@ interface AgentEventLogDiff<TMachine extends AnyStateMachine> {
257
239
  stateChanges: AgentLogPatchOperation[];
258
240
  effectChanges: AgentEffectDiff;
259
241
  }
260
- /**
261
- * Folds a journal through `initialTransition`/`transition` WITHOUT executing
262
- * anything, then returns the final snapshot plus the still-owed effects
263
- * ({@link getAgentEffects} of the final frontier, occurrence counts taken from
264
- * the whole log). Crash recovery, fork resume, and time travel in one call.
265
- *
266
- * `entries` is a versioned {@link AgentLogEntry} array. A reserved
267
- * {@link initEntry} first envelope carries `{ type: '@agent.init', input }`,
268
- * so a complete log replays with no side-channel; when absent,
269
- * `options.input` is used instead.
270
- * Raised/internal events are never in the journal — replay re-derives them
271
- * deterministically from the machine's own logic.
272
- */
273
242
  declare function replay<TMachine extends AnyStateMachine>(machine: TMachine, entries: readonly AgentLogEntry[], options?: ReplayOptions): ReplayResult<TMachine>;
274
243
  /** Requires and checks every entry's recorded state/effect hashes. */
275
244
  declare function verifyReplay<TMachine extends AnyStateMachine>(machine: TMachine, entries: readonly AgentLogEntry[], options?: Omit<ReplayOptions, "verify">): ReplayResult<TMachine>;
@@ -299,13 +268,13 @@ type AgentStepRequest = AgentRequest | AgentDecisionRequest;
299
268
  * Resolves one **text** request against a host's {@link AgentRequestExecutors}
300
269
  * — merges the request's tools, dispatches to `generateText`/`streamText` per
301
270
  * `mode`, and validates the result against the request's `outputSchema` if
302
- * present. Accepts either a `kind: 'text'` `AgentEffect` (the thin-loop shape
303
- * from `getAgentEffects`) or a legacy {@link AgentRequest} envelope.
271
+ * present. Accepts either a `kind: 'text'` `AgentEffect` (the step-path shape
272
+ * from `getAgentEffects`) or an {@link AgentRequest} envelope.
304
273
  * **Text-only**: passing a `kind: 'decision'` request throws, directing the
305
- * caller to `resolveDecision(request, executors.decide, ...)` instead. By default
306
- * returns the normalized output; pass `{ verbose: true }` to also get the
307
- * raw executor result (tool calls, usage, finish reason — needed for
308
- * observability and event-sourced replay).
274
+ * caller to `resolveDecision(request, executors.decide, ...)` instead. Always
275
+ * returns both the normalized `output` and the `raw` executor result (tool
276
+ * calls, usage, finish reason — needed for observability and event-sourced
277
+ * replay).
309
278
  */
310
279
  /** A `kind: 'text'` `AgentEffect` (structural, to avoid an import cycle with effects.ts). */
311
280
  interface TextEffectLike {
@@ -314,10 +283,7 @@ interface TextEffectLike {
314
283
  request: AgentTextRequest;
315
284
  mode?: AgentRequestMode;
316
285
  }
317
- declare function executeAgentRequest(request: AgentRequest | TextEffectLike, executors: Partial<AgentRequestExecutors>): Promise<unknown>;
318
- declare function executeAgentRequest(request: AgentRequest | TextEffectLike, executors: Partial<AgentRequestExecutors>, options: {
319
- verbose: true;
320
- }): Promise<{
286
+ declare function executeAgentRequest(requestOrEffect: AgentRequest | TextEffectLike, executors: Partial<AgentRequestExecutors>): Promise<{
321
287
  output: unknown;
322
288
  raw: unknown;
323
289
  }>;
@@ -514,73 +480,36 @@ type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
514
480
  error: unknown;
515
481
  snapshot: SnapshotFrom<TMachine>;
516
482
  }));
483
+ /**
484
+ * Fields a JSON projection keeps VERBATIM: {@link TRACE_ENVELOPE_KEYS} (the
485
+ * envelope, the `type`/`status`/`cause` discriminants, and the payload fields
486
+ * that are already plain strings) plus `usage.dropped`'s `reason`, which is a
487
+ * string literal — sanitizing it is the identity, so it keeps its literal type.
488
+ * Every other payload field narrows to {@link JsonValue}. @internal
489
+ */
490
+ type TraceVerbatimKey = (typeof TRACE_ENVELOPE_KEYS)[number] | "reason";
491
+ /** One trace variant's JSON projection. Homomorphic, so `?` modifiers survive. @internal */
492
+ type JsonProjectedTraceVariant<TEvent> = { [K in keyof TEvent]: K extends TraceVerbatimKey ? TEvent[K] : JsonValue };
493
+ /**
494
+ * `raw` is written only when `includeRaw` was set, so it is optional on the
495
+ * JSON side even though the live trace always carries it. @internal
496
+ */
497
+ type WithOptionalRaw<T> = "raw" extends keyof T ? Omit<T, "raw"> & {
498
+ raw?: JsonValue;
499
+ } : T;
517
500
  /**
518
501
  * The JSON-safe projection of an {@link AgentTraceEvent} produced by
519
502
  * {@link serializeTraceEvent}: the envelope fields are unchanged, and every
520
503
  * payload field that can hold a live object (snapshots, machine events, request
521
504
  * objects, raw SDK results, errors) is narrowed to a {@link JsonValue}. Safe to
522
505
  * hand straight to `JSON.stringify` for a JSONL trace file.
506
+ *
507
+ * DERIVED from {@link AgentTraceEvent}, so a new trace variant cannot silently
508
+ * miss the JSON side. `src/serialize-trace-event.test.ts` pins the result to
509
+ * the shape this type had when it was hand-maintained.
523
510
  */
524
- type JsonSerializableTraceEvent = {
525
- schemaVersion: typeof AGENT_TRACE_SCHEMA_VERSION;
526
- runId: string;
527
- seq: number;
528
- timestamp: string;
529
- machineId: string;
530
- machineVersion: string;
531
- } & ({
532
- type: "run.start";
533
- input?: JsonValue;
534
- snapshot?: JsonValue;
535
- event?: JsonValue;
536
- } | {
537
- type: "request.start";
538
- request: JsonValue;
539
- } | {
540
- type: "request.end";
541
- request: JsonValue;
542
- output: JsonValue; /** Present only when `includeRaw` was set; the raw executor result, sanitized. */
543
- raw?: JsonValue;
544
- reasoning?: string; /** Present only when the executor reported it; plain numbers, passed through as-is. */
545
- usage?: JsonValue;
546
- } | {
547
- type: "request.error";
548
- request: JsonValue;
549
- error: JsonValue;
550
- } | {
551
- type: "stream.chunk";
552
- request: JsonValue;
553
- chunk: string;
554
- } | {
555
- type: "machine.transition";
556
- snapshot: JsonValue;
557
- event: JsonValue;
558
- eventId?: string;
559
- } | {
560
- type: "emit";
561
- event: JsonValue;
562
- } | {
563
- type: "usage.dropped";
564
- event: JsonValue;
565
- reason: "settled";
566
- } | {
567
- type: "run.end";
568
- status: "done";
569
- output: JsonValue;
570
- snapshot: JsonValue;
571
- } | {
572
- type: "run.end";
573
- status: "idle";
574
- snapshot: JsonValue;
575
- pendingUserInputs?: JsonValue;
576
- persistedSnapshot?: JsonValue;
577
- } | {
578
- type: "run.end";
579
- status: "error";
580
- cause: RunAgentErrorCause;
581
- error: JsonValue;
582
- snapshot: JsonValue;
583
- });
511
+ type JsonSerializableTraceEvent = AgentTraceEvent extends infer TEvent ? TEvent extends unknown ? WithOptionalRaw<JsonProjectedTraceVariant<TEvent>> : never : never;
512
+ declare const TRACE_ENVELOPE_KEYS: readonly ["schemaVersion", "runId", "seq", "timestamp", "machineId", "machineVersion", "type", "status", "cause", "eventId", "reasoning", "chunk"];
584
513
  /**
585
514
  * Projects an {@link AgentTraceEvent} into a guaranteed JSON-safe envelope —
586
515
  * the form the trace stream is actually sold for (one `JSON.stringify` per line
@@ -624,8 +553,15 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
624
553
  * kind, so e.g. a stream-only machine may pass `{ streamText }` alone.
625
554
  */
626
555
  executors?: Partial<AgentRequestExecutors>;
627
- /** Machine input, passed straight to `createActor(machine, { input })`. Omit when resuming via `snapshot`. */
628
- input?: InputFrom<TMachine>;
556
+ /**
557
+ * Machine input. Validated against the machine's declared input schema —
558
+ * defaults filled, transforms applied — before it reaches
559
+ * `createActor(machine, { input })` and the replayable event log; invalid
560
+ * input throws an {@link AgentError} with code `invalid-machine-input`.
561
+ * Typed as {@link AgentInputFrom}, so fields the schema defaults are optional
562
+ * here. Omit when resuming via `snapshot`.
563
+ */
564
+ input?: AgentInputFrom<TMachine>;
629
565
  /** A previously-settled run's `result.snapshot`, to resume from instead of starting fresh. Pair with `event` to deliver the event that unblocks the resumed idle state. */
630
566
  snapshot?: Snapshot<unknown>;
631
567
  /** An event to send immediately after starting/resuming the actor (e.g. the human's answer to an idle-state prompt). */
@@ -760,11 +696,21 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
760
696
  * with no extra wiring — read it with `getAgentMessages(snapshot)`.
761
697
  */
762
698
  messages?: AgentMessage[] | ((prior: AgentMessage[]) => AgentMessage[]);
763
- /** Fires for each streamed chunk of a `mode: 'stream'` text request, alongside the {@link AgentRequest} that produced it (parallel states can interleave multiple streams). Purely observational. */
699
+ /**
700
+ * Sugar over {@link onTrace}'s `stream.chunk` events: fires for each streamed
701
+ * chunk of a `mode: 'stream'` text request, alongside the {@link AgentRequest}
702
+ * that produced it (parallel states can interleave multiple streams). Purely
703
+ * observational.
704
+ */
764
705
  onChunk?: (chunk: string, info: {
765
706
  request: AgentRequest;
766
707
  }) => void;
767
- /** Fires once per resolved text/decision request with its normalized output and the raw executor result (tool calls, usage, …) — the seam for tracing/observability and event-sourced replay logging. */
708
+ /**
709
+ * Sugar over {@link onTrace}'s `request.end` events: fires once per resolved
710
+ * text/decision request with its normalized output and the raw executor
711
+ * result (tool calls, usage, …) — the seam for tracing/observability and
712
+ * event-sourced replay logging.
713
+ */
768
714
  onResult?: (request: AgentStepRequest, result: {
769
715
  output: unknown;
770
716
  raw: unknown;
@@ -779,8 +725,9 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
779
725
  /** Fires a single ordered stream of run/request/chunk/transition/emit/end events. Intended for eval traces, JSONL logs, and adapter-owned telemetry/exporters. */
780
726
  onTrace?: (event: AgentTraceEvent<TMachine>) => void;
781
727
  /**
782
- * Fires on every machine transition (snapshot + causing event). Pure
783
- * observation progress UIs, logging, tracing. Cannot send events.
728
+ * Sugar over {@link onTrace}'s `machine.transition` events: fires on every
729
+ * root-machine transition (snapshot + causing event). Pure observation
730
+ * progress UIs, logging, tracing. Cannot send events.
784
731
  */
785
732
  onTransition?: (snapshot: SnapshotFrom<TMachine>, event: EventFromLogic<TMachine>) => void;
786
733
  /**
@@ -901,6 +848,20 @@ type RunAgentResult<TMachine extends AnyStateMachine> = RunAgentOutcome<TMachine
901
848
  * - `'stopped'` — the actor was stopped externally (`status === 'stopped'`).
902
849
  */
903
850
  type RunAgentErrorCause = "aborted" | "max-model-calls" | "decision-exhausted" | "machine" | "stopped";
851
+ /**
852
+ * The machine input a run accepts, which is the schema's *pre*-validation side.
853
+ *
854
+ * XState's `schemas` are types only — it never validates, and it resolves
855
+ * `schemas.input` to one type shared by `createActor`'s `input` option and the
856
+ * `context: ({ input })` factory. A schema field declared with a default
857
+ * therefore reads as required at the call site even though the caller is meant
858
+ * to omit it. `setupAgent` brands the machine's input type with its own schema
859
+ * ({@link WithAgentInputSchema}), so this recovers the looser caller-facing
860
+ * side while the factory keeps seeing the validated one. Machines with no
861
+ * declared input schema — and machines reached through `.provide(...)`, which
862
+ * drops the brand — fall back to xstate's `InputFrom`.
863
+ */
864
+ type AgentInputFrom<TMachine extends AnyStateMachine> = InputFrom<TMachine> extends WithAgentInputSchema<infer TInputSchema> ? [TInputSchema] extends [StandardSchemaV1] ? InferInput<TInputSchema> : InputFrom<TMachine> : InputFrom<TMachine>;
904
865
  /**
905
866
  * Runs an agent machine to completion or idle: a `createActor` host that
906
867
  * binds `options`' host executors onto the machine's `agent.*`/`TextLogic`/
@@ -1061,4 +1022,4 @@ declare function inspectTransitions(handler: (snapshot: AnyMachineSnapshot, acto
1061
1022
  */
1062
1023
  declare function traceTransitions<TMachine extends AnyStateMachine = AnyStateMachine>(onTrace: (event: AgentTraceEvent<TMachine>) => void): (inspectionEvent: InspectionEvent) => void;
1063
1024
  //#endregion
1064
- export { AgentEffectDiff as A, createReplayEntry as B, AgentStateRequest as C, AGENT_INIT_EVENT_TYPE as D, executeAgentRequest as E, AgentUsageEvent as F, replay as G, getAgentEffects as H, CreateReplayEntryOptions as I, verifyReplay as K, GetAgentEffectsOptions as L, AgentLogPatchOperation as M, AgentReplayDivergenceError as N, AGENT_USAGE_EVENT_TYPE as O, AgentReplayMachineMismatchError as P, ReplayOptions as R, traceTransitions as S, AgentStepRequest as T, getCallUsage as U, diffEventLogs as V, initEntry as W, createAgentActor as _, AgentMessageInfo as a, runAgent as b, AgentTraceEvent as c, InspectedActorRef as d, JsonSerializableTraceEvent as f, RunAgentResult as g, RunAgentOptions as h, AgentIllegalResumeEventError as i, AgentEventLogDiff as j, AgentEffect as k, AgentUserInputExecutor as l, RunAgentErrorCause as m, AgentActorSession as n, AgentRunMeta as o, PendingUserInput as p, AgentIdleError as r, AgentSnapshotVersionMismatchError as s, AGENT_TRACE_SCHEMA_VERSION as t, GenerateResult as u, generateResult as v, AgentRequest as w, serializeTraceEvent as x, inspectTransitions as y, ReplayResult as z };
1025
+ export { AgentEffect as A, ReplayResult as B, traceTransitions as C, executeAgentRequest as D, AgentStepRequest as E, AgentReplayMachineMismatchError as F, replay as G, diffEventLogs as H, AgentUsageEvent as I, verifyReplay as K, CreateReplayEntryOptions as L, AgentEventLogDiff as M, AgentLogPatchOperation as N, AGENT_INIT_EVENT_TYPE as O, AgentReplayDivergenceError as P, GetAgentEffectsOptions as R, serializeTraceEvent as S, AgentRequest as T, getAgentEffects as U, createReplayEntry as V, initEntry as W, RunAgentResult as _, AgentInputFrom as a, inspectTransitions as b, AgentSnapshotVersionMismatchError as c, GenerateResult as d, InspectedActorRef as f, RunAgentOptions as g, RunAgentErrorCause as h, AgentIllegalResumeEventError as i, AgentEffectDiff as j, AGENT_USAGE_EVENT_TYPE as k, AgentTraceEvent as l, PendingUserInput as m, AgentActorSession as n, AgentMessageInfo as o, JsonSerializableTraceEvent as p, AgentIdleError as r, AgentRunMeta as s, AGENT_TRACE_SCHEMA_VERSION as t, AgentUserInputExecutor as u, createAgentActor as v, AgentStateRequest as w, runAgent as x, generateResult as y, ReplayOptions as z };