@statelyai/agent 2.0.0-alpha.18 → 2.0.0-alpha.20
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.
- package/dist/ai-sdk.cjs +4 -2
- package/dist/ai-sdk.d.cts +1 -1
- package/dist/ai-sdk.d.mts +1 -1
- package/dist/ai-sdk.mjs +3 -2
- package/dist/{decision-C11xuud2.mjs → decision-BfhSgCc6.mjs} +48 -28
- package/dist/{decision-DnQCQPew.cjs → decision-DhsKLYAI.cjs} +64 -43
- package/dist/{event-log-store-CQJq8_v4.d.cts → event-log-store-Bz7HDBkE.d.cts} +11 -12
- package/dist/{event-log-store-B-1fcfkT.mjs → event-log-store-DmIDosD6.mjs} +22 -14
- package/dist/{event-log-store-yquOV1TX.cjs → event-log-store-a_TKy1gk.cjs} +22 -14
- package/dist/{event-log-store-BrC9Q1xW.d.mts → event-log-store-hrA1vqtN.d.mts} +11 -12
- package/dist/index.cjs +458 -109
- package/dist/index.d.cts +209 -81
- package/dist/index.d.mts +209 -81
- package/dist/index.mjs +455 -108
- package/dist/machines.cjs +13 -17
- package/dist/machines.d.cts +14 -17
- package/dist/machines.d.mts +14 -17
- package/dist/machines.mjs +13 -17
- package/dist/otel.cjs +1 -0
- package/dist/otel.d.cts +1 -1
- package/dist/otel.d.mts +1 -1
- package/dist/{run-agent-r9OD4z8F.d.cts → run-agent--4bbms-D.d.cts} +121 -48
- package/dist/{run-agent-DQIDikfd.d.mts → run-agent-CwmzAZwj.d.mts} +121 -48
- package/dist/{setup-agent-BrE2zFDy.mjs → setup-agent-BOcSpsIq.mjs} +38 -28
- package/dist/{setup-agent-C3ETi_HZ.cjs → setup-agent-gISRLxRe.cjs} +44 -33
- package/dist/sqlite.cjs +3 -9
- package/dist/sqlite.d.cts +1 -1
- package/dist/sqlite.d.mts +1 -1
- package/dist/sqlite.mjs +3 -9
- package/dist/{text-logic-VcWqO-Cl.d.cts → text-logic-Cavva1W6.d.cts} +24 -8
- package/dist/{text-logic-RvnlD-An.d.mts → text-logic-Er5KkTX6.d.mts} +24 -8
- package/dist/validate.cjs +436 -0
- package/dist/validate.d.cts +31 -0
- package/dist/validate.d.mts +31 -0
- package/dist/validate.mjs +411 -0
- package/package.json +17 -3
- package/schemas/agent-workflow.json +2 -2
- package/skills/generate-machine/SKILL.md +12 -14
package/dist/index.d.mts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { C as ToolResultPart, S as ToolMessage, T as WithAgentInputSchema, _ as NormalizedEventSchemas, a as AgentToolChoice, b as TextPart, c as AgentTools, d as ChosenEvent, f as EventUnion, g as InferOutput, h as InferInput, i as AgentTool, l as AllowedEvents, m as ImagePart, n as AgentMessage, o as AgentToolDescriptor, p as FilePart, r as AgentSnapshotStore, s as AgentToolExecute, t as AgentEventSchemaInputMap, u as AssistantMessage, v as StandardSchemaV1, w as UserMessage, x as ToolCallPart, y as SystemMessage } from "./types-DYpK3QF4.mjs";
|
|
2
2
|
import { t as AgentError } from "./errors-C9rxnWbX.mjs";
|
|
3
|
-
import { A as AgentDecisionExecutor, B as AgentEventToolNameResolver, C as buildEnvelopeSchema, D as parseModelRef, E as getCallUsage, F as DecisionLogicConfig, G as parseAgentEvent, H as AgentRequestSource, I as ResolveDecisionOptions, L as renderDecisionAttempts, M as AgentDecisionInput, N as AgentDecisionRequest, O as parseOutput, P as DecisionAttempt, R as resolveDecision, S as bindRequestExecutor, T as getAgentOutputMode, U as AgentSchemas, V as AgentRequestOptions, W as getAcceptedEvents, _ as StructuredOutputEnvelope, a as AgentOutputMode, b as TextLogicExecuteArgs, c as AgentRequestExecutorResult, d as AgentTextRequest, f as AgentUsage, g as BuiltinAgentActors, h as AiSdkShapedTextResult, i as AgentModelRef, j as AgentDecisionExhaustedError, k as parseStructuredEnvelope, l as AgentRequestExecutors, m as AiSdkShapedStreamResult, n as AgentExecutorTextRequest, o as AgentRequestExecutor, p as AgentUserInput, r as AgentModelMap, s as AgentRequestExecutorInfo, t as AgentCallUsage, u as AgentRequestMode, v as TextLogic, w as createTextLogic, x as TextLogicExecutor, y as TextLogicConfig, z as AgentEventDescriptor } from "./text-logic-
|
|
4
|
-
import { a as AgentLogVerification, c as assertAgentLogEntry, d as assertEventLogStoreConformance, i as AgentLogEntry, l as assertJsonSerializable, n as AgentEventLogConflictError, o as JsonValue, r as AgentEventLogStore, s as NonSerializableAgentEventError, t as AGENT_EVENT_SCHEMA_VERSION, u as createInMemoryEventLogStore } from "./event-log-store-
|
|
5
|
-
import { A as
|
|
6
|
-
import { AnyActorLogic, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, EventFromLogic, EventObject, InputFrom, MachineContext, MetaObject, NonReducibleUnknown, SetupReturnFromConfig, SetupStateSchema, SnapshotFrom, StateValue } from "xstate";
|
|
3
|
+
import { A as AgentDecisionExecutor, B as AgentEventToolNameResolver, C as buildEnvelopeSchema, D as parseModelRef, E as getCallUsage, F as DecisionLogicConfig, G as parseAgentEvent, H as AgentRequestSource, I as ResolveDecisionOptions, L as renderDecisionAttempts, M as AgentDecisionInput, N as AgentDecisionRequest, O as parseOutput, P as DecisionAttempt, R as resolveDecision, S as bindRequestExecutor, T as getAgentOutputMode, U as AgentSchemas, V as AgentRequestOptions, W as getAcceptedEvents, _ as StructuredOutputEnvelope, a as AgentOutputMode, b as TextLogicExecuteArgs, c as AgentRequestExecutorResult, d as AgentTextRequest, f as AgentUsage, g as BuiltinAgentActors, h as AiSdkShapedTextResult, i as AgentModelRef, j as AgentDecisionExhaustedError, k as parseStructuredEnvelope, l as AgentRequestExecutors, m as AiSdkShapedStreamResult, n as AgentExecutorTextRequest, o as AgentRequestExecutor, p as AgentUserInput, r as AgentModelMap, s as AgentRequestExecutorInfo, t as AgentCallUsage, u as AgentRequestMode, v as TextLogic, w as createTextLogic, x as TextLogicExecutor, y as TextLogicConfig, z as AgentEventDescriptor } from "./text-logic-Er5KkTX6.mjs";
|
|
4
|
+
import { a as AgentLogVerification, c as assertAgentLogEntry, d as assertEventLogStoreConformance, i as AgentLogEntry, l as assertJsonSerializable, n as AgentEventLogConflictError, o as JsonValue, r as AgentEventLogStore, s as NonSerializableAgentEventError, t as AGENT_EVENT_SCHEMA_VERSION, u as createInMemoryEventLogStore } from "./event-log-store-hrA1vqtN.mjs";
|
|
5
|
+
import { A as AgentRequest, B as AgentReplayMachineMismatchError, C as getSnapshotNodes, D as serializeTraceEvent, E as runAgent, F as AgentEffect, G as ReplayResult, H as CreateReplayEntryOptions, I as AgentEffectDiff, J as getAgentEffects, K as createReplayEntry, L as AgentEventLogDiff, M as executeAgentRequest, N as AGENT_INIT_EVENT_TYPE, O as traceTransitions, P as AGENT_USAGE_EVENT_TYPE, R as AgentLogPatchOperation, S as generateResult, T as inspectTransitions, U as GetAgentEffectsOptions, V as AgentUsageEvent, W as ReplayOptions, X as replay, Y as initEntry, _ as PendingUserInput, a as AgentInputFrom, b as RunAgentResult, c as AgentRunMeta, d as AgentTraceEvent, f as AgentUserInputExecutor, g as JsonSerializableTraceEvent, h as InspectedActorRef, i as AgentIllegalResumeEventError, j as AgentStepRequest, k as AgentStateRequest, l as AgentSnapshotNode, m as GetSnapshotRequestsOptions, n as AgentActorSession, o as AgentMaxModelCallsExceededError, p as GenerateResult, q as diffEventLogs, r as AgentIdleError, s as AgentMessageInfo, t as AGENT_TRACE_SCHEMA_VERSION, u as AgentSnapshotVersionMismatchError, v as RunAgentErrorCause, w as getSnapshotRequests, x as createAgentActor, y as RunAgentOptions, z as AgentReplayDivergenceError } from "./run-agent-CwmzAZwj.mjs";
|
|
6
|
+
import { AnyActorLogic, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, EventFromLogic, EventObject, InputFrom, MachineContext, MetaObject, NonReducibleUnknown, OutputFrom, SetupReturnFromConfig, SetupStateSchema, SnapshotFrom, StateValue } from "xstate";
|
|
7
7
|
|
|
8
8
|
//#region src/messages.d.ts
|
|
9
9
|
/**
|
|
@@ -99,14 +99,14 @@ interface AgentWorkflowConfig {
|
|
|
99
99
|
/**
|
|
100
100
|
* State tags that mark an INTENTIONAL wait for an external event (a human
|
|
101
101
|
* approval, an inbound webhook, …) — the declarative form of `setupAgent({
|
|
102
|
-
*
|
|
102
|
+
* isIdle })`, since a config cannot carry a function. Lowered to a
|
|
103
103
|
* `snapshot.hasTag(...)`-any-of predicate so `runAgent` settles those
|
|
104
104
|
* snapshots idle deterministically instead of using its timing heuristic.
|
|
105
105
|
* Every listed tag must appear in some state's `tags` — an unused tag is a
|
|
106
|
-
* build-time error. A `fromConfig(config, {
|
|
107
|
-
* precedence; a `runAgent({
|
|
106
|
+
* build-time error. A `fromConfig(config, { isIdle })` option takes
|
|
107
|
+
* precedence; a `runAgent({ isIdle })` host override beats both.
|
|
108
108
|
*/
|
|
109
|
-
|
|
109
|
+
idleTags?: string[];
|
|
110
110
|
meta?: Record<string, unknown>;
|
|
111
111
|
}
|
|
112
112
|
/** A `requests` entry in {@link AgentWorkflowConfig} — the JSON equivalent of a `setupAgent({ requests })` `TextLogicConfig`. Fields beyond `input`/`output`/`tools`/`mode`/`description` are `unknown` because they accept template-expression strings (see {@link AgentWorkflowConfig}). */
|
|
@@ -241,14 +241,14 @@ interface FromConfigOptions {
|
|
|
241
241
|
actions?: Record<string, (params: any) => unknown>;
|
|
242
242
|
/**
|
|
243
243
|
* Detects a snapshot that is an INTENTIONAL wait for an external event —
|
|
244
|
-
* the same machine-carried predicate `setupAgent({
|
|
244
|
+
* the same machine-carried predicate `setupAgent({ isIdle })` declares
|
|
245
245
|
* for TS-authored machines, registered here because a function cannot live
|
|
246
246
|
* in the workflow config itself. Takes precedence over the config's
|
|
247
|
-
* declarative {@link AgentWorkflowConfig.
|
|
248
|
-
* `runAgent({
|
|
247
|
+
* declarative {@link AgentWorkflowConfig.idleTags}; a
|
|
248
|
+
* `runAgent({ isIdle })` host override beats both. Travels with the
|
|
249
249
|
* machine through `machine.provide(...)`.
|
|
250
250
|
*/
|
|
251
|
-
|
|
251
|
+
isIdle?: (snapshot: AnyMachineSnapshot) => boolean;
|
|
252
252
|
}
|
|
253
253
|
//#endregion
|
|
254
254
|
//#region src/setup-agent.d.ts
|
|
@@ -412,14 +412,14 @@ type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string,
|
|
|
412
412
|
/**
|
|
413
413
|
* Detects a snapshot that is an INTENTIONAL wait for an external event (a
|
|
414
414
|
* human approval, an inbound webhook, …) — the machine's own declaration of
|
|
415
|
-
* what "
|
|
415
|
+
* what "idle" means for it, so `runAgent` settles those snapshots idle
|
|
416
416
|
* deterministically instead of using its timing heuristic. Travels with the
|
|
417
|
-
* machine through `machine.provide(...)`. A `runAgent({
|
|
417
|
+
* machine through `machine.provide(...)`. A `runAgent({ isIdle })` host
|
|
418
418
|
* override takes precedence; with neither, `runAgent` falls back to the timing
|
|
419
419
|
* heuristic. Declare your own signal — e.g. `(s) => s.hasTag('awaiting-review')`
|
|
420
420
|
* or `(s) => getStateMeta(s).interaction !== undefined`.
|
|
421
421
|
*/
|
|
422
|
-
|
|
422
|
+
isIdle?: (snapshot: AnyMachineSnapshot) => boolean;
|
|
423
423
|
};
|
|
424
424
|
type SetupAgentXStateResult<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, AgentSetupStateSchema> = Record<string, AgentSetupStateSchema>> = SetupReturnFromConfig<AgentSetupXStateConfig<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, ResolveAgentStateSchemas<TContextSchema, TStateSchemas>>>;
|
|
425
425
|
/**
|
|
@@ -656,9 +656,12 @@ interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMac
|
|
|
656
656
|
* Throws at bind time if a source needs an executor kind that `executors` does
|
|
657
657
|
* not provide.
|
|
658
658
|
*
|
|
659
|
-
*
|
|
660
|
-
* machine
|
|
661
|
-
*
|
|
659
|
+
* Executor inheritance is RECURSIVE, exactly as in `runAgent`: a string-keyed
|
|
660
|
+
* invoked child machine is rebound too, so its own text/decision requests — at
|
|
661
|
+
* any depth — reach the same host executors. A direct-object invoke `src`
|
|
662
|
+
* cannot be swapped via `.provide`, so nothing under one inherits; bind those
|
|
663
|
+
* with `.withExecutor(...)` or register the child as a string-keyed source. A
|
|
664
|
+
* source that already carries its own executor is never overwritten.
|
|
662
665
|
*/
|
|
663
666
|
declare function provideExecutors<TMachine extends AnyStateMachine>(machine: TMachine, executors: AgentRequestExecutors, options?: ProvideExecutorsOptions<TMachine>): TMachine;
|
|
664
667
|
//#endregion
|
|
@@ -677,10 +680,18 @@ interface AgentLintDiagnostic {
|
|
|
677
680
|
path: string;
|
|
678
681
|
message: string;
|
|
679
682
|
}
|
|
680
|
-
/** Options for {@link lintAgentMachine}.
|
|
683
|
+
/** Options for {@link lintAgentMachine}. */
|
|
681
684
|
interface LintAgentMachineOptions {
|
|
682
685
|
/** Skip these check codes entirely. */
|
|
683
686
|
disable?: AgentLintDiagnostic["code"][];
|
|
687
|
+
/**
|
|
688
|
+
* Throw {@link AgentLintError} on failing diagnostics instead of returning
|
|
689
|
+
* them. Fails on error-severity findings; add `warnings: true` to fail on
|
|
690
|
+
* warnings too.
|
|
691
|
+
*/
|
|
692
|
+
throw?: boolean;
|
|
693
|
+
/** With `throw: true`, also fail on warning-severity findings. Default: errors only. */
|
|
694
|
+
warnings?: boolean;
|
|
684
695
|
}
|
|
685
696
|
/**
|
|
686
697
|
* Runs static structural checks over a built agent machine and returns the
|
|
@@ -693,20 +704,28 @@ interface LintAgentMachineOptions {
|
|
|
693
704
|
* call this to catch dead states, undeliverable decisions, un-rebindable
|
|
694
705
|
* invoke srcs, and output-contract gaps before ever running it.
|
|
695
706
|
*
|
|
707
|
+
* Pass `{ throw: true }` for the one-liner form used in tests and generation
|
|
708
|
+
* loops: it returns silently when the machine is clean and throws
|
|
709
|
+
* {@link AgentLintError} (findings on `.diagnostics`) on error-severity
|
|
710
|
+
* findings, or on warnings too with `{ throw: true, warnings: true }`.
|
|
711
|
+
*
|
|
696
712
|
* @example
|
|
697
713
|
* ```ts
|
|
698
714
|
* const errors = lintAgentMachine(machine).filter((d) => d.severity === 'error');
|
|
699
715
|
* if (errors.length) throw new Error(errors.map((e) => `${e.path}: ${e.message}`).join('\n'));
|
|
700
716
|
* ```
|
|
717
|
+
*
|
|
718
|
+
* @example Throwing form
|
|
719
|
+
* ```ts
|
|
720
|
+
* test('agent machine is structurally sound', () => {
|
|
721
|
+
* lintAgentMachine(machine, { throw: true });
|
|
722
|
+
* });
|
|
723
|
+
* ```
|
|
701
724
|
*/
|
|
702
725
|
declare function lintAgentMachine(machine: AnyStateMachine, options?: LintAgentMachineOptions): AgentLintDiagnostic[];
|
|
703
|
-
/** Options for {@link assertAgentMachine}. */
|
|
704
|
-
interface AssertAgentMachineOptions extends LintAgentMachineOptions {
|
|
705
|
-
/** Also fail on warning-severity findings. Default: errors only. */
|
|
706
|
-
warnings?: boolean;
|
|
707
|
-
}
|
|
708
726
|
/**
|
|
709
|
-
* Thrown by {
|
|
727
|
+
* Thrown by `lintAgentMachine(machine, { throw: true })` when lint finds
|
|
728
|
+
* failing diagnostics.
|
|
710
729
|
* `diagnostics` holds the findings; the message lists them one per finding,
|
|
711
730
|
* so a test runner's failure output reads like the CLI's lint report.
|
|
712
731
|
*/
|
|
@@ -714,20 +733,6 @@ declare class AgentLintError extends AgentError {
|
|
|
714
733
|
readonly diagnostics: AgentLintDiagnostic[];
|
|
715
734
|
constructor(machineId: string, diagnostics: AgentLintDiagnostic[]);
|
|
716
735
|
}
|
|
717
|
-
/**
|
|
718
|
-
* Asserts a machine passes {@link lintAgentMachine}: returns silently when
|
|
719
|
-
* clean, throws {@link AgentLintError} (with the findings on `.diagnostics`)
|
|
720
|
-
* otherwise. Fails on error-severity findings; set `warnings: true` to fail on
|
|
721
|
-
* warnings too. The one-liner for tests and generation loops:
|
|
722
|
-
*
|
|
723
|
-
* @example
|
|
724
|
-
* ```ts
|
|
725
|
-
* test('agent machine is structurally sound', () => {
|
|
726
|
-
* assertAgentMachine(machine);
|
|
727
|
-
* });
|
|
728
|
-
* ```
|
|
729
|
-
*/
|
|
730
|
-
declare function assertAgentMachine(machine: AnyStateMachine, options?: AssertAgentMachineOptions): void;
|
|
731
736
|
/**
|
|
732
737
|
* Scripted responses for a {@link simulateAgent} playthrough. Each channel is a
|
|
733
738
|
* by-`src` map of FIFO queues, consumed in the order the machine reaches the
|
|
@@ -736,13 +741,17 @@ declare function assertAgentMachine(machine: AnyStateMachine, options?: AssertAg
|
|
|
736
741
|
* `setupAgent({ requests })` key, or `agent.generateText`/`agent.streamText`).
|
|
737
742
|
* - `decisions` — the {@link ChosenEvent} to apply for a decision request,
|
|
738
743
|
* keyed by decision src (usually `agent.decide`).
|
|
739
|
-
* - `invokes` — output values for scripted invokes (
|
|
740
|
-
*
|
|
744
|
+
* - `invokes` — output values for scripted invokes (any actor whose output must
|
|
745
|
+
* be canned), keyed by src.
|
|
746
|
+
* - `userInput` — a flat FIFO queue of answers for `agent.userInput`, the
|
|
747
|
+
* shorthand for `invokes: { 'agent.userInput': [...] }`. Entries here are
|
|
748
|
+
* consumed before that src's `invokes` queue.
|
|
741
749
|
*/
|
|
742
750
|
interface SimulationScript {
|
|
743
751
|
text?: Record<string, unknown[]>;
|
|
744
752
|
decisions?: Record<string, ChosenEvent[]>;
|
|
745
753
|
invokes?: Record<string, unknown[]>;
|
|
754
|
+
userInput?: unknown[];
|
|
746
755
|
}
|
|
747
756
|
/** One entry in a {@link SimulateAgentResult.trail}: the state after this step, plus what drove the step. */
|
|
748
757
|
interface SimulationTrailEntry {
|
|
@@ -798,8 +807,17 @@ interface ExplorePathsOptions {
|
|
|
798
807
|
maxDepth?: number;
|
|
799
808
|
/** Total path cap before exploration stops (reported via `hitPathCap`). Default 200. */
|
|
800
809
|
maxPaths?: number;
|
|
801
|
-
/**
|
|
802
|
-
|
|
810
|
+
/**
|
|
811
|
+
* Canned output for each text request, keyed by src (the
|
|
812
|
+
* `setupAgent({ requests })` key, or `agent.generateText`/`agent.streamText`).
|
|
813
|
+
* One value per src, reused every time that src is reached. A missing src
|
|
814
|
+
* halts that branch with a `needs-output` terminal.
|
|
815
|
+
*/
|
|
816
|
+
text?: Record<string, unknown>;
|
|
817
|
+
/** Canned output for scripted invokes, keyed by src. Same one-value-per-src rule as `text`. */
|
|
818
|
+
invokes?: Record<string, unknown>;
|
|
819
|
+
/** Canned output for `agent.userInput`, the shorthand for `invokes['agent.userInput']`. */
|
|
820
|
+
userInput?: unknown;
|
|
803
821
|
}
|
|
804
822
|
/** A single explored path's terminal outcome. */
|
|
805
823
|
interface AgentPathTerminal {
|
|
@@ -831,9 +849,10 @@ interface AgentPathReport {
|
|
|
831
849
|
* depth, model-free, and reports which states are reached and how each path
|
|
832
850
|
* terminates. At each decision request it forks one branch per candidate event
|
|
833
851
|
* (guard-rejected candidates are counted in `prunedByGuard`, not explored); at
|
|
834
|
-
* an idle wait it forks per externally-accepted event. Text
|
|
835
|
-
*
|
|
836
|
-
*
|
|
852
|
+
* an idle wait it forks per externally-accepted event. Text requests resolve
|
|
853
|
+
* from `text`, other invokes from `invokes` (or `userInput` for
|
|
854
|
+
* `agent.userInput`) — all by-src canned-output maps, and a missing src halts
|
|
855
|
+
* that branch with a `needs-output` terminal rather than throwing.
|
|
837
856
|
*
|
|
838
857
|
* Combinatorics are bounded by `maxDepth` (default 8) and `maxPaths` (default
|
|
839
858
|
* 200, reported via `hitPathCap`).
|
|
@@ -847,19 +866,21 @@ interface AgentPathReport {
|
|
|
847
866
|
declare function explorePaths(machine: AnyStateMachine, options?: ExplorePathsOptions): Promise<AgentPathReport>;
|
|
848
867
|
/** The result of a {@link canReach} query. */
|
|
849
868
|
interface CanReachResult {
|
|
850
|
-
|
|
869
|
+
/** True when the target state was reached within the exploration bounds. */
|
|
870
|
+
reachable: boolean;
|
|
851
871
|
/** When reachable, the sequence of chosen/applied events that gets there. */
|
|
852
872
|
witness?: ChosenEvent[];
|
|
853
873
|
}
|
|
854
874
|
/**
|
|
855
875
|
* Answers "can the machine reach `statePath`?" by exploring its branches (a
|
|
856
|
-
* thin wrapper over {@link explorePaths}). Returns
|
|
857
|
-
* with the event sequence that reaches it, or
|
|
876
|
+
* thin wrapper over {@link explorePaths}). Returns
|
|
877
|
+
* `{ reachable: true, witness }` with the event sequence that reaches it, or
|
|
878
|
+
* `{ reachable: false }`.
|
|
858
879
|
*
|
|
859
880
|
* @example
|
|
860
881
|
* ```ts
|
|
861
|
-
* const {
|
|
862
|
-
* //
|
|
882
|
+
* const { reachable, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
|
|
883
|
+
* // reachable → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
|
|
863
884
|
* ```
|
|
864
885
|
*/
|
|
865
886
|
declare function canReach(machine: AnyStateMachine, statePath: string, options?: ExplorePathsOptions): Promise<CanReachResult>;
|
|
@@ -984,13 +1005,40 @@ type ScriptedDecisionEntry = ScriptedDecisionValue | ((request: AgentDecisionReq
|
|
|
984
1005
|
* `{ output, usage }`), wrap it once more: `{ output: { output: '…' } }`.
|
|
985
1006
|
*/
|
|
986
1007
|
type ScriptedTextEntry = ((request: AgentTextRequest, info?: AgentRequestExecutorInfo) => unknown) | string | number | boolean | null | object;
|
|
987
|
-
/**
|
|
1008
|
+
/**
|
|
1009
|
+
* One entry in the `userInput` queue: the string the simulated human typed, or
|
|
1010
|
+
* a function of the {@link AgentUserInput} request (its `prompt`/`metadata`)
|
|
1011
|
+
* returning one.
|
|
1012
|
+
*/
|
|
1013
|
+
type ScriptedUserInputEntry = string | ((input: AgentUserInput) => string | PromiseLike<string>);
|
|
1014
|
+
/**
|
|
1015
|
+
* The script {@link createScriptedExecutors} plays back.
|
|
1016
|
+
*
|
|
1017
|
+
* The key names match `simulateAgent`'s script (`decisions`, `text`,
|
|
1018
|
+
* `invokes`, `userInput`), but the shapes differ by design: `simulateAgent`
|
|
1019
|
+
* drives the pure step path and keys each channel BY SRC
|
|
1020
|
+
* (`text: { summarize: [...] }`), while these executors sit behind the real
|
|
1021
|
+
* executor contract, where one flat FIFO queue per channel is the ergonomic
|
|
1022
|
+
* form — route per request inside a function entry (`request.name`) when one
|
|
1023
|
+
* script must serve several requests. There is no `invokes` queue here:
|
|
1024
|
+
* non-`userInput` invokes are plain actors, supplied via `actors`.
|
|
1025
|
+
*/
|
|
988
1026
|
interface ScriptedExecutorsScript {
|
|
989
1027
|
/** Answers for `decide` requests, consumed in order. */
|
|
990
1028
|
decisions?: ScriptedDecisionEntry[];
|
|
991
1029
|
/** Answers for text requests, consumed in order. `generateText` and `streamText` share this one queue. */
|
|
992
1030
|
text?: ScriptedTextEntry[];
|
|
1031
|
+
/** Answers for `agent.userInput` requests, consumed in order. */
|
|
1032
|
+
userInput?: ScriptedUserInputEntry[];
|
|
993
1033
|
}
|
|
1034
|
+
/**
|
|
1035
|
+
* What {@link createScriptedExecutors} returns: the full executor set, plus a
|
|
1036
|
+
* `userInput` handler for `runAgent`'s own `userInput` option (the builtin
|
|
1037
|
+
* `agent.userInput` actor is not an executor slot).
|
|
1038
|
+
*/
|
|
1039
|
+
type ScriptedExecutors = Required<AgentRequestExecutors> & {
|
|
1040
|
+
userInput: (input: AgentUserInput) => Promise<string>;
|
|
1041
|
+
};
|
|
994
1042
|
/**
|
|
995
1043
|
* Keyless executors that replay a script instead of calling a model. Every
|
|
996
1044
|
* slot is provided, so any machine binds; a request with no entry left throws a
|
|
@@ -1019,18 +1067,16 @@ interface ScriptedExecutorsScript {
|
|
|
1019
1067
|
* decisions: [(request) => ({ type: request.events[0]!.type })],
|
|
1020
1068
|
* });
|
|
1021
1069
|
* ```
|
|
1070
|
+
*
|
|
1071
|
+
* @example Scripted human input
|
|
1072
|
+
* ```ts
|
|
1073
|
+
* const scripted = createScriptedExecutors({ userInput: ['ship it'] });
|
|
1074
|
+
* await runAgent(machine, { executors: scripted, userInput: scripted.userInput });
|
|
1075
|
+
* ```
|
|
1022
1076
|
*/
|
|
1023
|
-
declare function createScriptedExecutors(script?: ScriptedExecutorsScript):
|
|
1077
|
+
declare function createScriptedExecutors(script?: ScriptedExecutorsScript): ScriptedExecutors;
|
|
1024
1078
|
//#endregion
|
|
1025
1079
|
//#region src/utils.d.ts
|
|
1026
|
-
/**
|
|
1027
|
-
* Deep-clones a snapshot to a plain-JSON value via a `JSON` round-trip, the
|
|
1028
|
-
* shape you persist and later feed back to `runAgent({ snapshot })`. Asserts
|
|
1029
|
-
* JSON-serializability: functions, `undefined`, and other non-JSON values are
|
|
1030
|
-
* dropped or throw exactly as `JSON.stringify`/`JSON.parse` would. Returns a
|
|
1031
|
-
* plain-JSON deep clone, not a live snapshot.
|
|
1032
|
-
*/
|
|
1033
|
-
declare function persistSnapshot<TSnapshot>(snapshot: TSnapshot): TSnapshot;
|
|
1034
1080
|
/**
|
|
1035
1081
|
* A stable, dependency-free structural fingerprint of a machine — a short hex
|
|
1036
1082
|
* `djb2` hash over its **structural** config only: state ids/nesting, transition
|
|
@@ -1043,7 +1089,7 @@ declare function persistSnapshot<TSnapshot>(snapshot: TSnapshot): TSnapshot;
|
|
|
1043
1089
|
* Used by {@link runAgent} to stamp settled snapshots with a `version` and to
|
|
1044
1090
|
* detect a structurally-edited machine on resume. It is a change detector, not
|
|
1045
1091
|
* a cryptographic digest — collisions are possible but unlikely for real
|
|
1046
|
-
* configs.
|
|
1092
|
+
* configs. Declare `createMachine({ version })` to pin an explicit version instead.
|
|
1047
1093
|
*/
|
|
1048
1094
|
declare function getMachineStructuralHash(machine: AnyStateMachine): string;
|
|
1049
1095
|
/** Builds a {@link UserMessage} from a string or multimodal content parts. */
|
|
@@ -1063,8 +1109,15 @@ type MetaOfSnapshot<TSnapshot extends {
|
|
|
1063
1109
|
*
|
|
1064
1110
|
* `snapshot.getMeta()` is keyed by state id; a leaf machine has one active
|
|
1065
1111
|
* state, but parallel/nested machines can have several. This shallow-merges
|
|
1066
|
-
* every active state's meta into one object
|
|
1067
|
-
*
|
|
1112
|
+
* every active state's meta into one object and returns `{}` when no active
|
|
1113
|
+
* state declares meta.
|
|
1114
|
+
*
|
|
1115
|
+
* Merge order is fixed and does not depend on XState's internal node order:
|
|
1116
|
+
* entries are sorted by structural depth (the state node's distance from the
|
|
1117
|
+
* root, regardless of custom `id` strings), then by state id lexicographically,
|
|
1118
|
+
* and merged in that order. So a deeper state's key wins over an ancestor's,
|
|
1119
|
+
* and between equal-depth parallel siblings the later state id alphabetically
|
|
1120
|
+
* wins.
|
|
1068
1121
|
*
|
|
1069
1122
|
* The return type is recovered from the snapshot's own `getMeta()` type, so a
|
|
1070
1123
|
* schema-typed machine (`setupAgent({ meta })`) yields the meta schema's
|
|
@@ -1119,20 +1172,17 @@ declare function getJsonSchemaSync(schema?: StandardSchemaV1): Record<string, un
|
|
|
1119
1172
|
//#endregion
|
|
1120
1173
|
//#region src/seam.d.ts
|
|
1121
1174
|
/**
|
|
1122
|
-
* Which model call is under test: the Nth call
|
|
1123
|
-
* `
|
|
1124
|
-
*
|
|
1125
|
-
*
|
|
1175
|
+
* Which model call is under test: the Nth call with this request `name` (the
|
|
1176
|
+
* `setupAgent({ requests })` key, or `createTextLogic({ name })`). Name the
|
|
1177
|
+
* requests you want to score — a seam is a developer-facing handle, not a
|
|
1178
|
+
* model binding, so there is no addressing by model key.
|
|
1126
1179
|
*/
|
|
1127
|
-
|
|
1128
|
-
/** The request's registered `name`. */
|
|
1129
|
-
|
|
1130
|
-
occurrence
|
|
1131
|
-
} | {
|
|
1132
|
-
/** The `defineModels` key the request names. */model: string;
|
|
1133
|
-
request?: undefined; /** 0-based occurrence among the calls matching this key. Default `0`. */
|
|
1180
|
+
interface SeamRef {
|
|
1181
|
+
/** The request's registered `name`. */
|
|
1182
|
+
request: string;
|
|
1183
|
+
/** 0-based occurrence among the calls with this name. Default `0`. */
|
|
1134
1184
|
occurrence?: number;
|
|
1135
|
-
}
|
|
1185
|
+
}
|
|
1136
1186
|
/**
|
|
1137
1187
|
* One idle pause, handed to {@link RunSeamOptions.respond} so the simulated
|
|
1138
1188
|
* user answers off the machine's own state rather than a fixed transcript — a
|
|
@@ -1172,11 +1222,17 @@ interface RunSeamOptions<TMachine extends AnyStateMachine> {
|
|
|
1172
1222
|
* by model.
|
|
1173
1223
|
*
|
|
1174
1224
|
* Entries follow {@link ScriptedTextEntry} conventions (a value, an
|
|
1175
|
-
* `{ output, usage? }` envelope, or a function of the request).
|
|
1176
|
-
*
|
|
1177
|
-
*
|
|
1225
|
+
* `{ output, usage? }` envelope, or a function of the request). A queue that
|
|
1226
|
+
* runs dry throws; set {@link RunSeamOptions.repeatLast} to replay its last
|
|
1227
|
+
* entry instead.
|
|
1178
1228
|
*/
|
|
1179
1229
|
scripts?: Record<string, ScriptedTextEntry[]>;
|
|
1230
|
+
/**
|
|
1231
|
+
* Replay the LAST entry of a queue once it is exhausted, so a live seam that
|
|
1232
|
+
* sends the run down a longer branch still finds an answer. Off by default:
|
|
1233
|
+
* a dry queue throws, the same as every other scripted surface.
|
|
1234
|
+
*/
|
|
1235
|
+
repeatLast?: boolean;
|
|
1180
1236
|
/** The call under test. */
|
|
1181
1237
|
seam: SeamRef;
|
|
1182
1238
|
/**
|
|
@@ -1200,7 +1256,7 @@ interface RunSeamOptions<TMachine extends AnyStateMachine> {
|
|
|
1200
1256
|
*/
|
|
1201
1257
|
executors?: Partial<AgentRequestExecutors>;
|
|
1202
1258
|
/** Passed through to `runAgent`: the deterministic idle-state predicate. */
|
|
1203
|
-
|
|
1259
|
+
isIdle?: RunAgentOptions<TMachine>["isIdle"];
|
|
1204
1260
|
/** Passed through to `runAgent`: actor implementations merged onto the machine. */
|
|
1205
1261
|
actors?: RunAgentOptions<TMachine>["actors"];
|
|
1206
1262
|
}
|
|
@@ -1253,4 +1309,76 @@ interface RunSeamResult<TMachine extends AnyStateMachine> {
|
|
|
1253
1309
|
*/
|
|
1254
1310
|
declare function runSeam<TMachine extends AnyStateMachine>(machine: TMachine, options: RunSeamOptions<TMachine>): Promise<RunSeamResult<TMachine>>;
|
|
1255
1311
|
//#endregion
|
|
1256
|
-
|
|
1312
|
+
//#region src/durable.d.ts
|
|
1313
|
+
/** Options for {@link runDurableAgent}. */
|
|
1314
|
+
interface RunDurableAgentOptions<TMachine extends AnyStateMachine> extends Pick<ProvideExecutorsOptions<TMachine>, "actors" | "onChunk" | "onTrace"> {
|
|
1315
|
+
/** Machine input for a FRESH run (ignored when `entries` has an init entry). */
|
|
1316
|
+
input?: InputFrom<TMachine>;
|
|
1317
|
+
/**
|
|
1318
|
+
* The journal to resume from — the `entries` a previous
|
|
1319
|
+
* {@link runDurableAgent} result returned (or any replay-compatible
|
|
1320
|
+
* {@link AgentLogEntry} log with a reserved `@agent.init` first entry).
|
|
1321
|
+
*/
|
|
1322
|
+
entries?: readonly AgentLogEntry[];
|
|
1323
|
+
/** One external event to feed after the journal is folded (a user reply, a timer). */
|
|
1324
|
+
event?: EventFromLogic<TMachine>;
|
|
1325
|
+
/** Host executors, bound with {@link provideExecutors} semantics. */
|
|
1326
|
+
executors?: AgentRequestExecutors;
|
|
1327
|
+
/** Called with each entry as it is appended, for incremental persistence. */
|
|
1328
|
+
onEntry?: (entry: AgentLogEntry) => void;
|
|
1329
|
+
/**
|
|
1330
|
+
* Settle `idle` when this returns true for the current snapshot even though
|
|
1331
|
+
* children are still pending — for machines whose wait states keep a
|
|
1332
|
+
* never-resolving invoke in flight (e.g. an unbound `agent.userInput`).
|
|
1333
|
+
*/
|
|
1334
|
+
isIdle?: (snapshot: SnapshotFrom<TMachine>) => boolean;
|
|
1335
|
+
/** Explicit machine version for entry stamping; defaults to the structural hash. */
|
|
1336
|
+
machineVersion?: string;
|
|
1337
|
+
/**
|
|
1338
|
+
* Record replay-verification hashes on appended entries. Off by default:
|
|
1339
|
+
* hashing replays the whole prefix per entry, which is quadratic in log
|
|
1340
|
+
* length.
|
|
1341
|
+
*/
|
|
1342
|
+
verification?: boolean;
|
|
1343
|
+
}
|
|
1344
|
+
/** The settled result of a {@link runDurableAgent} call. */
|
|
1345
|
+
type DurableAgentResult<TMachine extends AnyStateMachine> = {
|
|
1346
|
+
/** The machine reached a final state. */status: "done";
|
|
1347
|
+
output: OutputFrom<TMachine>;
|
|
1348
|
+
snapshot: SnapshotFrom<TMachine>; /** The complete journal; replaying it reproduces this run. */
|
|
1349
|
+
entries: AgentLogEntry[];
|
|
1350
|
+
} | {
|
|
1351
|
+
/** The machine is waiting for an external event. Persist `entries`; resume with them plus `event`. */status: "idle";
|
|
1352
|
+
snapshot: SnapshotFrom<TMachine>;
|
|
1353
|
+
entries: AgentLogEntry[];
|
|
1354
|
+
};
|
|
1355
|
+
/**
|
|
1356
|
+
* Runs an agent machine as a durable execution: journal in, journal out.
|
|
1357
|
+
*
|
|
1358
|
+
* A fresh call starts from `input` and appends a reserved init entry; a
|
|
1359
|
+
* resume call folds `entries` through pure transitions first — invokes whose
|
|
1360
|
+
* completions are journaled are suppressed (their recorded results replay
|
|
1361
|
+
* instead of re-executing), while work that was in flight at the crash
|
|
1362
|
+
* re-executes live. After the journal, an optional `options.event` is
|
|
1363
|
+
* delivered. The call settles:
|
|
1364
|
+
*
|
|
1365
|
+
* - `done` when the machine reaches a final state, with `output`;
|
|
1366
|
+
* - `idle` when the frontier needs an external event the host has not
|
|
1367
|
+
* supplied (no live work pending, or `isIdle` says the pending work is a
|
|
1368
|
+
* human wait). Persist `entries` and call again with them later.
|
|
1369
|
+
*
|
|
1370
|
+
* ```ts
|
|
1371
|
+
* const first = await runDurableAgent(machine, { input, executors });
|
|
1372
|
+
* // ... persist first.entries; later, in a new process:
|
|
1373
|
+
* const next = await runDurableAgent(machine, {
|
|
1374
|
+
* entries: first.entries,
|
|
1375
|
+
* event: { type: "APPROVE" },
|
|
1376
|
+
* executors,
|
|
1377
|
+
* });
|
|
1378
|
+
* ```
|
|
1379
|
+
*
|
|
1380
|
+
* @experimental Built on xstate's experimental `xstate/durable` entrypoint.
|
|
1381
|
+
*/
|
|
1382
|
+
declare function runDurableAgent<TMachine extends AnyStateMachine>(machine: TMachine, options?: RunDurableAgentOptions<TMachine>): Promise<DurableAgentResult<TMachine>>;
|
|
1383
|
+
//#endregion
|
|
1384
|
+
export { AGENT_EVENT_SCHEMA_VERSION, AGENT_INIT_EVENT_TYPE, AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, type AgentActorSession, type AgentCallUsage, type AgentDecisionExecutor, AgentDecisionExhaustedError, type AgentDecisionInput, type AgentDecisionRequest, type AgentEffect, type AgentEffectDiff, AgentError, type AgentEventDescriptor, AgentEventLogConflictError, type AgentEventLogDiff, type AgentEventLogStore, type AgentEventToolNameResolver, type AgentExecutorTextRequest, AgentIdleError, AgentIllegalResumeEventError, type AgentInputFrom, type AgentLintDiagnostic, AgentLintError, type AgentLintSeverity, type AgentLogEntry, type AgentLogPatchOperation, type AgentLogVerification, AgentMaxModelCallsExceededError, type AgentMessage, type AgentMessageInfo, type AgentModelRef, type AgentOutputMode, type AgentPathReport, type AgentPathTerminal, AgentReplayDivergenceError, AgentReplayMachineMismatchError, type AgentRequest, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestOptions, type AgentRequestSource, type AgentRun, type AgentRunMeta, type AgentSchemaPack, type AgentSchemas, type AgentSnapshotNode, type AgentSnapshotStore, AgentSnapshotVersionMismatchError, type AgentStateRequest, type AgentStepRequest, type AgentTextRequest, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentTools, type AgentTraceEvent, type AgentUsage, type AgentUsageEvent, type AgentUsageEventPayload, type AgentUserInput, type AgentUserInputExecutor, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AiSdkShapedStreamResult, type AiSdkShapedTextResult, type AllowedEvents, type AssistantMessage, type CanReachResult, type ChosenEvent, type CreateReplayEntryOptions, type DecisionAttempt, type DecisionLogicConfig, type DurableAgentResult, type ExplorePathsOptions, type FilePart, type FromConfigOptions, type FromConfigResult, type GenerateResult, type GetAgentEffectsOptions, type GetSnapshotRequestsOptions, type ImagePart, type InferInput, type InferOutput, type InspectedActorRef, type JsonSerializableTraceEvent, type JsonValue, type LintAgentMachineOptions, type MatchTrajectoryOptions, NonSerializableAgentEventError, type PendingUserInput, type ProvideExecutorsOptions, type ReplayOptions, type ReplayResult, type ResolveDecisionOptions, type RunAgentErrorCause, type RunAgentOptions, type RunAgentResult, type RunDurableAgentOptions, type RunSeamOptions, type RunSeamResult, type SchemaCompiler, type ScriptedDecisionEntry, type ScriptedDecisionValue, type ScriptedExecutors, type ScriptedExecutorsScript, type ScriptedTextEntry, type ScriptedUserInputEntry, type SeamRef, type SeamSlice, type SeamTurn, type SimulateAgentOptions, type SimulateAgentResult, type SimulationScript, type SimulationTrailEntry, type StandardSchemaV1, type StructuredOutputEnvelope, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultPart, type TrajectoryEvent, type TrajectoryItem, type TrajectoryMatch, type TrajectoryMiss, type UserMessage, type WithAgentUsageEvent, appendMessages, assertAgentLogEntry, assertEventLogStoreConformance, assertJsonSerializable, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentActor, createAgentRun, createAgentSchemas, createInMemoryEventLogStore, createReplayEntry, createScriptedExecutors, createTextLogic, diffEventLogs, executeAgentRequest, explorePaths, generateResult, getAcceptedEvents, getAgentEffects, getAgentMessages, getAgentOutputMode, getAgentSchemas, getCallUsage, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getSnapshotNodes, getSnapshotRequests, getStateMeta, initEntry, inspectTransitions, isStandardSchema, lintAgentMachine, matchesTrajectory, messagesSchema, parseAgentEvent, parseModelRef, parseOutput, parseStructuredEnvelope, provideExecutors, renderDecisionAttempts, replay, resolveDecision, runAgent, runDurableAgent, runSeam, serializeTraceEvent, setupAgent, simulateAgent, systemMessage, toolMessage, traceTransitions, userMessage };
|