@statelyai/agent 2.0.0-alpha.5 → 2.0.0-alpha.7
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 +67 -5
- package/dist/ai-sdk.d.cts +11 -2
- package/dist/ai-sdk.d.mts +11 -2
- package/dist/ai-sdk.mjs +68 -7
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/{decision-pC-bY2DE.cjs → decision-BnATHy0W.cjs} +58 -3
- package/dist/{decision-FTmbqSEe.mjs → decision-mPR_YQd8.mjs} +41 -4
- package/dist/index.cjs +4 -2
- package/dist/index.d.cts +47 -14
- package/dist/index.d.mts +47 -14
- package/dist/index.mjs +3 -3
- package/dist/openai-compat.cjs +1 -1
- package/dist/openai-compat.d.cts +1 -1
- package/dist/openai-compat.d.mts +1 -1
- package/dist/openai-compat.mjs +1 -1
- package/dist/{src-CjpHDU8F.mjs → src-BpQdxsKc.mjs} +69 -19
- package/dist/{src-DcRsWPfV.cjs → src-MysDmqwT.cjs} +69 -19
- package/dist/{text-logic-2EMJIS-n.d.mts → text-logic-2wFNEznm.d.mts} +33 -5
- package/dist/{text-logic-1ZQkO3zr.d.cts → text-logic-4Q2F9kyr.d.cts} +33 -5
- package/package.json +2 -2
- package/readme.md +1 -0
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { C as ToolCallPart, D as UserMessage, E as ToolResultPart, S as TextPart, T as ToolResultOutput, _ as ImagePart, a as AgentToolDescriptor, b as StandardSchemaV1, c as AgentTools, d as AssistantMessage, f as ChosenEvent, g as FilePart, h as EventUnion, i as AgentToolChoice, l as AllowedEventPattern, m as EventPayload, n as AgentSnapshotStore, o as AgentToolExecute, p as DataContent, r as AgentTool, s as AgentToolSchema, t as AgentMessage, u as AllowedEvents, v as InferOutput, w as ToolMessage, x as SystemMessage, y as ProviderOptions } from "./types-Cq1YlAQ6.mjs";
|
|
2
|
-
import { A as
|
|
2
|
+
import { A as AgentDecisionInput, B as renderDecisionAttempts, C as createTextLogic, D as parseOutput, E as parseModelRef, F as DecisionExhaustedError, G as AgentRequestSource, H as AgentEventDescriptor, I as DecisionLogic, J as matchesEventPattern, K as EVENT_TOOL_PREFIX, L as DecisionLogicConfig, M as AgentPlanInput, N as AgentPlanOutput, O as parseStructuredEnvelope, P as DecisionAttempt, R as PLAN_DONE_EVENT_TYPE, S as buildEnvelopeSchema, T as isStructuredOutputSchema, U as AgentEventToolNameResolver, V as resolveDecision, W as AgentRequestOptions, Y as parseAgentEvent, _ as TextLogicExecuteArgs, a as AgentRequestExecutorInfo, b as TextLogicOutput, c as AgentRequestMode, d as AiSdkShapedStreamResult, f as AiSdkShapedTextResult, g as TextLogicConfig, h as TextLogic, i as AgentRequestExecutor, j as AgentDecisionRequest, k as AgentDecisionExecutor, l as AgentTextRequest, m as StructuredOutputEnvelope, n as AgentModelRef, o as AgentRequestExecutorResult, p as BuiltinAgentActors, q as getAcceptedEvents, r as AgentOutputMode, s as AgentRequestExecutors, t as AgentModelMap, u as AgentUserInput, v as TextLogicExecutor, w as getAgentOutputMode, x as bindRequestExecutor, y as TextLogicInput, z as ResolveDecisionOptions } from "./text-logic-2wFNEznm.mjs";
|
|
3
3
|
import { a as getMachineStructuralHash, c as persistSnapshot, d as userMessage, f as validateSchemaSync, i as getJsonSchemaSync, l as systemMessage, n as getAgentMessages, o as getStateMeta, r as getJsonSchema, s as isStandardSchema, t as assistantMessage, u as toolMessage } from "./utils-CWUCa3pF.mjs";
|
|
4
4
|
import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, InputFrom, InspectionEvent, MachineContext, MetaObject, NonReducibleUnknown, OutputFrom, SetupReturnFromConfig, SetupStateSchema, Snapshot, SnapshotFrom } from "xstate";
|
|
5
5
|
|
|
@@ -256,16 +256,49 @@ type AgentSetupXStateConfig<TContextSchema extends StandardSchemaV1<Record<strin
|
|
|
256
256
|
guards?: NonNullable<AnySetupConfig["guards"]>;
|
|
257
257
|
delays?: NonNullable<AnySetupConfig["delays"]>;
|
|
258
258
|
};
|
|
259
|
-
|
|
259
|
+
/**
|
|
260
|
+
* Field-level context-narrowing sugar for one `setupAgent({ states })` entry:
|
|
261
|
+
* each `context` entry overrides that field's schema inside the state; every
|
|
262
|
+
* other field keeps the base context schema. Sugar for the full xstate form —
|
|
263
|
+
* `{ context: { draft: z.string() } }` resolves to
|
|
264
|
+
* `{ schemas: { context: <base with draft: string> } }` — so only the fields
|
|
265
|
+
* that change are declared, not the whole context schema.
|
|
266
|
+
*/
|
|
267
|
+
interface AgentStateNarrowing {
|
|
268
|
+
context: Record<string, StandardSchemaV1>;
|
|
269
|
+
states?: Record<string, AgentSetupStateSchema>;
|
|
270
|
+
}
|
|
271
|
+
/** One `setupAgent({ states })` entry: xstate's {@link SetupStateSchema} full form, or the {@link AgentStateNarrowing} field-level sugar. */
|
|
272
|
+
type AgentSetupStateSchema = SetupStateSchema | AgentStateNarrowing;
|
|
273
|
+
type NarrowedContext<TContextSchema extends StandardSchemaV1, TFields extends Record<string, StandardSchemaV1>> = Omit<InferOutput<TContextSchema>, keyof TFields> & { [K in keyof TFields]: InferOutput<TFields[K]> };
|
|
274
|
+
type ResolveAgentStateSchema<TContextSchema extends StandardSchemaV1, T> = T extends {
|
|
275
|
+
context: infer TFields extends Record<string, StandardSchemaV1>;
|
|
276
|
+
} ? {
|
|
277
|
+
schemas: {
|
|
278
|
+
context: StandardSchemaV1<NarrowedContext<TContextSchema, TFields>>;
|
|
279
|
+
};
|
|
280
|
+
} & (T extends {
|
|
281
|
+
states: infer TChildren extends Record<string, AgentSetupStateSchema>;
|
|
282
|
+
} ? {
|
|
283
|
+
states: ResolveAgentStateSchemas<TContextSchema, TChildren>;
|
|
284
|
+
} : {}) : T extends {
|
|
285
|
+
states: infer TChildren extends Record<string, AgentSetupStateSchema>;
|
|
286
|
+
} ? Omit<T, "states"> & {
|
|
287
|
+
states: ResolveAgentStateSchemas<TContextSchema, TChildren>;
|
|
288
|
+
} : T;
|
|
289
|
+
type ResolveAgentStateSchemas<TContextSchema extends StandardSchemaV1, TStates extends Record<string, AgentSetupStateSchema>> = Constrain<{ [K in keyof TStates]: ResolveAgentStateSchema<TContextSchema, TStates[K]> }, Record<string, SetupStateSchema>>;
|
|
290
|
+
type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TRequestSchemas extends AgentRequestSchemaMap, TModels extends AgentModelMap, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, TStateSchemas extends Record<string, AgentSetupStateSchema> = Record<string, AgentSetupStateSchema>> = ({
|
|
260
291
|
schemas: AgentSchemaPack<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>;
|
|
261
292
|
} | AgentSchemaConfig<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>) & {
|
|
262
293
|
models?: TModels;
|
|
263
294
|
actorSources?: TActors;
|
|
264
295
|
/**
|
|
265
|
-
* Per-state schemas, mirroring xstate's `setup({ states })`:
|
|
266
|
-
* `
|
|
267
|
-
*
|
|
268
|
-
*
|
|
296
|
+
* Per-state schemas, mirroring xstate's `setup({ states })`: narrow
|
|
297
|
+
* `context` inside a state (invoke `input`, transition fns, final `output`)
|
|
298
|
+
* — e.g. mark a field non-null in states only reachable after it is set.
|
|
299
|
+
* Two forms per state: the {@link AgentStateNarrowing} sugar
|
|
300
|
+
* (`{ context: { draft: z.string() } }` — only the fields that change) or
|
|
301
|
+
* xstate's full `{ schemas: { context } }` with a complete context schema.
|
|
269
302
|
*/
|
|
270
303
|
states?: TStateSchemas;
|
|
271
304
|
requests?: AgentRequestInput<TRequestSchemas, AgentModelRef<TModels>>;
|
|
@@ -284,7 +317,7 @@ type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string,
|
|
|
284
317
|
*/
|
|
285
318
|
isSuspended?: (snapshot: AnyMachineSnapshot) => boolean;
|
|
286
319
|
};
|
|
287
|
-
type SetupAgentXStateResult<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, 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,
|
|
320
|
+
type SetupAgentXStateResult<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, 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>>>;
|
|
288
321
|
/**
|
|
289
322
|
* The object returned by {@link setupAgent}: an xstate `setup(...)` result
|
|
290
323
|
* (`createMachine`, `assign`, …) extended with `schemas` (the resolved
|
|
@@ -293,7 +326,7 @@ type SetupAgentXStateResult<TContextSchema extends StandardSchemaV1<Record<strin
|
|
|
293
326
|
* `runAgent` and the free step helpers can resolve their schemas/actors
|
|
294
327
|
* without re-passing them each call.
|
|
295
328
|
*/
|
|
296
|
-
type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, 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,
|
|
329
|
+
type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, 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>> = Omit<SetupAgentXStateResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>, "createMachine"> & {
|
|
297
330
|
/**
|
|
298
331
|
* Creates the agent machine — XState's own `createMachine`, plus: the
|
|
299
332
|
* machine is registered so step helpers and {@link runAgent} can resolve
|
|
@@ -358,7 +391,7 @@ type SetupAgentResult<TContextSchema extends StandardSchemaV1<Record<string, unk
|
|
|
358
391
|
* });
|
|
359
392
|
* ```
|
|
360
393
|
*/
|
|
361
|
-
declare function setupAgent<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap = {}, TInputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TMetaSchema extends StandardSchemaV1 = StandardSchemaV1<MetaObject>, TModels extends AgentModelMap = {}, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, const TStateSchemas extends Record<string,
|
|
394
|
+
declare function setupAgent<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends Record<string, StandardSchemaV1>, TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap = {}, TInputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TMetaSchema extends StandardSchemaV1 = StandardSchemaV1<MetaObject>, TModels extends AgentModelMap = {}, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}, const TStateSchemas extends Record<string, AgentSetupStateSchema> = Record<string, AgentSetupStateSchema>>(config: SetupAgentBaseConfig<TContextSchema, TEventSchemas, TActors, TInputSchema, TOutputSchema, TMetaSchema, TRequestSchemas, TModels, TEmittedSchemas, TStateSchemas>): SetupAgentResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>;
|
|
362
395
|
declare namespace setupAgent {
|
|
363
396
|
/**
|
|
364
397
|
* Builds a state machine from a serializable {@link AgentWorkflowConfig}
|
|
@@ -658,9 +691,9 @@ declare class AgentIdleError extends Error {
|
|
|
658
691
|
readonly acceptedTypes: string[];
|
|
659
692
|
constructor(snapshot: AnyMachineSnapshot, acceptedTypes: string[]);
|
|
660
693
|
}
|
|
661
|
-
/** Handler for `agent.userInput` invokes passed as {@link RunAgentOptions.userInput}. */
|
|
694
|
+
/** Handler for `agent.userInput` invokes passed as {@link RunAgentOptions.userInput}. Resolves to what the human typed. */
|
|
662
695
|
interface AgentUserInputExecutor {
|
|
663
|
-
(input: AgentUserInput): PromiseLike<
|
|
696
|
+
(input: AgentUserInput): PromiseLike<string>;
|
|
664
697
|
}
|
|
665
698
|
type AgentTraceEvent<TMachine extends AnyStateMachine = AnyStateMachine> = {
|
|
666
699
|
runId: string;
|
|
@@ -842,7 +875,7 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
|
|
|
842
875
|
* that sends no event settles idle. Every model call counts against
|
|
843
876
|
* `maxModelCalls`.
|
|
844
877
|
*/
|
|
845
|
-
getRequests?: (snapshot: SnapshotFrom<TMachine>,
|
|
878
|
+
getRequests?: (snapshot: SnapshotFrom<TMachine>, agentContext: {
|
|
846
879
|
messages: readonly AgentMessage[];
|
|
847
880
|
}) => AgentStateRequest | readonly AgentStateRequest[] | undefined;
|
|
848
881
|
/**
|
|
@@ -924,7 +957,7 @@ interface RunAgentOptions<TMachine extends AnyStateMachine> {
|
|
|
924
957
|
* actor is stopped on every settle path — there is no live actor to resume;
|
|
925
958
|
* resume is always by snapshot.
|
|
926
959
|
*/
|
|
927
|
-
/** A pending unhandled `agent.userInput` invoke surfaced on an idle settle — `id` is the invoke's id, `input` its resolved invoke input (prompt,
|
|
960
|
+
/** A pending unhandled `agent.userInput` invoke surfaced on an idle settle — `id` is the invoke's id, `input` its resolved invoke input (prompt, metadata). Answer it by resuming with a `userInput` handler. */
|
|
928
961
|
interface PendingUserInput {
|
|
929
962
|
id: string;
|
|
930
963
|
input: AgentUserInput | undefined;
|
|
@@ -1214,4 +1247,4 @@ interface CanReachResult {
|
|
|
1214
1247
|
*/
|
|
1215
1248
|
declare function canReach(machine: AnyStateMachine, statePath: string, options?: ExplorePathsOptions): Promise<CanReachResult>;
|
|
1216
1249
|
//#endregion
|
|
1217
|
-
export { type AgentDecisionExecutor, type AgentDecisionInput, type AgentDecisionRequest, type AgentEventDescriptor, type AgentEventToolNameResolver, AgentIdleError, type AgentLintDiagnostic, type AgentLintSeverity, type AgentMessage, type AgentModelMap, type AgentModelRef, type AgentOutputMode, type AgentPathReport, type AgentPathTerminal, type AgentPlanInput, type AgentPlanOutput, type AgentPlanRequest, type AgentRequest, type AgentRequestConfig, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestMode, type AgentRequestOptions, type AgentRequestSource, type AgentSchemaPack, type AgentSnapshotStore, type AgentStateRequest, type AgentStep, type AgentStepRequest, type AgentTextRequest, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentToolSchema, type AgentTools, type AgentTraceEvent, type AgentUserInput, type AgentUserInputExecutor, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AiSdkShapedStreamResult, type AiSdkShapedTextResult, type AllowedEventPattern, type AllowedEvents, type AssistantMessage, type CanReachResult, type ChosenEvent, type DataContent, type DecisionAttempt, DecisionExhaustedError, type DecisionLogic, type DecisionLogicConfig, EVENT_TOOL_PREFIX, type EventPayload, type EventUnion, type ExplorePathsOptions, type FilePart, type FromConfigOptions, IllegalResumeEventError, type ImagePart, type InferOutput, type InspectedActorRef, type LintAgentMachineOptions, PLAN_DONE_EVENT_TYPE, type PendingUserInput, type ProviderOptions, type ResolveAgentRequestsOptions, type ResolveDecisionOptions, type RunAgentOptions, type RunAgentResult, type SchemaCompiler, type SimulateAgentOptions, type SimulateAgentResult, type SimulationScript, type SimulationTrailEntry, SnapshotVersionMismatchError, type StandardSchemaV1, type StructuredOutputEnvelope, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextLogicInput, type TextLogicOutput, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultOutput, type ToolResultPart, type UserMessage, appendMessages, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentSchemas, createTextLogic, executeAgentRequest, explorePaths, getAcceptedEvents, getAgentMessages, getAgentOutputMode, getAgentRequests, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getStateMeta, initialAgentStep, inspectTransitions, isStandardSchema, isStructuredOutputSchema, lintAgentMachine, matchesEventPattern, messagesSchema, parseAgentEvent, parseOutput, persistSnapshot, renderDecisionAttempts, resolveAgentRequests, resolveAgentStep, resolveDecision, runAgent, runAgentToCompletion, setupAgent, simulateAgent, systemMessage, toolMessage, transitionAgentStep, userMessage, validateSchemaSync };
|
|
1250
|
+
export { type AgentDecisionExecutor, type AgentDecisionInput, type AgentDecisionRequest, type AgentEventDescriptor, type AgentEventToolNameResolver, AgentIdleError, type AgentLintDiagnostic, type AgentLintSeverity, type AgentMessage, type AgentModelMap, type AgentModelRef, type AgentOutputMode, type AgentPathReport, type AgentPathTerminal, type AgentPlanInput, type AgentPlanOutput, type AgentPlanRequest, type AgentRequest, type AgentRequestConfig, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestMode, type AgentRequestOptions, type AgentRequestSource, type AgentSchemaPack, type AgentSetupStateSchema, type AgentSnapshotStore, type AgentStateNarrowing, type AgentStateRequest, type AgentStep, type AgentStepRequest, type AgentTextRequest, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentToolSchema, type AgentTools, type AgentTraceEvent, type AgentUserInput, type AgentUserInputExecutor, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AiSdkShapedStreamResult, type AiSdkShapedTextResult, type AllowedEventPattern, type AllowedEvents, type AssistantMessage, type CanReachResult, type ChosenEvent, type DataContent, type DecisionAttempt, DecisionExhaustedError, type DecisionLogic, type DecisionLogicConfig, EVENT_TOOL_PREFIX, type EventPayload, type EventUnion, type ExplorePathsOptions, type FilePart, type FromConfigOptions, IllegalResumeEventError, type ImagePart, type InferOutput, type InspectedActorRef, type LintAgentMachineOptions, PLAN_DONE_EVENT_TYPE, type PendingUserInput, type ProviderOptions, type ResolveAgentRequestsOptions, type ResolveDecisionOptions, type RunAgentOptions, type RunAgentResult, type SchemaCompiler, type SimulateAgentOptions, type SimulateAgentResult, type SimulationScript, type SimulationTrailEntry, SnapshotVersionMismatchError, type StandardSchemaV1, type StructuredOutputEnvelope, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextLogicInput, type TextLogicOutput, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultOutput, type ToolResultPart, type UserMessage, appendMessages, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentSchemas, createTextLogic, executeAgentRequest, explorePaths, getAcceptedEvents, getAgentMessages, getAgentOutputMode, getAgentRequests, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getStateMeta, initialAgentStep, inspectTransitions, isStandardSchema, isStructuredOutputSchema, lintAgentMachine, matchesEventPattern, messagesSchema, parseAgentEvent, parseModelRef, parseOutput, parseStructuredEnvelope, persistSnapshot, renderDecisionAttempts, resolveAgentRequests, resolveAgentStep, resolveDecision, runAgent, runAgentToCompletion, setupAgent, simulateAgent, systemMessage, toolMessage, transitionAgentStep, userMessage, validateSchemaSync };
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { _ as createAgentSchemas, a as AgentIdleError, b as messagesSchema, c as inspectTransitions, d as executeAgentRequest, f as getAgentRequests, g as transitionAgentStep, h as resolveAgentStep, i as simulateAgent, l as runAgent, m as resolveAgentRequests, n as explorePaths, o as IllegalResumeEventError, p as initialAgentStep, r as lintAgentMachine, s as SnapshotVersionMismatchError, t as canReach, u as runAgentToCompletion, v as setupAgent, y as appendMessages } from "./src-
|
|
2
|
-
import { B as
|
|
3
|
-
export { AgentIdleError, DecisionExhaustedError, EVENT_TOOL_PREFIX, IllegalResumeEventError, PLAN_DONE_EVENT_TYPE, SnapshotVersionMismatchError, appendMessages, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentSchemas, createTextLogic, executeAgentRequest, explorePaths, getAcceptedEvents, getAgentMessages, getAgentOutputMode, getAgentRequests, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getStateMeta, initialAgentStep, inspectTransitions, isStandardSchema, isStructuredOutputSchema, lintAgentMachine, matchesEventPattern, messagesSchema, parseAgentEvent, parseOutput, persistSnapshot, renderDecisionAttempts, resolveAgentRequests, resolveAgentStep, resolveDecision, runAgent, runAgentToCompletion, setupAgent, simulateAgent, systemMessage, toolMessage, transitionAgentStep, userMessage, validateSchemaSync };
|
|
1
|
+
import { _ as createAgentSchemas, a as AgentIdleError, b as messagesSchema, c as inspectTransitions, d as executeAgentRequest, f as getAgentRequests, g as transitionAgentStep, h as resolveAgentStep, i as simulateAgent, l as runAgent, m as resolveAgentRequests, n as explorePaths, o as IllegalResumeEventError, p as initialAgentStep, r as lintAgentMachine, s as SnapshotVersionMismatchError, t as canReach, u as runAgentToCompletion, v as setupAgent, y as appendMessages } from "./src-BpQdxsKc.mjs";
|
|
2
|
+
import { A as parseOutput, B as assistantMessage, C as createTextLogic, E as isStructuredOutputSchema, G as getMachineStructuralHash, H as getAgentMessages, J as persistSnapshot, K as getStateMeta, Q as validateSchemaSync, T as getAgentOutputMode, U as getJsonSchema, W as getJsonSchemaSync, X as toolMessage, Y as systemMessage, Z as userMessage, b as bindRequestExecutor, d as EVENT_TOOL_PREFIX, f as getAcceptedEvents, j as parseStructuredEnvelope, k as parseModelRef, l as renderDecisionAttempts, m as parseAgentEvent, n as PLAN_DONE_EVENT_TYPE, p as matchesEventPattern, q as isStandardSchema, t as DecisionExhaustedError, u as resolveDecision, x as buildEnvelopeSchema } from "./decision-mPR_YQd8.mjs";
|
|
3
|
+
export { AgentIdleError, DecisionExhaustedError, EVENT_TOOL_PREFIX, IllegalResumeEventError, PLAN_DONE_EVENT_TYPE, SnapshotVersionMismatchError, appendMessages, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentSchemas, createTextLogic, executeAgentRequest, explorePaths, getAcceptedEvents, getAgentMessages, getAgentOutputMode, getAgentRequests, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getStateMeta, initialAgentStep, inspectTransitions, isStandardSchema, isStructuredOutputSchema, lintAgentMachine, matchesEventPattern, messagesSchema, parseAgentEvent, parseModelRef, parseOutput, parseStructuredEnvelope, persistSnapshot, renderDecisionAttempts, resolveAgentRequests, resolveAgentStep, resolveDecision, runAgent, runAgentToCompletion, setupAgent, simulateAgent, systemMessage, toolMessage, transitionAgentStep, userMessage, validateSchemaSync };
|
package/dist/openai-compat.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_decision = require("./decision-
|
|
2
|
+
const require_decision = require("./decision-BnATHy0W.cjs");
|
|
3
3
|
//#region src/openai-compat/index.ts
|
|
4
4
|
/**
|
|
5
5
|
* OpenAI-compatible Chat Completions adapter — a COMPLETE `{ generateText,
|
package/dist/openai-compat.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { c as AgentTools } from "./types-BHjeDdch.cjs";
|
|
2
|
-
import {
|
|
2
|
+
import { H as AgentEventDescriptor, j as AgentDecisionRequest, k as AgentDecisionExecutor, l as AgentTextRequest, s as AgentRequestExecutors } from "./text-logic-4Q2F9kyr.cjs";
|
|
3
3
|
import { r as getJsonSchema } from "./utils-lK1wnL2i.cjs";
|
|
4
4
|
|
|
5
5
|
//#region src/openai-compat/index.d.ts
|
package/dist/openai-compat.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { c as AgentTools } from "./types-Cq1YlAQ6.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { H as AgentEventDescriptor, j as AgentDecisionRequest, k as AgentDecisionExecutor, l as AgentTextRequest, s as AgentRequestExecutors } from "./text-logic-2wFNEznm.mjs";
|
|
3
3
|
import { r as getJsonSchema } from "./utils-CWUCa3pF.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/openai-compat/index.d.ts
|
package/dist/openai-compat.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { T as getAgentOutputMode, U as getJsonSchema, W as getJsonSchemaSync, l as renderDecisionAttempts, q as isStandardSchema, x as buildEnvelopeSchema } from "./decision-mPR_YQd8.mjs";
|
|
2
2
|
//#region src/openai-compat/index.ts
|
|
3
3
|
/**
|
|
4
4
|
* OpenAI-compatible Chat Completions adapter — a COMPLETE `{ generateText,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { B as assistantMessage, C as createTextLogic, D as isTextLogic, F as getMachineSuspensionPredicate, G as getMachineStructuralHash, H as getAgentMessages, I as getRegisteredAgentExecutionOptions, L as isUnboundPlaceholder, M as userInputActor, N as agentExecutionOptions, O as normalizeGeneratorResult, P as executorBoundLogics, Q as validateSchemaSync, R as machineSuspensionPredicates, S as builtinTextActors, V as findNonSerializableContextPaths, W as getJsonSchemaSync, Z as userMessage, _ as INTERPRET_SOURCE, a as createPlanActor, c as isPlanLogic, f as getAcceptedEvents, g as DECIDE_ACTOR, h as sanitizeEventToolName, i as createDecideActor, n as PLAN_DONE_EVENT_TYPE, o as initialPlanLedger, r as advancePlanLedger, s as isDecisionLogic, t as DecisionExhaustedError, u as resolveDecision, v as PLAN_ACTOR, w as executeAgentTextRequest, y as USER_INPUT_ACTOR, z as missingActor } from "./decision-mPR_YQd8.mjs";
|
|
2
2
|
import { createActor, createAsyncLogic, getNextTransitions, initialTransition, setup, transition } from "xstate";
|
|
3
3
|
//#region src/messages.ts
|
|
4
4
|
function addMessages(resolve) {
|
|
@@ -278,6 +278,43 @@ function createAgentSchemas(schemas) {
|
|
|
278
278
|
emitted: schemas.emitted
|
|
279
279
|
};
|
|
280
280
|
}
|
|
281
|
+
function mergeContextSchema(base, fields) {
|
|
282
|
+
return { "~standard": {
|
|
283
|
+
version: 1,
|
|
284
|
+
vendor: "statelyai-agent",
|
|
285
|
+
validate(value) {
|
|
286
|
+
const baseResult = base["~standard"].validate(value);
|
|
287
|
+
if (baseResult instanceof Promise) throw new Error("setupAgent: async context schemas are not supported.");
|
|
288
|
+
if (baseResult.issues) return baseResult;
|
|
289
|
+
const merged = { ...baseResult.value };
|
|
290
|
+
const issues = [];
|
|
291
|
+
for (const [key, fieldSchema] of Object.entries(fields)) {
|
|
292
|
+
const fieldResult = fieldSchema["~standard"].validate(value[key]);
|
|
293
|
+
if (fieldResult instanceof Promise) throw new Error("setupAgent: async context schemas are not supported.");
|
|
294
|
+
if (fieldResult.issues) issues.push(...fieldResult.issues.map((issue) => ({
|
|
295
|
+
...issue,
|
|
296
|
+
path: [key, ...issue.path ?? []]
|
|
297
|
+
})));
|
|
298
|
+
else merged[key] = fieldResult.value;
|
|
299
|
+
}
|
|
300
|
+
return issues.length > 0 ? { issues } : { value: merged };
|
|
301
|
+
}
|
|
302
|
+
} };
|
|
303
|
+
}
|
|
304
|
+
function resolveAgentStateSchemas(contextSchema, states) {
|
|
305
|
+
return Object.fromEntries(Object.entries(states).map(([key, state]) => {
|
|
306
|
+
if (!state || typeof state !== "object") return [key, state];
|
|
307
|
+
const children = "states" in state && state.states ? resolveAgentStateSchemas(contextSchema, state.states) : void 0;
|
|
308
|
+
if ("context" in state && state.context) return [key, {
|
|
309
|
+
schemas: { context: mergeContextSchema(contextSchema, state.context) },
|
|
310
|
+
...children ? { states: children } : {}
|
|
311
|
+
}];
|
|
312
|
+
return [key, children ? {
|
|
313
|
+
...state,
|
|
314
|
+
states: children
|
|
315
|
+
} : state];
|
|
316
|
+
}));
|
|
317
|
+
}
|
|
281
318
|
/**
|
|
282
319
|
* Schema-first `setup(...)` for agent machines — the standard entry point
|
|
283
320
|
* for authoring a machine (the blueprint) that this library then runs (via
|
|
@@ -418,7 +455,7 @@ function createAgentSetupConfig(schemas, actorSources, config) {
|
|
|
418
455
|
meta: schemas.meta,
|
|
419
456
|
...schemas.emitted && Object.keys(schemas.emitted).length > 0 ? { emitted: schemas.emitted } : {}
|
|
420
457
|
},
|
|
421
|
-
...config.states ? { states: config.states } : {},
|
|
458
|
+
...config.states ? { states: resolveAgentStateSchemas(schemas.context, config.states) } : {},
|
|
422
459
|
actorSources,
|
|
423
460
|
actions: config.actions,
|
|
424
461
|
guards: config.guards,
|
|
@@ -463,6 +500,18 @@ function createSetupAgent(config) {
|
|
|
463
500
|
* `resolveAgentRequests`.
|
|
464
501
|
* @module
|
|
465
502
|
*/
|
|
503
|
+
/** @internal Normalizes current and legacy XState invoke effect shapes. */
|
|
504
|
+
function getInvokeEffectMetadata(action) {
|
|
505
|
+
if (action.type === "@xstate.spawn") return action;
|
|
506
|
+
if (action.type === "xstate.spawnChild") {
|
|
507
|
+
const params = action.params;
|
|
508
|
+
return params ? {
|
|
509
|
+
...params,
|
|
510
|
+
logic: action.logic
|
|
511
|
+
} : void 0;
|
|
512
|
+
}
|
|
513
|
+
if (action.type === "@xstate.start" && typeof action.src === "string") return action;
|
|
514
|
+
}
|
|
466
515
|
/**
|
|
467
516
|
* Scans a set of executable actions (as returned by xstate's `transition`/
|
|
468
517
|
* `initialTransition`) for spawned `TextLogic`/`DecisionLogic` invokes and
|
|
@@ -478,11 +527,10 @@ function createSetupAgent(config) {
|
|
|
478
527
|
*/
|
|
479
528
|
function getAgentRequestsWith(actions, options = {}) {
|
|
480
529
|
return [...actions.flatMap((action) => {
|
|
481
|
-
|
|
482
|
-
const params = action.type === "@xstate.start" ? action : action.params;
|
|
530
|
+
const params = getInvokeEffectMetadata(action);
|
|
483
531
|
if (!params || typeof params.src !== "string") return [];
|
|
484
532
|
if (typeof params.id !== "string" || params.id.length === 0) throw new Error(`Agent invoke '${params.src}' must define a durable string id.`);
|
|
485
|
-
const registeredLogic = isTextLogic(
|
|
533
|
+
const registeredLogic = isTextLogic(params.logic) || isDecisionLogic(params.logic) ? params.logic : options.actorSources?.[params.src];
|
|
486
534
|
if (isDecisionLogic(registeredLogic)) {
|
|
487
535
|
const decisionRequest = registeredLogic.request(params.input);
|
|
488
536
|
const allowedEventTypes = registeredLogic.allowedEventTypes?.(params.input);
|
|
@@ -840,7 +888,7 @@ async function runTextPhase(stateRequest, baseMessages, deps) {
|
|
|
840
888
|
const agentRequest = {
|
|
841
889
|
kind: "text",
|
|
842
890
|
id,
|
|
843
|
-
src:
|
|
891
|
+
src: INTERPRET_SOURCE,
|
|
844
892
|
mode: "generate",
|
|
845
893
|
input: request,
|
|
846
894
|
tools: {},
|
|
@@ -855,6 +903,8 @@ async function runTextPhase(stateRequest, baseMessages, deps) {
|
|
|
855
903
|
try {
|
|
856
904
|
const raw = await deps.generateText(request, { signal: deps.signal });
|
|
857
905
|
output = await normalizeGeneratorResult(raw, id, { request });
|
|
906
|
+
const rawReasoning = raw?.reasoning;
|
|
907
|
+
const reasoning = typeof rawReasoning === "string" ? rawReasoning : void 0;
|
|
858
908
|
deps.onResult?.(agentRequest, {
|
|
859
909
|
output,
|
|
860
910
|
raw
|
|
@@ -863,7 +913,8 @@ async function runTextPhase(stateRequest, baseMessages, deps) {
|
|
|
863
913
|
type: "request.end",
|
|
864
914
|
request: agentRequest,
|
|
865
915
|
output,
|
|
866
|
-
raw
|
|
916
|
+
raw,
|
|
917
|
+
...reasoning !== void 0 ? { reasoning } : {}
|
|
867
918
|
});
|
|
868
919
|
} catch (error) {
|
|
869
920
|
deps.onTrace?.({
|
|
@@ -916,8 +967,8 @@ async function runAdvancePhase(plan, deps) {
|
|
|
916
967
|
signal: deps.signal,
|
|
917
968
|
canTake: (event) => deps.getSnapshot().can(event)
|
|
918
969
|
});
|
|
919
|
-
deps.appendToLog(assistantMessage(`[chose: ${chosen.type}]`));
|
|
920
970
|
if (deps.isSettled()) return false;
|
|
971
|
+
deps.appendToLog(assistantMessage(`[chose: ${chosen.type}]`));
|
|
921
972
|
deps.send(chosen);
|
|
922
973
|
return true;
|
|
923
974
|
}
|
|
@@ -1571,10 +1622,10 @@ async function runAgent(machine, options) {
|
|
|
1571
1622
|
}
|
|
1572
1623
|
}
|
|
1573
1624
|
}
|
|
1574
|
-
const priorMessages = effectiveSnapshot
|
|
1625
|
+
const priorMessages = getAgentMessages(effectiveSnapshot);
|
|
1575
1626
|
const messages = typeof options.messages === "function" ? [...options.messages([...priorMessages])] : [...priorMessages, ...options.messages ?? []];
|
|
1576
1627
|
const stampMessages = (snapshot) => {
|
|
1577
|
-
if (!options.getRequests && !options.messages) return;
|
|
1628
|
+
if (!options.getRequests && !options.messages && messages.length === 0) return;
|
|
1578
1629
|
if (snapshot && typeof snapshot === "object") snapshot.messages = [...messages];
|
|
1579
1630
|
};
|
|
1580
1631
|
if (effectiveSnapshot !== void 0 && options.event !== void 0 && (options.onIllegalResumeEvent ?? "throw") === "throw") {
|
|
@@ -1631,10 +1682,11 @@ async function runAgent(machine, options) {
|
|
|
1631
1682
|
messages.push(...items);
|
|
1632
1683
|
if (options.onMessage) for (const item of items) options.onMessage(item);
|
|
1633
1684
|
};
|
|
1685
|
+
const runErrorCause = (error) => budgetExceeded ? "max-model-calls" : wrapsDecisionExhausted(error) ? "decision-exhausted" : "machine";
|
|
1634
1686
|
const settleInterpretError = (error) => {
|
|
1635
1687
|
settle({
|
|
1636
1688
|
status: "error",
|
|
1637
|
-
cause:
|
|
1689
|
+
cause: runErrorCause(error),
|
|
1638
1690
|
error,
|
|
1639
1691
|
snapshot: actor.getSnapshot()
|
|
1640
1692
|
});
|
|
@@ -1664,7 +1716,7 @@ async function runAgent(machine, options) {
|
|
|
1664
1716
|
settleInterpretError(error);
|
|
1665
1717
|
return true;
|
|
1666
1718
|
}
|
|
1667
|
-
const requests = (Array.isArray(requested) ? requested : requested ? [requested] : []).filter(Boolean);
|
|
1719
|
+
const requests = (Array.isArray(requested) ? requested : requested ? [requested] : []).filter((stateRequest) => Boolean(stateRequest));
|
|
1668
1720
|
if (requests.length === 0) return false;
|
|
1669
1721
|
interpreting = true;
|
|
1670
1722
|
runStateRequestPass(requests, passDeps).then(({ sentAny }) => {
|
|
@@ -1712,7 +1764,7 @@ async function runAgent(machine, options) {
|
|
|
1712
1764
|
if (snapshot.status === "error") {
|
|
1713
1765
|
settle({
|
|
1714
1766
|
status: "error",
|
|
1715
|
-
cause:
|
|
1767
|
+
cause: runErrorCause(snapshot.error),
|
|
1716
1768
|
error: snapshot.error,
|
|
1717
1769
|
snapshot
|
|
1718
1770
|
});
|
|
@@ -2139,12 +2191,10 @@ function lintAgentMachine(machine, options = {}) {
|
|
|
2139
2191
|
function pendingInvokes(step) {
|
|
2140
2192
|
const out = [];
|
|
2141
2193
|
for (const action of step.actions) {
|
|
2142
|
-
const
|
|
2143
|
-
if (
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
id: params.id,
|
|
2147
|
-
src: params.src
|
|
2194
|
+
const metadata = getInvokeEffectMetadata(action);
|
|
2195
|
+
if (typeof metadata?.src === "string" && typeof metadata.id === "string") out.push({
|
|
2196
|
+
id: metadata.id,
|
|
2197
|
+
src: metadata.src
|
|
2148
2198
|
});
|
|
2149
2199
|
}
|
|
2150
2200
|
return out;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const require_decision = require("./decision-
|
|
1
|
+
const require_decision = require("./decision-BnATHy0W.cjs");
|
|
2
2
|
let xstate = require("xstate");
|
|
3
3
|
//#region src/messages.ts
|
|
4
4
|
function addMessages(resolve) {
|
|
@@ -278,6 +278,43 @@ function createAgentSchemas(schemas) {
|
|
|
278
278
|
emitted: schemas.emitted
|
|
279
279
|
};
|
|
280
280
|
}
|
|
281
|
+
function mergeContextSchema(base, fields) {
|
|
282
|
+
return { "~standard": {
|
|
283
|
+
version: 1,
|
|
284
|
+
vendor: "statelyai-agent",
|
|
285
|
+
validate(value) {
|
|
286
|
+
const baseResult = base["~standard"].validate(value);
|
|
287
|
+
if (baseResult instanceof Promise) throw new Error("setupAgent: async context schemas are not supported.");
|
|
288
|
+
if (baseResult.issues) return baseResult;
|
|
289
|
+
const merged = { ...baseResult.value };
|
|
290
|
+
const issues = [];
|
|
291
|
+
for (const [key, fieldSchema] of Object.entries(fields)) {
|
|
292
|
+
const fieldResult = fieldSchema["~standard"].validate(value[key]);
|
|
293
|
+
if (fieldResult instanceof Promise) throw new Error("setupAgent: async context schemas are not supported.");
|
|
294
|
+
if (fieldResult.issues) issues.push(...fieldResult.issues.map((issue) => ({
|
|
295
|
+
...issue,
|
|
296
|
+
path: [key, ...issue.path ?? []]
|
|
297
|
+
})));
|
|
298
|
+
else merged[key] = fieldResult.value;
|
|
299
|
+
}
|
|
300
|
+
return issues.length > 0 ? { issues } : { value: merged };
|
|
301
|
+
}
|
|
302
|
+
} };
|
|
303
|
+
}
|
|
304
|
+
function resolveAgentStateSchemas(contextSchema, states) {
|
|
305
|
+
return Object.fromEntries(Object.entries(states).map(([key, state]) => {
|
|
306
|
+
if (!state || typeof state !== "object") return [key, state];
|
|
307
|
+
const children = "states" in state && state.states ? resolveAgentStateSchemas(contextSchema, state.states) : void 0;
|
|
308
|
+
if ("context" in state && state.context) return [key, {
|
|
309
|
+
schemas: { context: mergeContextSchema(contextSchema, state.context) },
|
|
310
|
+
...children ? { states: children } : {}
|
|
311
|
+
}];
|
|
312
|
+
return [key, children ? {
|
|
313
|
+
...state,
|
|
314
|
+
states: children
|
|
315
|
+
} : state];
|
|
316
|
+
}));
|
|
317
|
+
}
|
|
281
318
|
/**
|
|
282
319
|
* Schema-first `setup(...)` for agent machines — the standard entry point
|
|
283
320
|
* for authoring a machine (the blueprint) that this library then runs (via
|
|
@@ -418,7 +455,7 @@ function createAgentSetupConfig(schemas, actorSources, config) {
|
|
|
418
455
|
meta: schemas.meta,
|
|
419
456
|
...schemas.emitted && Object.keys(schemas.emitted).length > 0 ? { emitted: schemas.emitted } : {}
|
|
420
457
|
},
|
|
421
|
-
...config.states ? { states: config.states } : {},
|
|
458
|
+
...config.states ? { states: resolveAgentStateSchemas(schemas.context, config.states) } : {},
|
|
422
459
|
actorSources,
|
|
423
460
|
actions: config.actions,
|
|
424
461
|
guards: config.guards,
|
|
@@ -463,6 +500,18 @@ function createSetupAgent(config) {
|
|
|
463
500
|
* `resolveAgentRequests`.
|
|
464
501
|
* @module
|
|
465
502
|
*/
|
|
503
|
+
/** @internal Normalizes current and legacy XState invoke effect shapes. */
|
|
504
|
+
function getInvokeEffectMetadata(action) {
|
|
505
|
+
if (action.type === "@xstate.spawn") return action;
|
|
506
|
+
if (action.type === "xstate.spawnChild") {
|
|
507
|
+
const params = action.params;
|
|
508
|
+
return params ? {
|
|
509
|
+
...params,
|
|
510
|
+
logic: action.logic
|
|
511
|
+
} : void 0;
|
|
512
|
+
}
|
|
513
|
+
if (action.type === "@xstate.start" && typeof action.src === "string") return action;
|
|
514
|
+
}
|
|
466
515
|
/**
|
|
467
516
|
* Scans a set of executable actions (as returned by xstate's `transition`/
|
|
468
517
|
* `initialTransition`) for spawned `TextLogic`/`DecisionLogic` invokes and
|
|
@@ -478,11 +527,10 @@ function createSetupAgent(config) {
|
|
|
478
527
|
*/
|
|
479
528
|
function getAgentRequestsWith(actions, options = {}) {
|
|
480
529
|
return [...actions.flatMap((action) => {
|
|
481
|
-
|
|
482
|
-
const params = action.type === "@xstate.start" ? action : action.params;
|
|
530
|
+
const params = getInvokeEffectMetadata(action);
|
|
483
531
|
if (!params || typeof params.src !== "string") return [];
|
|
484
532
|
if (typeof params.id !== "string" || params.id.length === 0) throw new Error(`Agent invoke '${params.src}' must define a durable string id.`);
|
|
485
|
-
const registeredLogic = require_decision.isTextLogic(
|
|
533
|
+
const registeredLogic = require_decision.isTextLogic(params.logic) || require_decision.isDecisionLogic(params.logic) ? params.logic : options.actorSources?.[params.src];
|
|
486
534
|
if (require_decision.isDecisionLogic(registeredLogic)) {
|
|
487
535
|
const decisionRequest = registeredLogic.request(params.input);
|
|
488
536
|
const allowedEventTypes = registeredLogic.allowedEventTypes?.(params.input);
|
|
@@ -840,7 +888,7 @@ async function runTextPhase(stateRequest, baseMessages, deps) {
|
|
|
840
888
|
const agentRequest = {
|
|
841
889
|
kind: "text",
|
|
842
890
|
id,
|
|
843
|
-
src:
|
|
891
|
+
src: require_decision.INTERPRET_SOURCE,
|
|
844
892
|
mode: "generate",
|
|
845
893
|
input: request,
|
|
846
894
|
tools: {},
|
|
@@ -855,6 +903,8 @@ async function runTextPhase(stateRequest, baseMessages, deps) {
|
|
|
855
903
|
try {
|
|
856
904
|
const raw = await deps.generateText(request, { signal: deps.signal });
|
|
857
905
|
output = await require_decision.normalizeGeneratorResult(raw, id, { request });
|
|
906
|
+
const rawReasoning = raw?.reasoning;
|
|
907
|
+
const reasoning = typeof rawReasoning === "string" ? rawReasoning : void 0;
|
|
858
908
|
deps.onResult?.(agentRequest, {
|
|
859
909
|
output,
|
|
860
910
|
raw
|
|
@@ -863,7 +913,8 @@ async function runTextPhase(stateRequest, baseMessages, deps) {
|
|
|
863
913
|
type: "request.end",
|
|
864
914
|
request: agentRequest,
|
|
865
915
|
output,
|
|
866
|
-
raw
|
|
916
|
+
raw,
|
|
917
|
+
...reasoning !== void 0 ? { reasoning } : {}
|
|
867
918
|
});
|
|
868
919
|
} catch (error) {
|
|
869
920
|
deps.onTrace?.({
|
|
@@ -916,8 +967,8 @@ async function runAdvancePhase(plan, deps) {
|
|
|
916
967
|
signal: deps.signal,
|
|
917
968
|
canTake: (event) => deps.getSnapshot().can(event)
|
|
918
969
|
});
|
|
919
|
-
deps.appendToLog(require_decision.assistantMessage(`[chose: ${chosen.type}]`));
|
|
920
970
|
if (deps.isSettled()) return false;
|
|
971
|
+
deps.appendToLog(require_decision.assistantMessage(`[chose: ${chosen.type}]`));
|
|
921
972
|
deps.send(chosen);
|
|
922
973
|
return true;
|
|
923
974
|
}
|
|
@@ -1571,10 +1622,10 @@ async function runAgent(machine, options) {
|
|
|
1571
1622
|
}
|
|
1572
1623
|
}
|
|
1573
1624
|
}
|
|
1574
|
-
const priorMessages = effectiveSnapshot
|
|
1625
|
+
const priorMessages = require_decision.getAgentMessages(effectiveSnapshot);
|
|
1575
1626
|
const messages = typeof options.messages === "function" ? [...options.messages([...priorMessages])] : [...priorMessages, ...options.messages ?? []];
|
|
1576
1627
|
const stampMessages = (snapshot) => {
|
|
1577
|
-
if (!options.getRequests && !options.messages) return;
|
|
1628
|
+
if (!options.getRequests && !options.messages && messages.length === 0) return;
|
|
1578
1629
|
if (snapshot && typeof snapshot === "object") snapshot.messages = [...messages];
|
|
1579
1630
|
};
|
|
1580
1631
|
if (effectiveSnapshot !== void 0 && options.event !== void 0 && (options.onIllegalResumeEvent ?? "throw") === "throw") {
|
|
@@ -1631,10 +1682,11 @@ async function runAgent(machine, options) {
|
|
|
1631
1682
|
messages.push(...items);
|
|
1632
1683
|
if (options.onMessage) for (const item of items) options.onMessage(item);
|
|
1633
1684
|
};
|
|
1685
|
+
const runErrorCause = (error) => budgetExceeded ? "max-model-calls" : wrapsDecisionExhausted(error) ? "decision-exhausted" : "machine";
|
|
1634
1686
|
const settleInterpretError = (error) => {
|
|
1635
1687
|
settle({
|
|
1636
1688
|
status: "error",
|
|
1637
|
-
cause:
|
|
1689
|
+
cause: runErrorCause(error),
|
|
1638
1690
|
error,
|
|
1639
1691
|
snapshot: actor.getSnapshot()
|
|
1640
1692
|
});
|
|
@@ -1664,7 +1716,7 @@ async function runAgent(machine, options) {
|
|
|
1664
1716
|
settleInterpretError(error);
|
|
1665
1717
|
return true;
|
|
1666
1718
|
}
|
|
1667
|
-
const requests = (Array.isArray(requested) ? requested : requested ? [requested] : []).filter(Boolean);
|
|
1719
|
+
const requests = (Array.isArray(requested) ? requested : requested ? [requested] : []).filter((stateRequest) => Boolean(stateRequest));
|
|
1668
1720
|
if (requests.length === 0) return false;
|
|
1669
1721
|
interpreting = true;
|
|
1670
1722
|
runStateRequestPass(requests, passDeps).then(({ sentAny }) => {
|
|
@@ -1712,7 +1764,7 @@ async function runAgent(machine, options) {
|
|
|
1712
1764
|
if (snapshot.status === "error") {
|
|
1713
1765
|
settle({
|
|
1714
1766
|
status: "error",
|
|
1715
|
-
cause:
|
|
1767
|
+
cause: runErrorCause(snapshot.error),
|
|
1716
1768
|
error: snapshot.error,
|
|
1717
1769
|
snapshot
|
|
1718
1770
|
});
|
|
@@ -2139,12 +2191,10 @@ function lintAgentMachine(machine, options = {}) {
|
|
|
2139
2191
|
function pendingInvokes(step) {
|
|
2140
2192
|
const out = [];
|
|
2141
2193
|
for (const action of step.actions) {
|
|
2142
|
-
const
|
|
2143
|
-
if (
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
id: params.id,
|
|
2147
|
-
src: params.src
|
|
2194
|
+
const metadata = getInvokeEffectMetadata(action);
|
|
2195
|
+
if (typeof metadata?.src === "string" && typeof metadata.id === "string") out.push({
|
|
2196
|
+
id: metadata.id,
|
|
2197
|
+
src: metadata.src
|
|
2148
2198
|
});
|
|
2149
2199
|
}
|
|
2150
2200
|
return out;
|