@statelyai/agent 2.0.0-alpha.27 → 2.0.0-alpha.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-sdk.cjs +149 -26
- package/dist/ai-sdk.d.cts +57 -34
- package/dist/ai-sdk.d.mts +57 -34
- package/dist/ai-sdk.mjs +147 -23
- package/dist/{decision-RQ0iv0oZ.mjs → decision-Bl_rKQnU.mjs} +73 -7
- package/dist/{decision-CmM8-HHz.cjs → decision-oevZnkBe.cjs} +112 -29
- package/dist/{text-logic-f5F5sCdc.cjs → event-log-Dtb16p1p.cjs} +813 -6
- package/dist/{text-logic-CIqHAmBi.mjs → event-log-GPZO9p7_.mjs} +679 -3
- package/dist/{event-log-store-BIPOz-di.d.mts → event-log-store-CN9ygggF.d.cts} +90 -5
- package/dist/{event-log-store-2xzFmgr2.d.cts → event-log-store-DS836wch.d.mts} +90 -5
- package/dist/event-log-store-bCdskPNS.cjs +95 -0
- package/dist/event-log-store-yalq8C77.mjs +84 -0
- package/dist/index.cjs +571 -58
- package/dist/index.d.cts +104 -510
- package/dist/index.d.mts +104 -510
- package/dist/index.mjs +542 -32
- package/dist/log.cjs +77 -20
- package/dist/log.d.cts +5 -5
- package/dist/log.d.mts +5 -5
- package/dist/log.mjs +58 -3
- package/dist/machines.cjs +1 -1
- package/dist/machines.d.cts +15 -15
- package/dist/machines.d.mts +15 -15
- package/dist/machines.mjs +1 -1
- package/dist/model-source-C7FFP2Sj.mjs +39 -0
- package/dist/model-source-DjJPjGSP.cjs +44 -0
- package/dist/openai.cjs +10 -10
- package/dist/openai.d.cts +27 -25
- package/dist/openai.d.mts +27 -25
- package/dist/openai.mjs +2 -2
- package/dist/otel.cjs +5 -4
- package/dist/otel.d.cts +5 -7
- package/dist/otel.d.mts +5 -7
- package/dist/otel.mjs +5 -3
- package/dist/{run-agent-COXXc0RW.d.mts → run-agent-C9ubX8Tx.d.cts} +87 -30
- package/dist/{run-agent-xNTxpt82.mjs → run-agent-CuQT1xSS.mjs} +170 -42
- package/dist/{run-agent-ByO-Bxyd.d.cts → run-agent-CxSyZmIE.d.mts} +87 -30
- package/dist/{run-agent-Dmf8GV2d.cjs → run-agent-cToZ3K42.cjs} +219 -86
- package/dist/{setup-agent-DV4cTou-.cjs → setup-agent-DTF3NQg3.cjs} +31 -20
- package/dist/setup-agent-DlbgwsIJ.d.cts +577 -0
- package/dist/{setup-agent-BuanDXeh.mjs → setup-agent-DniLvDu7.mjs} +15 -9
- package/dist/setup-agent-tsc3vm5I.d.mts +577 -0
- package/dist/tanstack-ai.cjs +627 -0
- package/dist/tanstack-ai.d.cts +204 -0
- package/dist/tanstack-ai.d.mts +204 -0
- package/dist/tanstack-ai.mjs +618 -0
- package/dist/testing.cjs +98 -985
- package/dist/testing.d.cts +51 -347
- package/dist/testing.d.mts +51 -347
- package/dist/testing.mjs +86 -973
- package/dist/{text-logic-IjfYy9DP.d.cts → text-logic-9fv1i9aK.d.cts} +50 -10
- package/dist/{text-logic-D-czVPYp.d.mts → text-logic-BDbGjYMh.d.mts} +50 -10
- package/dist/{types-BgNbNKnJ.d.mts → types-Dp5_Ru4R.d.cts} +2 -2
- package/dist/{types-hR5f5YXa.d.cts → types-Dp5_Ru4R.d.mts} +2 -2
- package/dist/usage-D8UphgEA.d.mts +17 -0
- package/dist/usage-R1NTmLxY.d.cts +17 -0
- package/dist/{utils-_q7F-AZu.d.mts → utils-BnXdWih3.d.mts} +1 -2
- package/dist/{utils-o4YRdHJX.d.cts → utils-ebVpCYoF.d.cts} +1 -2
- package/dist/validate.cjs +239 -8
- package/dist/validate.d.cts +110 -3
- package/dist/validate.d.mts +110 -3
- package/dist/validate.mjs +238 -7
- package/dist/verify-B5qGC5WN.mjs +1181 -0
- package/dist/verify-CBuYIpsa.d.mts +414 -0
- package/dist/verify-Cqghu4gz.cjs +1222 -0
- package/dist/verify-DYH_2VzU.d.cts +414 -0
- package/package.json +44 -31
- package/readme.md +23 -5
- package/skills/generate-machine/SKILL.md +136 -64
- package/skills/improve-machine/SKILL.md +190 -0
- package/skills/improve-machine/reference.md +96 -0
- package/dist/event-log-store-2pAFiWuc.mjs +0 -576
- package/dist/event-log-store-C-COhIXP.cjs +0 -702
- package/dist/usage-BdEjFuIi.mjs +0 -5
- package/dist/usage-efOQPdf_.cjs +0 -10
package/dist/index.d.cts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { C as UserMessage, S as ToolResultPart, _ as StandardSchemaV1, a as AgentToolDescriptor, b as ToolCallPart, c as AllowedEvents, d as EventUnion, f as FilePart,
|
|
2
|
-
import { A as AgentDecisionExhaustedError, B as
|
|
3
|
-
import {
|
|
4
|
-
import { c as
|
|
5
|
-
import { a as
|
|
6
|
-
import {
|
|
7
|
-
|
|
1
|
+
import { C as UserMessage, S as ToolResultPart, _ as StandardSchemaV1, a as AgentToolDescriptor, b as ToolCallPart, c as AllowedEvents, d as EventUnion, f as FilePart, h as InferOutput, i as AgentToolChoice, l as AssistantMessage, m as InferInput, n as AgentMessage, o as AgentToolExecute, p as ImagePart, r as AgentTool, s as AgentTools, u as ChosenEvent, v as SystemMessage, x as ToolMessage, y as TextPart } from "./types-Dp5_Ru4R.cjs";
|
|
2
|
+
import { $ as AgentTruncatedError, A as AgentDecisionExhaustedError, B as createDecisionLogic, C as getAgentOutputMode, D as parseProviderOutput, E as parseOutput, F as CreateDecisionRequestOptions, G as AgentInvalidEventPayloadError, H as renderDecisionAttempts, I as DecisionAttempt, J as AgentSchemas, K as AgentRequestOptions, L as DecisionLogic, M as AgentDecisionOption, N as AgentDecisionRequest, O as providerOutputSchema, P as AgentExecutorDecisionRequest, Q as AgentError, R as DecisionLogicConfig, S as createTextLogic, T as getCallUsage, U as resolveDecision, V as createDecisionRequest, W as AgentEventDescriptor, X as getAcceptedEvents, Y as EventFromSnapshot, Z as parseAgentEvent, _ as TextLogic, a as AgentModelRef, b as TextLogicExecutor, c as AgentRequestExecutorInfo, f as AgentTextRequest, g as ProviderStructuredOutput, j as AgentDecisionInput, k as AgentDecisionExecutor, l as AgentRequestExecutorResult, m as AgentUsage, n as AgentExecutorTextRequest, o as AgentOutputMode, p as AgentTextResult, q as AgentRequestSource, r as AgentFinishReason, s as AgentRequestExecutor, t as AgentCallUsage, u as AgentRequestExecutors, v as TextLogicConfig, w as getCallFinishReason, x as bindRequestExecutor, y as TextLogicExecuteArgs, z as ResolveDecisionOptions } from "./text-logic-9fv1i9aK.cjs";
|
|
3
|
+
import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-R1NTmLxY.cjs";
|
|
4
|
+
import { C as AgentInteractionEventMeta, D as getInteraction, E as eventFromInteraction, O as interactionMetaSchema, S as AgentInteractionEvent, T as GetInteractionOptions, _ as FromConfigResult, a as WithAgentUsageEvent, b as AgentInteractionChoice, c as setupAgent, d as AgentWorkflowConfig, f as AgentWorkflowInvokeConfig, g as FromConfigOptions, h as AgentWorkflowTransitionConfig, i as WithAgentEvents, l as AgentWorkflowActionConfig, m as AgentWorkflowStateConfig, n as AgentSchemaPack, o as createAgentSchemas, p as AgentWorkflowRequestConfig, r as AgentUsageEventPayload, s as getAgentSchemas, t as AgentDefaultMeta, u as AgentWorkflowActorConfig, v as SchemaCompiler, w as AgentInteractionMeta, x as AgentInteractionDescriptor, y as AgentInteraction } from "./setup-agent-DlbgwsIJ.cjs";
|
|
5
|
+
import { C as runAgent, D as AgentRequest, E as traceTransitions, O as AgentStepRequest, S as isAgentIdle, T as serializeTraceEvent, _ as AgentTransitionHandler, a as AgentRunErrorCause, b as createAgentRuntime, c as AgentRunOptions, d as AgentRuntime, f as AgentRuntimeOptions, g as AgentTraceEvent, h as AgentTimerScheduler, i as AgentMaxModelCallsExceededError, l as AgentRunResult, m as AgentTimerEvent, n as AgentEffects, o as AgentRunInit, p as AgentSnapshotDivergedError, r as AgentInputFrom, s as AgentRunMeta, t as AGENT_TRACE_SCHEMA_VERSION, u as AgentRunStart, v as InspectedActorRef, w as runToQuiescence, x as inspectTransitions, y as JsonSerializableTraceEvent } from "./run-agent-C9ubX8Tx.cjs";
|
|
6
|
+
import { c as AgentLogEntry, d as AgentMachineVersionMismatchError, n as AgentEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-CN9ygggF.cjs";
|
|
7
|
+
import { a as getMachineStructuralHash, c as getStatePath, d as toolMessage, f as userMessage, i as getJsonSchemaSync, l as isStandardSchema, n as assistantMessage, o as getMessageText, r as getJsonSchema, s as getStateMeta, u as systemMessage } from "./utils-ebVpCYoF.cjs";
|
|
8
|
+
import { AnyActorLogic, AnyMachineSnapshot, AnyStateMachine, ContextFrom, DoneActorEvent, EventFromLogic, InputFrom, OutputFrom, SnapshotFrom, StateValueFrom } from "xstate";
|
|
8
9
|
//#region src/type-helpers.d.ts
|
|
9
10
|
type SchemaAt<T, TKey extends PropertyKey> = T extends {
|
|
10
11
|
schemas: Record<TKey, infer TSchema extends StandardSchemaV1>;
|
|
@@ -62,534 +63,127 @@ type DoneActorEventOf<TLogic extends AnyActorLogic, TId extends string = string>
|
|
|
62
63
|
* context schema write `z.custom<AgentMessage[]>(isAgentMessages)`, which runs
|
|
63
64
|
* this same validator (see {@link isAgentMessages}).
|
|
64
65
|
*/
|
|
65
|
-
declare const messagesSchema: StandardSchemaV1<AgentMessage[]>;
|
|
66
|
+
export declare const messagesSchema: StandardSchemaV1<AgentMessage[]>;
|
|
66
67
|
/**
|
|
67
68
|
* Type guard over {@link messagesSchema}: `true` when `value` is a valid
|
|
68
69
|
* `AgentMessage[]`. The one-liner for zod context schemas:
|
|
69
70
|
* `messages: z.custom<AgentMessage[]>(isAgentMessages)`.
|
|
70
71
|
*/
|
|
71
|
-
declare function isAgentMessages(value: unknown): value is AgentMessage[];
|
|
72
|
+
export declare function isAgentMessages(value: unknown): value is AgentMessage[];
|
|
72
73
|
//#endregion
|
|
73
|
-
//#region src/
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
/** Optional fixed fields merged into the event when this choice is selected. */
|
|
79
|
-
event?: Record<string, unknown>;
|
|
80
|
-
}
|
|
81
|
-
interface AgentInteraction<TEvent extends EventObject = EventObject> {
|
|
82
|
-
label: string;
|
|
83
|
-
events: AgentInteractionEvent<TEvent["type"]>[];
|
|
84
|
-
/** Event type used for a free-text response. */
|
|
85
|
-
textEvent?: TEvent["type"];
|
|
86
|
-
}
|
|
87
|
-
/**
|
|
88
|
-
* One choice as authored in `meta.interaction.events`: a bare label, or a
|
|
89
|
-
* descriptor carrying a `style` and the fixed `event` fields merged in when the
|
|
90
|
-
* choice is selected.
|
|
91
|
-
*/
|
|
92
|
-
type AgentInteractionEventMeta = string | {
|
|
93
|
-
label?: string;
|
|
94
|
-
style?: string;
|
|
95
|
-
event?: Record<string, unknown>;
|
|
96
|
-
};
|
|
97
|
-
/**
|
|
98
|
-
* The `interaction` descriptor {@link getInteraction} reads off a state's meta.
|
|
99
|
-
* `TEvent` is the machine's event-type union, so a choice or `textEvent` that
|
|
100
|
-
* names an event the machine never declared is a compile error.
|
|
101
|
-
*/
|
|
102
|
-
interface AgentInteractionDescriptor<TEvent extends string = string> {
|
|
103
|
-
/** Label text, or a function of the machine context. `{path.to.field}` interpolates. */
|
|
104
|
-
label?: string | ((args: {
|
|
105
|
-
context: any;
|
|
106
|
-
}) => string);
|
|
107
|
-
events?: { [K in TEvent]?: AgentInteractionEventMeta };
|
|
108
|
-
textEvent?: TEvent;
|
|
109
|
-
}
|
|
110
|
-
/**
|
|
111
|
-
* The state-meta shape the interaction protocol reads. `setupAgent` types
|
|
112
|
-
* every state's `meta` as this by default, with `TEvent` narrowed to the
|
|
113
|
-
* machine's declared events; see {@link interactionMetaSchema} for the runtime
|
|
114
|
-
* schema when a machine declares its own `meta` schema.
|
|
115
|
-
*/
|
|
116
|
-
interface AgentInteractionMeta<TEvent extends string = string> {
|
|
117
|
-
interaction?: AgentInteractionDescriptor<TEvent>;
|
|
74
|
+
//#region src/describe-machine.d.ts
|
|
75
|
+
/** Options for {@link describeMachine}. */
|
|
76
|
+
interface DescribeMachineOptions {
|
|
77
|
+
/** Marks the state nodes active in this snapshot with `*`. */
|
|
78
|
+
snapshot?: AnyMachineSnapshot;
|
|
118
79
|
}
|
|
119
80
|
/**
|
|
120
|
-
*
|
|
121
|
-
*
|
|
122
|
-
*
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
* `
|
|
126
|
-
*
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
* layout. Turn it on when the label is deliberately multi-line (a rendered
|
|
136
|
-
* diff, a preformatted block).
|
|
137
|
-
*/
|
|
138
|
-
preserveWhitespace?: boolean;
|
|
139
|
-
}
|
|
140
|
-
/** Reads the active state's interaction metadata and filters it through the
|
|
141
|
-
* events XState currently accepts. Returns `undefined` when none is declared. */
|
|
142
|
-
declare function getInteraction<TSnapshot extends AnyMachineSnapshot>(snapshot: TSnapshot, options?: GetInteractionOptions): AgentInteraction<EventFromSnapshot<TSnapshot>> | undefined;
|
|
143
|
-
/** Converts a rendered interaction choice back into a schema-validated machine
|
|
144
|
-
* event. Fixed fields declared in metadata are merged before user fields. */
|
|
145
|
-
declare function eventFromInteraction<TSnapshot extends AnyMachineSnapshot>(snapshot: TSnapshot, choice: ({
|
|
146
|
-
type: string;
|
|
147
|
-
} & Record<string, unknown>) | {
|
|
148
|
-
text: string;
|
|
149
|
-
}): EventFromSnapshot<TSnapshot>;
|
|
150
|
-
//#endregion
|
|
151
|
-
//#region src/workflow-config.d.ts
|
|
152
|
-
type JsonSchemaObject = {
|
|
153
|
-
type?: string | string[];
|
|
154
|
-
properties?: Record<string, JsonSchemaObject>;
|
|
155
|
-
required?: string[];
|
|
156
|
-
items?: JsonSchemaObject;
|
|
157
|
-
enum?: unknown[];
|
|
158
|
-
const?: unknown;
|
|
159
|
-
additionalProperties?: unknown;
|
|
160
|
-
[key: string]: unknown;
|
|
161
|
-
};
|
|
162
|
-
/**
|
|
163
|
-
* Compiles a JSON Schema object (from an `AgentWorkflowConfig`) into a
|
|
164
|
-
* runtime `StandardSchemaV1` validator. `setupAgent.fromConfig(...)` calls
|
|
165
|
-
* this once per schema in the config (context/events/input/output/meta,
|
|
166
|
-
* request input/output) — bring your own engine (Ajv, @cfworker/json-schema,
|
|
167
|
-
* a compiled-Zod-from-JSON-Schema pipeline, ...). Core intentionally ships no
|
|
168
|
-
* JSON Schema engine.
|
|
169
|
-
*/
|
|
170
|
-
type SchemaCompiler = (jsonSchema: Record<string, unknown>, name: string) => StandardSchemaV1;
|
|
171
|
-
/**
|
|
172
|
-
* Serializable JSON/YAML machine definition — the config a database, visual
|
|
173
|
-
* editor, or LLM could produce and hand to `setupAgent.fromConfig(config, {
|
|
174
|
-
* compileSchema })` to get back the same kind of `AnyStateMachine`
|
|
175
|
-
* TypeScript `setupAgent(...)` authoring would build. JS/TS authoring should
|
|
176
|
-
* use `setupAgent(...)` directly instead of this JSON form. Any `unknown`-
|
|
177
|
-
* typed field here (`model`, `guard`, action `params`, …) accepts either a
|
|
178
|
-
* literal JSON value or a `"{{ path.to.value }}"` template-expression string
|
|
179
|
-
* resolved against `{ context, event, input, output }` at machine-build/
|
|
180
|
-
* transition time — see the sibling `evaluateWorkflowConfigValue` lowering.
|
|
181
|
-
*/
|
|
182
|
-
interface AgentWorkflowConfig {
|
|
183
|
-
/** JSON Schema reference (`"$schema"`) editors attach to a config file. Ignored by the lowering. */
|
|
184
|
-
$schema?: string;
|
|
185
|
-
key?: string;
|
|
186
|
-
id?: string;
|
|
187
|
-
version?: string;
|
|
188
|
-
description?: string;
|
|
189
|
-
schemas?: {
|
|
190
|
-
input?: JsonSchemaObject;
|
|
191
|
-
context?: JsonSchemaObject;
|
|
192
|
-
events?: Record<string, JsonSchemaObject>;
|
|
193
|
-
emitted?: Record<string, JsonSchemaObject>;
|
|
194
|
-
output?: JsonSchemaObject;
|
|
195
|
-
meta?: JsonSchemaObject;
|
|
196
|
-
};
|
|
197
|
-
context?: Record<string, unknown>;
|
|
198
|
-
requests?: Record<string, AgentWorkflowRequestConfig>;
|
|
199
|
-
actors?: Record<string, AgentWorkflowActorConfig>;
|
|
200
|
-
initial: string;
|
|
201
|
-
states: Record<string, AgentWorkflowStateConfig>;
|
|
202
|
-
meta?: Record<string, unknown>;
|
|
203
|
-
}
|
|
204
|
-
/** 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}). */
|
|
205
|
-
interface AgentWorkflowRequestConfig {
|
|
206
|
-
mode?: AgentRequestMode;
|
|
207
|
-
description?: string;
|
|
208
|
-
model: unknown;
|
|
209
|
-
system?: unknown;
|
|
210
|
-
prompt?: unknown;
|
|
211
|
-
messages?: unknown;
|
|
212
|
-
input: JsonSchemaObject;
|
|
213
|
-
output: JsonSchemaObject;
|
|
214
|
-
tools?: AgentTools;
|
|
215
|
-
toolChoice?: AgentToolChoice | unknown;
|
|
216
|
-
/** Opt into the provider output's `reasoning` field (see `AgentTextRequest.includeReasoning`). */
|
|
217
|
-
includeReasoning?: boolean;
|
|
218
|
-
temperature?: unknown;
|
|
219
|
-
maxOutputTokens?: unknown;
|
|
220
|
-
topP?: unknown;
|
|
221
|
-
topK?: unknown;
|
|
222
|
-
seed?: unknown;
|
|
223
|
-
stopSequences?: unknown;
|
|
224
|
-
metadata?: unknown;
|
|
225
|
-
}
|
|
226
|
-
/** An `actors` entry in {@link AgentWorkflowConfig} — declares a placeholder actor source (by key) with no host execution wired from JSON; provide it via `machine.provide({ actors })` after `setupAgent.fromConfig(...)`. */
|
|
227
|
-
interface AgentWorkflowActorConfig {
|
|
228
|
-
input?: JsonSchemaObject;
|
|
229
|
-
output?: JsonSchemaObject;
|
|
230
|
-
description?: string;
|
|
231
|
-
}
|
|
232
|
-
/** A `states` entry in {@link AgentWorkflowConfig} — the JSON equivalent of an XState state node config. */
|
|
233
|
-
interface AgentWorkflowStateConfig {
|
|
234
|
-
description?: string;
|
|
235
|
-
type?: "parallel" | "history" | "final" | "choice";
|
|
236
|
-
initial?: string;
|
|
237
|
-
states?: Record<string, AgentWorkflowStateConfig>;
|
|
238
|
-
choice?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
|
|
239
|
-
invoke?: AgentWorkflowInvokeConfig | AgentWorkflowInvokeConfig[];
|
|
240
|
-
on?: Record<string, AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[]>;
|
|
241
|
-
always?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
|
|
242
|
-
onDone?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
|
|
243
|
-
after?: Record<string, AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[]>;
|
|
244
|
-
entry?: AgentWorkflowActionConfig | AgentWorkflowActionConfig[];
|
|
245
|
-
exit?: AgentWorkflowActionConfig | AgentWorkflowActionConfig[];
|
|
246
|
-
tags?: string[];
|
|
247
|
-
output?: unknown;
|
|
248
|
-
meta?: Record<string, unknown>;
|
|
249
|
-
}
|
|
250
|
-
/**
|
|
251
|
-
* An `invoke` entry in {@link AgentWorkflowStateConfig}. For `src:
|
|
252
|
-
* 'agent.decide'`, the chosen event is delivered automatically and handled by
|
|
253
|
-
* the state's `on` transitions — a decision has no output of its own, so an
|
|
254
|
-
* `onDone` there is always a config error and is rejected at
|
|
255
|
-
* `setupAgent.fromConfig(...)` time. `onError` handles retries-exhausted.
|
|
256
|
-
*/
|
|
257
|
-
interface AgentWorkflowInvokeConfig {
|
|
258
|
-
id?: string;
|
|
259
|
-
src: string;
|
|
260
|
-
input?: unknown;
|
|
261
|
-
onDone?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
|
|
262
|
-
onError?: AgentWorkflowTransitionConfig | AgentWorkflowTransitionConfig[];
|
|
263
|
-
meta?: Record<string, unknown>;
|
|
264
|
-
}
|
|
265
|
-
/**
|
|
266
|
-
* A transition target in {@link AgentWorkflowConfig}
|
|
267
|
-
* (`on`/`always`/`onDone`/`after`/invoke `onDone`/`onError`) — the JSON
|
|
268
|
-
* equivalent of an XState transition config. A string `guard` containing
|
|
269
|
-
* `{{ ... }}` is a template expression evaluated as truthy/falsy; any other
|
|
270
|
-
* string is a named guard reference resolved against the `guards` passed to
|
|
271
|
-
* `setupAgent.fromConfig(config, { guards })` (unresolvable references throw
|
|
272
|
-
* at build time).
|
|
273
|
-
*/
|
|
274
|
-
interface AgentWorkflowTransitionConfig {
|
|
275
|
-
target?: string | string[];
|
|
276
|
-
guard?: unknown;
|
|
277
|
-
assign?: Record<string, unknown>;
|
|
278
|
-
actions?: AgentWorkflowActionConfig | AgentWorkflowActionConfig[];
|
|
279
|
-
description?: string;
|
|
280
|
-
reenter?: boolean;
|
|
281
|
-
meta?: Record<string, unknown>;
|
|
282
|
-
}
|
|
283
|
-
/** An `entry`/`exit`/transition `actions` entry in {@link AgentWorkflowConfig} — a bare context `assign`, an `emit`, or a named action `type` (with template-expression `params`) resolved against the `actions` passed to `setupAgent.fromConfig(config, { actions })`. */
|
|
284
|
-
interface AgentWorkflowActionConfig {
|
|
285
|
-
type?: string;
|
|
286
|
-
params?: unknown;
|
|
287
|
-
assign?: Record<string, unknown>;
|
|
288
|
-
emit?: unknown;
|
|
289
|
-
[key: string]: unknown;
|
|
290
|
-
}
|
|
291
|
-
/**
|
|
292
|
-
* What `setupAgent.fromConfig(...)` returns: the built machine plus the
|
|
293
|
-
* schema pack compiled from the config's `schemas` (with `compileSchema`).
|
|
294
|
-
* The pack is what hosts need for the runtime work the machine's types can't
|
|
295
|
-
* do for a JSON-authored agent — e.g. validating an inbound raw event:
|
|
81
|
+
* Describes a machine in plain text for a model to read. The machine's
|
|
82
|
+
* `description` is its goal, so it leads: `Machine <id>`, then `Goal: …`.
|
|
83
|
+
* Then every state node, indented by depth, with its type, tags, interaction
|
|
84
|
+
* label and description (`*` marks the active ones when `snapshot` is given),
|
|
85
|
+
* and under it every transition leaving it, one per line: `on EVENT`,
|
|
86
|
+
* `always`, `after <delay>`, invoke `done`/`error`, and `choice` branches,
|
|
87
|
+
* each with its guard (`if …`), where it goes (`→ review`), and what it sets
|
|
88
|
+
* in context (`sets draft, attempts`). An `Events` section lists the
|
|
89
|
+
* machine's event schemas with their descriptions and fields.
|
|
90
|
+
*
|
|
91
|
+
* A transition written as a function shows the targets its source names
|
|
92
|
+
* (`→ review (conditional)` when it may decline or pick among several),
|
|
93
|
+
* `(stays)` when its source has no `target`, or `→ ?` when no target can be
|
|
94
|
+
* read. A `setupAgent.fromConfig(...)` machine is read from its config, so
|
|
95
|
+
* its targets, guards and context patches are always known.
|
|
296
96
|
*
|
|
297
97
|
* @example
|
|
298
98
|
* ```ts
|
|
299
|
-
* const
|
|
300
|
-
* const event = parseAgentEvent(snapshot, raw, { events: schemas.events });
|
|
99
|
+
* const prompt = `Propose a better machine for this goal.\n\n${describeMachine(machine)}`;
|
|
301
100
|
* ```
|
|
302
101
|
*/
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
/**
|
|
309
|
-
|
|
102
|
+
export declare function describeMachine(machine: AnyStateMachine, options?: DescribeMachineOptions): string;
|
|
103
|
+
//#endregion
|
|
104
|
+
//#region src/decide-next.d.ts
|
|
105
|
+
/** Options for {@link decideNext}. */
|
|
106
|
+
interface DecideNextOptions<TSnapshot extends AnyMachineSnapshot = AnyMachineSnapshot> {
|
|
107
|
+
/** The decide executor that asks a model to pick one option. */
|
|
108
|
+
decide: AgentDecisionExecutor;
|
|
109
|
+
/** Model ref, passed through to the executor. */
|
|
110
|
+
model: string;
|
|
111
|
+
/** Event types the model may choose: exact types or wildcards (`'desk.*'`, `'*'`). */
|
|
112
|
+
allowedEvents: string | readonly string[];
|
|
310
113
|
/**
|
|
311
|
-
*
|
|
312
|
-
*
|
|
313
|
-
*
|
|
114
|
+
* Concrete payloads per event type, without `type`. One option per payload.
|
|
115
|
+
* A candidate type with no key is offered bare, as `{ type }`; an empty list
|
|
116
|
+
* offers nothing for it. To withhold a type, give it `[]`:
|
|
117
|
+
* `(s) => ({ "desk.refund": [{ amount: s.context.requested }], "desk.close": [] })`.
|
|
314
118
|
*/
|
|
315
|
-
|
|
119
|
+
payloads?: (snapshot: TSnapshot) => Partial<Record<string, Record<string, unknown>[]>>;
|
|
120
|
+
system?: string;
|
|
121
|
+
prompt?: string;
|
|
122
|
+
/** Semantic request name, for traces and scripted executors. Default `'decideNext'`. */
|
|
123
|
+
name?: string;
|
|
316
124
|
/**
|
|
317
|
-
*
|
|
318
|
-
*
|
|
319
|
-
*
|
|
320
|
-
*
|
|
125
|
+
* Describe what each option changes: the state value and the changed
|
|
126
|
+
* top-level context keys, computed with xstate's pure `transition()`.
|
|
127
|
+
* An array limits which context keys are reported (a state value change is
|
|
128
|
+
* always reported). Each reported value is cut to 120 characters.
|
|
321
129
|
*/
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
130
|
+
lookahead?: boolean | readonly string[];
|
|
131
|
+
/** Retries after a failed choice. Default `2`. */
|
|
132
|
+
maxRetries?: number;
|
|
133
|
+
signal?: AbortSignal;
|
|
134
|
+
}
|
|
135
|
+
/** Result of {@link decideNext}. */
|
|
136
|
+
interface DecideNextResult<TEvent = ChosenEvent> {
|
|
137
|
+
/** The chosen event, or `null` when the snapshot accepts none of the options. */
|
|
138
|
+
event: TEvent | null;
|
|
139
|
+
/** Failed attempts before the choice landed. */
|
|
140
|
+
attempts: DecisionAttempt[];
|
|
141
|
+
/** The request built for the executor, with the offered `options` and the same `withheld`. */
|
|
142
|
+
request: AgentDecisionRequest;
|
|
326
143
|
/**
|
|
327
|
-
*
|
|
328
|
-
*
|
|
329
|
-
*
|
|
330
|
-
* into `params` via `{{ ... }}` templates. A named action type with no
|
|
331
|
-
* implementation here is a build-time error.
|
|
144
|
+
* The candidates the snapshot rejected: every `allowedEvents` type × payload,
|
|
145
|
+
* built the same way as the offered options, where `snapshot.can(event)` was
|
|
146
|
+
* false. Never offered to the model. Filled when nothing is offered too.
|
|
332
147
|
*/
|
|
333
|
-
|
|
148
|
+
withheld: ChosenEvent[];
|
|
334
149
|
}
|
|
335
|
-
//#endregion
|
|
336
|
-
//#region src/setup-agent.d.ts
|
|
337
|
-
type Constrain<T, TConstraint> = T extends TConstraint ? T : TConstraint;
|
|
338
|
-
type ContextOf$1<TContextSchema extends StandardSchemaV1> = Constrain<InferOutput<TContextSchema>, MachineContext>;
|
|
339
|
-
type EventsOf<TEventSchemas extends AgentEventSchemaInputMap> = Constrain<EventUnion<TEventSchemas>, EventObject>;
|
|
340
|
-
/**
|
|
341
|
-
* The first argument a guard or delay source receives. `context` and `event`
|
|
342
|
-
* come from the agent's own schemas, so an inline source is contextually typed
|
|
343
|
-
* and an annotated one stays assignable. XState's remaining fields (`self`,
|
|
344
|
-
* `parent`, `value`, `children`, `stateNode`) are deliberately not modeled:
|
|
345
|
-
* `setupAgent` only forwards these sources to `setup()`, which types them for
|
|
346
|
-
* real where the machine is built.
|
|
347
|
-
*/
|
|
348
|
-
type AgentSourceArgs<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap> = {
|
|
349
|
-
context: ContextOf$1<TContextSchema>;
|
|
350
|
-
event: EventsOf<TEventSchemas>;
|
|
351
|
-
};
|
|
352
|
-
/** Guard sources for `setupAgent({ guards })`, typed against the agent's own context and events. */
|
|
353
|
-
type AgentGuardSources<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap> = Record<string, (args: AgentSourceArgs<TContextSchema, TEventSchemas>, ...params: any[]) => boolean>;
|
|
354
|
-
/** Delay sources for `setupAgent({ delays })`, typed the same way as {@link AgentGuardSources}. */
|
|
355
|
-
type AgentDelaySources<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap> = Record<string, number | ((args: AgentSourceArgs<TContextSchema, TEventSchemas>) => number)>;
|
|
356
|
-
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] };
|
|
357
|
-
type AgentSetupActors<TActors extends { [K in keyof TActors]: AnyActorLogic }, TEvent extends string = string, TModel extends string = string> = TActors & BuiltinAgentActors<TEvent, TModel>;
|
|
358
|
-
/**
|
|
359
|
-
* The default `meta` type of an agent machine: the interaction descriptor
|
|
360
|
-
* `getInteraction` reads, keyed by the machine's own event types (the
|
|
361
|
-
* reserved `@agent.*` events excluded). A machine that declares `meta`
|
|
362
|
-
* replaces this default.
|
|
363
|
-
*/
|
|
364
|
-
type AgentDefaultMeta<TEventSchemas extends AgentEventSchemaInputMap> = AgentInteractionMeta<Exclude<keyof TEventSchemas & string, typeof AGENT_USAGE_EVENT_TYPE>>;
|
|
365
|
-
/**
|
|
366
|
-
* A machine's full schema set — context, event payloads, machine input/
|
|
367
|
-
* output, and state/transition meta — as returned by {@link createAgentSchemas}
|
|
368
|
-
* and retained on `setupAgent(...)`'s `result.schemas` for runtime
|
|
369
|
-
* validation (e.g. by `getAcceptedEvents` to attach event payload schemas). Unlike
|
|
370
|
-
* `AgentSchemaConfig` (the input to `createAgentSchemas`), every field here
|
|
371
|
-
* is required — `events`/`input`/`output`/`meta` default to empty/unknown
|
|
372
|
-
* schemas when not supplied.
|
|
373
|
-
*/
|
|
374
|
-
interface AgentSchemaPack<TContextSchema extends StandardSchemaV1<Record<string, unknown>> = StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap = AgentEventSchemaInputMap, TInputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TMetaSchema extends StandardSchemaV1 = StandardSchemaV1<AgentDefaultMeta<TEventSchemas>>, TEmittedSchemas extends Record<string, StandardSchemaV1> = Record<string, StandardSchemaV1>> {
|
|
375
|
-
context: TContextSchema;
|
|
376
|
-
events: NormalizedEventSchemas<TEventSchemas>;
|
|
377
|
-
input: TInputSchema;
|
|
378
|
-
output: TOutputSchema;
|
|
379
|
-
meta: TMetaSchema;
|
|
380
|
-
/** Schemas for events the machine emits (`enq.emit(...)`), keyed by event type — they type `enq.emit` in the machine and the `on` handlers of {@link createAgentRuntime}. Optional: omitted means emitted events stay untyped. */
|
|
381
|
-
emitted?: TEmittedSchemas;
|
|
382
|
-
}
|
|
383
|
-
type AgentSchemaConfig<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap, TInputSchema extends StandardSchemaV1, TOutputSchema extends StandardSchemaV1, TMetaSchema extends StandardSchemaV1, TEmittedSchemas extends Record<string, StandardSchemaV1> = Record<string, StandardSchemaV1>> = {
|
|
384
|
-
context: TContextSchema;
|
|
385
|
-
events?: TEventSchemas;
|
|
386
|
-
input?: TInputSchema;
|
|
387
|
-
output?: TOutputSchema;
|
|
388
|
-
meta?: TMetaSchema;
|
|
389
|
-
emitted?: TEmittedSchemas;
|
|
390
|
-
};
|
|
391
|
-
/**
|
|
392
|
-
* The payload of the reserved `'@agent.usage'` event — {@link AgentUsageEvent}
|
|
393
|
-
* without its `type`. It is what a machine's `'@agent.usage'` handler receives
|
|
394
|
-
* alongside `type`, since event schemas describe payloads only.
|
|
395
|
-
*/
|
|
396
|
-
type AgentUsageEventPayload = Omit<AgentUsageEvent, "type">;
|
|
397
|
-
/**
|
|
398
|
-
* An authored event schema map with the reserved `'@agent.usage'` entry added —
|
|
399
|
-
* every agent machine's event union includes it, so `on: { '@agent.usage': … }`
|
|
400
|
-
* is typed (and autocompletes) without the machine declaring anything.
|
|
401
|
-
* Idempotent: re-applying it to an already-registered map is a no-op.
|
|
402
|
-
*/
|
|
403
|
-
type WithAgentEvents<T extends AgentEventSchemaInputMap> = Omit<T, typeof AGENT_USAGE_EVENT_TYPE> & {
|
|
404
|
-
[AGENT_USAGE_EVENT_TYPE]: StandardSchemaV1<AgentUsageEventPayload>;
|
|
405
|
-
};
|
|
406
|
-
/** @deprecated Use {@link WithAgentEvents}. */
|
|
407
|
-
type WithAgentUsageEvent<T extends AgentEventSchemaInputMap> = WithAgentEvents<T>;
|
|
408
|
-
/**
|
|
409
|
-
* Builds a machine's {@link AgentSchemaPack} from a partial schema
|
|
410
|
-
* declaration — only `context` is required; `events`/`input`/`output`/`meta`
|
|
411
|
-
* default to empty/unknown schemas when omitted. Pass the result as
|
|
412
|
-
* `setupAgent({ schemas })`'s `schemas` (or spread the individual fields
|
|
413
|
-
* directly into `setupAgent({ context, events, ... })` — both forms are
|
|
414
|
-
* accepted).
|
|
415
|
-
*/
|
|
416
|
-
declare function createAgentSchemas<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap = {}, TInputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TOutputSchema extends StandardSchemaV1 = StandardSchemaV1<NonReducibleUnknown>, TMetaSchema extends StandardSchemaV1 = StandardSchemaV1<AgentDefaultMeta<TEventSchemas>>, TEmittedSchemas extends Record<string, StandardSchemaV1> = {}>(schemas: AgentSchemaConfig<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>): AgentSchemaPack<TContextSchema, WithAgentUsageEvent<TEventSchemas>, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>;
|
|
417
|
-
type AgentRequestSchemaMap = Record<string, {
|
|
418
|
-
input?: StandardSchemaV1;
|
|
419
|
-
output?: StandardSchemaV1;
|
|
420
|
-
}>;
|
|
421
|
-
type ResolvedRequestSchema<TSchema, TFallback> = [NonNullable<TSchema>] extends [never] ? TFallback : [NonNullable<TSchema>] extends [StandardSchemaV1] ? NonNullable<TSchema> : TFallback;
|
|
422
|
-
type RequestInputSchema<TSchemas extends {
|
|
423
|
-
input?: StandardSchemaV1;
|
|
424
|
-
}> = ResolvedRequestSchema<TSchemas["input"], StandardSchemaV1<undefined>>;
|
|
425
|
-
type RequestOutputSchema<TSchemas extends {
|
|
426
|
-
output?: StandardSchemaV1;
|
|
427
|
-
}> = ResolvedRequestSchema<TSchemas["output"], StandardSchemaV1<string>>;
|
|
428
|
-
type AgentRequestInput<TRequestSchemas extends AgentRequestSchemaMap, TModel extends string = string> = { [K in keyof TRequestSchemas]: Omit<TextLogicConfig<RequestInputSchema<TRequestSchemas[K]>, RequestOutputSchema<TRequestSchemas[K]>, Record<string, unknown>, TModel>, "schemas"> & {
|
|
429
|
-
schemas: TRequestSchemas[K];
|
|
430
|
-
} };
|
|
431
|
-
type RequestActors<TRequestSchemas extends AgentRequestSchemaMap> = { [K in keyof TRequestSchemas]: TextLogic<RequestInputSchema<TRequestSchemas[K]>, RequestOutputSchema<TRequestSchemas[K]>> };
|
|
432
|
-
type AgentAllActors<TActors extends { [K in keyof TActors]: AnyActorLogic }, TRequestSchemas extends AgentRequestSchemaMap> = TActors & RequestActors<TRequestSchemas>;
|
|
433
|
-
type AgentSetupEventsSchema<TEventSchemas extends AgentEventSchemaInputMap> = {
|
|
434
|
-
events: NormalizedEventSchemas<WithAgentUsageEvent<TEventSchemas>>;
|
|
435
|
-
};
|
|
436
|
-
type AgentSetupEmittedSchema<TEmittedSchemas extends Record<string, StandardSchemaV1>> = [keyof TEmittedSchemas] extends [never] ? {} : {
|
|
437
|
-
emitted: TEmittedSchemas;
|
|
438
|
-
};
|
|
439
150
|
/**
|
|
440
|
-
*
|
|
441
|
-
*
|
|
151
|
+
* Asks a model to choose the next event for ANY XState snapshot, including a
|
|
152
|
+
* machine built with plain `createMachine`/`setup` that knows nothing about AI.
|
|
153
|
+
* The candidates are the `allowedEvents` an active state handles, one option per
|
|
154
|
+
* payload, kept only where `snapshot.can(event)` is true; the rest come back as
|
|
155
|
+
* `withheld`. Each option is
|
|
156
|
+
* described from the transition's `description`, else the event schema's,
|
|
157
|
+
* plus (with `lookahead`) what it changes. The chosen event must equal one
|
|
158
|
+
* offered option; anything else is retried.
|
|
442
159
|
*
|
|
443
|
-
*
|
|
444
|
-
*
|
|
445
|
-
*
|
|
446
|
-
*
|
|
447
|
-
* (filling defaults) and reads this brand back through `AgentInputFrom` to
|
|
448
|
-
* accept the schema's looser *input* side, while the factory keeps seeing the
|
|
449
|
-
* validated *output* side.
|
|
450
|
-
*
|
|
451
|
-
* Only object-shaped input is branded: with no declared input schema the
|
|
452
|
-
* resolved type is xstate's `NonReducibleUnknown` (a union including `null`),
|
|
453
|
-
* and intersecting a brand into that collapses members to `never`.
|
|
454
|
-
*/
|
|
455
|
-
type BrandedInputSchema<TInputSchema extends StandardSchemaV1> = InferOutput<TInputSchema> extends Record<string, unknown> ? StandardSchemaV1<InferInput<TInputSchema>, InferOutput<TInputSchema> & WithAgentInputSchema<TInputSchema>> : TInputSchema;
|
|
456
|
-
type AgentSetupXStateConfig<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, SetupStateSchema> = Record<string, SetupStateSchema>> = {
|
|
457
|
-
schemas: {
|
|
458
|
-
context: TContextSchema;
|
|
459
|
-
input: BrandedInputSchema<TInputSchema>;
|
|
460
|
-
output: TOutputSchema;
|
|
461
|
-
meta: TMetaSchema;
|
|
462
|
-
} & AgentSetupEventsSchema<TEventSchemas> & AgentSetupEmittedSchema<TEmittedSchemas>;
|
|
463
|
-
states?: TStateSchemas;
|
|
464
|
-
actors: SetupActors<AgentSetupActors<AgentAllActors<TActors, TRequestSchemas>, Exclude<keyof TEventSchemas & string, typeof AGENT_USAGE_EVENT_TYPE>, AgentModelRef<TModels>>>;
|
|
465
|
-
actions?: NonNullable<AnySetupConfig["actions"]>;
|
|
466
|
-
guards?: NonNullable<AnySetupConfig["guards"]>;
|
|
467
|
-
delays?: NonNullable<AnySetupConfig["delays"]>;
|
|
468
|
-
};
|
|
469
|
-
type SetupAgentBaseConfig<TContextSchema extends StandardSchemaV1<Record<string, unknown>>, TEventSchemas extends AgentEventSchemaInputMap, 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, SetupStateSchema> = Record<string, SetupStateSchema>> = ({
|
|
470
|
-
schemas: AgentSchemaPack<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>;
|
|
471
|
-
} | AgentSchemaConfig<TContextSchema, TEventSchemas, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>) & {
|
|
472
|
-
models?: TModels;
|
|
473
|
-
actors?: TActors;
|
|
474
|
-
/**
|
|
475
|
-
* Per-state schemas, mirroring xstate's `setup({ states })`: narrow
|
|
476
|
-
* `context` inside a state (invoke `input`, transition fns, final `output`)
|
|
477
|
-
* — e.g. mark a field non-null in states only reachable after it is set.
|
|
478
|
-
* Use xstate's native `{ schemas: { context } }` form with a complete
|
|
479
|
-
* context schema.
|
|
480
|
-
*/
|
|
481
|
-
states?: TStateSchemas;
|
|
482
|
-
requests?: AgentRequestInput<TRequestSchemas, AgentModelRef<TModels>>;
|
|
483
|
-
actions?: NonNullable<AnySetupConfig["actions"]>;
|
|
484
|
-
guards?: AgentGuardSources<TContextSchema, TEventSchemas>;
|
|
485
|
-
delays?: AgentDelaySources<TContextSchema, TEventSchemas>;
|
|
486
|
-
};
|
|
487
|
-
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, SetupStateSchema> = Record<string, SetupStateSchema>> = SetupReturnFromConfig<AgentSetupXStateConfig<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>>;
|
|
488
|
-
/**
|
|
489
|
-
* The object returned by {@link setupAgent}: an xstate `setup(...)` result
|
|
490
|
-
* (`createMachine`, `assign`, …) extended with `schemas` (the resolved
|
|
491
|
-
* {@link AgentSchemaPack}), `models`, and `requests` (the built request
|
|
492
|
-
* actors). Machines created here are registered so
|
|
493
|
-
* `createAgentRuntime` can resolve their schemas/actors
|
|
494
|
-
* without re-passing them each call.
|
|
495
|
-
*/
|
|
496
|
-
type SetupAgentResult<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, SetupStateSchema> = Record<string, SetupStateSchema>> = Omit<SetupAgentXStateResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>, "createMachine"> & {
|
|
497
|
-
/**
|
|
498
|
-
* Creates the agent machine — XState's own `createMachine`, plus: the
|
|
499
|
-
* machine is registered so {@link createAgentRuntime} can resolve
|
|
500
|
-
* its schemas/actors without re-passing them, and a single final state's
|
|
501
|
-
* `output` is copied to the machine root when the root declares none.
|
|
502
|
-
*/
|
|
503
|
-
createMachine: SetupAgentXStateResult<TContextSchema, TEventSchemas, TActors, TRequestSchemas, TInputSchema, TOutputSchema, TMetaSchema, TModels, TEmittedSchemas, TStateSchemas>["createMachine"]; /** The retained schema pack ({@link AgentSchemaPack}) for host-side validation and tooling. Its `events` include the reserved `'@agent.usage'` entry setupAgent registers by default. */
|
|
504
|
-
schemas: AgentSchemaPack<TContextSchema, WithAgentUsageEvent<TEventSchemas>, TInputSchema, TOutputSchema, TMetaSchema, TEmittedSchemas>; /** The `models` registry passed to `setupAgent(...)`, if any (used to type-narrow `AgentModelRef`). */
|
|
505
|
-
readonly models: TModels; /** The {@link TextLogic} actors built from `setupAgent({ requests })`, keyed the same way. */
|
|
506
|
-
readonly requests: RequestActors<TRequestSchemas>;
|
|
507
|
-
};
|
|
508
|
-
/**
|
|
509
|
-
* Schema-first `setup(...)` for agent machines — the standard entry point
|
|
510
|
-
* for authoring a machine (the blueprint) that this library then runs (via
|
|
511
|
-
* {@link createAgentRuntime}) against host-supplied model/decision
|
|
512
|
-
* executors. Context, events, machine input, machine output, and
|
|
513
|
-
* state/transition meta are all standard schemas — no `{} as Type` casts —
|
|
514
|
-
* and are retained on `result.schemas` for runtime validation. Also
|
|
515
|
-
* registers the `agent.generateText`/`agent.streamText`/
|
|
516
|
-
* `agent.decide` builtin actors and lowers `requests`/`actors` into the
|
|
517
|
-
* machine's actor sources. The result is the xstate `setup(...)` object with
|
|
518
|
-
* a wrapped `result.createMachine(...)` plus `result.schemas`/`models`/
|
|
519
|
-
* `requests` attached. Also has a
|
|
520
|
-
* `setupAgent.fromConfig(...)` namespace member for building a machine from
|
|
521
|
-
* a serializable {@link AgentWorkflowConfig} instead of this TS API.
|
|
160
|
+
* It never sends. The host sends the event, re-checking `can` first, because
|
|
161
|
+
* the actor may have moved while the model was thinking. With no options it
|
|
162
|
+
* returns `{ event: null }` without calling the executor. Exhausting retries
|
|
163
|
+
* throws `AgentDecisionExhaustedError`.
|
|
522
164
|
*
|
|
523
165
|
* @example
|
|
524
|
-
* ```ts
|
|
525
|
-
*
|
|
526
|
-
*
|
|
527
|
-
*
|
|
528
|
-
*
|
|
529
|
-
*
|
|
530
|
-
*
|
|
531
|
-
*
|
|
532
|
-
*
|
|
533
|
-
*
|
|
534
|
-
* })
|
|
535
|
-
*
|
|
536
|
-
*
|
|
537
|
-
*
|
|
538
|
-
*
|
|
539
|
-
*
|
|
540
|
-
*
|
|
541
|
-
* invoke: {
|
|
542
|
-
* id: 'joke',
|
|
543
|
-
* src: 'tellJoke',
|
|
544
|
-
* input: ({ context }) => ({ topic: context.topic }),
|
|
545
|
-
* onDone: ({ output }) => ({ target: 'done', context: { joke: output } }),
|
|
546
|
-
* },
|
|
547
|
-
* },
|
|
548
|
-
* done: { type: 'final', output: ({ context }) => ({ joke: context.joke ?? '' }) },
|
|
549
|
-
* },
|
|
166
|
+
* ```ts no-check
|
|
167
|
+
* let busy = false;
|
|
168
|
+
* actor.subscribe(async (snapshot) => {
|
|
169
|
+
* if (busy || !snapshot.matches('reviewing')) return;
|
|
170
|
+
* busy = true;
|
|
171
|
+
* try {
|
|
172
|
+
* const { event } = await decideNext(snapshot, {
|
|
173
|
+
* decide,
|
|
174
|
+
* model: 'quick',
|
|
175
|
+
* allowedEvents: 'desk.*',
|
|
176
|
+
* payloads: (s) => ({ 'desk.refund': [{ amount: s.context.requested }] }),
|
|
177
|
+
* lookahead: true,
|
|
178
|
+
* });
|
|
179
|
+
* if (event && actor.getSnapshot().can(event)) actor.send(event);
|
|
180
|
+
* } finally {
|
|
181
|
+
* busy = false;
|
|
182
|
+
* }
|
|
550
183
|
* });
|
|
551
184
|
* ```
|
|
552
185
|
*/
|
|
553
|
-
declare function
|
|
554
|
-
declare namespace setupAgent {
|
|
555
|
-
/**
|
|
556
|
-
* Builds a state machine from a serializable {@link AgentWorkflowConfig}
|
|
557
|
-
* (JSON/YAML) instead of the TypeScript `setupAgent(...)` API — the same
|
|
558
|
-
* kind of machine a database, visual editor, or LLM could produce and hand
|
|
559
|
-
* back. Requires a `compileSchema` (see {@link FromConfigOptions}) since
|
|
560
|
-
* the library bundles no JSON Schema engine itself; bring Ajv,
|
|
561
|
-
* @cfworker/json-schema, or another compiler that returns Standard Schema.
|
|
562
|
-
*
|
|
563
|
-
* Returns the built `machine` plus the compiled `schemas` pack (context,
|
|
564
|
-
* events, input, output, meta, emitted) — a JSON-authored agent has no
|
|
565
|
-
* TypeScript types, so hosts need the runtime schemas for things like
|
|
566
|
-
* validating an inbound raw event with `parseAgentEvent`.
|
|
567
|
-
*
|
|
568
|
-
* @example
|
|
569
|
-
* ```ts
|
|
570
|
-
* const { machine, schemas } = setupAgent.fromConfig(workflowConfig, {
|
|
571
|
-
* compileSchema,
|
|
572
|
-
* });
|
|
573
|
-
* const result = await runToQuiescence(
|
|
574
|
-
* createAgentRuntime(machine, { executors: { generateText, decide } }),
|
|
575
|
-
* { input: { ticket } },
|
|
576
|
-
* );
|
|
577
|
-
* const event = parseAgentEvent(result.snapshot, raw, { events: schemas.events });
|
|
578
|
-
* ```
|
|
579
|
-
*/
|
|
580
|
-
function fromConfig(config: AgentWorkflowConfig, options: FromConfigOptions): FromConfigResult;
|
|
581
|
-
}
|
|
582
|
-
/**
|
|
583
|
-
* The schema pack a machine was built with — `setupAgent(...).createMachine`
|
|
584
|
-
* and `setupAgent.fromConfig(...)` both register one, so hosts can read a
|
|
585
|
-
* machine's input/event schemas at runtime without knowing how it was
|
|
586
|
-
* authored. Returns `undefined` for machines not built by either (a plain
|
|
587
|
-
* xstate `createMachine`/`setup` machine).
|
|
588
|
-
*
|
|
589
|
-
* Registration also travels through `machine.provide(...)`: the pack is keyed
|
|
590
|
-
* on the machine's root `config`, which `.provide` shares by reference.
|
|
591
|
-
*/
|
|
592
|
-
declare function getAgentSchemas(machine: AnyStateMachine): AgentSchemas | undefined;
|
|
186
|
+
export declare function decideNext<TSnapshot extends AnyMachineSnapshot>(snapshot: TSnapshot, options: DecideNextOptions<TSnapshot>): Promise<DecideNextResult<EventFromSnapshot<TSnapshot>>>;
|
|
593
187
|
//#endregion
|
|
594
188
|
//#region src/provide-executors.d.ts
|
|
595
189
|
/** Options for {@link provideExecutors}. */
|
|
@@ -657,6 +251,6 @@ interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMac
|
|
|
657
251
|
* with `.withExecutor(...)` or register the child as a string-keyed source. A
|
|
658
252
|
* source that already carries its own executor is never overwritten.
|
|
659
253
|
*/
|
|
660
|
-
declare function provideExecutors<TMachine extends AnyStateMachine>(machine: TMachine, executors: AgentRequestExecutors, options?: ProvideExecutorsOptions<TMachine>): TMachine;
|
|
254
|
+
export declare function provideExecutors<TMachine extends AnyStateMachine>(machine: TMachine, executors: AgentRequestExecutors, options?: ProvideExecutorsOptions<TMachine>): TMachine;
|
|
661
255
|
//#endregion
|
|
662
|
-
export { AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, type AgentCallUsage, type AgentDecisionExecutor, AgentDecisionExhaustedError, type AgentDecisionInput, type AgentDecisionRequest, type AgentDefaultMeta, type AgentEffects, AgentError, type AgentEventDescriptor, AgentEventLogConflictError, type AgentEventLogStore, type AgentExecutorDecisionRequest, type AgentExecutorTextRequest, type AgentFinishReason, type AgentInputFrom, type AgentInteraction, type AgentInteractionDescriptor, type AgentInteractionEvent, type AgentInteractionEventMeta, type AgentInteractionMeta, AgentInvalidEventPayloadError, type AgentLogEntry, AgentMachineVersionMismatchError, AgentMaxModelCallsExceededError, type AgentMessage, type AgentModelRef, type AgentOutputMode, type AgentRequest, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestOptions, type AgentRequestSource, type AgentRunErrorCause, type AgentRunInit, type AgentRunMeta, type AgentRunResult, type AgentRunStart, type AgentRuntime, type AgentRuntimeOptions, type AgentSchemaPack, type AgentSchemas, AgentSnapshotDivergedError, type AgentStepRequest, type AgentTextRequest, type AgentTextResult, type AgentTimerEvent, type AgentTimerScheduler, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentTools, type AgentTraceEvent, type AgentTransitionHandler, AgentTruncatedError, type AgentUsage, type AgentUsageEvent, type AgentUsageEventPayload, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AllowedEvents, type AssistantMessage, type ChosenEvent, type ContextOf, type CreateDecisionRequestOptions, type DecisionAttempt, type DecisionLogic, type DecisionLogicConfig, type DoneActorEventOf, type EventOf, type FilePart, type FromConfigOptions, type FromConfigResult, type GetInteractionOptions, type ImagePart, type InferInput, type InferOutput, type InputOf, type InspectedActorRef, type JsonSerializableTraceEvent, type MetaOf, type OutputOf, type ProvideExecutorsOptions, type ProviderStructuredOutput, type RequestNamesOf, type ResolveDecisionOptions, type SchemaCompiler, type SnapshotOf, type StandardSchemaV1, type StateValueOf, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultPart, type UserMessage, type WithAgentEvents, type WithAgentUsageEvent, assistantMessage, bindRequestExecutor, createAgentRuntime, createAgentSchemas, createDecisionLogic, createDecisionRequest, createTextLogic, eventFromInteraction, getAcceptedEvents, getAgentOutputMode, getAgentSchemas, getCallFinishReason, getCallUsage, getInteraction, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getMessageText, getStateMeta, getStatePath, inspectTransitions, interactionMetaSchema, isAgentIdle,
|
|
256
|
+
export { AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, type AgentCallUsage, type AgentDecisionExecutor, AgentDecisionExhaustedError, type AgentDecisionInput, type AgentDecisionOption, type AgentDecisionRequest, type AgentDefaultMeta, type AgentEffects, AgentError, type AgentEventDescriptor, AgentEventLogConflictError, type AgentEventLogStore, type AgentExecutorDecisionRequest, type AgentExecutorTextRequest, type AgentFinishReason, type AgentInputFrom, type AgentInteraction, type AgentInteractionChoice, type AgentInteractionDescriptor, type AgentInteractionEvent, type AgentInteractionEventMeta, type AgentInteractionMeta, AgentInvalidEventPayloadError, type AgentLogEntry, AgentMachineVersionMismatchError, AgentMaxModelCallsExceededError, type AgentMessage, type AgentModelRef, type AgentOutputMode, type AgentRequest, type AgentRequestExecutor, type AgentRequestExecutorInfo, type AgentRequestExecutorResult, type AgentRequestExecutors, type AgentRequestOptions, type AgentRequestSource, type AgentRunErrorCause, type AgentRunInit, type AgentRunMeta, type AgentRunOptions, type AgentRunResult, type AgentRunStart, type AgentRuntime, type AgentRuntimeOptions, type AgentSchemaPack, type AgentSchemas, AgentSnapshotDivergedError, type AgentStepRequest, type AgentTextRequest, type AgentTextResult, type AgentTimerEvent, type AgentTimerScheduler, type AgentTool, type AgentToolChoice, type AgentToolDescriptor, type AgentToolExecute, type AgentTools, type AgentTraceEvent, type AgentTransitionHandler, AgentTruncatedError, type AgentUsage, type AgentUsageEvent, type AgentUsageEventPayload, type AgentWorkflowActionConfig, type AgentWorkflowActorConfig, type AgentWorkflowConfig, type AgentWorkflowInvokeConfig, type AgentWorkflowRequestConfig, type AgentWorkflowStateConfig, type AgentWorkflowTransitionConfig, type AllowedEvents, type AssistantMessage, type ChosenEvent, type ContextOf, type CreateDecisionRequestOptions, type DecisionAttempt, type DecisionLogic, type DecisionLogicConfig, type DoneActorEventOf, type EventOf, type FilePart, type FromConfigOptions, type FromConfigResult, type GetInteractionOptions, type ImagePart, type InferInput, type InferOutput, type InputOf, type InspectedActorRef, type JsonSerializableTraceEvent, type MetaOf, type OutputOf, type ProvideExecutorsOptions, type ProviderStructuredOutput, type RequestNamesOf, type ResolveDecisionOptions, type SchemaCompiler, type SnapshotOf, type StandardSchemaV1, type StateValueOf, type SystemMessage, type TextLogic, type TextLogicConfig, type TextLogicExecuteArgs, type TextLogicExecutor, type TextPart, type ToolCallPart, type ToolMessage, type ToolResultPart, type UserMessage, type WithAgentEvents, type WithAgentUsageEvent, assistantMessage, bindRequestExecutor, createAgentRuntime, createAgentSchemas, createDecisionLogic, createDecisionRequest, createTextLogic, eventFromInteraction, getAcceptedEvents, getAgentOutputMode, getAgentSchemas, getCallFinishReason, getCallUsage, getInteraction, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getMessageText, getStateMeta, getStatePath, inspectTransitions, interactionMetaSchema, isAgentIdle, isStandardSchema, parseAgentEvent, parseOutput, parseProviderOutput, providerOutputSchema, renderDecisionAttempts, resolveDecision, runAgent, runToQuiescence, serializeTraceEvent, setupAgent, systemMessage, toolMessage, traceTransitions, userMessage };
|