@statelyai/agent 2.0.0-alpha.30 → 2.0.0-alpha.32
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/CHANGELOG.md +1743 -0
- package/dist/ai-sdk.cjs +8 -8
- package/dist/ai-sdk.d.cts +1 -1
- package/dist/ai-sdk.d.mts +1 -1
- package/dist/ai-sdk.mjs +3 -3
- package/dist/{decision-CIb7ddIv.cjs → decision-BPdEaxPf.cjs} +30 -17
- package/dist/{decision-BHkvuImD.mjs → decision-CV7WiV5C.mjs} +22 -9
- package/dist/{event-log-BZRfBRd7.cjs → event-log-CKWeC7H-.cjs} +125 -27
- package/dist/{event-log-DJCMHek_.mjs → event-log-DAqsalT1.mjs} +108 -28
- package/dist/{event-log-store-DsP6GCRh.mjs → event-log-store-BGehvVTb.mjs} +2 -2
- package/dist/{event-log-store-CIIJohjj.d.mts → event-log-store-C2NjVlWU.d.mts} +13 -5
- package/dist/{event-log-store-DZR4IIWe.cjs → event-log-store-DKyE7JKr.cjs} +2 -2
- package/dist/{event-log-store-CLAC9q2Y.d.cts → event-log-store-s73r1Hxf.d.cts} +13 -5
- package/dist/index.cjs +129 -21
- package/dist/index.d.cts +59 -11
- package/dist/index.d.mts +59 -11
- package/dist/index.mjs +126 -19
- package/dist/log.cjs +40 -5
- package/dist/log.d.cts +1 -1
- package/dist/log.d.mts +1 -1
- package/dist/log.mjs +40 -5
- package/dist/machines.cjs +1 -1
- package/dist/machines.mjs +1 -1
- package/dist/{model-source-BCKg4qJ1.cjs → model-source-BQ97_l1-.cjs} +4 -5
- package/dist/{model-source-BaHwJ1wK.mjs → model-source-BilDEyqk.mjs} +1 -2
- package/dist/openai.cjs +2 -2
- package/dist/openai.d.cts +1 -1
- package/dist/openai.d.mts +1 -1
- package/dist/openai.mjs +2 -2
- package/dist/otel.d.cts +1 -1
- package/dist/otel.d.mts +1 -1
- package/dist/{run-agent-BpHqkaZw.mjs → run-agent-2UnSUhDb.mjs} +93 -37
- package/dist/{run-agent-CAVt5R-r.d.mts → run-agent-Atu-wEk7.d.mts} +17 -6
- package/dist/{run-agent-CTlMc3Jb.d.cts → run-agent-B5QhabdY.d.cts} +17 -6
- package/dist/{run-agent-ctLCvNgL.cjs → run-agent-Cg0xd3K-.cjs} +93 -37
- package/dist/{setup-agent-CLPCkXsu.d.cts → setup-agent-BiF1N3td.d.cts} +11 -3
- package/dist/{setup-agent-7rV_cujV.mjs → setup-agent-CmhB-U5P.mjs} +38 -3
- package/dist/{setup-agent-DoUk7EdC.cjs → setup-agent-CwUJyqKB.cjs} +38 -3
- package/dist/{setup-agent-CGELn1qZ.d.mts → setup-agent-J9f_Wu5T.d.mts} +11 -3
- package/dist/tanstack-ai.cjs +3 -3
- package/dist/tanstack-ai.d.cts +1 -1
- package/dist/tanstack-ai.d.mts +1 -1
- package/dist/tanstack-ai.mjs +3 -3
- package/dist/testing.cjs +73 -29
- package/dist/testing.d.cts +47 -10
- package/dist/testing.d.mts +47 -10
- package/dist/testing.mjs +65 -22
- package/dist/{text-logic-DmciuVUQ.d.cts → text-logic-CYP502VT.d.cts} +9 -3
- package/dist/{text-logic-BRYOPWvY.d.mts → text-logic-DuK9HIFM.d.mts} +9 -3
- package/dist/{usage-BkM3z02Y.d.mts → usage-D7JKAxLc.d.mts} +1 -1
- package/dist/{usage-Cm_ovz9V.d.cts → usage-DVw-646x.d.cts} +1 -1
- package/dist/validate.cjs +3 -3
- package/dist/validate.d.cts +2 -2
- package/dist/validate.d.mts +2 -2
- package/dist/validate.mjs +3 -3
- package/dist/{verify-Cn86rT8l.d.mts → verify-BVz4cURF.d.mts} +14 -6
- package/dist/{verify-COFWyprJ.mjs → verify-CoCvR1eM.mjs} +55 -5
- package/dist/{verify-CVlsTZ-V.cjs → verify-D_llRCTr.cjs} +57 -7
- package/dist/{verify-Dzwd4Mvk.d.cts → verify-Dk3Vwnha.d.cts} +14 -6
- package/package.json +34 -4
- package/readme.md +70 -40
- package/skills/add-evals/SKILL.md +23 -8
- package/skills/add-traces/SKILL.md +23 -11
- package/skills/generate-machine/SKILL.md +2 -2
- package/skills/graph-engineering/SKILL.md +1 -1
- package/skills/improve-machine/SKILL.md +7 -6
- package/skills/loop-to-machine/SKILL.md +34 -7
- package/skills/loop-to-machine/policy.md +14 -18
package/dist/index.d.cts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
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-
|
|
3
|
-
import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-
|
|
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-
|
|
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-
|
|
6
|
-
import { c as AgentLogEntry, d as AgentMachineVersionMismatchError, n as AgentEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-
|
|
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-CYP502VT.cjs";
|
|
3
|
+
import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-DVw-646x.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-BiF1N3td.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-B5QhabdY.cjs";
|
|
6
|
+
import { c as AgentLogEntry, d as AgentMachineVersionMismatchError, n as AgentEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-s73r1Hxf.cjs";
|
|
7
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
8
|
import { AnyActorLogic, AnyMachineSnapshot, AnyStateMachine, ContextFrom, DoneActorEvent, EventFromLogic, InputFrom, OutputFrom, SnapshotFrom, StateValueFrom } from "xstate";
|
|
9
9
|
//#region src/type-helpers.d.ts
|
|
@@ -84,9 +84,10 @@ interface DescribeMachineOptions {
|
|
|
84
84
|
* label and description (`*` marks the active ones when `snapshot` is given),
|
|
85
85
|
* and under it every transition leaving it, one per line: `on EVENT`,
|
|
86
86
|
* `always`, `after <delay>`, invoke `done`/`error`, and `choice` branches,
|
|
87
|
-
* each with its
|
|
88
|
-
*
|
|
89
|
-
* machine's event schemas with their
|
|
87
|
+
* each with `(human)` when its `meta.actor` is `"human"`, its guard (`if …`),
|
|
88
|
+
* where it goes (`→ review`), and what it sets in context (`sets draft,
|
|
89
|
+
* attempts`). An `Events` section lists the machine's event schemas with their
|
|
90
|
+
* descriptions and fields.
|
|
90
91
|
*
|
|
91
92
|
* A transition written as a function shows the targets its source names
|
|
92
93
|
* (`→ review (conditional)` when it may decline or pick among several),
|
|
@@ -143,7 +144,9 @@ interface DecideNextResult<TEvent = ChosenEvent> {
|
|
|
143
144
|
/**
|
|
144
145
|
* The candidates the snapshot rejected: every `allowedEvents` type × payload,
|
|
145
146
|
* built the same way as the offered options, where `snapshot.can(event)` was
|
|
146
|
-
* false
|
|
147
|
+
* false or the state handles the type through a transition tagged
|
|
148
|
+
* `meta: { actor: "human" }`. Never offered to the model. Filled when
|
|
149
|
+
* nothing is offered too.
|
|
147
150
|
*/
|
|
148
151
|
withheld: ChosenEvent[];
|
|
149
152
|
}
|
|
@@ -151,7 +154,8 @@ interface DecideNextResult<TEvent = ChosenEvent> {
|
|
|
151
154
|
* Asks a model to choose the next event for ANY XState snapshot, including a
|
|
152
155
|
* machine built with plain `createMachine`/`setup` that knows nothing about AI.
|
|
153
156
|
* The candidates are the `allowedEvents` an active state handles, one option per
|
|
154
|
-
* payload, kept only where `snapshot.can(event)` is true
|
|
157
|
+
* payload, kept only where `snapshot.can(event)` is true and no transition
|
|
158
|
+
* tagged `meta: { actor: "human" }` handles the type; the rest come back as
|
|
155
159
|
* `withheld`. Each option is
|
|
156
160
|
* described from the transition's `description`, else the event schema's,
|
|
157
161
|
* plus (with `lookahead`) what it changes. The chosen event must equal one
|
|
@@ -185,6 +189,50 @@ interface DecideNextResult<TEvent = ChosenEvent> {
|
|
|
185
189
|
*/
|
|
186
190
|
export declare function decideNext<TSnapshot extends AnyMachineSnapshot>(snapshot: TSnapshot, options: DecideNextOptions<TSnapshot>): Promise<DecideNextResult<EventFromSnapshot<TSnapshot>>>;
|
|
187
191
|
//#endregion
|
|
192
|
+
//#region src/policy-decider.d.ts
|
|
193
|
+
/** Options for {@link createPolicyDecider}: everything {@link runAgent} takes for the policy run, except how the run opens. */
|
|
194
|
+
interface PolicyDeciderOptions<TPolicy extends AnyStateMachine> extends Omit<AgentRunOptions<TPolicy>, "input" | "event" | "attempts" | "snapshot" | "events" | "onIdle" | "signal" | "threadId"> {
|
|
195
|
+
/**
|
|
196
|
+
* The `store` thread for one decision's policy run. Every decision, and every
|
|
197
|
+
* retry of one, needs its own thread: a thread that already has entries is
|
|
198
|
+
* resumed, so a shared one would return an earlier decision's choice. Default
|
|
199
|
+
* with a `store`: `policy:${info.callKey}:${hash}`, where `hash` is the
|
|
200
|
+
* SHA-256 of the policy input's canonical JSON. The call key is unique per
|
|
201
|
+
* call and attempt and stays the same when a crashed run re-issues the call;
|
|
202
|
+
* the hash keeps a machine that asks something else at the same call site
|
|
203
|
+
* after a version bridge, which keeps the call key, off the earlier thread. Required
|
|
204
|
+
* with a `store` when the decider is called without a `callKey`.
|
|
205
|
+
*/
|
|
206
|
+
threadId?: (request: AgentExecutorDecisionRequest, info?: AgentRequestExecutorInfo) => string;
|
|
207
|
+
/**
|
|
208
|
+
* Builds the policy's input from the decision request. Default:
|
|
209
|
+
* `{ facts: request.metadata?.facts, options, system: request.system, prompt: request.prompt }`,
|
|
210
|
+
* where `options` are the offered events (`request.options[].event`). The
|
|
211
|
+
* policy's input schema validates it.
|
|
212
|
+
*/
|
|
213
|
+
input?: (request: AgentExecutorDecisionRequest) => InputFrom<TPolicy>;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Runs a policy machine as a decide executor: each decision request starts one
|
|
217
|
+
* run of `policy`, and its output is the chosen event. The policy can answer
|
|
218
|
+
* with a rule (a `choice` over the facts, no model call) and invoke
|
|
219
|
+
* `agent.decide` for the rest, answered by `options.executors`.
|
|
220
|
+
*
|
|
221
|
+
* The environment still judges the event: one it does not accept is retried
|
|
222
|
+
* like any other decider's choice. The policy's input must be JSON (it opens
|
|
223
|
+
* the policy run's event log): the default drops keys whose value is
|
|
224
|
+
* `undefined`, and any other value that is not JSON throws before the run. The policy's token usage is reported on the
|
|
225
|
+
* result, and left out when the policy made no model call. A run that does not
|
|
226
|
+
* end `done` with an event throws `AgentError` with code `policy-not-done`.
|
|
227
|
+
*
|
|
228
|
+
* @example
|
|
229
|
+
* ```ts no-check
|
|
230
|
+
* const decide = createPolicyDecider(policyMachine, { executors: modelExecutors });
|
|
231
|
+
* await runAgent(deskMachine, { input, executors: { ...modelExecutors, decide } });
|
|
232
|
+
* ```
|
|
233
|
+
*/
|
|
234
|
+
export declare function createPolicyDecider<TPolicy extends AnyStateMachine>(policy: TPolicy, options?: PolicyDeciderOptions<TPolicy>): AgentDecisionExecutor;
|
|
235
|
+
//#endregion
|
|
188
236
|
//#region src/provide-executors.d.ts
|
|
189
237
|
/** Options for {@link provideExecutors}. */
|
|
190
238
|
interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMachine> {
|
|
@@ -253,4 +301,4 @@ interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMac
|
|
|
253
301
|
*/
|
|
254
302
|
export declare function provideExecutors<TMachine extends AnyStateMachine>(machine: TMachine, executors: AgentRequestExecutors, options?: ProvideExecutorsOptions<TMachine>): TMachine;
|
|
255
303
|
//#endregion
|
|
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 };
|
|
304
|
+
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 PolicyDeciderOptions, 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 };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
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.mjs";
|
|
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-
|
|
3
|
-
import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-
|
|
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-
|
|
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-
|
|
6
|
-
import { c as AgentLogEntry, d as AgentMachineVersionMismatchError, n as AgentEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-
|
|
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-DuK9HIFM.mjs";
|
|
3
|
+
import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-D7JKAxLc.mjs";
|
|
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-J9f_Wu5T.mjs";
|
|
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-Atu-wEk7.mjs";
|
|
6
|
+
import { c as AgentLogEntry, d as AgentMachineVersionMismatchError, n as AgentEventLogStore, t as AgentEventLogConflictError } from "./event-log-store-C2NjVlWU.mjs";
|
|
7
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-BnXdWih3.mjs";
|
|
8
8
|
import { AnyActorLogic, AnyMachineSnapshot, AnyStateMachine, ContextFrom, DoneActorEvent, EventFromLogic, InputFrom, OutputFrom, SnapshotFrom, StateValueFrom } from "xstate";
|
|
9
9
|
//#region src/type-helpers.d.ts
|
|
@@ -84,9 +84,10 @@ interface DescribeMachineOptions {
|
|
|
84
84
|
* label and description (`*` marks the active ones when `snapshot` is given),
|
|
85
85
|
* and under it every transition leaving it, one per line: `on EVENT`,
|
|
86
86
|
* `always`, `after <delay>`, invoke `done`/`error`, and `choice` branches,
|
|
87
|
-
* each with its
|
|
88
|
-
*
|
|
89
|
-
* machine's event schemas with their
|
|
87
|
+
* each with `(human)` when its `meta.actor` is `"human"`, its guard (`if …`),
|
|
88
|
+
* where it goes (`→ review`), and what it sets in context (`sets draft,
|
|
89
|
+
* attempts`). An `Events` section lists the machine's event schemas with their
|
|
90
|
+
* descriptions and fields.
|
|
90
91
|
*
|
|
91
92
|
* A transition written as a function shows the targets its source names
|
|
92
93
|
* (`→ review (conditional)` when it may decline or pick among several),
|
|
@@ -143,7 +144,9 @@ interface DecideNextResult<TEvent = ChosenEvent> {
|
|
|
143
144
|
/**
|
|
144
145
|
* The candidates the snapshot rejected: every `allowedEvents` type × payload,
|
|
145
146
|
* built the same way as the offered options, where `snapshot.can(event)` was
|
|
146
|
-
* false
|
|
147
|
+
* false or the state handles the type through a transition tagged
|
|
148
|
+
* `meta: { actor: "human" }`. Never offered to the model. Filled when
|
|
149
|
+
* nothing is offered too.
|
|
147
150
|
*/
|
|
148
151
|
withheld: ChosenEvent[];
|
|
149
152
|
}
|
|
@@ -151,7 +154,8 @@ interface DecideNextResult<TEvent = ChosenEvent> {
|
|
|
151
154
|
* Asks a model to choose the next event for ANY XState snapshot, including a
|
|
152
155
|
* machine built with plain `createMachine`/`setup` that knows nothing about AI.
|
|
153
156
|
* The candidates are the `allowedEvents` an active state handles, one option per
|
|
154
|
-
* payload, kept only where `snapshot.can(event)` is true
|
|
157
|
+
* payload, kept only where `snapshot.can(event)` is true and no transition
|
|
158
|
+
* tagged `meta: { actor: "human" }` handles the type; the rest come back as
|
|
155
159
|
* `withheld`. Each option is
|
|
156
160
|
* described from the transition's `description`, else the event schema's,
|
|
157
161
|
* plus (with `lookahead`) what it changes. The chosen event must equal one
|
|
@@ -185,6 +189,50 @@ interface DecideNextResult<TEvent = ChosenEvent> {
|
|
|
185
189
|
*/
|
|
186
190
|
export declare function decideNext<TSnapshot extends AnyMachineSnapshot>(snapshot: TSnapshot, options: DecideNextOptions<TSnapshot>): Promise<DecideNextResult<EventFromSnapshot<TSnapshot>>>;
|
|
187
191
|
//#endregion
|
|
192
|
+
//#region src/policy-decider.d.ts
|
|
193
|
+
/** Options for {@link createPolicyDecider}: everything {@link runAgent} takes for the policy run, except how the run opens. */
|
|
194
|
+
interface PolicyDeciderOptions<TPolicy extends AnyStateMachine> extends Omit<AgentRunOptions<TPolicy>, "input" | "event" | "attempts" | "snapshot" | "events" | "onIdle" | "signal" | "threadId"> {
|
|
195
|
+
/**
|
|
196
|
+
* The `store` thread for one decision's policy run. Every decision, and every
|
|
197
|
+
* retry of one, needs its own thread: a thread that already has entries is
|
|
198
|
+
* resumed, so a shared one would return an earlier decision's choice. Default
|
|
199
|
+
* with a `store`: `policy:${info.callKey}:${hash}`, where `hash` is the
|
|
200
|
+
* SHA-256 of the policy input's canonical JSON. The call key is unique per
|
|
201
|
+
* call and attempt and stays the same when a crashed run re-issues the call;
|
|
202
|
+
* the hash keeps a machine that asks something else at the same call site
|
|
203
|
+
* after a version bridge, which keeps the call key, off the earlier thread. Required
|
|
204
|
+
* with a `store` when the decider is called without a `callKey`.
|
|
205
|
+
*/
|
|
206
|
+
threadId?: (request: AgentExecutorDecisionRequest, info?: AgentRequestExecutorInfo) => string;
|
|
207
|
+
/**
|
|
208
|
+
* Builds the policy's input from the decision request. Default:
|
|
209
|
+
* `{ facts: request.metadata?.facts, options, system: request.system, prompt: request.prompt }`,
|
|
210
|
+
* where `options` are the offered events (`request.options[].event`). The
|
|
211
|
+
* policy's input schema validates it.
|
|
212
|
+
*/
|
|
213
|
+
input?: (request: AgentExecutorDecisionRequest) => InputFrom<TPolicy>;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Runs a policy machine as a decide executor: each decision request starts one
|
|
217
|
+
* run of `policy`, and its output is the chosen event. The policy can answer
|
|
218
|
+
* with a rule (a `choice` over the facts, no model call) and invoke
|
|
219
|
+
* `agent.decide` for the rest, answered by `options.executors`.
|
|
220
|
+
*
|
|
221
|
+
* The environment still judges the event: one it does not accept is retried
|
|
222
|
+
* like any other decider's choice. The policy's input must be JSON (it opens
|
|
223
|
+
* the policy run's event log): the default drops keys whose value is
|
|
224
|
+
* `undefined`, and any other value that is not JSON throws before the run. The policy's token usage is reported on the
|
|
225
|
+
* result, and left out when the policy made no model call. A run that does not
|
|
226
|
+
* end `done` with an event throws `AgentError` with code `policy-not-done`.
|
|
227
|
+
*
|
|
228
|
+
* @example
|
|
229
|
+
* ```ts no-check
|
|
230
|
+
* const decide = createPolicyDecider(policyMachine, { executors: modelExecutors });
|
|
231
|
+
* await runAgent(deskMachine, { input, executors: { ...modelExecutors, decide } });
|
|
232
|
+
* ```
|
|
233
|
+
*/
|
|
234
|
+
export declare function createPolicyDecider<TPolicy extends AnyStateMachine>(policy: TPolicy, options?: PolicyDeciderOptions<TPolicy>): AgentDecisionExecutor;
|
|
235
|
+
//#endregion
|
|
188
236
|
//#region src/provide-executors.d.ts
|
|
189
237
|
/** Options for {@link provideExecutors}. */
|
|
190
238
|
interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMachine> {
|
|
@@ -253,4 +301,4 @@ interface ProvideExecutorsOptions<TMachine extends AnyStateMachine = AnyStateMac
|
|
|
253
301
|
*/
|
|
254
302
|
export declare function provideExecutors<TMachine extends AnyStateMachine>(machine: TMachine, executors: AgentRequestExecutors, options?: ProvideExecutorsOptions<TMachine>): TMachine;
|
|
255
303
|
//#endregion
|
|
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 };
|
|
304
|
+
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 PolicyDeciderOptions, 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 };
|
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { $ as getStateMeta, A as createTextLogic, C as AGENT_USAGE_EVENT_TYPE, H as getAgentExecutionOptions, I as parseOutput, L as parseProviderOutput, M as getCallFinishReason, N as getCallUsage, O as bindRequestExecutor, P as isTextLogic, Q as getMessageText, R as providerOutputSchema, V as executorBoundLogics, X as getJsonSchemaSync, Y as getJsonSchema, Z as getMachineStructuralHash, at as userMessage,
|
|
2
|
-
import { a as createDecisionRequest, c as renderDecisionAttempts, d as getAcceptedEvents, f as
|
|
3
|
-
import { n as getAgentSchemas, r as setupAgent, t as createAgentSchemas } from "./setup-agent-
|
|
4
|
-
import { t as AgentEventLogConflictError } from "./event-log-store-
|
|
5
|
-
import { a as bindDecisionForProvide, c as getConfiguredInvokeSrcs, d as isStateMachineLogic, f as runAgent, h as traceTransitions, i as bindChildMachineForProvide, l as inspectTransitions, m as serializeTraceEvent, n as AgentMaxModelCallsExceededError, o as bindTextForProvide, p as runToQuiescence, r as AgentSnapshotDivergedError, s as createAgentRuntime, t as AGENT_TRACE_SCHEMA_VERSION, u as isAgentIdle } from "./run-agent-
|
|
1
|
+
import { $ as getStateMeta, A as createTextLogic, C as AGENT_USAGE_EVENT_TYPE, H as getAgentExecutionOptions, I as parseOutput, L as parseProviderOutput, M as getCallFinishReason, N as getCallUsage, O as bindRequestExecutor, P as isTextLogic, Q as getMessageText, R as providerOutputSchema, V as executorBoundLogics, X as getJsonSchemaSync, Y as getJsonSchema, Z as getMachineStructuralHash, at as userMessage, dt as AgentTruncatedError, et as getStatePath, i as AgentMachineVersionMismatchError, it as toolMessage, j as getAgentOutputMode, l as assertJsonSerializable, lt as isRecord, q as assistantMessage, rt as systemMessage, tt as isStandardSchema, u as canonicalEventJson, ut as AgentError } from "./event-log-DAqsalT1.mjs";
|
|
2
|
+
import { a as createDecisionRequest, c as renderDecisionAttempts, d as getAcceptedEvents, f as getHumanEventTypes, i as createDecisionLogic, l as resolveDecision, m as parseAgentEvent, p as isEventPattern, s as isDecisionLogic, t as AgentDecisionExhaustedError, u as AgentInvalidEventPayloadError } from "./decision-CV7WiV5C.mjs";
|
|
3
|
+
import { n as getAgentSchemas, r as setupAgent, t as createAgentSchemas } from "./setup-agent-CmhB-U5P.mjs";
|
|
4
|
+
import { t as AgentEventLogConflictError } from "./event-log-store-BGehvVTb.mjs";
|
|
5
|
+
import { a as bindDecisionForProvide, c as getConfiguredInvokeSrcs, d as isStateMachineLogic, f as runAgent, h as traceTransitions, i as bindChildMachineForProvide, l as inspectTransitions, m as serializeTraceEvent, n as AgentMaxModelCallsExceededError, o as bindTextForProvide, p as runToQuiescence, r as AgentSnapshotDivergedError, s as createAgentRuntime, t as AGENT_TRACE_SCHEMA_VERSION, u as isAgentIdle } from "./run-agent-2UnSUhDb.mjs";
|
|
6
6
|
import { getNextTransitions, machineToJSON, transition } from "xstate";
|
|
7
7
|
//#region src/messages.ts
|
|
8
8
|
const KNOWN_PART_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -167,7 +167,8 @@ function validateChoice(value, path) {
|
|
|
167
167
|
* reads: an object whose optional `interaction` declares a `label` (a string
|
|
168
168
|
* with `{context.path}` interpolation, or a function of the context), an
|
|
169
169
|
* `events` map of choices, payload `choices` (an array, or a context path to
|
|
170
|
-
* one), and a `textEvent` (a type, or `{ type, field }`) for free-text answers
|
|
170
|
+
* one), and a `textEvent` (a type, or `{ type, field }`) for free-text answers; and
|
|
171
|
+
* an optional `actor: "human"`, which tags a transition as sent by a person. This is
|
|
171
172
|
* the default `meta` type `setupAgent` gives a machine; pass it to
|
|
172
173
|
* `createAgentSchemas({ meta: interactionMetaSchema })` only when building a
|
|
173
174
|
* schema pack by hand.
|
|
@@ -177,6 +178,8 @@ const interactionMetaSchema = { "~standard": {
|
|
|
177
178
|
vendor: "statelyai-agent",
|
|
178
179
|
validate(value) {
|
|
179
180
|
if (!value || typeof value !== "object" || Array.isArray(value)) return { issues: [{ message: "Expected a state meta object" }] };
|
|
181
|
+
const actor = value["actor"];
|
|
182
|
+
if (actor !== void 0 && actor !== "human") return { issues: [issue("Expected \"human\"", ["actor"])] };
|
|
180
183
|
const interaction = value["interaction"];
|
|
181
184
|
if (interaction === void 0) return { value };
|
|
182
185
|
if (!interaction || typeof interaction !== "object" || Array.isArray(interaction)) return { issues: [issue("Expected an interaction descriptor object", ["interaction"])] };
|
|
@@ -459,10 +462,36 @@ function guardText(guard) {
|
|
|
459
462
|
*/
|
|
460
463
|
const mayDecline = (code) => /\bundefined\b|\bnull\b|\bvoid 0\b|\breturn\s*;|\bif\s*\(|(?<!\?)\?(?![.?])|&&/.test(code.replace(/(["'`])(?:\\.|(?!\1)[^\\])*\1/g, "\"\""));
|
|
461
464
|
/**
|
|
465
|
+
* True when the function returns a call's result (`=> next(ctx)`, `return
|
|
466
|
+
* pick(x)`), so its target is not in its own source. Reads only the
|
|
467
|
+
* function's own returned expressions, not those of callbacks nested in it.
|
|
468
|
+
*/
|
|
469
|
+
function returnsCall(code) {
|
|
470
|
+
const text = code.replace(/(["'`])(?:\\.|(?!\1)[^\\])*\1/g, "\"\"");
|
|
471
|
+
const startsWithCall = (at) => /^[\s(]*[A-Za-z_$][\w$.]*\s*\(/.test(text.slice(at));
|
|
472
|
+
let parens = 0;
|
|
473
|
+
let body = -1;
|
|
474
|
+
for (let i = 0; i < text.length && body < 0; i++) {
|
|
475
|
+
const char = text[i];
|
|
476
|
+
if (char === "(") parens++;
|
|
477
|
+
else if (char === ")") parens--;
|
|
478
|
+
else if (parens === 0 && char === "=" && text[i + 1] === ">") body = i + 2;
|
|
479
|
+
else if (parens === 0 && char === "{") body = i;
|
|
480
|
+
}
|
|
481
|
+
if (body < 0) return false;
|
|
482
|
+
while (/\s/.test(text[body] ?? "")) body++;
|
|
483
|
+
if (text[body] !== "{") return startsWithCall(body);
|
|
484
|
+
let depth = 0;
|
|
485
|
+
for (let i = body; i < text.length; i++) if (text[i] === "{") depth++;
|
|
486
|
+
else if (text[i] === "}" && --depth === 0) return false;
|
|
487
|
+
else if (depth === 1 && text.startsWith("return", i) && !/[\w$]/.test(text[i - 1] ?? "") && !/[\w$]/.test(text[i + 6] ?? "") && startsWithCall(i + 6)) return true;
|
|
488
|
+
return false;
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
462
491
|
* Where a transition written as a function goes: every string literal after a
|
|
463
492
|
* `target:` that names a real state node, `(conditional)` when it may decline
|
|
464
493
|
* or pick among several, `(stays)` when its source has no `target`, `?` when
|
|
465
|
-
* it names none that resolves.
|
|
494
|
+
* it names none that resolves or returns a helper call's result.
|
|
466
495
|
*/
|
|
467
496
|
function targetsInSource(source, code, choice) {
|
|
468
497
|
const found = /* @__PURE__ */ new Set();
|
|
@@ -475,14 +504,15 @@ function targetsInSource(source, code, choice) {
|
|
|
475
504
|
const conditional = names.length > 1 || !choice && mayDecline(code);
|
|
476
505
|
return `${names.join(", ")}${conditional ? " (conditional)" : ""}`;
|
|
477
506
|
}
|
|
478
|
-
return /\btarget\s*:/.test(code) ? "?" : "(stays)";
|
|
507
|
+
return /\btarget\s*:/.test(code) || returnsCall(code) ? "?" : "(stays)";
|
|
479
508
|
}
|
|
480
|
-
/** One transition, as a line: `on GO if context.ready → review; sets draft — description`. */
|
|
509
|
+
/** One transition, as a line: `on GO (human) if context.ready → review; sets draft — description`. */
|
|
481
510
|
function transitionLine(source, head, transition, options = {}) {
|
|
482
511
|
const code = codeOf(transition);
|
|
483
512
|
let to;
|
|
484
513
|
let guard;
|
|
485
514
|
let description;
|
|
515
|
+
let human = false;
|
|
486
516
|
let sets;
|
|
487
517
|
if (typeof transition === "string") {
|
|
488
518
|
const node = resolveTarget(source, transition);
|
|
@@ -499,12 +529,13 @@ function transitionLine(source, head, transition, options = {}) {
|
|
|
499
529
|
}).join(", ") : "(stays)";
|
|
500
530
|
guard = guardText(transition[options.guardKey ?? "guard"]);
|
|
501
531
|
description = typeof transition.description === "string" ? transition.description : void 0;
|
|
532
|
+
human = isObject(transition.meta) && transition.meta.actor === "human";
|
|
502
533
|
sets = contextKeys(transition, void 0);
|
|
503
534
|
} else {
|
|
504
535
|
to = "?";
|
|
505
536
|
sets = [];
|
|
506
537
|
}
|
|
507
|
-
return `${head}${guard ? ` if ${guard}` : ""} → ${to}${sets.length ? `; sets ${sets.join(", ")}` : ""}${description ? ` — ${oneLine(description)}` : ""}`;
|
|
538
|
+
return `${head}${human ? " (human)" : ""}${guard ? ` if ${guard}` : ""} → ${to}${sets.length ? `; sets ${sets.join(", ")}` : ""}${description ? ` — ${oneLine(description)}` : ""}`;
|
|
508
539
|
}
|
|
509
540
|
function formatMs(ms) {
|
|
510
541
|
if (ms < 1e3) return `${ms}ms`;
|
|
@@ -551,7 +582,7 @@ function stateLine(node, json) {
|
|
|
551
582
|
else if (node.type === "compound" && typeof json.initial === "string") marker = ` (initial: ${json.initial})`;
|
|
552
583
|
const tags = node.tags.length ? ` [tags: ${node.tags.join(", ")}]` : "";
|
|
553
584
|
const interaction = node.meta?.interaction;
|
|
554
|
-
const label = typeof interaction
|
|
585
|
+
const label = !interaction ? "" : typeof interaction.label === "string" ? ` [interaction: "${oneLine(interaction.label)}"]` : typeof interaction.label === "function" ? " [interaction: computed label]" : " [interaction]";
|
|
555
586
|
const description = node.description ? ` — ${oneLine(node.description)}` : "";
|
|
556
587
|
return `${node.key}${marker}${tags}${label}${description}`;
|
|
557
588
|
}
|
|
@@ -588,9 +619,10 @@ function eventLines(machine) {
|
|
|
588
619
|
* label and description (`*` marks the active ones when `snapshot` is given),
|
|
589
620
|
* and under it every transition leaving it, one per line: `on EVENT`,
|
|
590
621
|
* `always`, `after <delay>`, invoke `done`/`error`, and `choice` branches,
|
|
591
|
-
* each with its
|
|
592
|
-
*
|
|
593
|
-
* machine's event schemas with their
|
|
622
|
+
* each with `(human)` when its `meta.actor` is `"human"`, its guard (`if …`),
|
|
623
|
+
* where it goes (`→ review`), and what it sets in context (`sets draft,
|
|
624
|
+
* attempts`). An `Events` section lists the machine's event schemas with their
|
|
625
|
+
* descriptions and fields.
|
|
594
626
|
*
|
|
595
627
|
* A transition written as a function shows the targets its source names
|
|
596
628
|
* (`→ review (conditional)` when it may decline or pick among several),
|
|
@@ -634,7 +666,8 @@ function describeMachine(machine, options = {}) {
|
|
|
634
666
|
* Asks a model to choose the next event for ANY XState snapshot, including a
|
|
635
667
|
* machine built with plain `createMachine`/`setup` that knows nothing about AI.
|
|
636
668
|
* The candidates are the `allowedEvents` an active state handles, one option per
|
|
637
|
-
* payload, kept only where `snapshot.can(event)` is true
|
|
669
|
+
* payload, kept only where `snapshot.can(event)` is true and no transition
|
|
670
|
+
* tagged `meta: { actor: "human" }` handles the type; the rest come back as
|
|
638
671
|
* `withheld`. Each option is
|
|
639
672
|
* described from the transition's `description`, else the event schema's,
|
|
640
673
|
* plus (with `lookahead`) what it changes. The chosen event must equal one
|
|
@@ -669,19 +702,21 @@ function describeMachine(machine, options = {}) {
|
|
|
669
702
|
async function decideNext(snapshot, options) {
|
|
670
703
|
const patterns = typeof options.allowedEvents === "string" ? [options.allowedEvents] : options.allowedEvents;
|
|
671
704
|
const schemas = snapshot.machine.schemas?.events;
|
|
672
|
-
const
|
|
705
|
+
const candidates = getAcceptedEvents(snapshot, {
|
|
673
706
|
events: schemas,
|
|
674
707
|
eventTypes: patterns
|
|
675
708
|
}).filter((event) => !isEventPattern(event.type));
|
|
709
|
+
const humanEventTypes = getHumanEventTypes(snapshot);
|
|
710
|
+
const events = candidates.filter((event) => !humanEventTypes.has(event.type));
|
|
676
711
|
const payloads = options.payloads?.(snapshot) ?? {};
|
|
677
712
|
const accepted = [];
|
|
678
713
|
const withheld = [];
|
|
679
|
-
for (const { type } of
|
|
714
|
+
for (const { type } of candidates) for (const payload of payloads[type] ?? [{}]) {
|
|
680
715
|
const event = {
|
|
681
716
|
...payload,
|
|
682
717
|
type
|
|
683
718
|
};
|
|
684
|
-
(safeCan(snapshot, event) ? accepted : withheld).push(event);
|
|
719
|
+
(!humanEventTypes.has(type) && safeCan(snapshot, event) ? accepted : withheld).push(event);
|
|
685
720
|
}
|
|
686
721
|
const offered = accepted.map((event) => ({
|
|
687
722
|
event,
|
|
@@ -771,6 +806,78 @@ function short(value, max = 60) {
|
|
|
771
806
|
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
772
807
|
}
|
|
773
808
|
//#endregion
|
|
809
|
+
//#region src/policy-decider.ts
|
|
810
|
+
/**
|
|
811
|
+
* Runs a policy machine as a decide executor: each decision request starts one
|
|
812
|
+
* run of `policy`, and its output is the chosen event. The policy can answer
|
|
813
|
+
* with a rule (a `choice` over the facts, no model call) and invoke
|
|
814
|
+
* `agent.decide` for the rest, answered by `options.executors`.
|
|
815
|
+
*
|
|
816
|
+
* The environment still judges the event: one it does not accept is retried
|
|
817
|
+
* like any other decider's choice. The policy's input must be JSON (it opens
|
|
818
|
+
* the policy run's event log): the default drops keys whose value is
|
|
819
|
+
* `undefined`, and any other value that is not JSON throws before the run. The policy's token usage is reported on the
|
|
820
|
+
* result, and left out when the policy made no model call. A run that does not
|
|
821
|
+
* end `done` with an event throws `AgentError` with code `policy-not-done`.
|
|
822
|
+
*
|
|
823
|
+
* @example
|
|
824
|
+
* ```ts no-check
|
|
825
|
+
* const decide = createPolicyDecider(policyMachine, { executors: modelExecutors });
|
|
826
|
+
* await runAgent(deskMachine, { input, executors: { ...modelExecutors, decide } });
|
|
827
|
+
* ```
|
|
828
|
+
*/
|
|
829
|
+
function createPolicyDecider(policy, options = {}) {
|
|
830
|
+
const { input = defaultInput, threadId, ...runOptions } = options;
|
|
831
|
+
const id = policy.config.id ?? policy.id;
|
|
832
|
+
return async (request, info) => {
|
|
833
|
+
const policyInput = input(request);
|
|
834
|
+
assertJsonSerializable(policyInput, "policy input");
|
|
835
|
+
const thread = runOptions.store === void 0 ? void 0 : await policyThread(request, policyInput, info);
|
|
836
|
+
const result = await runAgent(policy, {
|
|
837
|
+
...runOptions,
|
|
838
|
+
input: policyInput,
|
|
839
|
+
...thread === void 0 ? {} : { threadId: thread },
|
|
840
|
+
...info?.signal ? { signal: info.signal } : {}
|
|
841
|
+
});
|
|
842
|
+
if (result.status !== "done") {
|
|
843
|
+
const why = result.status === "error" ? `: ${String(result.error)}` : "";
|
|
844
|
+
throw new AgentError("policy-not-done", `policy '${id}' settled '${result.status}'${why}`, { cause: result.status === "error" ? result.error : void 0 });
|
|
845
|
+
}
|
|
846
|
+
const event = result.output;
|
|
847
|
+
if (!isRecord(event) || typeof event.type !== "string") throw new AgentError("policy-not-done", `policy '${id}' output is not an event: ${JSON.stringify(event)}`);
|
|
848
|
+
const { modelCalls, ...usage } = result.usage;
|
|
849
|
+
return {
|
|
850
|
+
event,
|
|
851
|
+
...modelCalls > 0 ? { usage } : {}
|
|
852
|
+
};
|
|
853
|
+
};
|
|
854
|
+
async function policyThread(request, policyInput, info) {
|
|
855
|
+
if (threadId) return threadId(request, info);
|
|
856
|
+
if (info?.callKey) return `policy:${info.callKey}:${await sha256(canonicalEventJson(policyInput))}`;
|
|
857
|
+
throw new AgentError("missing-thread-id", `policy '${id}' has a store but no threadId, and the decision came with no callKey to derive one from`);
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
function defaultInput(request) {
|
|
861
|
+
const facts = request.metadata?.facts;
|
|
862
|
+
return withoutUndefinedKeys({
|
|
863
|
+
facts,
|
|
864
|
+
options: (request.options ?? []).map((option) => option.event),
|
|
865
|
+
system: request.system,
|
|
866
|
+
prompt: request.prompt
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
/** A copy of `value` with every object key whose value is `undefined` removed, at any depth. */
|
|
870
|
+
function withoutUndefinedKeys(value) {
|
|
871
|
+
if (Array.isArray(value)) return value.map(withoutUndefinedKeys);
|
|
872
|
+
if (!isRecord(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return value;
|
|
873
|
+
return Object.fromEntries(Object.entries(value).filter(([, child]) => child !== void 0).map(([key, child]) => [key, withoutUndefinedKeys(child)]));
|
|
874
|
+
}
|
|
875
|
+
/** Hex SHA-256 of `text`, with Web Crypto (Node, browsers, workers). */
|
|
876
|
+
async function sha256(text) {
|
|
877
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
|
878
|
+
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
879
|
+
}
|
|
880
|
+
//#endregion
|
|
774
881
|
//#region src/provide-executors.ts
|
|
775
882
|
/**
|
|
776
883
|
* Binds a machine's agent actor sources to a set of host `executors` in one
|
|
@@ -884,4 +991,4 @@ function missingExecutorError(src, kind, executor) {
|
|
|
884
991
|
return /* @__PURE__ */ new Error(`provideExecutors: actor source '${src}' is a ${kind} source but no '${executor}' executor was provided. Add it to the executors object, or bind the source with its own executor (logic.withExecutor(...)) before calling provideExecutors.`);
|
|
885
992
|
}
|
|
886
993
|
//#endregion
|
|
887
|
-
export { AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, AgentDecisionExhaustedError, AgentError, AgentEventLogConflictError, AgentInvalidEventPayloadError, AgentMachineVersionMismatchError, AgentMaxModelCallsExceededError, AgentSnapshotDivergedError, AgentTruncatedError, assistantMessage, bindRequestExecutor, createAgentRuntime, createAgentSchemas, createDecisionLogic, createDecisionRequest, createTextLogic, decideNext, describeMachine, eventFromInteraction, getAcceptedEvents, getAgentOutputMode, getAgentSchemas, getCallFinishReason, getCallUsage, getInteraction, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getMessageText, getStateMeta, getStatePath, inspectTransitions, interactionMetaSchema, isAgentIdle, isAgentMessages, isStandardSchema, messagesSchema, parseAgentEvent, parseOutput, parseProviderOutput, provideExecutors, providerOutputSchema, renderDecisionAttempts, resolveDecision, runAgent, runToQuiescence, serializeTraceEvent, setupAgent, systemMessage, toolMessage, traceTransitions, userMessage };
|
|
994
|
+
export { AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, AgentDecisionExhaustedError, AgentError, AgentEventLogConflictError, AgentInvalidEventPayloadError, AgentMachineVersionMismatchError, AgentMaxModelCallsExceededError, AgentSnapshotDivergedError, AgentTruncatedError, assistantMessage, bindRequestExecutor, createAgentRuntime, createAgentSchemas, createDecisionLogic, createDecisionRequest, createPolicyDecider, createTextLogic, decideNext, describeMachine, eventFromInteraction, getAcceptedEvents, getAgentOutputMode, getAgentSchemas, getCallFinishReason, getCallUsage, getInteraction, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getMessageText, getStateMeta, getStatePath, inspectTransitions, interactionMetaSchema, isAgentIdle, isAgentMessages, isStandardSchema, messagesSchema, parseAgentEvent, parseOutput, parseProviderOutput, provideExecutors, providerOutputSchema, renderDecisionAttempts, resolveDecision, runAgent, runToQuiescence, serializeTraceEvent, setupAgent, systemMessage, toolMessage, traceTransitions, userMessage };
|
package/dist/log.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_event_log = require("./event-log-
|
|
3
|
-
const require_event_log_store = require("./event-log-store-
|
|
2
|
+
const require_event_log = require("./event-log-CKWeC7H-.cjs");
|
|
3
|
+
const require_event_log_store = require("./event-log-store-DKyE7JKr.cjs");
|
|
4
4
|
//#region src/event-log-store-conformance.ts
|
|
5
5
|
/**
|
|
6
6
|
* The runner-agnostic conformance suite for {@link AgentEventLogStore}
|
|
@@ -30,8 +30,11 @@ function entry(index, type, metadata) {
|
|
|
30
30
|
...metadata !== void 0 ? { metadata } : {}
|
|
31
31
|
};
|
|
32
32
|
}
|
|
33
|
+
function initFixture(executionId = "exec-src") {
|
|
34
|
+
return entry(0, require_event_log.AGENT_INIT_EVENT_TYPE, { executionId });
|
|
35
|
+
}
|
|
33
36
|
function entriesFrom(start, count) {
|
|
34
|
-
return Array.from({ length: count }, (_unused, i) => entry(start + i, `e${start + i}`));
|
|
37
|
+
return Array.from({ length: count }, (_unused, i) => start + i === 0 ? initFixture() : entry(start + i, `e${start + i}`));
|
|
35
38
|
}
|
|
36
39
|
function assertJsonEqual(actual, expected, message) {
|
|
37
40
|
const a = JSON.stringify(actual);
|
|
@@ -281,10 +284,42 @@ const cases = [
|
|
|
281
284
|
expectedIndex: 1,
|
|
282
285
|
entries: [entry(1, "branch")]
|
|
283
286
|
});
|
|
284
|
-
assertJsonEqual((await store.read("fork-1")).map((e) => e.event.type), [
|
|
287
|
+
assertJsonEqual((await store.read("fork-1")).map((e) => e.event.type), [require_event_log.AGENT_INIT_EVENT_TYPE, "branch"], "a forked thread must append independently from its copied length");
|
|
285
288
|
if (await store.length("src") !== 3) fail("appending to a fork must not touch the source thread");
|
|
286
289
|
}
|
|
287
290
|
},
|
|
291
|
+
{
|
|
292
|
+
name: "a fork is its own lineage: a fresh executionId, and forkedFrom naming the parent",
|
|
293
|
+
async run(create) {
|
|
294
|
+
const store = await create();
|
|
295
|
+
const source = entriesFrom(0, 3);
|
|
296
|
+
await store.append({
|
|
297
|
+
threadId: "src",
|
|
298
|
+
expectedIndex: 0,
|
|
299
|
+
entries: source
|
|
300
|
+
});
|
|
301
|
+
await store.fork({
|
|
302
|
+
threadId: "src",
|
|
303
|
+
newThreadId: "fork-a",
|
|
304
|
+
upToIndex: 2
|
|
305
|
+
});
|
|
306
|
+
await store.fork({
|
|
307
|
+
threadId: "src",
|
|
308
|
+
newThreadId: "fork-b",
|
|
309
|
+
upToIndex: 2
|
|
310
|
+
});
|
|
311
|
+
const [a, b] = [await store.read("fork-a"), await store.read("fork-b")];
|
|
312
|
+
const ids = [require_event_log.getLogExecutionId(a), require_event_log.getLogExecutionId(b)];
|
|
313
|
+
if (typeof ids[0] !== "string" || typeof ids[1] !== "string") fail("a fork's init entry must carry a string metadata.executionId");
|
|
314
|
+
if (ids.includes("exec-src") || ids[0] === ids[1]) fail("every fork must mint its own executionId, not reuse the parent's or a sibling's");
|
|
315
|
+
assertJsonEqual(a[0].metadata?.forkedFrom, {
|
|
316
|
+
executionId: "exec-src",
|
|
317
|
+
logIndex: 2
|
|
318
|
+
}, "a fork's init entry must record forkedFrom: { executionId, logIndex }");
|
|
319
|
+
assertJsonEqual(a.slice(1), source.slice(1, 2), "a fork must copy every entry after the init entry unchanged");
|
|
320
|
+
assertJsonEqual(await store.read("src"), source, "forking must not touch the source thread");
|
|
321
|
+
}
|
|
322
|
+
},
|
|
288
323
|
{
|
|
289
324
|
name: "fork rejects a non-empty target, an unknown source, and an out-of-range cutoff (0 included)",
|
|
290
325
|
async run(create) {
|
|
@@ -357,7 +392,7 @@ const cases = [
|
|
|
357
392
|
]) await store.append({
|
|
358
393
|
threadId,
|
|
359
394
|
expectedIndex: 0,
|
|
360
|
-
entries: [
|
|
395
|
+
entries: [initFixture()]
|
|
361
396
|
});
|
|
362
397
|
await store.fork({
|
|
363
398
|
threadId: "user:a",
|
package/dist/log.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as rebindActorSession, C as createReplayEntry, D as getSnapshotStateHash, E as getLogExecutionId, M as replay, N as validateReplayEntries, O as getUsageFromEvents, S as assertJsonSerializable, T as getDecisionAttempts, _ as NonSerializableAgentEventError, a as AGENT_INIT_EVENT_TYPE, b as agentCallOccurrence, c as AgentLogEntry, d as AgentMachineVersionMismatchError, f as AgentPersistedSnapshot, g as LogRecorder, h as JsonValue, i as AGENT_EVENT_SCHEMA_VERSION, j as recordLog, k as initEntry, l as AgentLogInit, m as CreateReplayEntryOptions, n as AgentEventLogStore, o as AgentEventLogError, p as AgentReplayDivergenceError, r as createInMemoryEventLogStore, s as AgentInitEvent, t as AgentEventLogConflictError, u as AgentLogVerification, v as ReplayOptions, w as forkEventLog, x as assertAgentLogEntry, y as ReplayResult } from "./event-log-store-
|
|
1
|
+
import { A as rebindActorSession, C as createReplayEntry, D as getSnapshotStateHash, E as getLogExecutionId, M as replay, N as validateReplayEntries, O as getUsageFromEvents, S as assertJsonSerializable, T as getDecisionAttempts, _ as NonSerializableAgentEventError, a as AGENT_INIT_EVENT_TYPE, b as agentCallOccurrence, c as AgentLogEntry, d as AgentMachineVersionMismatchError, f as AgentPersistedSnapshot, g as LogRecorder, h as JsonValue, i as AGENT_EVENT_SCHEMA_VERSION, j as recordLog, k as initEntry, l as AgentLogInit, m as CreateReplayEntryOptions, n as AgentEventLogStore, o as AgentEventLogError, p as AgentReplayDivergenceError, r as createInMemoryEventLogStore, s as AgentInitEvent, t as AgentEventLogConflictError, u as AgentLogVerification, v as ReplayOptions, w as forkEventLog, x as assertAgentLogEntry, y as ReplayResult } from "./event-log-store-s73r1Hxf.cjs";
|
|
2
2
|
//#region src/event-log-store-conformance.d.ts
|
|
3
3
|
/** Produces a fresh, empty store for one case. */
|
|
4
4
|
type CreateStore = () => Promise<AgentEventLogStore> | AgentEventLogStore;
|
package/dist/log.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as rebindActorSession, C as createReplayEntry, D as getSnapshotStateHash, E as getLogExecutionId, M as replay, N as validateReplayEntries, O as getUsageFromEvents, S as assertJsonSerializable, T as getDecisionAttempts, _ as NonSerializableAgentEventError, a as AGENT_INIT_EVENT_TYPE, b as agentCallOccurrence, c as AgentLogEntry, d as AgentMachineVersionMismatchError, f as AgentPersistedSnapshot, g as LogRecorder, h as JsonValue, i as AGENT_EVENT_SCHEMA_VERSION, j as recordLog, k as initEntry, l as AgentLogInit, m as CreateReplayEntryOptions, n as AgentEventLogStore, o as AgentEventLogError, p as AgentReplayDivergenceError, r as createInMemoryEventLogStore, s as AgentInitEvent, t as AgentEventLogConflictError, u as AgentLogVerification, v as ReplayOptions, w as forkEventLog, x as assertAgentLogEntry, y as ReplayResult } from "./event-log-store-
|
|
1
|
+
import { A as rebindActorSession, C as createReplayEntry, D as getSnapshotStateHash, E as getLogExecutionId, M as replay, N as validateReplayEntries, O as getUsageFromEvents, S as assertJsonSerializable, T as getDecisionAttempts, _ as NonSerializableAgentEventError, a as AGENT_INIT_EVENT_TYPE, b as agentCallOccurrence, c as AgentLogEntry, d as AgentMachineVersionMismatchError, f as AgentPersistedSnapshot, g as LogRecorder, h as JsonValue, i as AGENT_EVENT_SCHEMA_VERSION, j as recordLog, k as initEntry, l as AgentLogInit, m as CreateReplayEntryOptions, n as AgentEventLogStore, o as AgentEventLogError, p as AgentReplayDivergenceError, r as createInMemoryEventLogStore, s as AgentInitEvent, t as AgentEventLogConflictError, u as AgentLogVerification, v as ReplayOptions, w as forkEventLog, x as assertAgentLogEntry, y as ReplayResult } from "./event-log-store-C2NjVlWU.mjs";
|
|
2
2
|
//#region src/event-log-store-conformance.d.ts
|
|
3
3
|
/** Produces a fresh, empty store for one case. */
|
|
4
4
|
type CreateStore = () => Promise<AgentEventLogStore> | AgentEventLogStore;
|