@statelyai/agent 2.0.0-alpha.38 → 2.0.0-alpha.39
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 +45 -0
- package/dist/{act-CrX0JwWY.cjs → act-B0CVbmo4.cjs} +1 -1
- package/dist/{act-B9hLQls6.mjs → act-Bsz-hUfD.mjs} +1 -1
- package/dist/ai-sdk.cjs +4 -4
- package/dist/ai-sdk.d.cts +2 -3
- package/dist/ai-sdk.d.mts +2 -3
- package/dist/ai-sdk.mjs +4 -4
- package/dist/{decision-m5hGmHpF.mjs → decision-B41YBx5U.mjs} +1 -1
- package/dist/{decision-CMeuNZ1g.cjs → decision-D8bcIGXQ.cjs} +1 -1
- package/dist/{decision-object-DBcLWVvv.d.cts → decision-object-BB8XV5Ec.d.cts} +1 -1
- package/dist/{decision-object-B5zGSPFp.d.mts → decision-object-CH_sE694.d.mts} +1 -1
- package/dist/effects-B9IvUPVh.mjs +23 -0
- package/dist/effects-DrWcUGgc.cjs +34 -0
- package/dist/evals.cjs +810 -0
- package/dist/evals.d.cts +595 -0
- package/dist/evals.d.mts +595 -0
- package/dist/evals.mjs +801 -0
- package/dist/{event-log-DkVlk3Rh.mjs → event-log-CEq_bVXQ.mjs} +8 -4
- package/dist/{event-log-Dkc-yIYu.cjs → event-log-dSOnXHuG.cjs} +7 -15
- package/dist/{event-log-store-Brx9tOHt.mjs → event-log-store-DLAfNM34.mjs} +1 -1
- package/dist/{event-log-store-BBS8so8a.d.mts → event-log-store-DYun526m.d.mts} +15 -14
- package/dist/{event-log-store-Cl-YWDnq.cjs → event-log-store-Dey9ufA4.cjs} +1 -1
- package/dist/{event-log-store-bc4ICGcS.d.cts → event-log-store-aFXK6yZX.d.cts} +15 -14
- package/dist/index.cjs +131 -93
- package/dist/index.d.cts +73 -134
- package/dist/index.d.mts +73 -134
- package/dist/index.mjs +112 -70
- package/dist/internal-BzlpzSux.d.cts +14 -0
- package/dist/internal-BzlpzSux.d.mts +14 -0
- package/dist/log.cjs +2 -3
- package/dist/log.d.cts +2 -2
- package/dist/log.d.mts +2 -2
- package/dist/log.mjs +3 -3
- package/dist/machines.cjs +1 -719
- package/dist/machines.d.cts +2 -424
- package/dist/machines.d.mts +2 -424
- package/dist/machines.mjs +2 -709
- package/dist/{model-source-kjGwqAV8.mjs → model-source-BrsLDvHL.mjs} +1 -1
- package/dist/{model-source-B4WQ8Idp.cjs → model-source-YpxjmWuX.cjs} +1 -1
- package/dist/openai.cjs +3 -3
- package/dist/openai.d.cts +2 -3
- package/dist/openai.d.mts +2 -3
- package/dist/openai.mjs +3 -3
- package/dist/otel.d.cts +1 -1
- package/dist/otel.d.mts +1 -1
- package/dist/policy.cjs +77 -0
- package/dist/policy.d.cts +143 -0
- package/dist/policy.d.mts +143 -0
- package/dist/policy.mjs +75 -0
- package/dist/{effects-BT_cSY0j.mjs → run-agent-BE7DOWD6.mjs} +150 -184
- package/dist/{run-agent-DlPzBWj-.d.mts → run-agent-DHlq87G7.d.mts} +18 -34
- package/dist/{effects-DDseYtJk.cjs → run-agent-De3xVFGw.cjs} +149 -201
- package/dist/{run-agent-30mH2moE.d.cts → run-agent-Dq0oSFRm.d.cts} +18 -34
- package/dist/{setup-agent-BDmNr6PC.mjs → setup-agent-CLm6QVGy.mjs} +3 -3
- package/dist/{setup-agent-BaNyz6Q3.d.cts → setup-agent-Cv8Hk3mX.d.cts} +12 -11
- package/dist/{setup-agent-C1CG_nfX.d.mts → setup-agent-DgFAhaPJ.d.mts} +12 -11
- package/dist/{setup-agent-CmEToB8y.cjs → setup-agent-Dv5VpuHe.cjs} +3 -3
- package/dist/tanstack-ai.cjs +4 -4
- package/dist/tanstack-ai.d.cts +2 -3
- package/dist/tanstack-ai.d.mts +2 -3
- package/dist/tanstack-ai.mjs +4 -4
- package/dist/testing.cjs +122 -996
- package/dist/testing.d.cts +36 -695
- package/dist/testing.d.mts +36 -695
- package/dist/testing.mjs +112 -977
- package/dist/{text-logic-BqxalgMr.d.mts → text-logic-x17uLBwA.d.cts} +238 -2
- package/dist/{text-logic-CSf9bqpP.d.cts → text-logic-x17uLBwA.d.mts} +238 -2
- package/dist/trajectory-BFjXaooB.d.cts +96 -0
- package/dist/trajectory-BFjXaooB.d.mts +96 -0
- package/dist/trajectory-BUXj_1Ue.mjs +152 -0
- package/dist/trajectory-CoZSv4wF.cjs +157 -0
- package/dist/{usage-Bm5nvpow.d.cts → usage-B4B-TQSV.d.mts} +1 -1
- package/dist/{usage-BnikdOca.d.mts → usage-DvGcoK6x.d.cts} +1 -1
- package/dist/{utils-7lSa4H-i.d.cts → utils-B8k-YPYI.d.mts} +23 -17
- package/dist/{utils-CBbKw2fM.d.mts → utils-DAclF-kw.d.cts} +23 -17
- package/dist/validate.cjs +4 -4
- package/dist/validate.d.cts +2 -2
- package/dist/validate.d.mts +2 -2
- package/dist/validate.mjs +4 -4
- package/dist/{verify-DJHfEfm6.d.cts → verify-BM0sGmsf.d.cts} +42 -6
- package/dist/{verify-ChyX6jq0.mjs → verify-CWlg3j7B.mjs} +153 -45
- package/dist/{verify-CwlombbC.cjs → verify-Dek6gHCS.cjs} +153 -45
- package/dist/{verify-i9Hiwc5g.d.mts → verify-H3Pr2gNw.d.mts} +42 -6
- package/dist/{with-model-calls-B_WLmOSl.cjs → with-model-calls-D50Ca6qW.cjs} +2 -2
- package/dist/{with-model-calls-BkOwdroS.mjs → with-model-calls-uY-KKliA.mjs} +2 -2
- package/docs/advanced.md +5 -5
- package/docs/choosing-a-run-mode.md +7 -7
- package/docs/debugging.md +6 -8
- package/docs/decisions.md +5 -4
- package/docs/environment-and-policy.md +1 -1
- package/docs/evals.md +57 -43
- package/docs/event-log.md +13 -15
- package/docs/from-a-loop.md +3 -3
- package/docs/generate-machines.md +4 -4
- package/docs/hosts.md +20 -27
- package/docs/human-in-the-loop.md +5 -8
- package/docs/index.md +4 -4
- package/docs/judgments.md +5 -7
- package/docs/langgraph-comparison.md +6 -6
- package/docs/machines-as-data.md +7 -12
- package/docs/machines-presets.md +17 -120
- package/docs/machines.md +13 -13
- package/docs/models-and-providers.md +19 -25
- package/docs/multi-agent.md +1 -1
- package/docs/observability.md +6 -8
- package/docs/persistence.md +10 -20
- package/docs/quickstart.md +3 -3
- package/docs/statechart-policy-examples.md +1 -1
- package/docs/steps.md +5 -6
- package/docs/strangler-fig.md +72 -7
- package/docs/text-requests.md +10 -12
- package/docs/thinking-in-state-machines.md +8 -8
- package/docs/tools.md +10 -12
- package/docs/upgrading.md +1 -1
- package/docs/usage-and-budgets.md +51 -56
- package/docs/validate-and-repair.md +9 -14
- package/docs/verify.md +53 -7
- package/docs/xstate-4-and-5-apps.md +19 -28
- package/llms.txt +1 -1
- package/package.json +31 -6
- package/readme.md +32 -24
- package/dist/internal-C3Lqu538.d.cts +0 -43
- package/dist/internal-DUcdhk-i.d.mts +0 -43
- package/dist/types-DQUOOaZO.d.cts +0 -238
- package/dist/types-DQUOOaZO.d.mts +0 -238
- package/skills/add-evals/SKILL.md +0 -152
- package/skills/add-traces/SKILL.md +0 -152
- package/skills/build-machine/SKILL.md +0 -84
- package/skills/generate-machine/SKILL.md +0 -335
- package/skills/graph-engineering/SKILL.md +0 -43
- package/skills/improve-machine/SKILL.md +0 -261
- package/skills/improve-machine/reference.md +0 -101
- package/skills/loop-to-machine/SKILL.md +0 -205
- package/skills/loop-to-machine/policy.md +0 -154
- package/skills/loop-to-machine/reference.md +0 -260
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { G as getAgentExecutionOptions, ft as isRecord } from "./event-log-CEq_bVXQ.mjs";
|
|
2
2
|
//#region src/internal/model-source.ts
|
|
3
3
|
function hasEntries(value) {
|
|
4
4
|
return isRecord(value) && Object.keys(value).length > 0;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const require_event_log = require("./event-log-
|
|
1
|
+
const require_event_log = require("./event-log-dSOnXHuG.cjs");
|
|
2
2
|
//#region src/internal/model-source.ts
|
|
3
3
|
function hasEntries(value) {
|
|
4
4
|
return require_event_log.isRecord(value) && Object.keys(value).length > 0;
|
package/dist/openai.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_event_log = require("./event-log-
|
|
3
|
-
const require_decision = require("./decision-
|
|
4
|
-
const require_with_model_calls = require("./with-model-calls-
|
|
2
|
+
const require_event_log = require("./event-log-dSOnXHuG.cjs");
|
|
3
|
+
const require_decision = require("./decision-D8bcIGXQ.cjs");
|
|
4
|
+
const require_with_model_calls = require("./with-model-calls-D50Ca6qW.cjs");
|
|
5
5
|
//#region src/openai/index.ts
|
|
6
6
|
/** Thrown for a message part Chat Completions cannot carry — dropping it would
|
|
7
7
|
* silently change what the model sees. */
|
package/dist/openai.d.cts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { n as DecisionModeOption, t as DecisionMode } from "./decision-object-DBcLWVvv.cjs";
|
|
1
|
+
import { I as AgentDecisionRejection, L as AgentDecisionRequest, Z as AgentEventDescriptor, c as AgentRequestExecutorInfo, dt as AgentToolChoice, f as AgentTextRequest, ht as AgentTools, lt as AgentMessage, r as AgentFinishReason, t as AgentCallUsage, yt as ChosenEvent } from "./text-logic-x17uLBwA.cjs";
|
|
2
|
+
import { n as DecisionModeOption, t as DecisionMode } from "./decision-object-BB8XV5Ec.cjs";
|
|
4
3
|
import OpenAI from "openai";
|
|
5
4
|
import { ChatCompletion, ChatCompletionCreateParamsNonStreaming, ChatCompletionMessageParam } from "openai/resources/chat/completions/completions.js";
|
|
6
5
|
import { FunctionTool, Response, ResponseInputItem, ResponseUsage } from "openai/resources/responses/responses.js";
|
package/dist/openai.d.mts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { n as DecisionModeOption, t as DecisionMode } from "./decision-object-B5zGSPFp.mjs";
|
|
1
|
+
import { I as AgentDecisionRejection, L as AgentDecisionRequest, Z as AgentEventDescriptor, c as AgentRequestExecutorInfo, dt as AgentToolChoice, f as AgentTextRequest, ht as AgentTools, lt as AgentMessage, r as AgentFinishReason, t as AgentCallUsage, yt as ChosenEvent } from "./text-logic-x17uLBwA.mjs";
|
|
2
|
+
import { n as DecisionModeOption, t as DecisionMode } from "./decision-object-CH_sE694.mjs";
|
|
4
3
|
import OpenAI from "openai";
|
|
5
4
|
import { ChatCompletion, ChatCompletionCreateParamsNonStreaming, ChatCompletionMessageParam } from "openai/resources/chat/completions/completions.js";
|
|
6
5
|
import { FunctionTool, Response, ResponseInputItem, ResponseUsage } from "openai/resources/responses/responses.js";
|
package/dist/openai.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
import { c as renderDecisionAttempts } from "./decision-
|
|
3
|
-
import { a as multipleCallsRejection, i as fromDecisionObject, n as rejectedAnswer, o as resolveDecisionMode, r as decisionObjectSchema, t as withModelCalls } from "./with-model-calls-
|
|
1
|
+
import { $ as getJsonSchemaSync, B as parseProviderOutput, E as AGENT_USAGE_TOKEN_FIELDS, N as getAgentOutputMode, Q as getJsonSchema, V as providerOutputSchema, mt as AgentTruncatedError, rt as isStandardSchema } from "./event-log-CEq_bVXQ.mjs";
|
|
2
|
+
import { c as renderDecisionAttempts } from "./decision-B41YBx5U.mjs";
|
|
3
|
+
import { a as multipleCallsRejection, i as fromDecisionObject, n as rejectedAnswer, o as resolveDecisionMode, r as decisionObjectSchema, t as withModelCalls } from "./with-model-calls-uY-KKliA.mjs";
|
|
4
4
|
//#region src/openai/index.ts
|
|
5
5
|
/** Thrown for a message part Chat Completions cannot carry — dropping it would
|
|
6
6
|
* silently change what the model sees. */
|
package/dist/otel.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { _ as AgentTraceEvent } from "./run-agent-
|
|
1
|
+
import { _ as AgentTraceEvent } from "./run-agent-Dq0oSFRm.cjs";
|
|
2
2
|
import { Attributes, Tracer, TracerProvider } from "@opentelemetry/api";
|
|
3
3
|
//#region src/otel/index.d.ts
|
|
4
4
|
/** Options for {@link createOtelTraceHandler}. */
|
package/dist/otel.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { _ as AgentTraceEvent } from "./run-agent-
|
|
1
|
+
import { _ as AgentTraceEvent } from "./run-agent-DHlq87G7.mjs";
|
|
2
2
|
import { Attributes, Tracer, TracerProvider } from "@opentelemetry/api";
|
|
3
3
|
//#region src/otel/index.d.ts
|
|
4
4
|
/** Options for {@link createOtelTraceHandler}. */
|
package/dist/policy.cjs
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_event_log = require("./event-log-dSOnXHuG.cjs");
|
|
3
|
+
const require_run_agent = require("./run-agent-De3xVFGw.cjs");
|
|
4
|
+
//#region src/policy-decider.ts
|
|
5
|
+
/**
|
|
6
|
+
* Runs a policy machine as a decide executor: each decision request starts one
|
|
7
|
+
* run of `policy`, and its output is the chosen event. The policy can answer
|
|
8
|
+
* with a rule (a `choice` over the facts, no model call) and invoke
|
|
9
|
+
* `agent.decide` for the rest, answered by `options.executors`.
|
|
10
|
+
*
|
|
11
|
+
* The environment still judges the event: one it does not accept is retried
|
|
12
|
+
* like any other decider's choice. The policy's input must be JSON (it opens
|
|
13
|
+
* the policy run's event log): the default drops keys whose value is
|
|
14
|
+
* `undefined`, and any other value that is not JSON throws before the run. The policy's token usage is reported on the
|
|
15
|
+
* result, and left out when the policy made no model call. A run that does not
|
|
16
|
+
* end `done` with an event throws `AgentError` with code `policy-not-done`.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts no-check
|
|
20
|
+
* const decide = createPolicyDecider(policyMachine, { executors: modelExecutors });
|
|
21
|
+
* await runAgent(deskMachine, { input, executors: { ...modelExecutors, decide } });
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
function createPolicyDecider(policy, options = {}) {
|
|
25
|
+
const { input = defaultInput, threadId, ...runOptions } = options;
|
|
26
|
+
const id = policy.config.id ?? policy.id;
|
|
27
|
+
return async (request, info) => {
|
|
28
|
+
const policyInput = input(request);
|
|
29
|
+
require_event_log.assertJsonSerializable(policyInput, "policy input");
|
|
30
|
+
const thread = runOptions.store === void 0 ? void 0 : await policyThread(request, policyInput, info);
|
|
31
|
+
const result = await require_run_agent.runAgent(policy, {
|
|
32
|
+
...runOptions,
|
|
33
|
+
input: policyInput,
|
|
34
|
+
...thread === void 0 ? {} : { threadId: thread },
|
|
35
|
+
...info?.signal ? { signal: info.signal } : {}
|
|
36
|
+
});
|
|
37
|
+
if (result.status !== "done") {
|
|
38
|
+
const why = result.status === "error" ? `: ${String(result.error)}` : "";
|
|
39
|
+
throw new require_event_log.AgentError("policy-not-done", `policy '${id}' settled '${result.status}'${why}`, { cause: result.status === "error" ? result.error : void 0 });
|
|
40
|
+
}
|
|
41
|
+
const event = result.output;
|
|
42
|
+
if (!require_event_log.isRecord(event) || typeof event.type !== "string") throw new require_event_log.AgentError("policy-not-done", `policy '${id}' output is not an event: ${JSON.stringify(event)}`);
|
|
43
|
+
const { modelCalls, ...usage } = result.usage;
|
|
44
|
+
return {
|
|
45
|
+
event,
|
|
46
|
+
...modelCalls > 0 ? { usage } : {}
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
async function policyThread(request, policyInput, info) {
|
|
50
|
+
if (threadId) return threadId(request, info);
|
|
51
|
+
if (info?.callKey) return `policy:${info.callKey}:${await sha256(require_event_log.canonicalEventJson(policyInput))}`;
|
|
52
|
+
throw new require_event_log.AgentError("missing-thread-id", `policy '${id}' has a store but no threadId, and the decision came with no callKey to derive one from`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function defaultInput(request) {
|
|
56
|
+
const facts = request.metadata?.facts;
|
|
57
|
+
return withoutUndefinedKeys({
|
|
58
|
+
facts,
|
|
59
|
+
options: (request.options ?? []).map((option) => option.event),
|
|
60
|
+
system: request.system,
|
|
61
|
+
prompt: request.prompt
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
/** A copy of `value` with every object key whose value is `undefined` removed, at any depth. */
|
|
65
|
+
function withoutUndefinedKeys(value) {
|
|
66
|
+
if (Array.isArray(value)) return value.map(withoutUndefinedKeys);
|
|
67
|
+
if (!require_event_log.isRecord(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return value;
|
|
68
|
+
return Object.fromEntries(Object.entries(value).filter(([, child]) => child !== void 0).map(([key, child]) => [key, withoutUndefinedKeys(child)]));
|
|
69
|
+
}
|
|
70
|
+
/** Hex SHA-256 of `text`, with Web Crypto (Node, browsers, workers). */
|
|
71
|
+
async function sha256(text) {
|
|
72
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
|
73
|
+
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
74
|
+
}
|
|
75
|
+
//#endregion
|
|
76
|
+
exports.createPolicyDecider = createPolicyDecider;
|
|
77
|
+
exports.decideNext = require_run_agent.decideNext;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { B as DecisionAttempt, J as DecisionStrategy, L as AgentDecisionRequest, M as AgentDecisionExecutor, R as AgentExecutorDecisionRequest, c as AgentRequestExecutorInfo, nt as EventFromSnapshot, s as AgentRequestExecutor, yt as ChosenEvent } from "./text-logic-x17uLBwA.cjs";
|
|
2
|
+
import { l as AgentRunOptions } from "./run-agent-Dq0oSFRm.cjs";
|
|
3
|
+
import { AnyMachineSnapshot, AnyStateMachine, InputFrom } from "xstate";
|
|
4
|
+
//#region src/decide-next.d.ts
|
|
5
|
+
/** Options for {@link decideNext}. */
|
|
6
|
+
interface DecideNextOptions<TSnapshot extends AnyMachineSnapshot = AnyMachineSnapshot> {
|
|
7
|
+
/** The decide executor that asks a model to pick one option. */
|
|
8
|
+
decide: AgentDecisionExecutor;
|
|
9
|
+
/** Model ref, passed through to the executor. */
|
|
10
|
+
model: string;
|
|
11
|
+
/** Event types the model may choose: exact types or wildcards (`'desk.*'`, `'*'`). */
|
|
12
|
+
allowedEvents: string | readonly string[];
|
|
13
|
+
/**
|
|
14
|
+
* Concrete payloads per event type, without `type`. One option per payload.
|
|
15
|
+
* A candidate type with no key is offered bare, as `{ type }`; an empty list
|
|
16
|
+
* offers nothing for it. To withhold a type, give it `[]`:
|
|
17
|
+
* `(s) => ({ "desk.refund": [{ amount: s.context.requested }], "desk.close": [] })`.
|
|
18
|
+
*/
|
|
19
|
+
payloads?: (snapshot: TSnapshot) => Partial<Record<string, Record<string, unknown>[]>>;
|
|
20
|
+
system?: string;
|
|
21
|
+
prompt?: string;
|
|
22
|
+
/** Semantic request name, for traces and scripted executors. Default `'decideNext'`. */
|
|
23
|
+
name?: string;
|
|
24
|
+
/**
|
|
25
|
+
* Describe what each option changes: the state value and the changed
|
|
26
|
+
* top-level context keys, computed with xstate's pure `transition()`.
|
|
27
|
+
* An array limits which context keys are reported (a state value change is
|
|
28
|
+
* always reported). Each reported value is cut to 120 characters.
|
|
29
|
+
*/
|
|
30
|
+
lookahead?: boolean | readonly string[];
|
|
31
|
+
/** Retries after a failed choice. Default `2`. */
|
|
32
|
+
maxRetries?: number;
|
|
33
|
+
signal?: AbortSignal;
|
|
34
|
+
/** How the decision is split into model calls. Default `'auto'`; see {@link DecisionStrategy}. */
|
|
35
|
+
strategy?: DecisionStrategy;
|
|
36
|
+
/** Model ref that fills open payload fields under `'pick-then-fill'`. */
|
|
37
|
+
fillModel?: string;
|
|
38
|
+
/** Named groups of event types for `'grouped'`; the rest group by prefix before the first `.`. */
|
|
39
|
+
groups?: Record<string, readonly string[]>;
|
|
40
|
+
/** Fills open payload fields with `fillModel`. */
|
|
41
|
+
generateText?: AgentRequestExecutor;
|
|
42
|
+
}
|
|
43
|
+
/** Result of {@link decideNext}. */
|
|
44
|
+
interface DecideNextResult<TEvent = ChosenEvent> {
|
|
45
|
+
/** The chosen event, or `null` when the snapshot accepts none of the options. */
|
|
46
|
+
event: TEvent | null;
|
|
47
|
+
/** Failed attempts before the choice landed. */
|
|
48
|
+
attempts: DecisionAttempt[];
|
|
49
|
+
/** The request built for the executor, with the offered `options` and the same `withheld`. */
|
|
50
|
+
request: AgentDecisionRequest;
|
|
51
|
+
/**
|
|
52
|
+
* The candidates the snapshot rejected: every `allowedEvents` type × payload,
|
|
53
|
+
* built the same way as the offered options, where `snapshot.can(event)` was
|
|
54
|
+
* false or the state handles the type through a transition tagged
|
|
55
|
+
* `meta: { actor: "human" }`. Never offered to the model. Filled when
|
|
56
|
+
* nothing is offered too.
|
|
57
|
+
*/
|
|
58
|
+
withheld: ChosenEvent[];
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Asks a model to choose the next event for ANY XState snapshot, including a
|
|
62
|
+
* machine built with plain `createMachine`/`setup` that knows nothing about AI.
|
|
63
|
+
* The candidates are the `allowedEvents` an active state handles, one option per
|
|
64
|
+
* payload, kept only where `snapshot.can(event)` is true and no transition
|
|
65
|
+
* tagged `meta: { actor: "human" }` handles the type; the rest come back as
|
|
66
|
+
* `withheld`. Each option is
|
|
67
|
+
* described from the transition's `description`, else the event schema's,
|
|
68
|
+
* plus (with `lookahead`) what it changes. The chosen event must equal one
|
|
69
|
+
* offered option; anything else is retried.
|
|
70
|
+
*
|
|
71
|
+
* It never sends. The host sends the event, re-checking `can` first, because
|
|
72
|
+
* the actor may have moved while the model was thinking. With no options it
|
|
73
|
+
* returns `{ event: null }` without calling the executor. Exhausting retries
|
|
74
|
+
* throws `AgentDecisionExhaustedError`.
|
|
75
|
+
*
|
|
76
|
+
* @example
|
|
77
|
+
* ```ts no-check
|
|
78
|
+
* let busy = false;
|
|
79
|
+
* actor.subscribe(async (snapshot) => {
|
|
80
|
+
* if (busy || !snapshot.matches('reviewing')) return;
|
|
81
|
+
* busy = true;
|
|
82
|
+
* try {
|
|
83
|
+
* const { event } = await decideNext(snapshot, {
|
|
84
|
+
* decide,
|
|
85
|
+
* model: 'quick',
|
|
86
|
+
* allowedEvents: 'desk.*',
|
|
87
|
+
* payloads: (s) => ({ 'desk.refund': [{ amount: s.context.requested }] }),
|
|
88
|
+
* lookahead: true,
|
|
89
|
+
* });
|
|
90
|
+
* if (event && actor.getSnapshot().can(event)) actor.send(event);
|
|
91
|
+
* } finally {
|
|
92
|
+
* busy = false;
|
|
93
|
+
* }
|
|
94
|
+
* });
|
|
95
|
+
* ```
|
|
96
|
+
*/
|
|
97
|
+
export declare function decideNext<TSnapshot extends AnyMachineSnapshot>(snapshot: TSnapshot, options: DecideNextOptions<TSnapshot>): Promise<DecideNextResult<EventFromSnapshot<TSnapshot>>>;
|
|
98
|
+
//#endregion
|
|
99
|
+
//#region src/policy-decider.d.ts
|
|
100
|
+
/** Options for {@link createPolicyDecider}: everything {@link runAgent} takes for the policy run, except how the run opens. */
|
|
101
|
+
interface PolicyDeciderOptions<TPolicy extends AnyStateMachine> extends Omit<AgentRunOptions<TPolicy>, "input" | "event" | "attempts" | "snapshot" | "events" | "onIdle" | "signal" | "threadId"> {
|
|
102
|
+
/**
|
|
103
|
+
* The `store` thread for one decision's policy run. Every decision, and every
|
|
104
|
+
* retry of one, needs its own thread: a thread that already has entries is
|
|
105
|
+
* resumed, so a shared one would return an earlier decision's choice. Default
|
|
106
|
+
* with a `store`: `policy:${info.callKey}:${hash}`, where `hash` is the
|
|
107
|
+
* SHA-256 of the policy input's canonical JSON. The call key is unique per
|
|
108
|
+
* call and attempt and stays the same when a crashed run re-issues the call;
|
|
109
|
+
* the hash keeps a machine that asks something else at the same call site
|
|
110
|
+
* after a version bridge, which keeps the call key, off the earlier thread. Required
|
|
111
|
+
* with a `store` when the decider is called without a `callKey`.
|
|
112
|
+
*/
|
|
113
|
+
threadId?: (request: AgentExecutorDecisionRequest, info?: AgentRequestExecutorInfo) => string;
|
|
114
|
+
/**
|
|
115
|
+
* Builds the policy's input from the decision request. Default:
|
|
116
|
+
* `{ facts: request.metadata?.facts, options, system: request.system, prompt: request.prompt }`,
|
|
117
|
+
* where `options` are the offered events (`request.options[].event`). The
|
|
118
|
+
* policy's input schema validates it.
|
|
119
|
+
*/
|
|
120
|
+
input?: (request: AgentExecutorDecisionRequest) => InputFrom<TPolicy>;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Runs a policy machine as a decide executor: each decision request starts one
|
|
124
|
+
* run of `policy`, and its output is the chosen event. The policy can answer
|
|
125
|
+
* with a rule (a `choice` over the facts, no model call) and invoke
|
|
126
|
+
* `agent.decide` for the rest, answered by `options.executors`.
|
|
127
|
+
*
|
|
128
|
+
* The environment still judges the event: one it does not accept is retried
|
|
129
|
+
* like any other decider's choice. The policy's input must be JSON (it opens
|
|
130
|
+
* the policy run's event log): the default drops keys whose value is
|
|
131
|
+
* `undefined`, and any other value that is not JSON throws before the run. The policy's token usage is reported on the
|
|
132
|
+
* result, and left out when the policy made no model call. A run that does not
|
|
133
|
+
* end `done` with an event throws `AgentError` with code `policy-not-done`.
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* ```ts no-check
|
|
137
|
+
* const decide = createPolicyDecider(policyMachine, { executors: modelExecutors });
|
|
138
|
+
* await runAgent(deskMachine, { input, executors: { ...modelExecutors, decide } });
|
|
139
|
+
* ```
|
|
140
|
+
*/
|
|
141
|
+
export declare function createPolicyDecider<TPolicy extends AnyStateMachine>(policy: TPolicy, options?: PolicyDeciderOptions<TPolicy>): AgentDecisionExecutor;
|
|
142
|
+
//#endregion
|
|
143
|
+
export type { DecideNextOptions, DecideNextResult, PolicyDeciderOptions };
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { B as DecisionAttempt, J as DecisionStrategy, L as AgentDecisionRequest, M as AgentDecisionExecutor, R as AgentExecutorDecisionRequest, c as AgentRequestExecutorInfo, nt as EventFromSnapshot, s as AgentRequestExecutor, yt as ChosenEvent } from "./text-logic-x17uLBwA.mjs";
|
|
2
|
+
import { l as AgentRunOptions } from "./run-agent-DHlq87G7.mjs";
|
|
3
|
+
import { AnyMachineSnapshot, AnyStateMachine, InputFrom } from "xstate";
|
|
4
|
+
//#region src/decide-next.d.ts
|
|
5
|
+
/** Options for {@link decideNext}. */
|
|
6
|
+
interface DecideNextOptions<TSnapshot extends AnyMachineSnapshot = AnyMachineSnapshot> {
|
|
7
|
+
/** The decide executor that asks a model to pick one option. */
|
|
8
|
+
decide: AgentDecisionExecutor;
|
|
9
|
+
/** Model ref, passed through to the executor. */
|
|
10
|
+
model: string;
|
|
11
|
+
/** Event types the model may choose: exact types or wildcards (`'desk.*'`, `'*'`). */
|
|
12
|
+
allowedEvents: string | readonly string[];
|
|
13
|
+
/**
|
|
14
|
+
* Concrete payloads per event type, without `type`. One option per payload.
|
|
15
|
+
* A candidate type with no key is offered bare, as `{ type }`; an empty list
|
|
16
|
+
* offers nothing for it. To withhold a type, give it `[]`:
|
|
17
|
+
* `(s) => ({ "desk.refund": [{ amount: s.context.requested }], "desk.close": [] })`.
|
|
18
|
+
*/
|
|
19
|
+
payloads?: (snapshot: TSnapshot) => Partial<Record<string, Record<string, unknown>[]>>;
|
|
20
|
+
system?: string;
|
|
21
|
+
prompt?: string;
|
|
22
|
+
/** Semantic request name, for traces and scripted executors. Default `'decideNext'`. */
|
|
23
|
+
name?: string;
|
|
24
|
+
/**
|
|
25
|
+
* Describe what each option changes: the state value and the changed
|
|
26
|
+
* top-level context keys, computed with xstate's pure `transition()`.
|
|
27
|
+
* An array limits which context keys are reported (a state value change is
|
|
28
|
+
* always reported). Each reported value is cut to 120 characters.
|
|
29
|
+
*/
|
|
30
|
+
lookahead?: boolean | readonly string[];
|
|
31
|
+
/** Retries after a failed choice. Default `2`. */
|
|
32
|
+
maxRetries?: number;
|
|
33
|
+
signal?: AbortSignal;
|
|
34
|
+
/** How the decision is split into model calls. Default `'auto'`; see {@link DecisionStrategy}. */
|
|
35
|
+
strategy?: DecisionStrategy;
|
|
36
|
+
/** Model ref that fills open payload fields under `'pick-then-fill'`. */
|
|
37
|
+
fillModel?: string;
|
|
38
|
+
/** Named groups of event types for `'grouped'`; the rest group by prefix before the first `.`. */
|
|
39
|
+
groups?: Record<string, readonly string[]>;
|
|
40
|
+
/** Fills open payload fields with `fillModel`. */
|
|
41
|
+
generateText?: AgentRequestExecutor;
|
|
42
|
+
}
|
|
43
|
+
/** Result of {@link decideNext}. */
|
|
44
|
+
interface DecideNextResult<TEvent = ChosenEvent> {
|
|
45
|
+
/** The chosen event, or `null` when the snapshot accepts none of the options. */
|
|
46
|
+
event: TEvent | null;
|
|
47
|
+
/** Failed attempts before the choice landed. */
|
|
48
|
+
attempts: DecisionAttempt[];
|
|
49
|
+
/** The request built for the executor, with the offered `options` and the same `withheld`. */
|
|
50
|
+
request: AgentDecisionRequest;
|
|
51
|
+
/**
|
|
52
|
+
* The candidates the snapshot rejected: every `allowedEvents` type × payload,
|
|
53
|
+
* built the same way as the offered options, where `snapshot.can(event)` was
|
|
54
|
+
* false or the state handles the type through a transition tagged
|
|
55
|
+
* `meta: { actor: "human" }`. Never offered to the model. Filled when
|
|
56
|
+
* nothing is offered too.
|
|
57
|
+
*/
|
|
58
|
+
withheld: ChosenEvent[];
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Asks a model to choose the next event for ANY XState snapshot, including a
|
|
62
|
+
* machine built with plain `createMachine`/`setup` that knows nothing about AI.
|
|
63
|
+
* The candidates are the `allowedEvents` an active state handles, one option per
|
|
64
|
+
* payload, kept only where `snapshot.can(event)` is true and no transition
|
|
65
|
+
* tagged `meta: { actor: "human" }` handles the type; the rest come back as
|
|
66
|
+
* `withheld`. Each option is
|
|
67
|
+
* described from the transition's `description`, else the event schema's,
|
|
68
|
+
* plus (with `lookahead`) what it changes. The chosen event must equal one
|
|
69
|
+
* offered option; anything else is retried.
|
|
70
|
+
*
|
|
71
|
+
* It never sends. The host sends the event, re-checking `can` first, because
|
|
72
|
+
* the actor may have moved while the model was thinking. With no options it
|
|
73
|
+
* returns `{ event: null }` without calling the executor. Exhausting retries
|
|
74
|
+
* throws `AgentDecisionExhaustedError`.
|
|
75
|
+
*
|
|
76
|
+
* @example
|
|
77
|
+
* ```ts no-check
|
|
78
|
+
* let busy = false;
|
|
79
|
+
* actor.subscribe(async (snapshot) => {
|
|
80
|
+
* if (busy || !snapshot.matches('reviewing')) return;
|
|
81
|
+
* busy = true;
|
|
82
|
+
* try {
|
|
83
|
+
* const { event } = await decideNext(snapshot, {
|
|
84
|
+
* decide,
|
|
85
|
+
* model: 'quick',
|
|
86
|
+
* allowedEvents: 'desk.*',
|
|
87
|
+
* payloads: (s) => ({ 'desk.refund': [{ amount: s.context.requested }] }),
|
|
88
|
+
* lookahead: true,
|
|
89
|
+
* });
|
|
90
|
+
* if (event && actor.getSnapshot().can(event)) actor.send(event);
|
|
91
|
+
* } finally {
|
|
92
|
+
* busy = false;
|
|
93
|
+
* }
|
|
94
|
+
* });
|
|
95
|
+
* ```
|
|
96
|
+
*/
|
|
97
|
+
export declare function decideNext<TSnapshot extends AnyMachineSnapshot>(snapshot: TSnapshot, options: DecideNextOptions<TSnapshot>): Promise<DecideNextResult<EventFromSnapshot<TSnapshot>>>;
|
|
98
|
+
//#endregion
|
|
99
|
+
//#region src/policy-decider.d.ts
|
|
100
|
+
/** Options for {@link createPolicyDecider}: everything {@link runAgent} takes for the policy run, except how the run opens. */
|
|
101
|
+
interface PolicyDeciderOptions<TPolicy extends AnyStateMachine> extends Omit<AgentRunOptions<TPolicy>, "input" | "event" | "attempts" | "snapshot" | "events" | "onIdle" | "signal" | "threadId"> {
|
|
102
|
+
/**
|
|
103
|
+
* The `store` thread for one decision's policy run. Every decision, and every
|
|
104
|
+
* retry of one, needs its own thread: a thread that already has entries is
|
|
105
|
+
* resumed, so a shared one would return an earlier decision's choice. Default
|
|
106
|
+
* with a `store`: `policy:${info.callKey}:${hash}`, where `hash` is the
|
|
107
|
+
* SHA-256 of the policy input's canonical JSON. The call key is unique per
|
|
108
|
+
* call and attempt and stays the same when a crashed run re-issues the call;
|
|
109
|
+
* the hash keeps a machine that asks something else at the same call site
|
|
110
|
+
* after a version bridge, which keeps the call key, off the earlier thread. Required
|
|
111
|
+
* with a `store` when the decider is called without a `callKey`.
|
|
112
|
+
*/
|
|
113
|
+
threadId?: (request: AgentExecutorDecisionRequest, info?: AgentRequestExecutorInfo) => string;
|
|
114
|
+
/**
|
|
115
|
+
* Builds the policy's input from the decision request. Default:
|
|
116
|
+
* `{ facts: request.metadata?.facts, options, system: request.system, prompt: request.prompt }`,
|
|
117
|
+
* where `options` are the offered events (`request.options[].event`). The
|
|
118
|
+
* policy's input schema validates it.
|
|
119
|
+
*/
|
|
120
|
+
input?: (request: AgentExecutorDecisionRequest) => InputFrom<TPolicy>;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Runs a policy machine as a decide executor: each decision request starts one
|
|
124
|
+
* run of `policy`, and its output is the chosen event. The policy can answer
|
|
125
|
+
* with a rule (a `choice` over the facts, no model call) and invoke
|
|
126
|
+
* `agent.decide` for the rest, answered by `options.executors`.
|
|
127
|
+
*
|
|
128
|
+
* The environment still judges the event: one it does not accept is retried
|
|
129
|
+
* like any other decider's choice. The policy's input must be JSON (it opens
|
|
130
|
+
* the policy run's event log): the default drops keys whose value is
|
|
131
|
+
* `undefined`, and any other value that is not JSON throws before the run. The policy's token usage is reported on the
|
|
132
|
+
* result, and left out when the policy made no model call. A run that does not
|
|
133
|
+
* end `done` with an event throws `AgentError` with code `policy-not-done`.
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* ```ts no-check
|
|
137
|
+
* const decide = createPolicyDecider(policyMachine, { executors: modelExecutors });
|
|
138
|
+
* await runAgent(deskMachine, { input, executors: { ...modelExecutors, decide } });
|
|
139
|
+
* ```
|
|
140
|
+
*/
|
|
141
|
+
export declare function createPolicyDecider<TPolicy extends AnyStateMachine>(policy: TPolicy, options?: PolicyDeciderOptions<TPolicy>): AgentDecisionExecutor;
|
|
142
|
+
//#endregion
|
|
143
|
+
export type { DecideNextOptions, DecideNextResult, PolicyDeciderOptions };
|
package/dist/policy.mjs
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { d as canonicalEventJson, ft as isRecord, pt as AgentError, u as assertJsonSerializable } from "./event-log-CEq_bVXQ.mjs";
|
|
2
|
+
import { p as runAgent, v as decideNext } from "./run-agent-BE7DOWD6.mjs";
|
|
3
|
+
//#region src/policy-decider.ts
|
|
4
|
+
/**
|
|
5
|
+
* Runs a policy machine as a decide executor: each decision request starts one
|
|
6
|
+
* run of `policy`, and its output is the chosen event. The policy can answer
|
|
7
|
+
* with a rule (a `choice` over the facts, no model call) and invoke
|
|
8
|
+
* `agent.decide` for the rest, answered by `options.executors`.
|
|
9
|
+
*
|
|
10
|
+
* The environment still judges the event: one it does not accept is retried
|
|
11
|
+
* like any other decider's choice. The policy's input must be JSON (it opens
|
|
12
|
+
* the policy run's event log): the default drops keys whose value is
|
|
13
|
+
* `undefined`, and any other value that is not JSON throws before the run. The policy's token usage is reported on the
|
|
14
|
+
* result, and left out when the policy made no model call. A run that does not
|
|
15
|
+
* end `done` with an event throws `AgentError` with code `policy-not-done`.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts no-check
|
|
19
|
+
* const decide = createPolicyDecider(policyMachine, { executors: modelExecutors });
|
|
20
|
+
* await runAgent(deskMachine, { input, executors: { ...modelExecutors, decide } });
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
function createPolicyDecider(policy, options = {}) {
|
|
24
|
+
const { input = defaultInput, threadId, ...runOptions } = options;
|
|
25
|
+
const id = policy.config.id ?? policy.id;
|
|
26
|
+
return async (request, info) => {
|
|
27
|
+
const policyInput = input(request);
|
|
28
|
+
assertJsonSerializable(policyInput, "policy input");
|
|
29
|
+
const thread = runOptions.store === void 0 ? void 0 : await policyThread(request, policyInput, info);
|
|
30
|
+
const result = await runAgent(policy, {
|
|
31
|
+
...runOptions,
|
|
32
|
+
input: policyInput,
|
|
33
|
+
...thread === void 0 ? {} : { threadId: thread },
|
|
34
|
+
...info?.signal ? { signal: info.signal } : {}
|
|
35
|
+
});
|
|
36
|
+
if (result.status !== "done") {
|
|
37
|
+
const why = result.status === "error" ? `: ${String(result.error)}` : "";
|
|
38
|
+
throw new AgentError("policy-not-done", `policy '${id}' settled '${result.status}'${why}`, { cause: result.status === "error" ? result.error : void 0 });
|
|
39
|
+
}
|
|
40
|
+
const event = result.output;
|
|
41
|
+
if (!isRecord(event) || typeof event.type !== "string") throw new AgentError("policy-not-done", `policy '${id}' output is not an event: ${JSON.stringify(event)}`);
|
|
42
|
+
const { modelCalls, ...usage } = result.usage;
|
|
43
|
+
return {
|
|
44
|
+
event,
|
|
45
|
+
...modelCalls > 0 ? { usage } : {}
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
async function policyThread(request, policyInput, info) {
|
|
49
|
+
if (threadId) return threadId(request, info);
|
|
50
|
+
if (info?.callKey) return `policy:${info.callKey}:${await sha256(canonicalEventJson(policyInput))}`;
|
|
51
|
+
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`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function defaultInput(request) {
|
|
55
|
+
const facts = request.metadata?.facts;
|
|
56
|
+
return withoutUndefinedKeys({
|
|
57
|
+
facts,
|
|
58
|
+
options: (request.options ?? []).map((option) => option.event),
|
|
59
|
+
system: request.system,
|
|
60
|
+
prompt: request.prompt
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/** A copy of `value` with every object key whose value is `undefined` removed, at any depth. */
|
|
64
|
+
function withoutUndefinedKeys(value) {
|
|
65
|
+
if (Array.isArray(value)) return value.map(withoutUndefinedKeys);
|
|
66
|
+
if (!isRecord(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return value;
|
|
67
|
+
return Object.fromEntries(Object.entries(value).filter(([, child]) => child !== void 0).map(([key, child]) => [key, withoutUndefinedKeys(child)]));
|
|
68
|
+
}
|
|
69
|
+
/** Hex SHA-256 of `text`, with Web Crypto (Node, browsers, workers). */
|
|
70
|
+
async function sha256(text) {
|
|
71
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
|
72
|
+
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
73
|
+
}
|
|
74
|
+
//#endregion
|
|
75
|
+
export { createPolicyDecider, decideNext };
|