@statelyai/agent 2.0.0-alpha.38 → 2.0.0-alpha.40
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 +59 -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 +142 -97
- package/dist/index.d.cts +97 -141
- package/dist/index.d.mts +97 -141
- package/dist/index.mjs +123 -74
- 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/machine-input-0YTPcnCm.mjs +27 -0
- package/dist/machine-input-DU3owLUr.cjs +32 -0
- 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/{run-agent-DlPzBWj-.d.mts → run-agent-BO9RSb7i.d.cts} +33 -40
- package/dist/{run-agent-30mH2moE.d.cts → run-agent-BxkeuAYR.d.mts} +33 -40
- package/dist/{effects-DDseYtJk.cjs → run-agent-COdR9FpM.cjs} +175 -228
- package/dist/{effects-BT_cSY0j.mjs → run-agent-D3gW9wfd.mjs} +176 -211
- 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-CIu4mqIZ.d.mts} +56 -6
- package/dist/{verify-i9Hiwc5g.d.mts → verify-CTHlmBbh.d.cts} +56 -6
- package/dist/{verify-ChyX6jq0.mjs → verify-Cacz6XSk.mjs} +170 -46
- package/dist/{verify-CwlombbC.cjs → verify-D8UDqU4l.cjs} +170 -46
- 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 +25 -30
- 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 +105 -33
- 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 +54 -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,5 +1,6 @@
|
|
|
1
|
-
const require_event_log = require("./event-log-
|
|
2
|
-
const require_decision = require("./decision-
|
|
1
|
+
const require_event_log = require("./event-log-dSOnXHuG.cjs");
|
|
2
|
+
const require_decision = require("./decision-D8bcIGXQ.cjs");
|
|
3
|
+
const require_machine_input = require("./machine-input-DU3owLUr.cjs");
|
|
3
4
|
let xstate = require("xstate");
|
|
4
5
|
//#region src/steps.ts
|
|
5
6
|
/**
|
|
@@ -578,6 +579,7 @@ function takeFromQueue(channel, src) {
|
|
|
578
579
|
* ```
|
|
579
580
|
*/
|
|
580
581
|
async function simulateAgent(machine, options) {
|
|
582
|
+
options = withMachineInput(machine, options, "simulateAgent");
|
|
581
583
|
const maxSteps = options.maxSteps ?? 100;
|
|
582
584
|
const script = {
|
|
583
585
|
text: mapValues(options.script.text ?? {}, (arr) => [...arr]),
|
|
@@ -990,7 +992,67 @@ function transientStateIds(node, ids = []) {
|
|
|
990
992
|
function hasParallelStates(node) {
|
|
991
993
|
return require_event_log.isRecord(node) && (node["type"] === "parallel" || Object.values(require_event_log.isRecord(node["states"]) ? node["states"] : {}).some(hasParallelStates));
|
|
992
994
|
}
|
|
993
|
-
function
|
|
995
|
+
function childSrcs(step) {
|
|
996
|
+
const children = step.snapshot.children ?? {};
|
|
997
|
+
const invoked = new Map(pendingInvokes(step).map((invoke) => [invoke.id, invoke.src]));
|
|
998
|
+
return Object.entries(children).flatMap(([id, ref]) => {
|
|
999
|
+
if (!ref) return [];
|
|
1000
|
+
const own = ref.src;
|
|
1001
|
+
const src = invoked.get(id) ?? (typeof own === "string" ? own : id);
|
|
1002
|
+
return [{
|
|
1003
|
+
id,
|
|
1004
|
+
session: childSession(id, ref),
|
|
1005
|
+
src
|
|
1006
|
+
}];
|
|
1007
|
+
});
|
|
1008
|
+
}
|
|
1009
|
+
function exploreStep(prev, next, event) {
|
|
1010
|
+
const before = prev ? childSrcs(prev) : [];
|
|
1011
|
+
const sessions = new Set(before.map((child) => child.session));
|
|
1012
|
+
const actorId = event.actorId;
|
|
1013
|
+
const settles = (event.type === "xstate.done.actor" || event.type === "xstate.error.actor") && typeof actorId === "string";
|
|
1014
|
+
return {
|
|
1015
|
+
event,
|
|
1016
|
+
state: next.snapshot.value,
|
|
1017
|
+
started: childSrcs(next).filter((child) => !sessions.has(child.session)).map((child) => child.src),
|
|
1018
|
+
settled: settles ? before.filter((child) => child.id === actorId).map((child) => child.src) : []
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
function stepsOf(log) {
|
|
1022
|
+
const steps = Array.from({ length: log?.length ?? 0 });
|
|
1023
|
+
for (let at = log; at; at = at.prev) steps[at.length - 1] = at.step;
|
|
1024
|
+
return steps;
|
|
1025
|
+
}
|
|
1026
|
+
function finishedInvokes(step) {
|
|
1027
|
+
const children = step.snapshot.children ?? {};
|
|
1028
|
+
return finishedChildren(step).map(({ id }) => {
|
|
1029
|
+
const ref = children[id];
|
|
1030
|
+
const own = ref;
|
|
1031
|
+
return {
|
|
1032
|
+
id,
|
|
1033
|
+
src: typeof own.src === "string" ? own.src : id,
|
|
1034
|
+
input: ref.options?.input,
|
|
1035
|
+
logic: own.logic,
|
|
1036
|
+
ref
|
|
1037
|
+
};
|
|
1038
|
+
});
|
|
1039
|
+
}
|
|
1040
|
+
function finishedChildren(step) {
|
|
1041
|
+
const children = step.snapshot.children ?? {};
|
|
1042
|
+
return Object.keys(children).sort().flatMap((id) => {
|
|
1043
|
+
const snapshot = children[id]?.getSnapshot?.();
|
|
1044
|
+
if (snapshot?.status === "done") return [{
|
|
1045
|
+
id,
|
|
1046
|
+
output: snapshot.output
|
|
1047
|
+
}];
|
|
1048
|
+
if (snapshot?.status === "error") return [{
|
|
1049
|
+
id,
|
|
1050
|
+
error: snapshot.error
|
|
1051
|
+
}];
|
|
1052
|
+
return [];
|
|
1053
|
+
});
|
|
1054
|
+
}
|
|
1055
|
+
function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef, trackTransits = nesting === 0 && hasTransientStates(machine.root), budget = startBudget(options.budget), stepping = false, ordering, stateTarget = false) {
|
|
994
1056
|
const maxDepth = options.maxDepth ?? 8;
|
|
995
1057
|
const maxPaths = options.maxPaths ?? 200;
|
|
996
1058
|
const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;
|
|
@@ -1026,9 +1088,33 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1026
1088
|
}
|
|
1027
1089
|
return next;
|
|
1028
1090
|
};
|
|
1029
|
-
const
|
|
1030
|
-
const
|
|
1031
|
-
const
|
|
1091
|
+
const logging = nesting === 0 && !stepping && (options.steps === true || ordering !== void 0);
|
|
1092
|
+
const logs = /* @__PURE__ */ new WeakMap();
|
|
1093
|
+
const timerDelivers = /* @__PURE__ */ new WeakMap();
|
|
1094
|
+
const logged = (prev, next, event) => {
|
|
1095
|
+
if (!logging) return next;
|
|
1096
|
+
const before = prev && logs.get(prev);
|
|
1097
|
+
const step = exploreStep(prev, next, timerDelivers.get(event) ?? event);
|
|
1098
|
+
const trigger = ordering?.after;
|
|
1099
|
+
const after = (before?.after ?? false) || trigger !== void 0 && (typeof trigger === "string" ? step.event.type === trigger : trigger(step));
|
|
1100
|
+
logs.set(next, {
|
|
1101
|
+
step,
|
|
1102
|
+
prev: before,
|
|
1103
|
+
length: (before?.length ?? 0) + 1,
|
|
1104
|
+
after,
|
|
1105
|
+
violated: (before?.violated ?? false) || after && ordering.reach(step)
|
|
1106
|
+
});
|
|
1107
|
+
return next;
|
|
1108
|
+
};
|
|
1109
|
+
const resolveStep = (prev, id, output) => {
|
|
1110
|
+
const event = doneEvent(prev.snapshot, id, output);
|
|
1111
|
+
return logged(prev, withTransits(resolveAgentStep(machine, prev, id, output), () => (0, xstate.getMicrosteps)(machine, prev.snapshot, event)), event);
|
|
1112
|
+
};
|
|
1113
|
+
const rejectStep = (prev, id, error) => {
|
|
1114
|
+
const event = errorEvent(prev.snapshot, id, error);
|
|
1115
|
+
return logged(prev, withTransits(rejectAgentStep(machine, prev, id, error), () => (0, xstate.getMicrosteps)(machine, prev.snapshot, event)), event);
|
|
1116
|
+
};
|
|
1117
|
+
const transitionStep = (prev, event) => logged(prev, withTransits(transitionAgentStep(machine, prev, event), () => (0, xstate.getMicrosteps)(machine, prev.snapshot, event)), event);
|
|
1032
1118
|
const settleStep = (prev, id, output, usage) => {
|
|
1033
1119
|
if (!usage) return {
|
|
1034
1120
|
step: resolveStep(prev, id, output),
|
|
@@ -1085,7 +1171,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1085
1171
|
if (accepted.length === 0) return;
|
|
1086
1172
|
return accepted.length < events.length ? [...accepted, void 0] : accepted;
|
|
1087
1173
|
};
|
|
1088
|
-
const stops = (step, kids) => stopWhen !== void 0 && (stopWhen(withKidSnapshots(step.snapshot, kids)) || (transits.get(step)?.some((snapshot) => stopWhen(withKidSnapshots(snapshot, kids))) ?? false));
|
|
1174
|
+
const stops = (step, kids) => ordering !== void 0 && logs.get(step)?.violated === true || stopWhen !== void 0 && (stopWhen(withKidSnapshots(step.snapshot, kids)) || (transits.get(step)?.some((snapshot) => stopWhen(withKidSnapshots(snapshot, kids))) ?? false));
|
|
1089
1175
|
const finiteCache = /* @__PURE__ */ new Map();
|
|
1090
1176
|
const schemaPayloads = (type, snapshot) => {
|
|
1091
1177
|
const schema = eventSchemas[type];
|
|
@@ -1096,12 +1182,12 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1096
1182
|
}
|
|
1097
1183
|
fill ??= {
|
|
1098
1184
|
payloads: [{}],
|
|
1099
|
-
complete: !mayReadPayload(snapshot, type)
|
|
1185
|
+
complete: ordering === void 0 && !mayReadPayload(snapshot, type)
|
|
1100
1186
|
};
|
|
1101
1187
|
if (!fill.complete && fill.payloads.length === 1 && Object.keys(fill.payloads[0]).length === 0 && mayReadPayload(snapshot, type)) vacuous.add(type);
|
|
1102
1188
|
if (!fill.complete && !unexpanded.has(type)) {
|
|
1103
1189
|
unexpanded.add(type);
|
|
1104
|
-
note(() => schema ? `unexpanded: event '${type}' has payload fields the schema fill cannot enumerate; add a payloads entry for it` : `unexpanded: event '${type}' has no schema and a transition that may read its payload; add a payloads entry for it`);
|
|
1190
|
+
note(() => schema ? `unexpanded: event '${type}' has payload fields the schema fill cannot enumerate; add a payloads entry for it` : ordering !== void 0 && !mayReadPayload(snapshot, type) ? `unexpanded: event '${type}' has no schema, and the ordering target may read its payload; add a payloads entry for it` : `unexpanded: event '${type}' has no schema and a transition that may read its payload; add a payloads entry for it`);
|
|
1105
1191
|
}
|
|
1106
1192
|
return fill.payloads;
|
|
1107
1193
|
};
|
|
@@ -1197,8 +1283,9 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1197
1283
|
const concurrentForks = (step) => {
|
|
1198
1284
|
if (options.children !== "explore" && !coupled) return;
|
|
1199
1285
|
const invokes = pendingInvokes(step);
|
|
1200
|
-
|
|
1201
|
-
|
|
1286
|
+
const finishedKids = coupled ? finishedInvokes(step).filter(isExploredChild) : [];
|
|
1287
|
+
if (!invokes.some(isExploredChild) && finishedKids.length === 0) return;
|
|
1288
|
+
const kids = coupled ? [...invokes.filter(isExploredChild), ...finishedKids] : [];
|
|
1202
1289
|
const blocked = [];
|
|
1203
1290
|
const asFork = (settle, id, src, isText, usage) => {
|
|
1204
1291
|
if ("fork" in settle) return [settle.fork];
|
|
@@ -1217,10 +1304,22 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1217
1304
|
};
|
|
1218
1305
|
const texts = step.requests.filter((request) => request.kind === "text");
|
|
1219
1306
|
const requestIds = new Set(step.requests.map((request) => request.id));
|
|
1220
|
-
const forks = [
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1307
|
+
const forks = [
|
|
1308
|
+
...texts.flatMap((request) => {
|
|
1309
|
+
const usage = usageFor(step, request);
|
|
1310
|
+
return asFork(settleFor(request.id, request.src, true, void 0, usage), request.id, request.src, true, usage);
|
|
1311
|
+
}),
|
|
1312
|
+
...invokes.filter((invoke) => !requestIds.has(invoke.id) && !kids.includes(invoke)).flatMap((invoke) => asFork(settleFor(invoke.id, invoke.src, false, invoke), invoke.id, invoke.src, false)),
|
|
1313
|
+
...finishedChildren(step).filter((finished) => !finishedKids.some((kid) => kid.id === finished.id)).map((finished) => "error" in finished ? {
|
|
1314
|
+
id: finished.id,
|
|
1315
|
+
errors: [finished.error],
|
|
1316
|
+
outputs: []
|
|
1317
|
+
} : {
|
|
1318
|
+
id: finished.id,
|
|
1319
|
+
errors: [],
|
|
1320
|
+
outputs: [finished.output]
|
|
1321
|
+
})
|
|
1322
|
+
];
|
|
1224
1323
|
const decisions = step.requests.filter((request) => request.kind === "decision");
|
|
1225
1324
|
for (const decision of decisions) {
|
|
1226
1325
|
const src = findInvokeMetadata(step, decision.id)?.src;
|
|
@@ -1261,7 +1360,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1261
1360
|
if (nesting === 0) unexplored.push(text());
|
|
1262
1361
|
};
|
|
1263
1362
|
let captured;
|
|
1264
|
-
const endPath = (path, terminal) => {
|
|
1363
|
+
const endPath = (path, step, terminal) => {
|
|
1265
1364
|
if (captured) {
|
|
1266
1365
|
captured.push({
|
|
1267
1366
|
status: terminal.status,
|
|
@@ -1274,7 +1373,8 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1274
1373
|
else if (terminal.status !== "done" && terminal.status !== "error") unfinished = true;
|
|
1275
1374
|
if (nesting === 0) terminals.push({
|
|
1276
1375
|
...terminal,
|
|
1277
|
-
path: pathOf(path)
|
|
1376
|
+
path: pathOf(path),
|
|
1377
|
+
...options.steps ? { steps: stepsOf(logs.get(step)) } : {}
|
|
1278
1378
|
});
|
|
1279
1379
|
};
|
|
1280
1380
|
let prunedByGuard = 0;
|
|
@@ -1308,11 +1408,8 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1308
1408
|
}
|
|
1309
1409
|
}
|
|
1310
1410
|
};
|
|
1311
|
-
const initial = stepping ? void 0 : withTransits(childStartStep(machine, options.input, childRef), () => (0, xstate.getInitialMicrosteps)(machine, options.input));
|
|
1312
|
-
if (initial)
|
|
1313
|
-
recordState(initial, childRef?._initialEffects ?? initial.actions);
|
|
1314
|
-
if (stops(initial)) witness = [];
|
|
1315
|
-
}
|
|
1411
|
+
const initial = stepping ? void 0 : logged(void 0, withTransits(childStartStep(machine, options.input, childRef), () => (0, xstate.getInitialMicrosteps)(machine, options.input)), { type: "xstate.init" });
|
|
1412
|
+
if (initial) recordState(initial, childRef?._initialEffects ?? initial.actions);
|
|
1316
1413
|
const undeliverable = /* @__PURE__ */ new Set();
|
|
1317
1414
|
const external = deliverable ?? (options.hostEvents === void 0 ? void 0 : new Set(options.hostEvents));
|
|
1318
1415
|
const arriving = (snapshot) => require_decision.getAcceptedEvents(snapshot).filter((descriptor) => {
|
|
@@ -1324,7 +1421,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1324
1421
|
const advance = (step, recordEvent, kids) => {
|
|
1325
1422
|
let current = step;
|
|
1326
1423
|
for (let i = 0; i < MAX_ADVANCE_STEPS; i++) {
|
|
1327
|
-
if (!awaitsKids(current, kids) && stops(current, kids)) return {
|
|
1424
|
+
if ((stateTarget || !awaitsKids(current, kids)) && stops(current, kids)) return {
|
|
1328
1425
|
step: current,
|
|
1329
1426
|
hit: true
|
|
1330
1427
|
};
|
|
@@ -1339,6 +1436,12 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1339
1436
|
decisions: concurrent.decisions,
|
|
1340
1437
|
...concurrent.kids?.length ? { kids: concurrent.kids } : {}
|
|
1341
1438
|
};
|
|
1439
|
+
const [finished] = finishedChildren(current);
|
|
1440
|
+
if (finished) {
|
|
1441
|
+
current = "error" in finished ? rejectStep(current, finished.id, finished.error) : resolveStep(current, finished.id, finished.output);
|
|
1442
|
+
recordState(current);
|
|
1443
|
+
continue;
|
|
1444
|
+
}
|
|
1342
1445
|
if (request && request.kind === "text") {
|
|
1343
1446
|
const usage = usageFor(current, request);
|
|
1344
1447
|
const settle = settleFor(request.id, request.src, true, void 0, usage);
|
|
@@ -1444,10 +1547,12 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1444
1547
|
}
|
|
1445
1548
|
return armed.map(({ event, key }) => {
|
|
1446
1549
|
const entry = { ...event };
|
|
1447
|
-
|
|
1550
|
+
const command = {
|
|
1448
1551
|
type: "xstate.timer",
|
|
1449
1552
|
...key
|
|
1450
|
-
}
|
|
1553
|
+
};
|
|
1554
|
+
timerFires.set(entry, command);
|
|
1555
|
+
timerDelivers.set(command, event);
|
|
1451
1556
|
return entry;
|
|
1452
1557
|
});
|
|
1453
1558
|
};
|
|
@@ -1503,7 +1608,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1503
1608
|
}
|
|
1504
1609
|
}
|
|
1505
1610
|
const maxDepthTerminal = (settled, path) => {
|
|
1506
|
-
endPath(path, {
|
|
1611
|
+
endPath(path, settled, {
|
|
1507
1612
|
status: "max-depth",
|
|
1508
1613
|
state: settled.snapshot.value
|
|
1509
1614
|
});
|
|
@@ -1530,7 +1635,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1530
1635
|
const pumped = /* @__PURE__ */ new WeakSet();
|
|
1531
1636
|
let outParent;
|
|
1532
1637
|
const register = (step, kids, queue) => {
|
|
1533
|
-
const live = pendingInvokes(step).filter(isExploredChild);
|
|
1638
|
+
const live = [...pendingInvokes(step), ...finishedInvokes(step)].filter(isExploredChild).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
1534
1639
|
const sessions = new Set(live.map((invoke) => childSession(invoke.id, invoke.ref)));
|
|
1535
1640
|
for (const session of kids.keys()) if (!sessions.has(session)) kids.delete(session);
|
|
1536
1641
|
for (const invoke of live) {
|
|
@@ -1575,7 +1680,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1575
1680
|
const awaitsKids = (step, kids) => {
|
|
1576
1681
|
if (!coupled || pumped.has(step)) return false;
|
|
1577
1682
|
const held = kids ?? /* @__PURE__ */ new Map();
|
|
1578
|
-
if (pendingInvokes(step).filter(isExploredChild).some((invoke) => !held.has(childSession(invoke.id, invoke.ref)))) return true;
|
|
1683
|
+
if ([...pendingInvokes(step), ...finishedInvokes(step)].filter(isExploredChild).some((invoke) => !held.has(childSession(invoke.id, invoke.ref)))) return true;
|
|
1579
1684
|
return (Array.isArray(step.actions) ? step.actions : []).some((effect) => require_event_log.isRecord(effect) && effect["type"] === "@xstate.sendTo" && kidSessionFor(step, effect["target"], held) !== void 0);
|
|
1580
1685
|
};
|
|
1581
1686
|
const pump = (start, link, kids, queue) => {
|
|
@@ -1590,7 +1695,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1590
1695
|
const delivered = kid.engine.deliver(kid, event);
|
|
1591
1696
|
if (delivered.overflow) {
|
|
1592
1697
|
overflow = true;
|
|
1593
|
-
endPath(link, {
|
|
1698
|
+
endPath(link, at, {
|
|
1594
1699
|
status: "max-depth",
|
|
1595
1700
|
state: at.snapshot.value
|
|
1596
1701
|
});
|
|
@@ -1613,17 +1718,20 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1613
1718
|
unexpanded.add(route.event.type);
|
|
1614
1719
|
note(() => `coupled: a child sent '${route.event.type}' to an actor the search does not model, at path [${pathTypes(link)}]`);
|
|
1615
1720
|
};
|
|
1721
|
+
const starting = /* @__PURE__ */ new WeakSet();
|
|
1616
1722
|
const flush = (at) => {
|
|
1617
1723
|
if (pumped.has(at)) return;
|
|
1618
1724
|
pumped.add(at);
|
|
1725
|
+
const queued = queue.length;
|
|
1619
1726
|
if (!register(at, kids, queue)) {
|
|
1620
1727
|
overflow = true;
|
|
1621
|
-
endPath(link, {
|
|
1728
|
+
endPath(link, at, {
|
|
1622
1729
|
status: "max-depth",
|
|
1623
1730
|
state: at.snapshot.value
|
|
1624
1731
|
});
|
|
1625
1732
|
return;
|
|
1626
1733
|
}
|
|
1734
|
+
for (const item of queue.slice(queued)) starting.add(item);
|
|
1627
1735
|
for (const effect of Array.isArray(at.actions) ? at.actions : []) {
|
|
1628
1736
|
if (!require_event_log.isRecord(effect) || effect["type"] !== "@xstate.sendTo" || !require_event_log.isRecord(effect["event"]) || typeof effect["event"]["type"] !== "string") continue;
|
|
1629
1737
|
deliverTo(at, effect["target"], effect["event"]);
|
|
@@ -1634,7 +1742,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1634
1742
|
for (let i = 0; queue.length > 0 && !overflow; i++) {
|
|
1635
1743
|
if (step.done || step.snapshot.status !== "active" || witness !== void 0) break;
|
|
1636
1744
|
if (i >= MAX_PUMP) {
|
|
1637
|
-
endPath(link, {
|
|
1745
|
+
endPath(link, step, {
|
|
1638
1746
|
status: "max-depth",
|
|
1639
1747
|
state: step.snapshot.value
|
|
1640
1748
|
});
|
|
@@ -1683,7 +1791,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1683
1791
|
recordState(step);
|
|
1684
1792
|
outbound.push(...outboundOf(step.actions, outParent, step.snapshot.children));
|
|
1685
1793
|
flush(step);
|
|
1686
|
-
if (!overflow && stops(step, kids)) {
|
|
1794
|
+
if (!overflow && (stateTarget || !queue.some((queuedItem) => starting.has(queuedItem))) && stops(step, kids)) {
|
|
1687
1795
|
witness = pathOf(link);
|
|
1688
1796
|
break;
|
|
1689
1797
|
}
|
|
@@ -1749,7 +1857,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1749
1857
|
}
|
|
1750
1858
|
}
|
|
1751
1859
|
if (options.dedupeBy) {
|
|
1752
|
-
const key = options.dedupeBy(withKidSnapshots(settled.snapshot, nodeKids)) + (delivered?.size ? `\u0001${[...delivered].sort().join("")}` : "") + kidsKey(nodeKids);
|
|
1860
|
+
const key = options.dedupeBy(withKidSnapshots(settled.snapshot, nodeKids)) + (delivered?.size ? `\u0001${[...delivered].sort().join("")}` : "") + kidsKey(nodeKids) + (logs.get(settled)?.after ? "after" : "");
|
|
1753
1861
|
const seenAt = visited.get(key);
|
|
1754
1862
|
if (seenAt !== void 0 && seenAt <= depth) return;
|
|
1755
1863
|
visited.set(key, depth);
|
|
@@ -1789,7 +1897,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1789
1897
|
for (const terminal of blocked) {
|
|
1790
1898
|
if (witness !== void 0 || capped()) return;
|
|
1791
1899
|
if (terminal.status === "idle" || terminal.status === "done" || terminal.status === "error") continue;
|
|
1792
|
-
endPath(path, {
|
|
1900
|
+
endPath(path, settled, {
|
|
1793
1901
|
status: terminal.status,
|
|
1794
1902
|
state: settled.snapshot.value,
|
|
1795
1903
|
...terminal.status === "needs-output" ? { missingSrc: terminal.missingSrc ?? kid.src } : {}
|
|
@@ -1843,7 +1951,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1843
1951
|
const registered = new Set([...(nodeKids ?? /* @__PURE__ */ new Map()).values()].map((kid) => kid.id));
|
|
1844
1952
|
for (const kid of pendingKids.filter((invoke) => !registered.has(invoke.id))) {
|
|
1845
1953
|
if (witness !== void 0 || capped()) return;
|
|
1846
|
-
endPath(path, {
|
|
1954
|
+
endPath(path, settled, {
|
|
1847
1955
|
status: "needs-output",
|
|
1848
1956
|
state: settled.snapshot.value,
|
|
1849
1957
|
missingSrc: kid.src
|
|
@@ -1862,7 +1970,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1862
1970
|
}
|
|
1863
1971
|
for (const src of blockedSiblings ?? []) {
|
|
1864
1972
|
if (witness !== void 0 || capped()) return;
|
|
1865
|
-
endPath(path, {
|
|
1973
|
+
endPath(path, settled, {
|
|
1866
1974
|
status: "needs-output",
|
|
1867
1975
|
state: settled.snapshot.value,
|
|
1868
1976
|
missingSrc: src
|
|
@@ -1912,14 +2020,14 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1912
2020
|
delivered: /* @__PURE__ */ new Set([...delivered ?? [], key])
|
|
1913
2021
|
};
|
|
1914
2022
|
}
|
|
1915
|
-
if (fork.stalls && witness === void 0 && !capped()) endPath(path, {
|
|
2023
|
+
if (fork.stalls && witness === void 0 && !capped()) endPath(path, settled, {
|
|
1916
2024
|
status: "idle",
|
|
1917
2025
|
state: settled.snapshot.value
|
|
1918
2026
|
});
|
|
1919
2027
|
for (const src of blockedSiblings ?? []) note(() => `needs-output: no \`outputs\` entry for src '${src}' at path [${pathTypes(path)}]`);
|
|
1920
2028
|
for (const incompleteSrc of [...[fork, ...siblings ?? []].flatMap((child) => child.incompleteSrc === void 0 ? [] : [child.incompleteSrc]), ...blockedSiblings ?? []]) {
|
|
1921
2029
|
if (witness !== void 0 || capped()) break;
|
|
1922
|
-
endPath(path, {
|
|
2030
|
+
endPath(path, settled, {
|
|
1923
2031
|
status: "needs-output",
|
|
1924
2032
|
state: settled.snapshot.value,
|
|
1925
2033
|
missingSrc: incompleteSrc
|
|
@@ -1933,7 +2041,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1933
2041
|
if (witness !== void 0) return;
|
|
1934
2042
|
}
|
|
1935
2043
|
if (blockedSrc) {
|
|
1936
|
-
endPath(path, {
|
|
2044
|
+
endPath(path, settled, {
|
|
1937
2045
|
status: "needs-output",
|
|
1938
2046
|
state: settled.snapshot.value,
|
|
1939
2047
|
missingSrc: blockedSrc
|
|
@@ -1944,7 +2052,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1944
2052
|
}
|
|
1945
2053
|
if (settled.done) {
|
|
1946
2054
|
const output = settled.snapshot.output;
|
|
1947
|
-
endPath(path, {
|
|
2055
|
+
endPath(path, settled, {
|
|
1948
2056
|
status: "done",
|
|
1949
2057
|
state: settled.snapshot.value,
|
|
1950
2058
|
...output === void 0 ? {} : { output }
|
|
@@ -1954,7 +2062,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1954
2062
|
}
|
|
1955
2063
|
if (settled.snapshot.status === "error") {
|
|
1956
2064
|
const error = settled.snapshot.error;
|
|
1957
|
-
endPath(path, {
|
|
2065
|
+
endPath(path, settled, {
|
|
1958
2066
|
status: "error",
|
|
1959
2067
|
state: settled.snapshot.value,
|
|
1960
2068
|
error
|
|
@@ -1969,14 +2077,14 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
1969
2077
|
const requestOptions = request?.kind === "decision" ? require_decision.acceptedDecisionOptions(request, () => true) : void 0;
|
|
1970
2078
|
const branchEvents = request?.kind === "decision" ? request.events.flatMap((descriptor) => variantsOf(descriptor.type, snapshot, table, requestOptions)) : acceptedVariants(snapshot, path, table);
|
|
1971
2079
|
if (branchEvents.length === 0 && request?.kind !== "decision") {
|
|
1972
|
-
endPath(path, {
|
|
2080
|
+
endPath(path, settled, {
|
|
1973
2081
|
status: "idle",
|
|
1974
2082
|
state: settled.snapshot.value
|
|
1975
2083
|
});
|
|
1976
2084
|
return;
|
|
1977
2085
|
}
|
|
1978
2086
|
if (depth >= maxDepth) {
|
|
1979
|
-
endPath(path, {
|
|
2087
|
+
endPath(path, settled, {
|
|
1980
2088
|
status: "max-depth",
|
|
1981
2089
|
state: settled.snapshot.value
|
|
1982
2090
|
});
|
|
@@ -2000,7 +2108,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
2000
2108
|
};
|
|
2001
2109
|
}
|
|
2002
2110
|
if (request?.kind !== "decision" && taken === 0 && witness === void 0 && !capped()) {
|
|
2003
|
-
endPath(path, {
|
|
2111
|
+
endPath(path, settled, {
|
|
2004
2112
|
status: "idle",
|
|
2005
2113
|
state: settled.snapshot.value
|
|
2006
2114
|
});
|
|
@@ -2128,6 +2236,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
2128
2236
|
stepper
|
|
2129
2237
|
};
|
|
2130
2238
|
}
|
|
2239
|
+
if (initial && (stateTarget || !awaitsKids(initial, void 0)) && stops(initial)) witness = [];
|
|
2131
2240
|
const root = {
|
|
2132
2241
|
step: initial,
|
|
2133
2242
|
path: void 0,
|
|
@@ -2186,6 +2295,19 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
2186
2295
|
};
|
|
2187
2296
|
}
|
|
2188
2297
|
/**
|
|
2298
|
+
* Validates `options.input` against the machine's input schema, as a run
|
|
2299
|
+
* would, and seeds the search with the parsed value (defaults filled). Input
|
|
2300
|
+
* the machine would reject throws `invalid-machine-input` instead of giving a
|
|
2301
|
+
* proof over a start state no run can reach.
|
|
2302
|
+
*/
|
|
2303
|
+
function withMachineInput(machine, options, caller) {
|
|
2304
|
+
if (options.input === void 0) return options;
|
|
2305
|
+
return {
|
|
2306
|
+
...options,
|
|
2307
|
+
input: require_machine_input.resolveMachineInput(machine, options.input, caller)
|
|
2308
|
+
};
|
|
2309
|
+
}
|
|
2310
|
+
/**
|
|
2189
2311
|
* Enumerates a machine's decision and external-event branches to a bounded
|
|
2190
2312
|
* depth, model-free, and reports which states are reached and how each path
|
|
2191
2313
|
* terminates. At each decision request it forks one branch per candidate event
|
|
@@ -2222,7 +2344,7 @@ function explore(machine, options, stopWhen, nesting = 0, deliverable, childRef,
|
|
|
2222
2344
|
* ```
|
|
2223
2345
|
*/
|
|
2224
2346
|
async function explorePaths(machine, options = {}) {
|
|
2225
|
-
return explore(machine, options).report;
|
|
2347
|
+
return explore(machine, withMachineInput(machine, options, "explorePaths")).report;
|
|
2226
2348
|
}
|
|
2227
2349
|
/** Thrown when a string reachability target is not a state in the machine. */
|
|
2228
2350
|
var AgentUnknownStateError = class extends require_event_log.AgentError {
|
|
@@ -2271,8 +2393,10 @@ function resolveStateTarget(machine, target) {
|
|
|
2271
2393
|
* ```
|
|
2272
2394
|
*/
|
|
2273
2395
|
async function canReach(machine, target, options = {}) {
|
|
2396
|
+
options = withMachineInput(machine, options, "canReach");
|
|
2274
2397
|
const resolvedTarget = typeof target === "string" ? resolveStateTarget(machine, target) : void 0;
|
|
2275
|
-
const
|
|
2398
|
+
const ordering = typeof target === "object" ? target : void 0;
|
|
2399
|
+
const { witness, report } = explore(machine, options, typeof target === "function" ? target : ordering ? () => false : (snapshot) => snapshot.nodes.some((node) => node.id === resolvedTarget), 0, void 0, void 0, resolvedTarget !== void 0 && hasTransientStates(machine.getStateNodeById(resolvedTarget)), void 0, false, ordering, resolvedTarget !== void 0);
|
|
2276
2400
|
if (witness !== void 0) return {
|
|
2277
2401
|
reachable: true,
|
|
2278
2402
|
witness,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const require_event_log = require("./event-log-
|
|
2
|
-
const require_decision = require("./decision-
|
|
1
|
+
const require_event_log = require("./event-log-dSOnXHuG.cjs");
|
|
2
|
+
const require_decision = require("./decision-D8bcIGXQ.cjs");
|
|
3
3
|
//#region src/internal/decision-object.ts
|
|
4
4
|
/** Resolves a host's `decideMode`; incompatible object payloads default to `'tool'`. @internal */
|
|
5
5
|
function resolveDecisionMode(option, request) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { o as decisionOptionIds } from "./decision-
|
|
1
|
+
import { $ as getJsonSchemaSync, ft as isRecord } from "./event-log-CEq_bVXQ.mjs";
|
|
2
|
+
import { o as decisionOptionIds } from "./decision-B41YBx5U.mjs";
|
|
3
3
|
//#region src/internal/decision-object.ts
|
|
4
4
|
/** Resolves a host's `decideMode`; incompatible object payloads default to `'tool'`. @internal */
|
|
5
5
|
function resolveDecisionMode(option, request) {
|
package/docs/advanced.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Advanced: bare XState actors and hand-written executors
|
|
2
2
|
|
|
3
|
-
Most hosts call `
|
|
3
|
+
Most hosts call `runAgent`, or drive the [runtime loop](steps.md) themselves. This page covers the two things underneath those: binding executors onto a machine so it runs as a plain XState actor, and writing an executor without an adapter.
|
|
4
4
|
|
|
5
5
|
## `provideExecutors`: the machine as a plain actor
|
|
6
6
|
|
|
@@ -21,7 +21,7 @@ Reach for this when:
|
|
|
21
21
|
- **The agent machine is a child in a larger XState system.** Invoke or spawn the bound machine from a parent machine like any other actor logic; its decisions and requests run inside the parent's actor system.
|
|
22
22
|
- **The actor is long-lived.** A chat session, a game loop, or a device controller keeps one actor running across many human turns instead of resuming from a snapshot per turn.
|
|
23
23
|
|
|
24
|
-
What you give up compared with `
|
|
24
|
+
What you give up compared with `runAgent`: there is no idle settling, no `maxModelCalls` cap, no event log or `snapshot`/`event` resume options, and no `run.start`/`run.end` trace boundary. The actor runs until you stop it. Usage events (`@agent.usage`) are still delivered to the machine, and `onTrace` still receives the request-level trace.
|
|
25
25
|
|
|
26
26
|
```ts no-check
|
|
27
27
|
const bound = provideExecutors(machine, executors, {
|
|
@@ -32,9 +32,9 @@ const bound = provideExecutors(machine, executors, {
|
|
|
32
32
|
|
|
33
33
|
- `actors` merges extra actor sources before binding, the same shape as `machine.provide({ actors })`.
|
|
34
34
|
- `onChunk` receives every chunk of every `mode: 'stream'` request.
|
|
35
|
-
- `onTrace` receives `request.start`, `request.end`, `request.error`, and `stream.chunk` events with the same envelope `
|
|
35
|
+
- `onTrace` receives `request.start`, `request.end`, `request.error`, and `stream.chunk` events with the same envelope `runAgent` emits, minted per root actor. Pair it with `traceTransitions` on the actor's `inspect` option to fold `machine.transition` events into the same stream.
|
|
36
36
|
|
|
37
|
-
`provideExecutors` does not descend into invoked child machines. A child with its own agent requests needs its own `provideExecutors(...)` call, or `bindRequestExecutor` on its request logic (below). `
|
|
37
|
+
`provideExecutors` does not descend into invoked child machines. A child with its own agent requests needs its own `provideExecutors(...)` call, or `bindRequestExecutor` on its request logic (below). `runAgent` rebinds children for you.
|
|
38
38
|
|
|
39
39
|
## Writing an executor by hand
|
|
40
40
|
|
|
@@ -60,7 +60,7 @@ const executors = {
|
|
|
60
60
|
|
|
61
61
|
- `result` is the value: the text, or the structured object the request's output schema describes. Core validates it against that schema.
|
|
62
62
|
- `messages` are the provider's response messages for this call. They arrive on `output.messages` in `onDone`, so the machine decides what to keep.
|
|
63
|
-
- `usage` is this call's token usage on the flat `inputTokens`/`outputTokens`/`totalTokens` names. `
|
|
63
|
+
- `usage` is this call's token usage on the flat `inputTokens`/`outputTokens`/`totalTokens` names. `runAgent` folds it into the run's aggregate and the `@agent.usage` event.
|
|
64
64
|
- Anything else (`finishReason`, `toolCalls`, `raw`) rides along to `onResult(request, { raw })` and the `request.end` trace.
|
|
65
65
|
|
|
66
66
|
`streamText` returns the same shape once the stream finishes and calls `info.onChunk` for each chunk on the way. `decide` returns `{ event }`, the machine event the model chose from `request.events`; see [Decisions](decisions.md).
|
|
@@ -4,34 +4,34 @@ The machine is the artifact. Runners only decide how one host executes its XStat
|
|
|
4
4
|
|
|
5
5
|
| Need | Use |
|
|
6
6
|
| -------------------------------- | ---------------------------------------------------------------------- |
|
|
7
|
-
| One request/response run | `
|
|
8
|
-
| Several idle/resume turns | `
|
|
7
|
+
| One request/response run | `runAgent(machine, options)` |
|
|
8
|
+
| Several idle/resume turns | `runAgent` in a loop over `result.persist()`, or `onIdle` |
|
|
9
9
|
| Transition-by-transition control | The explicit `AgentRuntime` loop |
|
|
10
10
|
| A long-lived actor | `provideExecutors` + XState `createActor`, see [Advanced](advanced.md) |
|
|
11
11
|
|
|
12
12
|
## Managed run
|
|
13
13
|
|
|
14
14
|
```ts no-check
|
|
15
|
-
const result = await
|
|
15
|
+
const result = await runAgent(machine, { executors, input });
|
|
16
16
|
|
|
17
17
|
if (result.status === "idle") {
|
|
18
18
|
await storage.save(result.persist());
|
|
19
19
|
}
|
|
20
20
|
```
|
|
21
21
|
|
|
22
|
-
`
|
|
23
|
-
|
|
22
|
+
`runAgent` binds request executors and drives the durable transition loop until
|
|
23
|
+
the run is done, idle, or errors. Storage remains host-owned.
|
|
24
24
|
|
|
25
25
|
## Idle/resume loop
|
|
26
26
|
|
|
27
27
|
```ts no-check
|
|
28
|
-
let result = await
|
|
28
|
+
let result = await runAgent(machine, { executors, input });
|
|
29
29
|
|
|
30
30
|
while (result.status === "idle") {
|
|
31
31
|
const snapshot = result.persist();
|
|
32
32
|
await storage.save(snapshot);
|
|
33
33
|
const event = await nextExternalEvent(result.snapshot);
|
|
34
|
-
result = await
|
|
34
|
+
result = await runAgent(machine, { executors, snapshot, event });
|
|
35
35
|
}
|
|
36
36
|
```
|
|
37
37
|
|
package/docs/debugging.md
CHANGED
|
@@ -3,14 +3,12 @@
|
|
|
3
3
|
Use the XState inspection protocol for framework behavior and Agent traces for request behavior.
|
|
4
4
|
|
|
5
5
|
```ts no-check
|
|
6
|
-
const result = await
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
{ input },
|
|
13
|
-
);
|
|
6
|
+
const result = await runAgent(machine, {
|
|
7
|
+
executors,
|
|
8
|
+
inspect: (event) => inspector.next(event),
|
|
9
|
+
onTrace: (event) => logger.write(serializeTraceEvent(event)),
|
|
10
|
+
input,
|
|
11
|
+
});
|
|
14
12
|
```
|
|
15
13
|
|
|
16
14
|
`inspect` is the raw XState stream. `onTrace` adds Agent request start/end/error, chunks, usage, emitted events, transitions, and the terminal run result.
|
package/docs/decisions.md
CHANGED
|
@@ -52,7 +52,7 @@ deciding: {
|
|
|
52
52
|
|
|
53
53
|
The `allowedEvents` list is typed against the machine's user-authored event schema, so a typo is a compile error. Framework events such as `@agent.usage` can be handled by the machine but are never model-facing candidates. Listing events explicitly also makes the candidate set visible in the machine.
|
|
54
54
|
|
|
55
|
-
> **Note:** `agent.decide` needs a snapshot-aware host such as `
|
|
55
|
+
> **Note:** `agent.decide` needs a snapshot-aware host such as `runAgent` to know which events are currently legal. With a [long-lived actor](choosing-a-run-mode.md#long-lived-actor), list `allowedEvents` explicitly. Wildcards and the omitted default cannot expand there.
|
|
56
56
|
|
|
57
57
|
### `allowedEvents` patterns
|
|
58
58
|
|
|
@@ -100,7 +100,7 @@ Guards are transition functions that return `undefined`. See [Transitions](machi
|
|
|
100
100
|
|
|
101
101
|
The candidate set is the `allowedEvents` list intersected with the events the state statically accepts. After the model picks one, `snapshot.can(event)` decides whether it is legal in the current snapshot. A chosen `ASK` on the final turn is rejected, and the model is asked again.
|
|
102
102
|
|
|
103
|
-
`
|
|
103
|
+
`runAgent` performs this check for you. When you call `resolveDecision` directly with a [long-lived actor](choosing-a-run-mode.md#long-lived-actor), pass the check through `canTake`:
|
|
104
104
|
|
|
105
105
|
```ts
|
|
106
106
|
import { resolveDecision } from "@statelyai/agent";
|
|
@@ -375,7 +375,8 @@ A decision model such as Jev answers only closed choices. `'pick-then-fill'` tur
|
|
|
375
375
|
A decision can be answered by another machine: a policy that applies a rule when the facts are enough and asks a model only for the rest. `createPolicyDecider` turns a policy machine into a decide executor.
|
|
376
376
|
|
|
377
377
|
```ts no-check
|
|
378
|
-
import {
|
|
378
|
+
import { runAgent } from "@statelyai/agent";
|
|
379
|
+
import { createPolicyDecider } from "@statelyai/agent/policy";
|
|
379
380
|
|
|
380
381
|
const decide = createPolicyDecider(policyMachine, { executors: modelExecutors });
|
|
381
382
|
|
|
@@ -408,7 +409,7 @@ A machine does not have to know about AI. `decideNext` asks a model to pick one
|
|
|
408
409
|
- It never sends. The host sends the event, after checking `can` again, because the actor may have moved while the model was choosing.
|
|
409
410
|
|
|
410
411
|
```ts
|
|
411
|
-
import { decideNext } from "@statelyai/agent";
|
|
412
|
+
import { decideNext } from "@statelyai/agent/policy";
|
|
412
413
|
import { createAiSdkExecutors } from "@statelyai/agent/ai-sdk";
|
|
413
414
|
import { openai } from "@ai-sdk/openai";
|
|
414
415
|
import { createActor, createMachine } from "xstate";
|