@statelyai/agent 2.0.0-alpha.19 → 2.0.0-alpha.21
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 +89 -25
- package/dist/ai-sdk.d.cts +56 -12
- package/dist/ai-sdk.d.mts +56 -12
- package/dist/ai-sdk.mjs +89 -26
- package/dist/{decision-t26zsnSR.cjs → decision-BnTCsuJv.cjs} +16 -4
- package/dist/{decision-DsIkEuHz.mjs → decision-JWx6n3xR.mjs} +5 -5
- package/dist/index.cjs +378 -24
- package/dist/index.d.cts +211 -19
- package/dist/index.d.mts +211 -19
- package/dist/index.mjs +378 -26
- package/dist/machines.cjs +1 -1
- package/dist/machines.d.cts +1 -1
- package/dist/machines.d.mts +1 -1
- package/dist/machines.mjs +1 -1
- package/dist/otel.d.cts +1 -1
- package/dist/otel.d.mts +1 -1
- package/dist/{run-agent-CwmzAZwj.d.mts → run-agent-DBNI8ETM.d.mts} +3 -3
- package/dist/{run-agent--4bbms-D.d.cts → run-agent-Do094mGu.d.cts} +3 -3
- package/dist/{setup-agent-BFA4VKpN.cjs → setup-agent-91FSuZbB.cjs} +2 -2
- package/dist/{setup-agent-CPFPN06s.mjs → setup-agent-DqqdcdNh.mjs} +2 -2
- package/dist/sqlite.d.cts +1 -1
- package/dist/sqlite.d.mts +1 -1
- package/dist/{text-logic-Er5KkTX6.d.mts → text-logic-BR5twXCv.d.mts} +8 -5
- package/dist/{text-logic-Cavva1W6.d.cts → text-logic-Mmbgb2jy.d.cts} +8 -5
- package/dist/{types-DYpK3QF4.d.mts → types-CvWRGFxP.d.mts} +6 -1
- package/dist/{types-pJ5Hn8fv.d.cts → types-DSdj2tGs.d.cts} +6 -1
- package/dist/validate.cjs +2 -2
- package/dist/validate.mjs +1 -1
- package/package.json +28 -28
- package/readme.md +4 -4
- package/schemas/agent-workflow.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
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-
|
|
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-CvWRGFxP.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-
|
|
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-BR5twXCv.mjs";
|
|
4
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-
|
|
6
|
-
import { AnyActorLogic, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, EventFromLogic, EventObject, InputFrom, MachineContext, MetaObject, NonReducibleUnknown, SetupReturnFromConfig, SetupStateSchema, SnapshotFrom, StateValue } from "xstate";
|
|
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-DBNI8ETM.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
|
/**
|
|
@@ -121,8 +121,8 @@ interface AgentWorkflowRequestConfig {
|
|
|
121
121
|
output: JsonSchemaObject;
|
|
122
122
|
tools?: AgentTools;
|
|
123
123
|
toolChoice?: AgentToolChoice | unknown;
|
|
124
|
-
/** Opt into the structured-output envelope's `reasoning` field (see `AgentTextRequest.
|
|
125
|
-
|
|
124
|
+
/** Opt into the structured-output envelope's `reasoning` field (see `AgentTextRequest.includeReasoning`). */
|
|
125
|
+
includeReasoning?: boolean;
|
|
126
126
|
temperature?: unknown;
|
|
127
127
|
maxOutputTokens?: unknown;
|
|
128
128
|
topP?: unknown;
|
|
@@ -255,6 +255,22 @@ interface FromConfigOptions {
|
|
|
255
255
|
type Constrain<T, TConstraint> = T extends TConstraint ? T : TConstraint;
|
|
256
256
|
type ContextOf<TContextSchema extends StandardSchemaV1> = Constrain<InferOutput<TContextSchema>, MachineContext>;
|
|
257
257
|
type EventsOf<TEventSchemas extends AgentEventSchemaInputMap> = Constrain<EventUnion<TEventSchemas>, EventObject>;
|
|
258
|
+
/**
|
|
259
|
+
* The first argument a guard or delay source receives. `context` and `event`
|
|
260
|
+
* come from the agent's own schemas, so an inline source is contextually typed
|
|
261
|
+
* and an annotated one stays assignable. XState's remaining fields (`self`,
|
|
262
|
+
* `parent`, `value`, `children`, `stateNode`) are deliberately not modeled:
|
|
263
|
+
* `setupAgent` only forwards these sources to `setup()`, which types them for
|
|
264
|
+
* real where the machine is built.
|
|
265
|
+
*/
|
|
266
|
+
type AgentSourceArgs<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap> = {
|
|
267
|
+
context: ContextOf<TContextSchema>;
|
|
268
|
+
event: EventsOf<TEventSchemas>;
|
|
269
|
+
};
|
|
270
|
+
/** Guard sources for `setupAgent({ guards })`, typed against the agent's own context and events. */
|
|
271
|
+
type AgentGuardSources<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap> = Record<string, (args: AgentSourceArgs<TContextSchema, TEventSchemas>, ...params: any[]) => boolean>;
|
|
272
|
+
/** Delay sources for `setupAgent({ delays })`, typed the same way as {@link AgentGuardSources}. */
|
|
273
|
+
type AgentDelaySources<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap> = Record<string, number | ((args: AgentSourceArgs<TContextSchema, TEventSchemas>) => number)>;
|
|
258
274
|
type SetupActors<TActors extends { [K in keyof TActors]: AnyActorLogic }> = { [K in keyof TActors]: TActors[K] extends AsyncActorLogic<infer TOutput, infer TInput> ? AsyncActorLogic<TOutput, TInput> : TActors[K] };
|
|
259
275
|
type AgentSetupActors<TActors extends { [K in keyof TActors]: AnyActorLogic }, TEvent extends string = string, TModel extends string = string> = TActors & BuiltinAgentActors<TEvent, TModel>;
|
|
260
276
|
/**
|
|
@@ -407,8 +423,8 @@ type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string,
|
|
|
407
423
|
states?: TStateSchemas;
|
|
408
424
|
requests?: AgentRequestInput<TRequestSchemas, AgentModelRef<TModels>>;
|
|
409
425
|
actions?: NonNullable<AnySetupConfig["actions"]>;
|
|
410
|
-
guards?:
|
|
411
|
-
delays?:
|
|
426
|
+
guards?: AgentGuardSources<TContextSchema, TEventSchemas>;
|
|
427
|
+
delays?: AgentDelaySources<TContextSchema, TEventSchemas>;
|
|
412
428
|
/**
|
|
413
429
|
* Detects a snapshot that is an INTENTIONAL wait for an external event (a
|
|
414
430
|
* human approval, an inbound webhook, …) — the machine's own declaration of
|
|
@@ -724,8 +740,8 @@ interface LintAgentMachineOptions {
|
|
|
724
740
|
*/
|
|
725
741
|
declare function lintAgentMachine(machine: AnyStateMachine, options?: LintAgentMachineOptions): AgentLintDiagnostic[];
|
|
726
742
|
/**
|
|
727
|
-
* Thrown by `lintAgentMachine(machine, { throw: true })`
|
|
728
|
-
* failing diagnostics.
|
|
743
|
+
* Thrown by `lintAgentMachine(machine, { throw: true })` (and its
|
|
744
|
+
* {@link assertAgentMachine} alias) when lint finds failing diagnostics.
|
|
729
745
|
* `diagnostics` holds the findings; the message lists them one per finding,
|
|
730
746
|
* so a test runner's failure output reads like the CLI's lint report.
|
|
731
747
|
*/
|
|
@@ -733,6 +749,26 @@ declare class AgentLintError extends AgentError {
|
|
|
733
749
|
readonly diagnostics: AgentLintDiagnostic[];
|
|
734
750
|
constructor(machineId: string, diagnostics: AgentLintDiagnostic[]);
|
|
735
751
|
}
|
|
752
|
+
/** Options for {@link assertAgentMachine}. */
|
|
753
|
+
interface AssertAgentMachineOptions extends LintAgentMachineOptions {
|
|
754
|
+
/** Also fail on warning-severity findings. Default: errors only. */
|
|
755
|
+
warnings?: boolean;
|
|
756
|
+
}
|
|
757
|
+
/**
|
|
758
|
+
* Asserts a machine passes {@link lintAgentMachine}: returns silently when
|
|
759
|
+
* clean, throws {@link AgentLintError} (with the findings on `.diagnostics`)
|
|
760
|
+
* otherwise — sugar for `lintAgentMachine(machine, { ...options, throw: true })`.
|
|
761
|
+
* Fails on error-severity findings; set `warnings: true` to fail on warnings
|
|
762
|
+
* too. The one-liner for tests and generation loops:
|
|
763
|
+
*
|
|
764
|
+
* @example
|
|
765
|
+
* ```ts
|
|
766
|
+
* test('agent machine is structurally sound', () => {
|
|
767
|
+
* assertAgentMachine(machine);
|
|
768
|
+
* });
|
|
769
|
+
* ```
|
|
770
|
+
*/
|
|
771
|
+
declare function assertAgentMachine(machine: AnyStateMachine, options?: AssertAgentMachineOptions): void;
|
|
736
772
|
/**
|
|
737
773
|
* Scripted responses for a {@link simulateAgent} playthrough. Each channel is a
|
|
738
774
|
* by-`src` map of FIFO queues, consumed in the order the machine reaches the
|
|
@@ -740,25 +776,49 @@ declare class AgentLintError extends AgentError {
|
|
|
740
776
|
* - `text` — output values for text requests, keyed by request src (the
|
|
741
777
|
* `setupAgent({ requests })` key, or `agent.generateText`/`agent.streamText`).
|
|
742
778
|
* - `decisions` — the {@link ChosenEvent} to apply for a decision request,
|
|
743
|
-
* keyed by decision src (usually `agent.decide`).
|
|
779
|
+
* keyed by decision src (usually `agent.decide`). An invoke whose src is an
|
|
780
|
+
* inline logic object has only an auto-generated src, so its queue may be
|
|
781
|
+
* keyed by the invoke's `id` instead.
|
|
744
782
|
* - `invokes` — output values for scripted invokes (any actor whose output must
|
|
745
783
|
* be canned), keyed by src.
|
|
746
784
|
* - `userInput` — a flat FIFO queue of answers for `agent.userInput`, the
|
|
747
785
|
* shorthand for `invokes: { 'agent.userInput': [...] }`. Entries here are
|
|
748
786
|
* consumed before that src's `invokes` queue.
|
|
787
|
+
* - `events` — a flat FIFO queue of external (human/host-sent) events. When the
|
|
788
|
+
* machine settles idle with no pending request or invoke — a human gate — the
|
|
789
|
+
* next queued event is applied, so a simulation can cross states that a live
|
|
790
|
+
* run crosses via `actor.send(...)`. An event the current state cannot take
|
|
791
|
+
* (no handler, or guard-rejected) throws rather than silently vanishing.
|
|
749
792
|
*/
|
|
750
793
|
interface SimulationScript {
|
|
751
794
|
text?: Record<string, unknown[]>;
|
|
752
795
|
decisions?: Record<string, ChosenEvent[]>;
|
|
753
796
|
invokes?: Record<string, unknown[]>;
|
|
754
797
|
userInput?: unknown[];
|
|
798
|
+
events?: ChosenEvent[];
|
|
755
799
|
}
|
|
756
|
-
/**
|
|
800
|
+
/**
|
|
801
|
+
* One entry in a {@link SimulateAgentResult.trail}: the state after this step,
|
|
802
|
+
* plus what drove the step. The first entry is always the machine's initial
|
|
803
|
+
* state, with no `appliedEvent`/`resolvedRequest` — so `trail.map((e) =>
|
|
804
|
+
* e.state)` is the complete state path, directly comparable with
|
|
805
|
+
* `matchesTrajectory` without prepending the initial state by hand.
|
|
806
|
+
*/
|
|
757
807
|
interface SimulationTrailEntry {
|
|
758
808
|
/** The machine state value after applying this step. */
|
|
759
809
|
state: unknown;
|
|
760
|
-
/** The chosen event applied (for a decision request). */
|
|
810
|
+
/** The chosen event applied (for a decision request), or the external event applied (when `external`). */
|
|
761
811
|
appliedEvent?: ChosenEvent;
|
|
812
|
+
/** True when `appliedEvent` came from the script's `events` queue (an external/user event), not a decision. */
|
|
813
|
+
external?: boolean;
|
|
814
|
+
/**
|
|
815
|
+
* Scripted decisions that failed validation (unknown event, invalid payload,
|
|
816
|
+
* or guard-rejected — live-run retry parity, see {@link simulateAgent})
|
|
817
|
+
* before this step settled. Present with an `appliedEvent` when a later
|
|
818
|
+
* scripted attempt succeeded, or alone when every attempt failed and the
|
|
819
|
+
* exhaustion error was routed through the decision invoke's `onError`.
|
|
820
|
+
*/
|
|
821
|
+
rejectedEvents?: ChosenEvent[];
|
|
762
822
|
/** The resolved request (for a text/userInput invoke): its kind and src. */
|
|
763
823
|
resolvedRequest?: {
|
|
764
824
|
kind: "text" | "userInput";
|
|
@@ -787,6 +847,21 @@ interface SimulateAgentResult {
|
|
|
787
847
|
* the real transition logic. Returns the terminal `status`, final `snapshot`,
|
|
788
848
|
* and a `trail` of every step taken.
|
|
789
849
|
*
|
|
850
|
+
* Decisions run through the live run's own validation/retry core,
|
|
851
|
+
* {@link resolveDecision}, with the script standing in for the model: each
|
|
852
|
+
* attempt consumes the next queued {@link ChosenEvent} for that src, so an
|
|
853
|
+
* unknown, payload-invalid, or guard-rejected event is NOT silently swallowed
|
|
854
|
+
* — the next queued decision is tried, exactly as a live run re-asks the
|
|
855
|
+
* model. The decision logic's `maxRetries` caps attempts as it would live;
|
|
856
|
+
* when retries continue past the end of the queue, the last queued decision
|
|
857
|
+
* repeats (a scripted model that insists). The repeat applies only within one
|
|
858
|
+
* decision request's retries — each new decision request must have its own
|
|
859
|
+
* queued entry, or the dry-script error throws as usual. Exhausting all
|
|
860
|
+
* attempts delivers
|
|
861
|
+
* the resulting {@link AgentDecisionExhaustedError} to the machine as the
|
|
862
|
+
* decision invoke's error (so an `onError` transition observes it, as it
|
|
863
|
+
* would live); with no `onError` to catch it, it is thrown.
|
|
864
|
+
*
|
|
790
865
|
* Throws a descriptive error when the script runs dry mid-request, naming the
|
|
791
866
|
* pending request's kind, src, and id so the missing scripted response is
|
|
792
867
|
* obvious.
|
|
@@ -795,7 +870,10 @@ interface SimulateAgentResult {
|
|
|
795
870
|
* ```ts
|
|
796
871
|
* const { status, snapshot } = simulateAgent(machine, {
|
|
797
872
|
* input: { topic: 'state machines' },
|
|
798
|
-
* script: {
|
|
873
|
+
* script: {
|
|
874
|
+
* decisions: { 'agent.decide': [{ type: 'ESCALATE' }] },
|
|
875
|
+
* events: [{ type: 'APPROVE' }], // crosses the human gate
|
|
876
|
+
* },
|
|
799
877
|
* });
|
|
800
878
|
* ```
|
|
801
879
|
*/
|
|
@@ -872,8 +950,11 @@ interface CanReachResult {
|
|
|
872
950
|
witness?: ChosenEvent[];
|
|
873
951
|
}
|
|
874
952
|
/**
|
|
875
|
-
* Answers "can the machine reach
|
|
876
|
-
*
|
|
953
|
+
* Answers "can the machine reach this?" by exploring its branches (a thin
|
|
954
|
+
* wrapper over {@link explorePaths}). The target is either a state path string
|
|
955
|
+
* (`snapshot.matches(...)` semantics) or a snapshot predicate — the predicate
|
|
956
|
+
* form checks any property (a context invariant, a tag, a state+context
|
|
957
|
+
* combination) without reifying a sentinel state for it. Returns
|
|
877
958
|
* `{ reachable: true, witness }` with the event sequence that reaches it, or
|
|
878
959
|
* `{ reachable: false }`.
|
|
879
960
|
*
|
|
@@ -882,8 +963,18 @@ interface CanReachResult {
|
|
|
882
963
|
* const { reachable, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
|
|
883
964
|
* // reachable → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
|
|
884
965
|
* ```
|
|
966
|
+
*
|
|
967
|
+
* @example Predicate target — a violation property, no sentinel state needed
|
|
968
|
+
* ```ts
|
|
969
|
+
* const violation = await canReach(
|
|
970
|
+
* refundMachine,
|
|
971
|
+
* (snapshot) => snapshot.matches('issued') && !snapshot.context.approved,
|
|
972
|
+
* { input: { amount: 5000 } },
|
|
973
|
+
* );
|
|
974
|
+
* // violation.reachable → false is the safety proof
|
|
975
|
+
* ```
|
|
885
976
|
*/
|
|
886
|
-
declare function canReach(machine: AnyStateMachine,
|
|
977
|
+
declare function canReach(machine: AnyStateMachine, target: string | ((snapshot: AnyMachineSnapshot) => boolean), options?: ExplorePathsOptions): Promise<CanReachResult>;
|
|
887
978
|
//#endregion
|
|
888
979
|
//#region src/trajectory.d.ts
|
|
889
980
|
/** An event-shaped trajectory item: anything with a string `type`. */
|
|
@@ -1204,6 +1295,26 @@ interface SeamTurn<TMachine extends AnyStateMachine> {
|
|
|
1204
1295
|
/** The `idle` result that produced the pause. */
|
|
1205
1296
|
result: RunAgentResult<TMachine>;
|
|
1206
1297
|
}
|
|
1298
|
+
/**
|
|
1299
|
+
* One text call in a {@link runSeam} run's ledger, in call order — the receipt
|
|
1300
|
+
* that says which answers came from the script and which one came from the
|
|
1301
|
+
* candidate, so "everything else stayed scripted" is a plain assertion on
|
|
1302
|
+
* {@link RunSeamResult.calls} rather than a recording function wrapped around
|
|
1303
|
+
* every script entry. Text calls only: `decide` and other base executors are
|
|
1304
|
+
* not routed by the seam and do not appear.
|
|
1305
|
+
*/
|
|
1306
|
+
interface SeamCall {
|
|
1307
|
+
/** The request's `name`, when it has one. */
|
|
1308
|
+
name?: string;
|
|
1309
|
+
/** The request's model key. */
|
|
1310
|
+
model: string;
|
|
1311
|
+
/** The `scripts` queue key that routed this call. */
|
|
1312
|
+
key: string;
|
|
1313
|
+
/** Where the answer came from: the script, or the seam's `candidate`. */
|
|
1314
|
+
source: "script" | "candidate";
|
|
1315
|
+
/** True for the seam call itself — scripted or candidate. */
|
|
1316
|
+
seam: boolean;
|
|
1317
|
+
}
|
|
1207
1318
|
/** One side of the seam: a trajectory pair ready for `matchesTrajectory`. */
|
|
1208
1319
|
interface SeamSlice {
|
|
1209
1320
|
/** State values entered on this side of the seam, in order. */
|
|
@@ -1240,7 +1351,7 @@ interface RunSeamOptions<TMachine extends AnyStateMachine> {
|
|
|
1240
1351
|
* request-shaped. Omit to run the seam scripted too: the whole seam run is
|
|
1241
1352
|
* then keyless and deterministic.
|
|
1242
1353
|
*/
|
|
1243
|
-
candidate?:
|
|
1354
|
+
candidate?: AgentRequestExecutor;
|
|
1244
1355
|
/**
|
|
1245
1356
|
* The simulated user. Called at every idle pause; return the event to send,
|
|
1246
1357
|
* or `null`/`undefined` to stop the run there. Omitted, the run stops at the
|
|
@@ -1269,8 +1380,17 @@ interface RunSeamResult<TMachine extends AnyStateMachine> {
|
|
|
1269
1380
|
result: RunAgentResult<TMachine>;
|
|
1270
1381
|
/** What the seam call returned, or `undefined` when the run never reached it. */
|
|
1271
1382
|
seamOutput: unknown;
|
|
1383
|
+
/**
|
|
1384
|
+
* The seam call's own reported token usage — the cost of the one live call
|
|
1385
|
+
* when a `candidate` is a real model. `undefined` when the run never reached
|
|
1386
|
+
* the seam or its answer reported no usage (scripted entries report usage
|
|
1387
|
+
* only via the `{ output, usage }` envelope).
|
|
1388
|
+
*/
|
|
1389
|
+
seamUsage?: AgentCallUsage;
|
|
1272
1390
|
/** Model calls made before the seam, or `-1` when the run never reached it. */
|
|
1273
1391
|
callsBeforeSeam: number;
|
|
1392
|
+
/** The run's text calls in order: what was served, and by whom. */
|
|
1393
|
+
calls: SeamCall[];
|
|
1274
1394
|
/** Everything up to the seam's own effect completion. */
|
|
1275
1395
|
before: SeamSlice;
|
|
1276
1396
|
/**
|
|
@@ -1309,4 +1429,76 @@ interface RunSeamResult<TMachine extends AnyStateMachine> {
|
|
|
1309
1429
|
*/
|
|
1310
1430
|
declare function runSeam<TMachine extends AnyStateMachine>(machine: TMachine, options: RunSeamOptions<TMachine>): Promise<RunSeamResult<TMachine>>;
|
|
1311
1431
|
//#endregion
|
|
1312
|
-
|
|
1432
|
+
//#region src/durable.d.ts
|
|
1433
|
+
/** Options for {@link runDurableAgent}. */
|
|
1434
|
+
interface RunDurableAgentOptions<TMachine extends AnyStateMachine> extends Pick<ProvideExecutorsOptions<TMachine>, "actors" | "onChunk" | "onTrace"> {
|
|
1435
|
+
/** Machine input for a FRESH run (ignored when `entries` has an init entry). */
|
|
1436
|
+
input?: InputFrom<TMachine>;
|
|
1437
|
+
/**
|
|
1438
|
+
* The journal to resume from — the `entries` a previous
|
|
1439
|
+
* {@link runDurableAgent} result returned (or any replay-compatible
|
|
1440
|
+
* {@link AgentLogEntry} log with a reserved `@agent.init` first entry).
|
|
1441
|
+
*/
|
|
1442
|
+
entries?: readonly AgentLogEntry[];
|
|
1443
|
+
/** One external event to feed after the journal is folded (a user reply, a timer). */
|
|
1444
|
+
event?: EventFromLogic<TMachine>;
|
|
1445
|
+
/** Host executors, bound with {@link provideExecutors} semantics. */
|
|
1446
|
+
executors?: AgentRequestExecutors;
|
|
1447
|
+
/** Called with each entry as it is appended, for incremental persistence. */
|
|
1448
|
+
onEntry?: (entry: AgentLogEntry) => void;
|
|
1449
|
+
/**
|
|
1450
|
+
* Settle `idle` when this returns true for the current snapshot even though
|
|
1451
|
+
* children are still pending — for machines whose wait states keep a
|
|
1452
|
+
* never-resolving invoke in flight (e.g. an unbound `agent.userInput`).
|
|
1453
|
+
*/
|
|
1454
|
+
isIdle?: (snapshot: SnapshotFrom<TMachine>) => boolean;
|
|
1455
|
+
/** Explicit machine version for entry stamping; defaults to the structural hash. */
|
|
1456
|
+
machineVersion?: string;
|
|
1457
|
+
/**
|
|
1458
|
+
* Record replay-verification hashes on appended entries. Off by default:
|
|
1459
|
+
* hashing replays the whole prefix per entry, which is quadratic in log
|
|
1460
|
+
* length.
|
|
1461
|
+
*/
|
|
1462
|
+
verification?: boolean;
|
|
1463
|
+
}
|
|
1464
|
+
/** The settled result of a {@link runDurableAgent} call. */
|
|
1465
|
+
type DurableAgentResult<TMachine extends AnyStateMachine> = {
|
|
1466
|
+
/** The machine reached a final state. */status: "done";
|
|
1467
|
+
output: OutputFrom<TMachine>;
|
|
1468
|
+
snapshot: SnapshotFrom<TMachine>; /** The complete journal; replaying it reproduces this run. */
|
|
1469
|
+
entries: AgentLogEntry[];
|
|
1470
|
+
} | {
|
|
1471
|
+
/** The machine is waiting for an external event. Persist `entries`; resume with them plus `event`. */status: "idle";
|
|
1472
|
+
snapshot: SnapshotFrom<TMachine>;
|
|
1473
|
+
entries: AgentLogEntry[];
|
|
1474
|
+
};
|
|
1475
|
+
/**
|
|
1476
|
+
* Runs an agent machine as a durable execution: journal in, journal out.
|
|
1477
|
+
*
|
|
1478
|
+
* A fresh call starts from `input` and appends a reserved init entry; a
|
|
1479
|
+
* resume call folds `entries` through pure transitions first — invokes whose
|
|
1480
|
+
* completions are journaled are suppressed (their recorded results replay
|
|
1481
|
+
* instead of re-executing), while work that was in flight at the crash
|
|
1482
|
+
* re-executes live. After the journal, an optional `options.event` is
|
|
1483
|
+
* delivered. The call settles:
|
|
1484
|
+
*
|
|
1485
|
+
* - `done` when the machine reaches a final state, with `output`;
|
|
1486
|
+
* - `idle` when the frontier needs an external event the host has not
|
|
1487
|
+
* supplied (no live work pending, or `isIdle` says the pending work is a
|
|
1488
|
+
* human wait). Persist `entries` and call again with them later.
|
|
1489
|
+
*
|
|
1490
|
+
* ```ts
|
|
1491
|
+
* const first = await runDurableAgent(machine, { input, executors });
|
|
1492
|
+
* // ... persist first.entries; later, in a new process:
|
|
1493
|
+
* const next = await runDurableAgent(machine, {
|
|
1494
|
+
* entries: first.entries,
|
|
1495
|
+
* event: { type: "APPROVE" },
|
|
1496
|
+
* executors,
|
|
1497
|
+
* });
|
|
1498
|
+
* ```
|
|
1499
|
+
*
|
|
1500
|
+
* @experimental Built on xstate's experimental `xstate/durable` entrypoint.
|
|
1501
|
+
*/
|
|
1502
|
+
declare function runDurableAgent<TMachine extends AnyStateMachine>(machine: TMachine, options?: RunDurableAgentOptions<TMachine>): Promise<DurableAgentResult<TMachine>>;
|
|
1503
|
+
//#endregion
|
|
1504
|
+
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 AssertAgentMachineOptions, 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 SeamCall, 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, assertAgentMachine, 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 };
|