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

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 (75) hide show
  1. package/dist/ai-sdk.cjs +149 -26
  2. package/dist/ai-sdk.d.cts +57 -34
  3. package/dist/ai-sdk.d.mts +57 -34
  4. package/dist/ai-sdk.mjs +147 -23
  5. package/dist/{decision-RQ0iv0oZ.mjs → decision-Bl_rKQnU.mjs} +73 -7
  6. package/dist/{decision-CmM8-HHz.cjs → decision-oevZnkBe.cjs} +112 -29
  7. package/dist/{text-logic-f5F5sCdc.cjs → event-log-Dtb16p1p.cjs} +813 -6
  8. package/dist/{text-logic-CIqHAmBi.mjs → event-log-GPZO9p7_.mjs} +679 -3
  9. package/dist/{event-log-store-BIPOz-di.d.mts → event-log-store-CN9ygggF.d.cts} +90 -5
  10. package/dist/{event-log-store-2xzFmgr2.d.cts → event-log-store-DS836wch.d.mts} +90 -5
  11. package/dist/event-log-store-bCdskPNS.cjs +95 -0
  12. package/dist/event-log-store-yalq8C77.mjs +84 -0
  13. package/dist/index.cjs +571 -58
  14. package/dist/index.d.cts +104 -510
  15. package/dist/index.d.mts +104 -510
  16. package/dist/index.mjs +542 -32
  17. package/dist/log.cjs +77 -20
  18. package/dist/log.d.cts +5 -5
  19. package/dist/log.d.mts +5 -5
  20. package/dist/log.mjs +58 -3
  21. package/dist/machines.cjs +1 -1
  22. package/dist/machines.d.cts +15 -15
  23. package/dist/machines.d.mts +15 -15
  24. package/dist/machines.mjs +1 -1
  25. package/dist/model-source-C7FFP2Sj.mjs +39 -0
  26. package/dist/model-source-DjJPjGSP.cjs +44 -0
  27. package/dist/openai.cjs +10 -10
  28. package/dist/openai.d.cts +27 -25
  29. package/dist/openai.d.mts +27 -25
  30. package/dist/openai.mjs +2 -2
  31. package/dist/otel.cjs +5 -4
  32. package/dist/otel.d.cts +5 -7
  33. package/dist/otel.d.mts +5 -7
  34. package/dist/otel.mjs +5 -3
  35. package/dist/{run-agent-COXXc0RW.d.mts → run-agent-C9ubX8Tx.d.cts} +87 -30
  36. package/dist/{run-agent-xNTxpt82.mjs → run-agent-CuQT1xSS.mjs} +170 -42
  37. package/dist/{run-agent-ByO-Bxyd.d.cts → run-agent-CxSyZmIE.d.mts} +87 -30
  38. package/dist/{run-agent-Dmf8GV2d.cjs → run-agent-cToZ3K42.cjs} +219 -86
  39. package/dist/{setup-agent-DV4cTou-.cjs → setup-agent-DTF3NQg3.cjs} +31 -20
  40. package/dist/setup-agent-DlbgwsIJ.d.cts +577 -0
  41. package/dist/{setup-agent-BuanDXeh.mjs → setup-agent-DniLvDu7.mjs} +15 -9
  42. package/dist/setup-agent-tsc3vm5I.d.mts +577 -0
  43. package/dist/tanstack-ai.cjs +627 -0
  44. package/dist/tanstack-ai.d.cts +204 -0
  45. package/dist/tanstack-ai.d.mts +204 -0
  46. package/dist/tanstack-ai.mjs +618 -0
  47. package/dist/testing.cjs +98 -985
  48. package/dist/testing.d.cts +51 -347
  49. package/dist/testing.d.mts +51 -347
  50. package/dist/testing.mjs +86 -973
  51. package/dist/{text-logic-IjfYy9DP.d.cts → text-logic-9fv1i9aK.d.cts} +50 -10
  52. package/dist/{text-logic-D-czVPYp.d.mts → text-logic-BDbGjYMh.d.mts} +50 -10
  53. package/dist/{types-BgNbNKnJ.d.mts → types-Dp5_Ru4R.d.cts} +2 -2
  54. package/dist/{types-hR5f5YXa.d.cts → types-Dp5_Ru4R.d.mts} +2 -2
  55. package/dist/usage-D8UphgEA.d.mts +17 -0
  56. package/dist/usage-R1NTmLxY.d.cts +17 -0
  57. package/dist/{utils-_q7F-AZu.d.mts → utils-BnXdWih3.d.mts} +1 -2
  58. package/dist/{utils-o4YRdHJX.d.cts → utils-ebVpCYoF.d.cts} +1 -2
  59. package/dist/validate.cjs +239 -8
  60. package/dist/validate.d.cts +110 -3
  61. package/dist/validate.d.mts +110 -3
  62. package/dist/validate.mjs +238 -7
  63. package/dist/verify-B5qGC5WN.mjs +1181 -0
  64. package/dist/verify-CBuYIpsa.d.mts +414 -0
  65. package/dist/verify-Cqghu4gz.cjs +1222 -0
  66. package/dist/verify-DYH_2VzU.d.cts +414 -0
  67. package/package.json +44 -31
  68. package/readme.md +38 -26
  69. package/skills/generate-machine/SKILL.md +140 -66
  70. package/skills/improve-machine/SKILL.md +190 -0
  71. package/skills/improve-machine/reference.md +96 -0
  72. package/dist/event-log-store-2pAFiWuc.mjs +0 -576
  73. package/dist/event-log-store-C-COhIXP.cjs +0 -702
  74. package/dist/usage-BdEjFuIi.mjs +0 -5
  75. package/dist/usage-efOQPdf_.cjs +0 -10
@@ -1,347 +1,8 @@
1
- import { u as ChosenEvent } from "./types-BgNbNKnJ.mjs";
2
- import { Z as AgentError, c as AgentRequestExecutorInfo, f as AgentTextRequest, s as AgentRequestExecutor, t as AgentCallUsage, u as AgentRequestExecutors } from "./text-logic-D-czVPYp.mjs";
3
- import { c as AgentRunResult, d as AgentRuntimeOptions, o as AgentRunInit } from "./run-agent-COXXc0RW.mjs";
4
- import { t as MetaOfSnapshot } from "./utils-_q7F-AZu.mjs";
5
- import { AnyMachineSnapshot, AnyStateMachine, EventFromLogic, InputFrom, SnapshotFrom, StateValue } from "xstate";
6
-
7
- //#region src/verify.d.ts
8
- /** Severity of an {@link AgentLintDiagnostic}. `error` findings fail CI/the CLI; `warning`s are advisory. */
9
- type AgentLintSeverity = "error" | "warning";
10
- /**
11
- * One static-analysis finding from {@link lintAgentMachine}. `code` names the
12
- * check (stable, machine-readable), `path` points at the offending state path
13
- * or config location, and `message` explains the problem and its remedy.
14
- */
15
- interface AgentLintDiagnostic {
16
- code: "decide-without-events" | "direct-object-src" | "invoke-without-on-error";
17
- severity: AgentLintSeverity;
18
- /** State path (`parent.child`) or config pointer (e.g. `(root)`, `context`) the finding is about. */
19
- path: string;
20
- message: string;
21
- }
22
- /** Options for {@link lintAgentMachine}. */
23
- interface LintAgentMachineOptions {
24
- /** Skip these check codes entirely. */
25
- disable?: AgentLintDiagnostic["code"][];
26
- /**
27
- * Throw {@link AgentLintError} on failing diagnostics instead of returning
28
- * them. Fails on error-severity findings; add `warnings: true` to fail on
29
- * warnings too.
30
- */
31
- throw?: boolean;
32
- /** With `throw: true`, also fail on warning-severity findings. Default: errors only. */
33
- warnings?: boolean;
34
- }
35
- /**
36
- * Runs static structural checks over a built agent machine and returns the
37
- * findings ({@link AgentLintDiagnostic}[], empty when clean). Works for
38
- * TS-authored (`setupAgent(...).createMachine(...)`) and
39
- * `setupAgent.fromConfig(...)`-compiled machines alike, reading `machine.config`
40
- * plus the schemas/actor sources the library already retains per machine.
41
- *
42
- * No model calls, no API keys — a coding agent that emits an agent machine can
43
- * call this to catch agent-specific mistakes such as undeliverable decisions,
44
- * un-rebindable request sources, and an unhandled transcript event. General
45
- * state-machine lint belongs to XState tooling.
46
- *
47
- * Pass `{ throw: true }` for the one-liner form used in tests and generation
48
- * loops: it returns silently when the machine is clean and throws
49
- * {@link AgentLintError} (findings on `.diagnostics`) on error-severity
50
- * findings, or on warnings too with `{ throw: true, warnings: true }`.
51
- *
52
- * @example
53
- * ```ts
54
- * const errors = lintAgentMachine(machine).filter((d) => d.severity === 'error');
55
- * if (errors.length) throw new Error(errors.map((e) => `${e.path}: ${e.message}`).join('\n'));
56
- * ```
57
- *
58
- * @example Throwing form
59
- * ```ts
60
- * test('agent machine is structurally sound', () => {
61
- * lintAgentMachine(machine, { throw: true });
62
- * });
63
- * ```
64
- */
65
- declare function lintAgentMachine(machine: AnyStateMachine, options?: LintAgentMachineOptions): AgentLintDiagnostic[];
66
- /**
67
- * Thrown by `lintAgentMachine(machine, { throw: true })` (and its
68
- * {@link assertAgentMachine} alias) when lint finds failing diagnostics.
69
- * `diagnostics` holds the findings; the message lists them one per finding,
70
- * so a test runner's failure output reads like the CLI's lint report.
71
- */
72
- declare class AgentLintError extends AgentError {
73
- readonly diagnostics: AgentLintDiagnostic[];
74
- constructor(machineId: string, diagnostics: AgentLintDiagnostic[]);
75
- }
76
- /** Options for {@link assertAgentMachine}. */
77
- interface AssertAgentMachineOptions extends LintAgentMachineOptions {
78
- /** Also fail on warning-severity findings. Default: errors only. */
79
- warnings?: boolean;
80
- }
81
- /**
82
- * Asserts a machine passes {@link lintAgentMachine}: returns silently when
83
- * clean, throws {@link AgentLintError} (with the findings on `.diagnostics`)
84
- * otherwise — sugar for `lintAgentMachine(machine, { ...options, throw: true })`.
85
- * Fails on error-severity findings; set `warnings: true` to fail on warnings
86
- * too. The one-liner for tests and generation loops:
87
- *
88
- * @example
89
- * ```ts
90
- * test('agent machine is structurally sound', () => {
91
- * assertAgentMachine(machine);
92
- * });
93
- * ```
94
- */
95
- declare function assertAgentMachine(machine: AnyStateMachine, options?: AssertAgentMachineOptions): void;
96
- /**
97
- * Scripted responses for a {@link simulateAgent} playthrough. Each channel is a
98
- * by-`src` map of FIFO queues, consumed in the order the machine reaches the
99
- * requests:
100
- * - `text` — output values for text requests, keyed by request src (the
101
- * `setupAgent({ requests })` key, or `agent.generateText`/`agent.streamText`).
102
- * - `decisions` — the {@link ChosenEvent} to apply for a decision request,
103
- * keyed by decision src (usually `agent.decide`). An invoke whose src is an
104
- * inline logic object has only an auto-generated src, so its queue may be
105
- * keyed by the invoke's `id` instead.
106
- * - `invokes` — output values for scripted invokes (any actor whose output must
107
- * be canned), keyed by src.
108
- * - `errors` — failure values to reject a request or invoke with instead of
109
- * resolving it, keyed by the same srcs the other channels use. An entry here
110
- * is consumed BEFORE that src's output queue, so a script can fail the first
111
- * call and let the second succeed. The invoke is rejected with
112
- * {@link rejectAgentStep}, so the machine takes its `onError`; for
113
- * `agent.decide` the entry stands in for retry exhaustion. A value can be
114
- * anything — an `Error`, a string, or an object such as `{ code: 'truncated' }`
115
- * for a machine that branches on `event.error.code`.
116
- * - `events` — a flat FIFO queue of external (human/host-sent) events. When the
117
- * machine settles idle with no pending request or invoke — a human gate — the
118
- * next queued event is applied, so a simulation can cross states that a live
119
- * run crosses via `actor.send(...)`. An event the current state cannot take
120
- * (no handler, or guard-rejected) throws rather than silently vanishing.
121
- */
122
- interface SimulationScript {
123
- text?: Record<string, unknown[]>;
124
- decisions?: Record<string, ChosenEvent[]>;
125
- invokes?: Record<string, unknown[]>;
126
- errors?: Record<string, unknown[]>;
127
- events?: ChosenEvent[];
128
- }
129
- /**
130
- * One entry in a {@link SimulateAgentResult.trail}: the state after this step,
131
- * plus what drove the step. The first entry is always the machine's initial
132
- * state, with no `appliedEvent`/`resolvedRequest` — so `trail.map((e) =>
133
- * e.state)` is the complete state path, directly comparable with
134
- * `matchesTrajectory` without prepending the initial state by hand.
135
- */
136
- interface SimulationTrailEntry {
137
- /** The machine state value after applying this step. */
138
- state: unknown;
139
- /** The chosen event applied (for a decision request), or the external event applied (when `external`). */
140
- appliedEvent?: ChosenEvent;
141
- /** True when `appliedEvent` came from the script's `events` queue (an external/user event), not a decision. */
142
- external?: boolean;
143
- /**
144
- * Scripted decisions that failed validation (unknown event, invalid payload,
145
- * or guard-rejected — live-run retry parity, see {@link simulateAgent})
146
- * before this step settled. Present with an `appliedEvent` when a later
147
- * scripted attempt succeeded, or alone when every attempt failed and the
148
- * exhaustion error was routed through the decision invoke's `onError`.
149
- */
150
- rejectedEvents?: ChosenEvent[];
151
- /**
152
- * The request this step settled (a text, decision, or scripted invoke): its
153
- * kind, src, and how it settled. `outcome` is `'output'` when a scripted
154
- * output resolved it and `'error'` when a `script.errors` entry rejected it,
155
- * in which case `error` carries the scripted failure value.
156
- */
157
- resolvedRequest?: {
158
- kind: "text" | "invoke" | "decision";
159
- src: string;
160
- id: string;
161
- outcome: "output" | "error";
162
- error?: unknown;
163
- };
164
- }
165
- /** Options for {@link simulateAgent}. */
166
- interface SimulateAgentOptions {
167
- input?: unknown;
168
- script: SimulationScript;
169
- /** Max steps before returning `'exhausted'`. Default 100. */
170
- maxSteps?: number;
171
- }
172
- /** The outcome of a {@link simulateAgent} playthrough. */
173
- interface SimulateAgentResult {
174
- /** `'done'` = reached a final state; `'idle'` = paused with no pending work; `'exhausted'` = hit `maxSteps`. */
175
- status: "done" | "idle" | "exhausted";
176
- snapshot: AnyMachineSnapshot;
177
- trail: SimulationTrailEntry[];
178
- }
179
- /**
180
- * Deterministically plays a machine through, resolving each request from a
181
- * {@link SimulationScript} instead of a model — no API keys, no model calls.
182
- * Runs on the pure step path ({@link initialAgentStep} etc.), so it exercises
183
- * the real transition logic. Returns the terminal `status`, final `snapshot`,
184
- * and a `trail` of every step taken.
185
- *
186
- * Decisions run through the live run's own validation/retry core,
187
- * {@link resolveDecision}, with the script standing in for the model: each
188
- * attempt consumes the next queued {@link ChosenEvent} for that src, so an
189
- * unknown, payload-invalid, or guard-rejected event is NOT silently swallowed
190
- * — the next queued decision is tried, exactly as a live run re-asks the
191
- * model. The decision logic's `maxRetries` caps attempts as it would live;
192
- * when retries continue past the end of the queue, the last queued decision
193
- * repeats (a scripted model that insists). The repeat applies only within one
194
- * decision request's retries — each new decision request must have its own
195
- * queued entry, or the dry-script error throws as usual. Exhausting all
196
- * attempts delivers
197
- * the resulting {@link AgentDecisionExhaustedError} to the machine as the
198
- * decision invoke's error (so an `onError` transition observes it, as it
199
- * would live); with no `onError` to catch it, it is thrown.
200
- *
201
- * Throws a descriptive error when the script runs dry mid-request, naming the
202
- * pending request's kind, src, and id so the missing scripted response is
203
- * obvious.
204
- *
205
- * @example
206
- * ```ts
207
- * const { status, snapshot } = simulateAgent(machine, {
208
- * input: { topic: 'state machines' },
209
- * script: {
210
- * decisions: { 'agent.decide': [{ type: 'ESCALATE' }] },
211
- * events: [{ type: 'APPROVE' }], // crosses the human gate
212
- * },
213
- * });
214
- * ```
215
- */
216
- declare function simulateAgent(machine: AnyStateMachine, options: SimulateAgentOptions): Promise<SimulateAgentResult>;
217
- /** Options for {@link explorePaths}. */
218
- interface ExplorePathsOptions {
219
- input?: unknown;
220
- /** Max branch points (decisions + external-event forks) along any path. Default 8. */
221
- maxDepth?: number;
222
- /** Total path cap before exploration stops (reported via `hitPathCap`). Default 200. */
223
- maxPaths?: number;
224
- /**
225
- * Canned output for each text request, keyed by src (the
226
- * `setupAgent({ requests })` key, or `agent.generateText`/`agent.streamText`).
227
- * One value per src, reused every time that src is reached. A missing src
228
- * halts that branch with a `needs-output` terminal.
229
- */
230
- text?: Record<string, unknown>;
231
- /** Canned output for scripted invokes, keyed by src. Same one-value-per-src rule as `text`. */
232
- invokes?: Record<string, unknown>;
233
- /**
234
- * A canned failure per src, keyed like `text`/`invokes`. A src listed here
235
- * forks an extra branch at that invoke, where the invoke is rejected and the
236
- * machine takes its `onError` — so states reachable only through a failure
237
- * are explored. When the src also has an output, both branches are explored;
238
- * when it has only an error, only the failing one is. Each fork counts
239
- * against `maxDepth`, and the failing branch records
240
- * `{ type: 'xstate.error.actor.<id>' }` in the path.
241
- *
242
- * A decision invoke can be keyed here too — by its src (usually
243
- * `agent.decide`) or by its invoke id — standing in for retry exhaustion.
244
- * Its success branch is the usual per-candidate-event fork, so the failing
245
- * branch is explored in addition to, not instead of, the candidates.
246
- *
247
- * A rejection that reaches no `onError` errors the machine, and that path
248
- * ends in an `error` terminal.
249
- */
250
- errors?: Record<string, unknown>;
251
- }
252
- /** A single explored path's terminal outcome. */
253
- interface AgentPathTerminal {
254
- /**
255
- * `'error'` is a scripted failure the machine had no `onError` for: the
256
- * snapshot is errored, exactly as a live run's unhandled invoke failure.
257
- */
258
- status: "done" | "idle" | "needs-output" | "max-depth" | "error";
259
- /** The chosen/applied events, in order, that produced this terminal. */
260
- path: ChosenEvent[];
261
- /** The final state value on this path. */
262
- state: unknown;
263
- /** For `needs-output`: the src whose canned output was missing. */
264
- missingSrc?: string;
265
- /** For `error`: the failure value that errored the machine. */
266
- error?: unknown;
267
- }
268
- /** The report returned by {@link explorePaths}. */
269
- interface AgentPathReport {
270
- /** Every distinct state value (JSON) encountered across all explored paths. */
271
- reachedStates: unknown[];
272
- /** One entry per explored path. */
273
- terminals: AgentPathTerminal[];
274
- /** How many candidate events were pruned because a guard rejected them. */
275
- prunedByGuard: number;
276
- /** Notes about coverage the exploration could not complete (missing outputs, depth/path caps). */
277
- unexplored: string[];
278
- /** Total paths explored. */
279
- pathsExplored: number;
280
- /** True when the total-paths cap was hit (report is partial). */
281
- hitPathCap: boolean;
282
- }
283
- /**
284
- * Enumerates a machine's decision and external-event branches to a bounded
285
- * depth, model-free, and reports which states are reached and how each path
286
- * terminates. At each decision request it forks one branch per candidate event
287
- * (guard-rejected candidates are counted in `prunedByGuard`, not explored); at
288
- * an idle wait it forks per externally-accepted event. Text requests resolve
289
- * from `text`, other invokes from `invokes` — all by-src canned-output maps, and a missing src halts
290
- * that branch with a `needs-output` terminal rather than throwing. A src in
291
- * `errors` forks an extra branch where that invoke is rejected, so states
292
- * behind an `onError` are explored too.
293
- *
294
- * Combinatorics are bounded by `maxDepth` (default 8) and `maxPaths` (default
295
- * 200, reported via `hitPathCap`).
296
- *
297
- * @example
298
- * ```ts
299
- * const report = await explorePaths(refundMachine, { input: { request: 'x', amount: 5000 } });
300
- * // report.terminals → both 'refunded' and 'denied'; report.prunedByGuard → 1
301
- * ```
302
- */
303
- declare function explorePaths(machine: AnyStateMachine, options?: ExplorePathsOptions): Promise<AgentPathReport>;
304
- /** The result of a {@link canReach} query. */
305
- interface CanReachResult {
306
- /** True when the target state was reached within the exploration bounds. */
307
- reachable: boolean;
308
- /** Resolved XState state-node id for a string target. */
309
- target?: string;
310
- /** When reachable, the sequence of chosen/applied events that gets there. */
311
- witness?: ChosenEvent[];
312
- }
313
- /** Thrown when a string reachability target is not a state in the machine. */
314
- declare class AgentUnknownStateError extends AgentError {
315
- readonly target: string;
316
- constructor(machineId: string, target: string);
317
- }
318
- /**
319
- * Answers "can the machine reach this?" by exploring its branches (a thin
320
- * wrapper over {@link explorePaths}). The target is either a state path string
321
- * (`snapshot.matches(...)` semantics) or a snapshot predicate — the predicate
322
- * form checks any property (a context invariant, a tag, a state+context
323
- * combination) without reifying a sentinel state for it. Returns
324
- * `{ reachable: true, witness }` with the event sequence that reaches it, or
325
- * `{ reachable: false }`.
326
- *
327
- * @example
328
- * ```ts
329
- * const { reachable, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
330
- * // reachable → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
331
- * ```
332
- *
333
- * @example Predicate target — a violation property, no sentinel state needed
334
- * ```ts
335
- * const violation = await canReach(
336
- * refundMachine,
337
- * (snapshot) => snapshot.matches('issued') && !snapshot.context.approved,
338
- * { input: { amount: 5000 } },
339
- * );
340
- * // violation.reachable → false is the safety proof
341
- * ```
342
- */
343
- declare function canReach(machine: AnyStateMachine, target: string | ((snapshot: AnyMachineSnapshot) => boolean), options?: ExplorePathsOptions): Promise<CanReachResult>;
344
- //#endregion
1
+ import { c as AgentRequestExecutorInfo, f as AgentTextRequest, s as AgentRequestExecutor, t as AgentCallUsage, u as AgentRequestExecutors } from "./text-logic-BDbGjYMh.mjs";
2
+ import { f as AgentRuntimeOptions, l as AgentRunResult, o as AgentRunInit } from "./run-agent-CxSyZmIE.mjs";
3
+ import { t as MetaOfSnapshot } from "./utils-BnXdWih3.mjs";
4
+ import { _ as explorePaths, a as AgentPathTerminal, c as CanReachResult, d as SimulateAgentOptions, f as SimulateAgentResult, g as canReach, h as assertAgentMachine, i as AgentPathReport, l as ExplorePathsOptions, m as SimulationTrailEntry, n as AgentLintError, o as AgentUnknownStateError, p as SimulationScript, r as AgentLintSeverity, s as AssertAgentMachineOptions, t as AgentLintDiagnostic, u as LintAgentMachineOptions, v as lintAgentMachine, y as simulateAgent } from "./verify-CBuYIpsa.mjs";
5
+ import { AnyStateMachine, EventFromLogic, InputFrom, SnapshotFrom, StateValue } from "xstate";
345
6
  //#region src/trajectory.d.ts
346
7
  /** An event-shaped trajectory item: anything with a string `type`. */
347
8
  interface TrajectoryEvent {
@@ -434,7 +95,7 @@ interface TrajectoryMatch {
434
95
  * return { name: 'state_path', score: match.score, metadata: { ...match.firstMiss } };
435
96
  * ```
436
97
  */
437
- declare function matchesTrajectory(actual: readonly unknown[], expected: readonly TrajectoryItem[], options?: MatchTrajectoryOptions): TrajectoryMatch;
98
+ export declare function matchesTrajectory(actual: readonly unknown[], expected: readonly TrajectoryItem[], options?: MatchTrajectoryOptions): TrajectoryMatch;
438
99
  //#endregion
439
100
  //#region src/seam.d.ts
440
101
  /**
@@ -614,6 +275,49 @@ interface RunSeamResult<TMachine extends AnyStateMachine> {
614
275
  * const run = await runSeam(emailDrafter, { ...row, candidate: generateText });
615
276
  * ```
616
277
  */
617
- declare function runSeam<TMachine extends AnyStateMachine>(machine: TMachine, options: RunSeamOptions<TMachine>): Promise<RunSeamResult<TMachine>>;
278
+ export declare function runSeam<TMachine extends AnyStateMachine>(machine: TMachine, options: RunSeamOptions<TMachine>): Promise<RunSeamResult<TMachine>>;
279
+ //#endregion
280
+ //#region src/fold-traces.d.ts
281
+ /** One state's numbers across many runs. See {@link foldTraces}. */
282
+ interface StateStats {
283
+ /** The state's dot-joined path from the root, e.g. `'deciding'` or `'work.review'`. */
284
+ state: string;
285
+ /** Runs that were in this state at least once. */
286
+ visits: number;
287
+ /** Of those runs, the ones `failed` flagged. */
288
+ failures: number;
289
+ /** Options withheld by the guards at decisions made in this state, summed over runs. */
290
+ withheld: number;
291
+ }
292
+ /** Options for {@link foldTraces}. */
293
+ interface FoldTracesOptions<TTrace> {
294
+ /** Whether a run failed, judged from its whole trace. */
295
+ failed: (trace: TTrace) => boolean;
296
+ }
297
+ /**
298
+ * Folds many runs' traces into per-state stats: how many runs visited each
299
+ * state, how many of those failed, and how many options the guards withheld
300
+ * at decisions made there. Pure; reads only:
301
+ *
302
+ * - `machine.transition`: the run visited `from.value` and `snapshot.value`.
303
+ * - `request.start` of a decision, first attempt only: its `request.withheld`
304
+ * counts toward the state the run was in, the `from.value` of the
305
+ * transition its choice causes.
306
+ *
307
+ * A trace is one run's events, live (`AgentTraceEvent`) or serialized
308
+ * (`serializeTraceEvent`). A host-driven `decideNext` traces nothing; push
309
+ * `{ type: 'request.start', request: result.request }` onto the trace before
310
+ * sending its event. Parallel states count once per active leaf.
311
+ *
312
+ * @example
313
+ * ```ts no-check
314
+ * const stats = foldTraces(traces, {
315
+ * failed: (trace) => trace.at(-1)?.type === 'run.end' && trace.at(-1).status === 'error',
316
+ * });
317
+ * ```
318
+ */
319
+ export declare function foldTraces<TTrace extends readonly {
320
+ readonly type: string;
321
+ }[]>(traces: Iterable<TTrace>, options: FoldTracesOptions<TTrace>): StateStats[];
618
322
  //#endregion
619
- export { type AgentLintDiagnostic, AgentLintError, type AgentLintSeverity, type AgentPathReport, type AgentPathTerminal, AgentUnknownStateError, type AssertAgentMachineOptions, type CanReachResult, type ExplorePathsOptions, type LintAgentMachineOptions, type MatchTrajectoryOptions, type RunSeamOptions, type RunSeamResult, type SeamCall, type SeamRef, type SeamScriptEntry, type SeamSlice, type SeamTurn, type SimulateAgentOptions, type SimulateAgentResult, type SimulationScript, type SimulationTrailEntry, type TrajectoryEvent, type TrajectoryItem, type TrajectoryMatch, type TrajectoryMiss, assertAgentMachine, canReach, explorePaths, lintAgentMachine, matchesTrajectory, runSeam, simulateAgent };
323
+ export { type AgentLintDiagnostic, AgentLintError, type AgentLintSeverity, type AgentPathReport, type AgentPathTerminal, AgentUnknownStateError, type AssertAgentMachineOptions, type CanReachResult, type ExplorePathsOptions, type FoldTracesOptions, type LintAgentMachineOptions, type MatchTrajectoryOptions, type RunSeamOptions, type RunSeamResult, type SeamCall, type SeamRef, type SeamScriptEntry, type SeamSlice, type SeamTurn, type SimulateAgentOptions, type SimulateAgentResult, type SimulationScript, type SimulationTrailEntry, type StateStats, type TrajectoryEvent, type TrajectoryItem, type TrajectoryMatch, type TrajectoryMiss, assertAgentMachine, canReach, explorePaths, lintAgentMachine, simulateAgent };