@statelyai/agent 2.0.0-alpha.29 → 2.0.0-alpha.31
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 +1733 -0
- package/dist/ai-sdk.cjs +9 -9
- package/dist/ai-sdk.d.cts +5 -5
- package/dist/ai-sdk.d.mts +5 -5
- package/dist/ai-sdk.mjs +4 -4
- package/dist/{decision-Bl_rKQnU.mjs → decision-DqO018Tp.mjs} +23 -10
- package/dist/{decision-oevZnkBe.cjs → decision-Iys2hzg3.cjs} +31 -18
- package/dist/{event-log-Dtb16p1p.cjs → event-log-Bdww2l1D.cjs} +104 -25
- package/dist/{event-log-GPZO9p7_.mjs → event-log-DE430ZCa.mjs} +87 -26
- package/dist/{event-log-store-bCdskPNS.cjs → event-log-store-BWMLi6oh.cjs} +1 -1
- package/dist/{event-log-store-yalq8C77.mjs → event-log-store-CCWdTPEP.mjs} +1 -1
- package/dist/{event-log-store-CN9ygggF.d.cts → event-log-store-DTf_OzB-.d.cts} +1 -1
- package/dist/{event-log-store-DS836wch.d.mts → event-log-store-RziIobdW.d.mts} +1 -1
- package/dist/index.cjs +136 -23
- package/dist/index.d.cts +58 -11
- package/dist/index.d.mts +58 -11
- package/dist/index.mjs +133 -21
- package/dist/log.cjs +2 -2
- package/dist/log.d.cts +1 -1
- package/dist/log.d.mts +1 -1
- package/dist/log.mjs +2 -2
- package/dist/machines.cjs +1 -1
- package/dist/machines.mjs +1 -1
- package/dist/{model-source-C7FFP2Sj.mjs → model-source-CXsSZPq0.mjs} +1 -2
- package/dist/{model-source-DjJPjGSP.cjs → model-source-DQ7KgJaT.cjs} +4 -5
- package/dist/openai.cjs +3 -3
- package/dist/openai.d.cts +2 -2
- package/dist/openai.d.mts +2 -2
- package/dist/openai.mjs +3 -3
- package/dist/otel.d.cts +1 -1
- package/dist/otel.d.mts +1 -1
- package/dist/{run-agent-C9ubX8Tx.d.cts → run-agent-B5opVUxx.d.cts} +25 -6
- package/dist/{run-agent-CxSyZmIE.d.mts → run-agent-D4MwS5GY.d.mts} +25 -6
- package/dist/{run-agent-CuQT1xSS.mjs → run-agent-DWZ1uyBJ.mjs} +100 -37
- package/dist/{run-agent-cToZ3K42.cjs → run-agent-tmk58M0x.cjs} +100 -37
- package/dist/{setup-agent-DniLvDu7.mjs → setup-agent-BaffhCcM.mjs} +38 -3
- package/dist/{setup-agent-tsc3vm5I.d.mts → setup-agent-CPyg2ic7.d.mts} +11 -3
- package/dist/{setup-agent-DTF3NQg3.cjs → setup-agent-D0L8Anl_.cjs} +38 -3
- package/dist/{setup-agent-DlbgwsIJ.d.cts → setup-agent-yFFVXf5s.d.cts} +11 -3
- package/dist/tanstack-ai.cjs +3 -3
- package/dist/tanstack-ai.d.cts +2 -2
- package/dist/tanstack-ai.d.mts +2 -2
- package/dist/tanstack-ai.mjs +3 -3
- package/dist/testing.cjs +176 -26
- package/dist/testing.d.cts +128 -10
- package/dist/testing.d.mts +128 -10
- package/dist/testing.mjs +168 -20
- package/dist/{text-logic-BDbGjYMh.d.mts → text-logic-BwdrDpO9.d.mts} +6 -2
- package/dist/{text-logic-9fv1i9aK.d.cts → text-logic-j9hShB7d.d.cts} +6 -2
- package/dist/{usage-D8UphgEA.d.mts → usage-BYqv7VBw.d.cts} +1 -1
- package/dist/{usage-R1NTmLxY.d.cts → usage-Bl4nK8D-.d.mts} +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-B5qGC5WN.mjs → verify-BH5e0XLK.mjs} +55 -5
- package/dist/{verify-DYH_2VzU.d.cts → verify-CPKDPMwY.d.cts} +14 -6
- package/dist/{verify-Cqghu4gz.cjs → verify-CS_xxvVU.cjs} +57 -7
- package/dist/{verify-CBuYIpsa.d.mts → verify-tkymWz6X.d.mts} +14 -6
- package/package.json +34 -4
- package/readme.md +72 -42
- package/skills/add-evals/SKILL.md +144 -0
- package/skills/add-traces/SKILL.md +147 -0
- package/skills/generate-machine/SKILL.md +6 -6
- package/skills/graph-engineering/SKILL.md +33 -0
- package/skills/improve-machine/SKILL.md +73 -21
- package/skills/improve-machine/reference.md +12 -7
- package/skills/loop-to-machine/SKILL.md +210 -0
- package/skills/loop-to-machine/policy.md +154 -0
|
@@ -54,6 +54,31 @@ var AgentTruncatedError = class extends AgentError {
|
|
|
54
54
|
}
|
|
55
55
|
};
|
|
56
56
|
//#endregion
|
|
57
|
+
//#region src/internal/is-record.ts
|
|
58
|
+
/** True for a plain object-like value (arrays excluded). @internal */
|
|
59
|
+
function isRecord(value) {
|
|
60
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* True for an object whose prototype is `null` or some realm's
|
|
64
|
+
* `Object.prototype`. Comparing against this realm's `Object.prototype` alone
|
|
65
|
+
* rejects plain objects built in another realm: a jest test file's vm
|
|
66
|
+
* context, or `structuredClone`'s output inside one. @internal
|
|
67
|
+
*/
|
|
68
|
+
function isPlainObject(value) {
|
|
69
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
70
|
+
const prototype = Object.getPrototypeOf(value);
|
|
71
|
+
return prototype === null || Object.getPrototypeOf(prototype) === null;
|
|
72
|
+
}
|
|
73
|
+
/** True for an `Error` from any realm, where `instanceof Error` sees only this one. @internal */
|
|
74
|
+
function isError(value) {
|
|
75
|
+
return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
|
|
76
|
+
}
|
|
77
|
+
/** JSON text with object keys sorted and `undefined` fields dropped, for comparing JSON-like values. @internal */
|
|
78
|
+
function canonicalJson(value) {
|
|
79
|
+
return JSON.stringify(value, (_key, item) => isPlainObject(item) ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, item[key]])) : item) ?? "undefined";
|
|
80
|
+
}
|
|
81
|
+
//#endregion
|
|
57
82
|
//#region src/utils.ts
|
|
58
83
|
/** Returns the human-readable text carried by a message, ignoring non-text parts. */
|
|
59
84
|
function getMessageText(message) {
|
|
@@ -103,8 +128,7 @@ function findNonSerializableContextPaths(context, limit = 5) {
|
|
|
103
128
|
seen.delete(obj);
|
|
104
129
|
return;
|
|
105
130
|
}
|
|
106
|
-
|
|
107
|
-
if (proto === Object.prototype || proto === null) {
|
|
131
|
+
if (isPlainObject(value)) {
|
|
108
132
|
seen.add(obj);
|
|
109
133
|
for (const [key, item] of Object.entries(value)) walk(item, `${path}.${key}`);
|
|
110
134
|
seen.delete(obj);
|
|
@@ -456,7 +480,7 @@ function responseMessagesOf(raw) {
|
|
|
456
480
|
}
|
|
457
481
|
function dropUndefined(value) {
|
|
458
482
|
if (Array.isArray(value)) return value.map(dropUndefined);
|
|
459
|
-
if (
|
|
483
|
+
if (isPlainObject(value)) {
|
|
460
484
|
const out = {};
|
|
461
485
|
for (const [key, entry] of Object.entries(value)) if (entry !== void 0) out[key] = dropUndefined(entry);
|
|
462
486
|
return out;
|
|
@@ -577,7 +601,7 @@ function resolveTextLogicValue(value, args) {
|
|
|
577
601
|
* export const tellJoke = createTextLogic({
|
|
578
602
|
* mode: 'stream',
|
|
579
603
|
* schemas: { input: z.object({ topic: z.string() }), output: z.string() },
|
|
580
|
-
* model: 'openai/gpt-
|
|
604
|
+
* model: 'openai/gpt-6-luna',
|
|
581
605
|
* system: 'You tell short, punchy jokes.',
|
|
582
606
|
* prompt: ({ input }) => `Tell a joke about ${input.topic}.`,
|
|
583
607
|
* });
|
|
@@ -932,8 +956,7 @@ function assertJsonSerializable(value, path = "entry", ancestors = /* @__PURE__
|
|
|
932
956
|
assertNoHiddenKeys(value, path, (key) => key === "length" || arrayIndexPattern.test(key));
|
|
933
957
|
return;
|
|
934
958
|
}
|
|
935
|
-
|
|
936
|
-
if (prototype !== Object.prototype && prototype !== null) throw new NonSerializableAgentEventError(path, value.constructor?.name ?? "object");
|
|
959
|
+
if (!isPlainObject(value)) throw new NonSerializableAgentEventError(path, value.constructor?.name ?? "object");
|
|
937
960
|
assertNoHiddenKeys(value, path);
|
|
938
961
|
for (const [key, child] of Object.entries(value)) assertJsonSerializable(child, `${path}.${key}`, ancestors);
|
|
939
962
|
} finally {
|
|
@@ -990,22 +1013,32 @@ function exhaustedAttemptsOf(error) {
|
|
|
990
1013
|
return Array.isArray(attempts) && isJsonSerializable(attempts) ? attempts : void 0;
|
|
991
1014
|
}
|
|
992
1015
|
/**
|
|
993
|
-
*
|
|
994
|
-
*
|
|
995
|
-
*
|
|
1016
|
+
* Marks an object {@link normalizeEventErrors} made from an `Error`, so replay
|
|
1017
|
+
* restores that object, and only that one, as an `Error`: a thrown plain
|
|
1018
|
+
* `{ name, message }` stays a plain object.
|
|
1019
|
+
*/
|
|
1020
|
+
const NORMALIZED_ERROR_KEY = "@error";
|
|
1021
|
+
/**
|
|
1022
|
+
* Replaces `Error` instances with plain `{ name, message, code?, cause?,
|
|
1023
|
+
* "@error": true }` objects so an `xstate.error.actor` payload survives the
|
|
1024
|
+
* log's JSON round-trip. `code` is kept when it is a string or a number; a
|
|
1025
|
+
* decision-exhausted error also keeps its `attempts`. Replay turns the
|
|
1026
|
+
* object back into an `Error` (see `restoreJournaledEvent`). Cycles
|
|
996
1027
|
* are preserved by identity; non-plain objects are left alone (and are then
|
|
997
1028
|
* rejected by {@link assertJsonSerializable}).
|
|
998
1029
|
*/
|
|
999
1030
|
function normalizeEventErrors(value, seen = /* @__PURE__ */ new WeakMap()) {
|
|
1000
|
-
if (value
|
|
1031
|
+
if (isError(value)) {
|
|
1001
1032
|
const normalized = {
|
|
1002
1033
|
name: value.name,
|
|
1003
|
-
message: value.message
|
|
1034
|
+
message: value.message,
|
|
1035
|
+
[NORMALIZED_ERROR_KEY]: true
|
|
1004
1036
|
};
|
|
1005
1037
|
seen.set(value, normalized);
|
|
1006
1038
|
if (value.cause !== void 0) normalized.cause = normalizeEventErrors(value.cause, seen);
|
|
1007
|
-
|
|
1008
|
-
|
|
1039
|
+
const code = value.code;
|
|
1040
|
+
if (typeof code === "string" || typeof code === "number" && Number.isFinite(code)) normalized.code = code;
|
|
1041
|
+
if (code === DECISION_EXHAUSTED_CODE) {
|
|
1009
1042
|
const attempts = exhaustedAttemptsOf(value);
|
|
1010
1043
|
if (attempts !== void 0) normalized.attempts = structuredClone(attempts);
|
|
1011
1044
|
}
|
|
@@ -1020,8 +1053,7 @@ function normalizeEventErrors(value, seen = /* @__PURE__ */ new WeakMap()) {
|
|
|
1020
1053
|
for (const item of value) result.push(normalizeEventErrors(item, seen));
|
|
1021
1054
|
return result;
|
|
1022
1055
|
}
|
|
1023
|
-
|
|
1024
|
-
if (prototype !== Object.prototype && prototype !== null) return value;
|
|
1056
|
+
if (!isPlainObject(value)) return value;
|
|
1025
1057
|
const result = {};
|
|
1026
1058
|
seen.set(value, result);
|
|
1027
1059
|
for (const [key, item] of Object.entries(value)) result[key] = normalizeEventErrors(item, seen);
|
|
@@ -1046,7 +1078,7 @@ function canonicalizeForHash(value, seen = /* @__PURE__ */ new WeakSet(), positi
|
|
|
1046
1078
|
if (typeof value === "symbol") return `[symbol:${String(value)}]`;
|
|
1047
1079
|
if (value === null || typeof value !== "object") return value;
|
|
1048
1080
|
if (value instanceof Date) return `[Date:${value.toISOString()}]`;
|
|
1049
|
-
if (value
|
|
1081
|
+
if (isError(value)) {
|
|
1050
1082
|
if (seen.has(value)) return "[circular]";
|
|
1051
1083
|
seen.add(value);
|
|
1052
1084
|
try {
|
|
@@ -1141,7 +1173,7 @@ function createReplayEntry(machine, entries, event, options = {}) {
|
|
|
1141
1173
|
recordedAt: options.recordedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
1142
1174
|
machineId: machineIdOf(machine),
|
|
1143
1175
|
machineVersion,
|
|
1144
|
-
event: normalizeDoneActorEvent(normalizeEventErrors(event)),
|
|
1176
|
+
event: normalizeDoneActorEvent(pruneUndefined(normalizeEventErrors(event))),
|
|
1145
1177
|
...options.causationId !== void 0 ? { causationId: options.causationId } : {},
|
|
1146
1178
|
...options.metadata !== void 0 ? { metadata: options.metadata } : {},
|
|
1147
1179
|
...options.attempts !== void 0 && options.attempts.length > 0 ? { attempts: options.attempts } : {}
|
|
@@ -1154,15 +1186,23 @@ function createReplayEntry(machine, entries, event, options = {}) {
|
|
|
1154
1186
|
}).persistedSnapshot) };
|
|
1155
1187
|
return entry;
|
|
1156
1188
|
}
|
|
1157
|
-
function pruneUndefined(value) {
|
|
1158
|
-
if (Array.isArray(value)) return value.map(pruneUndefined);
|
|
1189
|
+
function pruneUndefined(value, ancestors = /* @__PURE__ */ new WeakSet()) {
|
|
1159
1190
|
if (value === null || typeof value !== "object") return value;
|
|
1160
|
-
if (
|
|
1191
|
+
if (ancestors.has(value)) return value;
|
|
1192
|
+
if (Array.isArray(value)) {
|
|
1193
|
+
ancestors.add(value);
|
|
1194
|
+
const result = value.map((item) => pruneUndefined(item, ancestors));
|
|
1195
|
+
ancestors.delete(value);
|
|
1196
|
+
return result;
|
|
1197
|
+
}
|
|
1198
|
+
if (!isPlainObject(value)) return value;
|
|
1199
|
+
ancestors.add(value);
|
|
1161
1200
|
const result = {};
|
|
1162
1201
|
for (const [key, child] of Object.entries(value)) {
|
|
1163
1202
|
if (child === void 0) continue;
|
|
1164
|
-
result[key] = pruneUndefined(child);
|
|
1203
|
+
result[key] = pruneUndefined(child, ancestors);
|
|
1165
1204
|
}
|
|
1205
|
+
ancestors.delete(value);
|
|
1166
1206
|
return result;
|
|
1167
1207
|
}
|
|
1168
1208
|
/**
|
|
@@ -1359,12 +1399,33 @@ function rebindActorSession(event, snapshot, sessions) {
|
|
|
1359
1399
|
sessionId
|
|
1360
1400
|
};
|
|
1361
1401
|
}
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1402
|
+
/**
|
|
1403
|
+
* The event as the machine received it live: a done event's dropped
|
|
1404
|
+
* `undefined` output restored, and an error event's normalized error turned
|
|
1405
|
+
* back into an `Error`, so `error instanceof Error` holds on replay too.
|
|
1406
|
+
*/
|
|
1407
|
+
function restoreJournaledEvent(event) {
|
|
1408
|
+
if (event.type === DONE_ACTOR_EVENT_TYPE && !Object.hasOwn(event, "output")) return {
|
|
1365
1409
|
...event,
|
|
1366
1410
|
output: void 0
|
|
1367
1411
|
};
|
|
1412
|
+
if (event.type.startsWith(ERROR_ACTOR_EVENT_TYPE)) {
|
|
1413
|
+
const error = event.error;
|
|
1414
|
+
if (isNormalizedError(error)) return {
|
|
1415
|
+
...event,
|
|
1416
|
+
error: toError(error)
|
|
1417
|
+
};
|
|
1418
|
+
}
|
|
1419
|
+
return event;
|
|
1420
|
+
}
|
|
1421
|
+
function isNormalizedError(value) {
|
|
1422
|
+
return isPlainObject(value) && value[NORMALIZED_ERROR_KEY] === true && typeof value.name === "string" && typeof value.message === "string";
|
|
1423
|
+
}
|
|
1424
|
+
function toError(normalized) {
|
|
1425
|
+
const { name, message, cause, [NORMALIZED_ERROR_KEY]: _marker, ...rest } = normalized;
|
|
1426
|
+
const error = new Error(message, cause === void 0 ? void 0 : { cause: isNormalizedError(cause) ? toError(cause) : cause });
|
|
1427
|
+
error.name = name;
|
|
1428
|
+
return Object.assign(error, rest);
|
|
1368
1429
|
}
|
|
1369
1430
|
function verifyEntry(entry, persisted, mode) {
|
|
1370
1431
|
if (mode === false) return;
|
|
@@ -1412,7 +1473,7 @@ function foldLog(machine, entries, options = {}) {
|
|
|
1412
1473
|
verifyEntry(entries[0], persisted, options.verify);
|
|
1413
1474
|
const sessions = /* @__PURE__ */ new Map();
|
|
1414
1475
|
const apply = (entry) => {
|
|
1415
|
-
const event =
|
|
1476
|
+
const event = restoreJournaledEvent(rebindActorSession(entry.event, snapshot, sessions));
|
|
1416
1477
|
[snapshot] = transition(machine, snapshot, event);
|
|
1417
1478
|
persisted = machine.getPersistedSnapshot(snapshot);
|
|
1418
1479
|
return persisted;
|
|
@@ -1490,4 +1551,4 @@ function recordLog(actor) {
|
|
|
1490
1551
|
};
|
|
1491
1552
|
}
|
|
1492
1553
|
//#endregion
|
|
1493
|
-
export { getStateMeta as $, createTextLogic as A, responseMessagesOf as B, AGENT_USAGE_EVENT_TYPE as C, STREAM_TEXT_ACTOR as D, GENERATE_TEXT_ACTOR as E, normalizeGeneratorResult as F, missingActor as G, getAgentExecutionOptions as H, parseOutput as I, findNonSerializableContextPaths as J, setAgentExecutionOptions as K, parseProviderOutput as L, getCallFinishReason as M, getCallUsage as N, bindRequestExecutor as O, isTextLogic as P, getMessageText as Q, providerOutputSchema as R, validateReplayEntries as S, DECIDE_ACTOR as T, getRegisteredAgentExecutionOptions as U, executorBoundLogics as V, isUnboundPlaceholder as W, getJsonSchemaSync as X, getJsonSchema as Y, getMachineStructuralHash as Z, getUsageFromEvents as _, AgentReplayDivergenceError as a, userMessage as at, recordLog as b, assertAgentLogEntry as c,
|
|
1554
|
+
export { getStateMeta as $, createTextLogic as A, responseMessagesOf as B, AGENT_USAGE_EVENT_TYPE as C, STREAM_TEXT_ACTOR as D, GENERATE_TEXT_ACTOR as E, normalizeGeneratorResult as F, missingActor as G, getAgentExecutionOptions as H, parseOutput as I, findNonSerializableContextPaths as J, setAgentExecutionOptions as K, parseProviderOutput as L, getCallFinishReason as M, getCallUsage as N, bindRequestExecutor as O, isTextLogic as P, getMessageText as Q, providerOutputSchema as R, validateReplayEntries as S, DECIDE_ACTOR as T, getRegisteredAgentExecutionOptions as U, executorBoundLogics as V, isUnboundPlaceholder as W, getJsonSchemaSync as X, getJsonSchema as Y, getMachineStructuralHash as Z, getUsageFromEvents as _, AgentReplayDivergenceError as a, userMessage as at, recordLog as b, assertAgentLogEntry as c, isPlainObject as ct, createReplayEntry as d, AgentTruncatedError as dt, getStatePath as et, foldLog as f, getSnapshotStateHash as g, getLogExecutionId as h, AgentMachineVersionMismatchError as i, toolMessage as it, getAgentOutputMode as j, builtinTextActors as k, assertJsonSerializable as l, isRecord as lt, getDecisionAttempts as m, AGENT_INIT_EVENT_TYPE as n, resolveMachineVersion as nt, NonSerializableAgentEventError as o, validateSchemaSync as ot, forkEventLog as p, assistantMessage as q, AgentEventLogError as r, systemMessage as rt, agentCallOccurrence as s, canonicalJson as st, AGENT_EVENT_SCHEMA_VERSION as t, isStandardSchema as tt, canonicalEventJson as u, AgentError as ut, initEntry as v, AGENT_USAGE_TOKEN_FIELDS as w, replay as x, rebindActorSession as y, resolveTextLogicValue as z };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as assertAgentLogEntry,
|
|
1
|
+
import { c as assertAgentLogEntry, ut as AgentError } from "./event-log-DE430ZCa.mjs";
|
|
2
2
|
//#region src/event-log-store.ts
|
|
3
3
|
/**
|
|
4
4
|
* Durable storage for {@link AgentLogEntry} logs: the one interface a host
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { I as DecisionAttempt, Q as AgentError, t as AgentCallUsage } from "./text-logic-
|
|
1
|
+
import { I as DecisionAttempt, Q as AgentError, t as AgentCallUsage } from "./text-logic-j9hShB7d.cjs";
|
|
2
2
|
import { Actor, AnyMachineSnapshot, AnyStateMachine, EventObject, Snapshot, SnapshotFrom } from "xstate";
|
|
3
3
|
//#region src/event-log.d.ts
|
|
4
4
|
/** The durable entry envelope version. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { I as DecisionAttempt, Q as AgentError, t as AgentCallUsage } from "./text-logic-
|
|
1
|
+
import { I as DecisionAttempt, Q as AgentError, t as AgentCallUsage } from "./text-logic-BwdrDpO9.mjs";
|
|
2
2
|
import { Actor, AnyMachineSnapshot, AnyStateMachine, EventObject, Snapshot, SnapshotFrom } from "xstate";
|
|
3
3
|
//#region src/event-log.d.ts
|
|
4
4
|
/** The durable entry envelope version. */
|
package/dist/index.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
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_setup_agent = require("./setup-agent-
|
|
5
|
-
const require_event_log_store = require("./event-log-store-
|
|
6
|
-
const require_run_agent = require("./run-agent-
|
|
2
|
+
const require_event_log = require("./event-log-Bdww2l1D.cjs");
|
|
3
|
+
const require_decision = require("./decision-Iys2hzg3.cjs");
|
|
4
|
+
const require_setup_agent = require("./setup-agent-D0L8Anl_.cjs");
|
|
5
|
+
const require_event_log_store = require("./event-log-store-BWMLi6oh.cjs");
|
|
6
|
+
const require_run_agent = require("./run-agent-tmk58M0x.cjs");
|
|
7
7
|
let xstate = require("xstate");
|
|
8
8
|
//#region src/messages.ts
|
|
9
9
|
const KNOWN_PART_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -168,7 +168,8 @@ function validateChoice(value, path) {
|
|
|
168
168
|
* reads: an object whose optional `interaction` declares a `label` (a string
|
|
169
169
|
* with `{context.path}` interpolation, or a function of the context), an
|
|
170
170
|
* `events` map of choices, payload `choices` (an array, or a context path to
|
|
171
|
-
* one), and a `textEvent` (a type, or `{ type, field }`) for free-text answers
|
|
171
|
+
* one), and a `textEvent` (a type, or `{ type, field }`) for free-text answers; and
|
|
172
|
+
* an optional `actor: "human"`, which tags a transition as sent by a person. This is
|
|
172
173
|
* the default `meta` type `setupAgent` gives a machine; pass it to
|
|
173
174
|
* `createAgentSchemas({ meta: interactionMetaSchema })` only when building a
|
|
174
175
|
* schema pack by hand.
|
|
@@ -178,6 +179,8 @@ const interactionMetaSchema = { "~standard": {
|
|
|
178
179
|
vendor: "statelyai-agent",
|
|
179
180
|
validate(value) {
|
|
180
181
|
if (!value || typeof value !== "object" || Array.isArray(value)) return { issues: [{ message: "Expected a state meta object" }] };
|
|
182
|
+
const actor = value["actor"];
|
|
183
|
+
if (actor !== void 0 && actor !== "human") return { issues: [issue("Expected \"human\"", ["actor"])] };
|
|
181
184
|
const interaction = value["interaction"];
|
|
182
185
|
if (interaction === void 0) return { value };
|
|
183
186
|
if (!interaction || typeof interaction !== "object" || Array.isArray(interaction)) return { issues: [issue("Expected an interaction descriptor object", ["interaction"])] };
|
|
@@ -452,13 +455,44 @@ function guardText(guard) {
|
|
|
452
455
|
if (isObject(decoded) && typeof decoded.type === "string") return decoded.type.startsWith("__fromConfigGuard") ? "guarded" : decoded.type;
|
|
453
456
|
return "guarded";
|
|
454
457
|
}
|
|
455
|
-
/**
|
|
456
|
-
|
|
458
|
+
/**
|
|
459
|
+
* True when a transition function's source has a path that returns no
|
|
460
|
+
* transition, so it may not be taken. Matches minified source too: `void 0`
|
|
461
|
+
* for `undefined`, and a ternary `?` with no spaces (but not `?.` or `??`).
|
|
462
|
+
* String and template literals are blanked first, so their text never counts.
|
|
463
|
+
*/
|
|
464
|
+
const mayDecline = (code) => /\bundefined\b|\bnull\b|\bvoid 0\b|\breturn\s*;|\bif\s*\(|(?<!\?)\?(?![.?])|&&/.test(code.replace(/(["'`])(?:\\.|(?!\1)[^\\])*\1/g, "\"\""));
|
|
465
|
+
/**
|
|
466
|
+
* True when the function returns a call's result (`=> next(ctx)`, `return
|
|
467
|
+
* pick(x)`), so its target is not in its own source. Reads only the
|
|
468
|
+
* function's own returned expressions, not those of callbacks nested in it.
|
|
469
|
+
*/
|
|
470
|
+
function returnsCall(code) {
|
|
471
|
+
const text = code.replace(/(["'`])(?:\\.|(?!\1)[^\\])*\1/g, "\"\"");
|
|
472
|
+
const startsWithCall = (at) => /^[\s(]*[A-Za-z_$][\w$.]*\s*\(/.test(text.slice(at));
|
|
473
|
+
let parens = 0;
|
|
474
|
+
let body = -1;
|
|
475
|
+
for (let i = 0; i < text.length && body < 0; i++) {
|
|
476
|
+
const char = text[i];
|
|
477
|
+
if (char === "(") parens++;
|
|
478
|
+
else if (char === ")") parens--;
|
|
479
|
+
else if (parens === 0 && char === "=" && text[i + 1] === ">") body = i + 2;
|
|
480
|
+
else if (parens === 0 && char === "{") body = i;
|
|
481
|
+
}
|
|
482
|
+
if (body < 0) return false;
|
|
483
|
+
while (/\s/.test(text[body] ?? "")) body++;
|
|
484
|
+
if (text[body] !== "{") return startsWithCall(body);
|
|
485
|
+
let depth = 0;
|
|
486
|
+
for (let i = body; i < text.length; i++) if (text[i] === "{") depth++;
|
|
487
|
+
else if (text[i] === "}" && --depth === 0) return false;
|
|
488
|
+
else if (depth === 1 && text.startsWith("return", i) && !/[\w$]/.test(text[i - 1] ?? "") && !/[\w$]/.test(text[i + 6] ?? "") && startsWithCall(i + 6)) return true;
|
|
489
|
+
return false;
|
|
490
|
+
}
|
|
457
491
|
/**
|
|
458
492
|
* Where a transition written as a function goes: every string literal after a
|
|
459
493
|
* `target:` that names a real state node, `(conditional)` when it may decline
|
|
460
494
|
* or pick among several, `(stays)` when its source has no `target`, `?` when
|
|
461
|
-
* it names none that resolves.
|
|
495
|
+
* it names none that resolves or returns a helper call's result.
|
|
462
496
|
*/
|
|
463
497
|
function targetsInSource(source, code, choice) {
|
|
464
498
|
const found = /* @__PURE__ */ new Set();
|
|
@@ -471,14 +505,15 @@ function targetsInSource(source, code, choice) {
|
|
|
471
505
|
const conditional = names.length > 1 || !choice && mayDecline(code);
|
|
472
506
|
return `${names.join(", ")}${conditional ? " (conditional)" : ""}`;
|
|
473
507
|
}
|
|
474
|
-
return /\btarget\s*:/.test(code) ? "?" : "(stays)";
|
|
508
|
+
return /\btarget\s*:/.test(code) || returnsCall(code) ? "?" : "(stays)";
|
|
475
509
|
}
|
|
476
|
-
/** One transition, as a line: `on GO if context.ready → review; sets draft — description`. */
|
|
510
|
+
/** One transition, as a line: `on GO (human) if context.ready → review; sets draft — description`. */
|
|
477
511
|
function transitionLine(source, head, transition, options = {}) {
|
|
478
512
|
const code = codeOf(transition);
|
|
479
513
|
let to;
|
|
480
514
|
let guard;
|
|
481
515
|
let description;
|
|
516
|
+
let human = false;
|
|
482
517
|
let sets;
|
|
483
518
|
if (typeof transition === "string") {
|
|
484
519
|
const node = resolveTarget(source, transition);
|
|
@@ -495,12 +530,13 @@ function transitionLine(source, head, transition, options = {}) {
|
|
|
495
530
|
}).join(", ") : "(stays)";
|
|
496
531
|
guard = guardText(transition[options.guardKey ?? "guard"]);
|
|
497
532
|
description = typeof transition.description === "string" ? transition.description : void 0;
|
|
533
|
+
human = isObject(transition.meta) && transition.meta.actor === "human";
|
|
498
534
|
sets = contextKeys(transition, void 0);
|
|
499
535
|
} else {
|
|
500
536
|
to = "?";
|
|
501
537
|
sets = [];
|
|
502
538
|
}
|
|
503
|
-
return `${head}${guard ? ` if ${guard}` : ""} → ${to}${sets.length ? `; sets ${sets.join(", ")}` : ""}${description ? ` — ${oneLine(description)}` : ""}`;
|
|
539
|
+
return `${head}${human ? " (human)" : ""}${guard ? ` if ${guard}` : ""} → ${to}${sets.length ? `; sets ${sets.join(", ")}` : ""}${description ? ` — ${oneLine(description)}` : ""}`;
|
|
504
540
|
}
|
|
505
541
|
function formatMs(ms) {
|
|
506
542
|
if (ms < 1e3) return `${ms}ms`;
|
|
@@ -547,7 +583,7 @@ function stateLine(node, json) {
|
|
|
547
583
|
else if (node.type === "compound" && typeof json.initial === "string") marker = ` (initial: ${json.initial})`;
|
|
548
584
|
const tags = node.tags.length ? ` [tags: ${node.tags.join(", ")}]` : "";
|
|
549
585
|
const interaction = node.meta?.interaction;
|
|
550
|
-
const label = typeof interaction
|
|
586
|
+
const label = !interaction ? "" : typeof interaction.label === "string" ? ` [interaction: "${oneLine(interaction.label)}"]` : typeof interaction.label === "function" ? " [interaction: computed label]" : " [interaction]";
|
|
551
587
|
const description = node.description ? ` — ${oneLine(node.description)}` : "";
|
|
552
588
|
return `${node.key}${marker}${tags}${label}${description}`;
|
|
553
589
|
}
|
|
@@ -584,9 +620,10 @@ function eventLines(machine) {
|
|
|
584
620
|
* label and description (`*` marks the active ones when `snapshot` is given),
|
|
585
621
|
* and under it every transition leaving it, one per line: `on EVENT`,
|
|
586
622
|
* `always`, `after <delay>`, invoke `done`/`error`, and `choice` branches,
|
|
587
|
-
* each with its
|
|
588
|
-
*
|
|
589
|
-
* machine's event schemas with their
|
|
623
|
+
* each with `(human)` when its `meta.actor` is `"human"`, its guard (`if …`),
|
|
624
|
+
* where it goes (`→ review`), and what it sets in context (`sets draft,
|
|
625
|
+
* attempts`). An `Events` section lists the machine's event schemas with their
|
|
626
|
+
* descriptions and fields.
|
|
590
627
|
*
|
|
591
628
|
* A transition written as a function shows the targets its source names
|
|
592
629
|
* (`→ review (conditional)` when it may decline or pick among several),
|
|
@@ -630,7 +667,8 @@ function describeMachine(machine, options = {}) {
|
|
|
630
667
|
* Asks a model to choose the next event for ANY XState snapshot, including a
|
|
631
668
|
* machine built with plain `createMachine`/`setup` that knows nothing about AI.
|
|
632
669
|
* The candidates are the `allowedEvents` an active state handles, one option per
|
|
633
|
-
* payload, kept only where `snapshot.can(event)` is true
|
|
670
|
+
* payload, kept only where `snapshot.can(event)` is true and no transition
|
|
671
|
+
* tagged `meta: { actor: "human" }` handles the type; the rest come back as
|
|
634
672
|
* `withheld`. Each option is
|
|
635
673
|
* described from the transition's `description`, else the event schema's,
|
|
636
674
|
* plus (with `lookahead`) what it changes. The chosen event must equal one
|
|
@@ -665,19 +703,21 @@ function describeMachine(machine, options = {}) {
|
|
|
665
703
|
async function decideNext(snapshot, options) {
|
|
666
704
|
const patterns = typeof options.allowedEvents === "string" ? [options.allowedEvents] : options.allowedEvents;
|
|
667
705
|
const schemas = snapshot.machine.schemas?.events;
|
|
668
|
-
const
|
|
706
|
+
const candidates = require_decision.getAcceptedEvents(snapshot, {
|
|
669
707
|
events: schemas,
|
|
670
708
|
eventTypes: patterns
|
|
671
709
|
}).filter((event) => !require_decision.isEventPattern(event.type));
|
|
710
|
+
const humanEventTypes = require_decision.getHumanEventTypes(snapshot);
|
|
711
|
+
const events = candidates.filter((event) => !humanEventTypes.has(event.type));
|
|
672
712
|
const payloads = options.payloads?.(snapshot) ?? {};
|
|
673
713
|
const accepted = [];
|
|
674
714
|
const withheld = [];
|
|
675
|
-
for (const { type } of
|
|
715
|
+
for (const { type } of candidates) for (const payload of payloads[type] ?? [{}]) {
|
|
676
716
|
const event = {
|
|
677
717
|
...payload,
|
|
678
718
|
type
|
|
679
719
|
};
|
|
680
|
-
(safeCan(snapshot, event) ? accepted : withheld).push(event);
|
|
720
|
+
(!humanEventTypes.has(type) && safeCan(snapshot, event) ? accepted : withheld).push(event);
|
|
681
721
|
}
|
|
682
722
|
const offered = accepted.map((event) => ({
|
|
683
723
|
event,
|
|
@@ -737,7 +777,7 @@ function schemaDescription(schema) {
|
|
|
737
777
|
if (typeof direct === "string") return direct;
|
|
738
778
|
try {
|
|
739
779
|
const json = schema["~standard"].jsonSchema?.input?.({ target: "draft-2020-12" });
|
|
740
|
-
return
|
|
780
|
+
return require_event_log.isRecord(json) && typeof json.description === "string" ? json.description : void 0;
|
|
741
781
|
} catch {
|
|
742
782
|
return;
|
|
743
783
|
}
|
|
@@ -752,8 +792,8 @@ function describeEffect(snapshot, event, keys) {
|
|
|
752
792
|
}
|
|
753
793
|
const changes = [];
|
|
754
794
|
if (require_event_log.canonicalEventJson(snapshot.value) !== require_event_log.canonicalEventJson(next.value)) changes.push(`state: ${short(snapshot.value, maxLength)} → ${short(next.value, maxLength)}`);
|
|
755
|
-
const before =
|
|
756
|
-
const after =
|
|
795
|
+
const before = require_event_log.isRecord(snapshot.context) ? snapshot.context : {};
|
|
796
|
+
const after = require_event_log.isRecord(next.context) ? next.context : {};
|
|
757
797
|
for (const key of keys ?? /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])) if (require_event_log.canonicalEventJson(before[key]) !== require_event_log.canonicalEventJson(after[key])) changes.push(`${key}: ${short(before[key], maxLength)} → ${short(after[key], maxLength)}`);
|
|
758
798
|
return changes.length ? changes.join("; ") : "nothing changes";
|
|
759
799
|
}
|
|
@@ -767,6 +807,78 @@ function short(value, max = 60) {
|
|
|
767
807
|
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
768
808
|
}
|
|
769
809
|
//#endregion
|
|
810
|
+
//#region src/policy-decider.ts
|
|
811
|
+
/**
|
|
812
|
+
* Runs a policy machine as a decide executor: each decision request starts one
|
|
813
|
+
* run of `policy`, and its output is the chosen event. The policy can answer
|
|
814
|
+
* with a rule (a `choice` over the facts, no model call) and invoke
|
|
815
|
+
* `agent.decide` for the rest, answered by `options.executors`.
|
|
816
|
+
*
|
|
817
|
+
* The environment still judges the event: one it does not accept is retried
|
|
818
|
+
* like any other decider's choice. The policy's input must be JSON (it opens
|
|
819
|
+
* the policy run's event log): the default drops keys whose value is
|
|
820
|
+
* `undefined`, and any other value that is not JSON throws before the run. The policy's token usage is reported on the
|
|
821
|
+
* result, and left out when the policy made no model call. A run that does not
|
|
822
|
+
* end `done` with an event throws `AgentError` with code `policy-not-done`.
|
|
823
|
+
*
|
|
824
|
+
* @example
|
|
825
|
+
* ```ts no-check
|
|
826
|
+
* const decide = createPolicyDecider(policyMachine, { executors: modelExecutors });
|
|
827
|
+
* await runAgent(deskMachine, { input, executors: { ...modelExecutors, decide } });
|
|
828
|
+
* ```
|
|
829
|
+
*/
|
|
830
|
+
function createPolicyDecider(policy, options = {}) {
|
|
831
|
+
const { input = defaultInput, threadId, ...runOptions } = options;
|
|
832
|
+
const id = policy.config.id ?? policy.id;
|
|
833
|
+
return async (request, info) => {
|
|
834
|
+
const policyInput = input(request);
|
|
835
|
+
require_event_log.assertJsonSerializable(policyInput, "policy input");
|
|
836
|
+
const thread = runOptions.store === void 0 ? void 0 : await policyThread(request, policyInput, info);
|
|
837
|
+
const result = await require_run_agent.runAgent(policy, {
|
|
838
|
+
...runOptions,
|
|
839
|
+
input: policyInput,
|
|
840
|
+
...thread === void 0 ? {} : { threadId: thread },
|
|
841
|
+
...info?.signal ? { signal: info.signal } : {}
|
|
842
|
+
});
|
|
843
|
+
if (result.status !== "done") {
|
|
844
|
+
const why = result.status === "error" ? `: ${String(result.error)}` : "";
|
|
845
|
+
throw new require_event_log.AgentError("policy-not-done", `policy '${id}' settled '${result.status}'${why}`, { cause: result.status === "error" ? result.error : void 0 });
|
|
846
|
+
}
|
|
847
|
+
const event = result.output;
|
|
848
|
+
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)}`);
|
|
849
|
+
const { modelCalls, ...usage } = result.usage;
|
|
850
|
+
return {
|
|
851
|
+
event,
|
|
852
|
+
...modelCalls > 0 ? { usage } : {}
|
|
853
|
+
};
|
|
854
|
+
};
|
|
855
|
+
async function policyThread(request, policyInput, info) {
|
|
856
|
+
if (threadId) return threadId(request, info);
|
|
857
|
+
if (info?.callKey) return `policy:${info.callKey}:${await sha256(require_event_log.canonicalEventJson(policyInput))}`;
|
|
858
|
+
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`);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
function defaultInput(request) {
|
|
862
|
+
const facts = request.metadata?.facts;
|
|
863
|
+
return withoutUndefinedKeys({
|
|
864
|
+
facts,
|
|
865
|
+
options: (request.options ?? []).map((option) => option.event),
|
|
866
|
+
system: request.system,
|
|
867
|
+
prompt: request.prompt
|
|
868
|
+
});
|
|
869
|
+
}
|
|
870
|
+
/** A copy of `value` with every object key whose value is `undefined` removed, at any depth. */
|
|
871
|
+
function withoutUndefinedKeys(value) {
|
|
872
|
+
if (Array.isArray(value)) return value.map(withoutUndefinedKeys);
|
|
873
|
+
if (!require_event_log.isRecord(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return value;
|
|
874
|
+
return Object.fromEntries(Object.entries(value).filter(([, child]) => child !== void 0).map(([key, child]) => [key, withoutUndefinedKeys(child)]));
|
|
875
|
+
}
|
|
876
|
+
/** Hex SHA-256 of `text`, with Web Crypto (Node, browsers, workers). */
|
|
877
|
+
async function sha256(text) {
|
|
878
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
|
879
|
+
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
880
|
+
}
|
|
881
|
+
//#endregion
|
|
770
882
|
//#region src/provide-executors.ts
|
|
771
883
|
/**
|
|
772
884
|
* Binds a machine's agent actor sources to a set of host `executors` in one
|
|
@@ -896,6 +1008,7 @@ exports.createAgentRuntime = require_run_agent.createAgentRuntime;
|
|
|
896
1008
|
exports.createAgentSchemas = require_setup_agent.createAgentSchemas;
|
|
897
1009
|
exports.createDecisionLogic = require_decision.createDecisionLogic;
|
|
898
1010
|
exports.createDecisionRequest = require_decision.createDecisionRequest;
|
|
1011
|
+
exports.createPolicyDecider = createPolicyDecider;
|
|
899
1012
|
exports.createTextLogic = require_event_log.createTextLogic;
|
|
900
1013
|
exports.decideNext = decideNext;
|
|
901
1014
|
exports.describeMachine = describeMachine;
|