@statelyai/agent 2.0.0-alpha.15 → 2.0.0-alpha.17

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-D9Zi7Xi5.mjs → decision-C11xuud2.mjs} +35 -26
  6. package/dist/{decision-C0cUKvNt.cjs → decision-DnQCQPew.cjs} +46 -31
  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 +498 -520
  12. package/dist/index.d.cts +130 -104
  13. package/dist/index.d.mts +130 -104
  14. package/dist/index.mjs +497 -519
  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-B_n4Qxye.d.cts → run-agent-BxjGaVpL.d.cts} +49 -109
  22. package/dist/{run-agent-BWzo4FLv.d.mts → run-agent-COHoCgQd.d.mts} +49 -109
  23. package/dist/{setup-agent-DeHRW-qX.mjs → setup-agent-CTg57Pa4.mjs} +154 -167
  24. package/dist/{setup-agent-CpK0ZRWV.cjs → setup-agent-D_EyJ0Ik.cjs} +159 -172
  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-DZW7XWy9.d.cts → text-logic-BFX5q7fM.d.cts} +23 -2
  30. package/dist/{text-logic-C7anC7qX.d.mts → text-logic-DQW8_DWW.d.mts} +23 -2
  31. package/dist/{types-DFD28AWe.d.cts → types-DYpK3QF4.d.mts} +7 -6
  32. package/dist/{types-CTBhMnFu.d.mts → types-pJ5Hn8fv.d.cts} +7 -6
  33. package/package.json +28 -28
  34. package/readme.md +6 -19
  35. package/schemas/agent-workflow.json +9 -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-D_EyJ0Ik.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 { c as AgentTools, v as StandardSchemaV1 } from "./types-DFD28AWe.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 { c as AgentTools, v as StandardSchemaV1 } from "./types-CTBhMnFu.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-CTg57Pa4.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 { l as AgentTraceEvent } from "./run-agent-B_n4Qxye.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 { l as AgentTraceEvent } from "./run-agent-BWzo4FLv.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 { T as WithAgentInputSchema, c as AgentTools, d as ChosenEvent, h as InferInput, n as AgentMessage, v as StandardSchemaV1 } from "./types-DFD28AWe.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-DZW7XWy9.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
@@ -767,11 +696,21 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
767
696
  * with no extra wiring — read it with `getAgentMessages(snapshot)`.
768
697
  */
769
698
  messages?: AgentMessage[] | ((prior: AgentMessage[]) => AgentMessage[]);
770
- /** 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
+ */
771
705
  onChunk?: (chunk: string, info: {
772
706
  request: AgentRequest;
773
707
  }) => void;
774
- /** 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
+ */
775
714
  onResult?: (request: AgentStepRequest, result: {
776
715
  output: unknown;
777
716
  raw: unknown;
@@ -786,8 +725,9 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
786
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. */
787
726
  onTrace?: (event: AgentTraceEvent<TMachine>) => void;
788
727
  /**
789
- * Fires on every machine transition (snapshot + causing event). Pure
790
- * 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.
791
731
  */
792
732
  onTransition?: (snapshot: SnapshotFrom<TMachine>, event: EventFromLogic<TMachine>) => void;
793
733
  /**
@@ -1082,4 +1022,4 @@ declare function inspectTransitions(handler: (snapshot: AnyMachineSnapshot, acto
1082
1022
  */
1083
1023
  declare function traceTransitions<TMachine extends AnyStateMachine = AnyStateMachine>(onTrace: (event: AgentTraceEvent<TMachine>) => void): (inspectionEvent: InspectionEvent) => void;
1084
1024
  //#endregion
1085
- export { AgentEffect as A, ReplayResult as B, traceTransitions as C, executeAgentRequest as D, AgentStepRequest as E, AgentReplayMachineMismatchError as F, initEntry as G, diffEventLogs as H, AgentUsageEvent as I, replay 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, getCallUsage 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, verifyReplay as q, 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 };
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 { T as WithAgentInputSchema, c as AgentTools, d as ChosenEvent, h as InferInput, n as AgentMessage, v as StandardSchemaV1 } from "./types-CTBhMnFu.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-C7anC7qX.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
@@ -767,11 +696,21 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
767
696
  * with no extra wiring — read it with `getAgentMessages(snapshot)`.
768
697
  */
769
698
  messages?: AgentMessage[] | ((prior: AgentMessage[]) => AgentMessage[]);
770
- /** 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
+ */
771
705
  onChunk?: (chunk: string, info: {
772
706
  request: AgentRequest;
773
707
  }) => void;
774
- /** 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
+ */
775
714
  onResult?: (request: AgentStepRequest, result: {
776
715
  output: unknown;
777
716
  raw: unknown;
@@ -786,8 +725,9 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
786
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. */
787
726
  onTrace?: (event: AgentTraceEvent<TMachine>) => void;
788
727
  /**
789
- * Fires on every machine transition (snapshot + causing event). Pure
790
- * 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.
791
731
  */
792
732
  onTransition?: (snapshot: SnapshotFrom<TMachine>, event: EventFromLogic<TMachine>) => void;
793
733
  /**
@@ -1082,4 +1022,4 @@ declare function inspectTransitions(handler: (snapshot: AnyMachineSnapshot, acto
1082
1022
  */
1083
1023
  declare function traceTransitions<TMachine extends AnyStateMachine = AnyStateMachine>(onTrace: (event: AgentTraceEvent<TMachine>) => void): (inspectionEvent: InspectionEvent) => void;
1084
1024
  //#endregion
1085
- export { AgentEffect as A, ReplayResult as B, traceTransitions as C, executeAgentRequest as D, AgentStepRequest as E, AgentReplayMachineMismatchError as F, initEntry as G, diffEventLogs as H, AgentUsageEvent as I, replay 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, getCallUsage 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, verifyReplay as q, 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 };
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 };