@statelyai/agent 2.0.0-alpha.20 → 2.0.0-alpha.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-sdk.cjs +89 -25
- package/dist/ai-sdk.d.cts +56 -12
- package/dist/ai-sdk.d.mts +56 -12
- package/dist/ai-sdk.mjs +89 -26
- package/dist/{decision-DhsKLYAI.cjs → decision-BnTCsuJv.cjs} +15 -3
- package/dist/{decision-BfhSgCc6.mjs → decision-JWx6n3xR.mjs} +4 -4
- package/dist/index.cjs +202 -41
- package/dist/index.d.cts +138 -18
- package/dist/index.d.mts +138 -18
- package/dist/index.mjs +202 -42
- package/dist/machines.cjs +1 -1
- package/dist/machines.d.cts +1 -1
- package/dist/machines.d.mts +1 -1
- package/dist/machines.mjs +1 -1
- package/dist/otel.d.cts +1 -1
- package/dist/otel.d.mts +1 -1
- package/dist/{run-agent-CwmzAZwj.d.mts → run-agent-DBNI8ETM.d.mts} +3 -3
- package/dist/{run-agent--4bbms-D.d.cts → run-agent-Do094mGu.d.cts} +3 -3
- package/dist/{setup-agent-gISRLxRe.cjs → setup-agent-91FSuZbB.cjs} +2 -15
- package/dist/{setup-agent-BOcSpsIq.mjs → setup-agent-DqqdcdNh.mjs} +3 -10
- package/dist/sqlite.d.cts +1 -1
- package/dist/sqlite.d.mts +1 -1
- package/dist/{text-logic-Er5KkTX6.d.mts → text-logic-BR5twXCv.d.mts} +8 -5
- package/dist/{text-logic-Cavva1W6.d.cts → text-logic-Mmbgb2jy.d.cts} +8 -5
- package/dist/{types-DYpK3QF4.d.mts → types-CvWRGFxP.d.mts} +6 -1
- package/dist/{types-pJ5Hn8fv.d.cts → types-DSdj2tGs.d.cts} +6 -1
- package/dist/validate.cjs +2 -2
- package/dist/validate.mjs +1 -1
- package/package.json +28 -28
- package/readme.md +4 -4
- package/schemas/agent-workflow.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as AgentError } from "./errors-CeSXQx0v.mjs";
|
|
2
|
-
import { _ as
|
|
3
|
-
import { A as
|
|
2
|
+
import { _ as resolveAgentStep, a as AGENT_USAGE_EVENT_TYPE, b as messagesSchema, c as createReplayEntry, d as initEntry, f as replay, g as initialAgentStep, h as getInvokeEffectMetadata, i as AGENT_INIT_EVENT_TYPE, l as diffEventLogs, m as executeAgentRequest, n as getAgentSchemas, o as AgentReplayDivergenceError, p as validateReplayEntries, r as setupAgent, s as AgentReplayMachineMismatchError, t as createAgentSchemas, u as getAgentEffects, v as transitionAgentStep, y as appendMessages } from "./setup-agent-DqqdcdNh.mjs";
|
|
3
|
+
import { A as getMachineStaticTransitionTargets, B as getJsonSchema, C as parseModelRef, G as resolveMachineVersion, H as getMachineStructuralHash, I as assistantMessage, J as userMessage, K as systemMessage, M as isUnboundPlaceholder, O as executorBoundLogics, R as findNonSerializableContextPaths, S as normalizeGeneratorResult, T as parseStructuredEnvelope, U as getStateMeta, V as getJsonSchemaSync, W as isStandardSchema, Y as validateSchemaSync, _ as createTextLogic, a as resolveDecision, b as getCallUsage, c as AGENT_USAGE_TOKEN_FIELDS, d as INTERPRET_SOURCE, h as buildEnvelopeSchema, i as renderDecisionAttempts, j as getRegisteredAgentExecutionOptions, k as getMachineIdlePredicate, m as bindRequestExecutor, o as getAcceptedEvents, q as toolMessage, r as isDecisionLogic, s as parseAgentEvent, t as AgentDecisionExhaustedError, w as parseOutput, x as isTextLogic, y as getAgentOutputMode, z as getAgentMessages } from "./decision-JWx6n3xR.mjs";
|
|
4
4
|
import { a as assertJsonSerializable, i as assertAgentLogEntry, n as AgentEventLogConflictError, o as createInMemoryEventLogStore, r as NonSerializableAgentEventError, s as assertEventLogStoreConformance, t as AGENT_EVENT_SCHEMA_VERSION } from "./event-log-store-DmIDosD6.mjs";
|
|
5
5
|
import { createActor, createAsyncLogic, deliverEvent, getNextTransitions, isMachineSnapshot } from "xstate";
|
|
6
6
|
import { createDurable } from "xstate/durable";
|
|
@@ -568,9 +568,13 @@ function invokingActorOf(self, runCtx) {
|
|
|
568
568
|
* identical event shapes by construction. @internal
|
|
569
569
|
*/
|
|
570
570
|
function bindTextLogic(logic, runCtx) {
|
|
571
|
-
return logic.withExecutor(async ({ request, self: selfArg, signal }) => {
|
|
571
|
+
return logic.withExecutor(async ({ request: rawRequest, self: selfArg, signal }) => {
|
|
572
572
|
const self = selfArg;
|
|
573
573
|
const { id, src } = selfIdAndSrc(self);
|
|
574
|
+
const request = rawRequest.name === void 0 && src !== "" && src !== "agent.generateText" && src !== "agent.streamText" ? {
|
|
575
|
+
...rawRequest,
|
|
576
|
+
name: src
|
|
577
|
+
} : rawRequest;
|
|
574
578
|
const executor = logic.mode === "stream" ? runCtx.streamText : runCtx.generateText;
|
|
575
579
|
if (!executor) throw new Error(`No '${logic.mode === "stream" ? "streamText" : "generateText"}' executor provided.`);
|
|
576
580
|
const requestWithTools = {
|
|
@@ -2084,8 +2088,8 @@ function lintAgentMachine(machine, options = {}) {
|
|
|
2084
2088
|
return diagnostics;
|
|
2085
2089
|
}
|
|
2086
2090
|
/**
|
|
2087
|
-
* Thrown by `lintAgentMachine(machine, { throw: true })`
|
|
2088
|
-
* failing diagnostics.
|
|
2091
|
+
* Thrown by `lintAgentMachine(machine, { throw: true })` (and its
|
|
2092
|
+
* {@link assertAgentMachine} alias) when lint finds failing diagnostics.
|
|
2089
2093
|
* `diagnostics` holds the findings; the message lists them one per finding,
|
|
2090
2094
|
* so a test runner's failure output reads like the CLI's lint report.
|
|
2091
2095
|
*/
|
|
@@ -2098,6 +2102,26 @@ var AgentLintError = class extends AgentError {
|
|
|
2098
2102
|
this.diagnostics = diagnostics;
|
|
2099
2103
|
}
|
|
2100
2104
|
};
|
|
2105
|
+
/**
|
|
2106
|
+
* Asserts a machine passes {@link lintAgentMachine}: returns silently when
|
|
2107
|
+
* clean, throws {@link AgentLintError} (with the findings on `.diagnostics`)
|
|
2108
|
+
* otherwise — sugar for `lintAgentMachine(machine, { ...options, throw: true })`.
|
|
2109
|
+
* Fails on error-severity findings; set `warnings: true` to fail on warnings
|
|
2110
|
+
* too. The one-liner for tests and generation loops:
|
|
2111
|
+
*
|
|
2112
|
+
* @example
|
|
2113
|
+
* ```ts
|
|
2114
|
+
* test('agent machine is structurally sound', () => {
|
|
2115
|
+
* assertAgentMachine(machine);
|
|
2116
|
+
* });
|
|
2117
|
+
* ```
|
|
2118
|
+
*/
|
|
2119
|
+
function assertAgentMachine(machine, options = {}) {
|
|
2120
|
+
lintAgentMachine(machine, {
|
|
2121
|
+
...options,
|
|
2122
|
+
throw: true
|
|
2123
|
+
});
|
|
2124
|
+
}
|
|
2101
2125
|
function pendingInvokes(step) {
|
|
2102
2126
|
const out = [];
|
|
2103
2127
|
for (const action of step.actions) {
|
|
@@ -2124,6 +2148,21 @@ function takeFromQueue(channel, src) {
|
|
|
2124
2148
|
* the real transition logic. Returns the terminal `status`, final `snapshot`,
|
|
2125
2149
|
* and a `trail` of every step taken.
|
|
2126
2150
|
*
|
|
2151
|
+
* Decisions run through the live run's own validation/retry core,
|
|
2152
|
+
* {@link resolveDecision}, with the script standing in for the model: each
|
|
2153
|
+
* attempt consumes the next queued {@link ChosenEvent} for that src, so an
|
|
2154
|
+
* unknown, payload-invalid, or guard-rejected event is NOT silently swallowed
|
|
2155
|
+
* — the next queued decision is tried, exactly as a live run re-asks the
|
|
2156
|
+
* model. The decision logic's `maxRetries` caps attempts as it would live;
|
|
2157
|
+
* when retries continue past the end of the queue, the last queued decision
|
|
2158
|
+
* repeats (a scripted model that insists). The repeat applies only within one
|
|
2159
|
+
* decision request's retries — each new decision request must have its own
|
|
2160
|
+
* queued entry, or the dry-script error throws as usual. Exhausting all
|
|
2161
|
+
* attempts delivers
|
|
2162
|
+
* the resulting {@link AgentDecisionExhaustedError} to the machine as the
|
|
2163
|
+
* decision invoke's error (so an `onError` transition observes it, as it
|
|
2164
|
+
* would live); with no `onError` to catch it, it is thrown.
|
|
2165
|
+
*
|
|
2127
2166
|
* Throws a descriptive error when the script runs dry mid-request, naming the
|
|
2128
2167
|
* pending request's kind, src, and id so the missing scripted response is
|
|
2129
2168
|
* obvious.
|
|
@@ -2132,7 +2171,10 @@ function takeFromQueue(channel, src) {
|
|
|
2132
2171
|
* ```ts
|
|
2133
2172
|
* const { status, snapshot } = simulateAgent(machine, {
|
|
2134
2173
|
* input: { topic: 'state machines' },
|
|
2135
|
-
* script: {
|
|
2174
|
+
* script: {
|
|
2175
|
+
* decisions: { 'agent.decide': [{ type: 'ESCALATE' }] },
|
|
2176
|
+
* events: [{ type: 'APPROVE' }], // crosses the human gate
|
|
2177
|
+
* },
|
|
2136
2178
|
* });
|
|
2137
2179
|
* ```
|
|
2138
2180
|
*/
|
|
@@ -2141,11 +2183,12 @@ async function simulateAgent(machine, options) {
|
|
|
2141
2183
|
const script = {
|
|
2142
2184
|
text: mapValues(options.script.text ?? {}, (arr) => [...arr]),
|
|
2143
2185
|
decisions: mapValues(options.script.decisions ?? {}, (arr) => [...arr]),
|
|
2144
|
-
invokes: mapValues(options.script.invokes ?? {}, (arr) => [...arr])
|
|
2186
|
+
invokes: mapValues(options.script.invokes ?? {}, (arr) => [...arr]),
|
|
2187
|
+
events: [...options.script.events ?? []]
|
|
2145
2188
|
};
|
|
2146
2189
|
if (options.script.userInput?.length) script.invokes[USER_INPUT_SRC] = [...options.script.userInput, ...script.invokes[USER_INPUT_SRC] ?? []];
|
|
2147
2190
|
let step = initialAgentStep(machine, options.input);
|
|
2148
|
-
const trail = [];
|
|
2191
|
+
const trail = [{ state: step.snapshot.value }];
|
|
2149
2192
|
for (let i = 0; i < maxSteps; i++) {
|
|
2150
2193
|
if (step.done) return {
|
|
2151
2194
|
status: "done",
|
|
@@ -2155,14 +2198,10 @@ async function simulateAgent(machine, options) {
|
|
|
2155
2198
|
const request = step.requests[0];
|
|
2156
2199
|
if (request) {
|
|
2157
2200
|
if (request.kind === "decision") {
|
|
2158
|
-
const
|
|
2159
|
-
const
|
|
2160
|
-
|
|
2161
|
-
step =
|
|
2162
|
-
trail.push({
|
|
2163
|
-
state: step.snapshot.value,
|
|
2164
|
-
appliedEvent: taken.value
|
|
2165
|
-
});
|
|
2201
|
+
const invokeMeta = findInvokeMetadata(step, request.id);
|
|
2202
|
+
const src = invokeMeta?.src ?? request.id;
|
|
2203
|
+
const decisionSrc = src in (script.decisions ?? {}) ? src : request.id in (script.decisions ?? {}) ? request.id : src;
|
|
2204
|
+
step = await applyScriptedDecision(machine, step, request, decisionSrc, invokeMeta?.logic, script, trail);
|
|
2166
2205
|
continue;
|
|
2167
2206
|
}
|
|
2168
2207
|
const taken = takeFromQueue(script.text, request.src);
|
|
@@ -2193,6 +2232,18 @@ async function simulateAgent(machine, options) {
|
|
|
2193
2232
|
});
|
|
2194
2233
|
continue;
|
|
2195
2234
|
}
|
|
2235
|
+
const external = script.events;
|
|
2236
|
+
if (external.length > 0) {
|
|
2237
|
+
const event = external.shift();
|
|
2238
|
+
if (!step.snapshot.can(event)) throw new Error(`simulateAgent: scripted external event '${event.type}' cannot be taken in state ${JSON.stringify(step.snapshot.value)} (no handler, or its guard rejected it). A live run's send would be silently dropped here; fix the script's \`events\` queue.`);
|
|
2239
|
+
step = transitionAgentStep(machine, step, event);
|
|
2240
|
+
trail.push({
|
|
2241
|
+
state: step.snapshot.value,
|
|
2242
|
+
appliedEvent: event,
|
|
2243
|
+
external: true
|
|
2244
|
+
});
|
|
2245
|
+
continue;
|
|
2246
|
+
}
|
|
2196
2247
|
return {
|
|
2197
2248
|
status: "idle",
|
|
2198
2249
|
snapshot: step.snapshot,
|
|
@@ -2205,6 +2256,66 @@ async function simulateAgent(machine, options) {
|
|
|
2205
2256
|
trail
|
|
2206
2257
|
};
|
|
2207
2258
|
}
|
|
2259
|
+
async function applyScriptedDecision(machine, step, request, decisionSrc, invokeLogic, script, trail) {
|
|
2260
|
+
const dequeued = [];
|
|
2261
|
+
const decide = async () => {
|
|
2262
|
+
const taken = takeFromQueue(script.decisions, decisionSrc);
|
|
2263
|
+
if (taken.found) {
|
|
2264
|
+
dequeued.push(taken.value);
|
|
2265
|
+
return { event: taken.value };
|
|
2266
|
+
}
|
|
2267
|
+
if (dequeued.length === 0) throw scriptDryError("decision", decisionSrc, request.id, request);
|
|
2268
|
+
return { event: dequeued[dequeued.length - 1] };
|
|
2269
|
+
};
|
|
2270
|
+
const maxRetries = (isDecisionLogic(invokeLogic) ? invokeLogic : resolveRegisteredDecisionLogic(machine, decisionSrc))?.maxRetries;
|
|
2271
|
+
let chosen;
|
|
2272
|
+
try {
|
|
2273
|
+
chosen = await resolveDecision(request, { decide }, {
|
|
2274
|
+
maxRetries,
|
|
2275
|
+
canTake: (event) => step.snapshot.can(event)
|
|
2276
|
+
});
|
|
2277
|
+
} catch (error) {
|
|
2278
|
+
if (!(error instanceof AgentDecisionExhaustedError)) throw error;
|
|
2279
|
+
const next = transitionAgentStep(machine, step, {
|
|
2280
|
+
type: "xstate.error.actor",
|
|
2281
|
+
actorId: request.id,
|
|
2282
|
+
...sessionIdOf(step.snapshot, request.id),
|
|
2283
|
+
error
|
|
2284
|
+
});
|
|
2285
|
+
if (next.snapshot.status === "error") throw error;
|
|
2286
|
+
trail.push({
|
|
2287
|
+
state: next.snapshot.value,
|
|
2288
|
+
rejectedEvents: dequeued
|
|
2289
|
+
});
|
|
2290
|
+
return next;
|
|
2291
|
+
}
|
|
2292
|
+
const next = transitionAgentStep(machine, step, chosen);
|
|
2293
|
+
const rejected = dequeued.slice(0, -1);
|
|
2294
|
+
trail.push({
|
|
2295
|
+
state: next.snapshot.value,
|
|
2296
|
+
appliedEvent: chosen,
|
|
2297
|
+
...rejected.length > 0 ? { rejectedEvents: rejected } : {}
|
|
2298
|
+
});
|
|
2299
|
+
return next;
|
|
2300
|
+
}
|
|
2301
|
+
function findInvokeMetadata(step, id) {
|
|
2302
|
+
for (const action of step.actions) {
|
|
2303
|
+
const metadata = getInvokeEffectMetadata(action);
|
|
2304
|
+
if (metadata?.id !== id) continue;
|
|
2305
|
+
return {
|
|
2306
|
+
...typeof metadata.src === "string" ? { src: metadata.src } : {},
|
|
2307
|
+
logic: metadata.logic ?? (typeof metadata.src === "object" ? metadata.src : void 0)
|
|
2308
|
+
};
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
function resolveRegisteredDecisionLogic(machine, src) {
|
|
2312
|
+
const candidate = getRegisteredAgentExecutionOptions(machine).actors?.[src] ?? machine.sources?.actors?.[src];
|
|
2313
|
+
return isDecisionLogic(candidate) ? candidate : void 0;
|
|
2314
|
+
}
|
|
2315
|
+
function sessionIdOf(snapshot, id) {
|
|
2316
|
+
const child = snapshot.children[id];
|
|
2317
|
+
return typeof child?.sessionId === "string" ? { sessionId: child.sessionId } : {};
|
|
2318
|
+
}
|
|
2208
2319
|
function mapValues(obj, fn) {
|
|
2209
2320
|
return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, fn(value)]));
|
|
2210
2321
|
}
|
|
@@ -2241,6 +2352,10 @@ async function explore(machine, options, stopWhen) {
|
|
|
2241
2352
|
const advance = (step) => {
|
|
2242
2353
|
let current = step;
|
|
2243
2354
|
for (let i = 0; i < MAX_ADVANCE_STEPS; i++) {
|
|
2355
|
+
if (stopWhen?.(current.snapshot)) return {
|
|
2356
|
+
step: current,
|
|
2357
|
+
hit: true
|
|
2358
|
+
};
|
|
2244
2359
|
if (current.done) return { step: current };
|
|
2245
2360
|
const request = current.requests[0];
|
|
2246
2361
|
if (request && request.kind === "text") {
|
|
@@ -2273,8 +2388,8 @@ async function explore(machine, options, stopWhen) {
|
|
|
2273
2388
|
hitPathCap = true;
|
|
2274
2389
|
return;
|
|
2275
2390
|
}
|
|
2276
|
-
const { step: settled, blockedSrc } = advance(step);
|
|
2277
|
-
if (
|
|
2391
|
+
const { step: settled, blockedSrc, hit } = advance(step);
|
|
2392
|
+
if (hit) {
|
|
2278
2393
|
witness = path;
|
|
2279
2394
|
return;
|
|
2280
2395
|
}
|
|
@@ -2369,8 +2484,11 @@ async function explorePaths(machine, options = {}) {
|
|
|
2369
2484
|
return (await explore(machine, options)).report;
|
|
2370
2485
|
}
|
|
2371
2486
|
/**
|
|
2372
|
-
* Answers "can the machine reach
|
|
2373
|
-
*
|
|
2487
|
+
* Answers "can the machine reach this?" by exploring its branches (a thin
|
|
2488
|
+
* wrapper over {@link explorePaths}). The target is either a state path string
|
|
2489
|
+
* (`snapshot.matches(...)` semantics) or a snapshot predicate — the predicate
|
|
2490
|
+
* form checks any property (a context invariant, a tag, a state+context
|
|
2491
|
+
* combination) without reifying a sentinel state for it. Returns
|
|
2374
2492
|
* `{ reachable: true, witness }` with the event sequence that reaches it, or
|
|
2375
2493
|
* `{ reachable: false }`.
|
|
2376
2494
|
*
|
|
@@ -2379,11 +2497,21 @@ async function explorePaths(machine, options = {}) {
|
|
|
2379
2497
|
* const { reachable, witness } = await canReach(refundMachine, 'denied', { input: { request: 'x', amount: 5000 } });
|
|
2380
2498
|
* // reachable → true; witness → [{ type: 'NEEDS_REVIEW' }, { type: 'DENY' }]
|
|
2381
2499
|
* ```
|
|
2500
|
+
*
|
|
2501
|
+
* @example Predicate target — a violation property, no sentinel state needed
|
|
2502
|
+
* ```ts
|
|
2503
|
+
* const violation = await canReach(
|
|
2504
|
+
* refundMachine,
|
|
2505
|
+
* (snapshot) => snapshot.matches('issued') && !snapshot.context.approved,
|
|
2506
|
+
* { input: { amount: 5000 } },
|
|
2507
|
+
* );
|
|
2508
|
+
* // violation.reachable → false is the safety proof
|
|
2509
|
+
* ```
|
|
2382
2510
|
*/
|
|
2383
|
-
async function canReach(machine,
|
|
2384
|
-
const { witness } = await explore(machine, options, (snapshot) => {
|
|
2511
|
+
async function canReach(machine, target, options = {}) {
|
|
2512
|
+
const { witness } = await explore(machine, options, typeof target === "function" ? target : (snapshot) => {
|
|
2385
2513
|
try {
|
|
2386
|
-
return snapshot.matches(
|
|
2514
|
+
return snapshot.matches(target);
|
|
2387
2515
|
} catch {
|
|
2388
2516
|
return false;
|
|
2389
2517
|
}
|
|
@@ -2715,6 +2843,8 @@ async function runSeam(machine, options) {
|
|
|
2715
2843
|
let calls = 0;
|
|
2716
2844
|
let seamMatches = 0;
|
|
2717
2845
|
let seamOutput;
|
|
2846
|
+
let seamUsage;
|
|
2847
|
+
const callLog = [];
|
|
2718
2848
|
let seamReached = false;
|
|
2719
2849
|
let callsBeforeSeam = -1;
|
|
2720
2850
|
let seamStateAt = 0;
|
|
@@ -2739,6 +2869,15 @@ async function runSeam(machine, options) {
|
|
|
2739
2869
|
const route = async (request, info) => {
|
|
2740
2870
|
const callIndex = calls++;
|
|
2741
2871
|
const isSeam = request.name === seam.request && seamMatches++ === (seam.occurrence ?? 0);
|
|
2872
|
+
const ledger = (source) => {
|
|
2873
|
+
callLog.push({
|
|
2874
|
+
...request.name !== void 0 ? { name: request.name } : {},
|
|
2875
|
+
model: request.model,
|
|
2876
|
+
key: queueKeyOf(request),
|
|
2877
|
+
source,
|
|
2878
|
+
seam: isSeam
|
|
2879
|
+
});
|
|
2880
|
+
};
|
|
2742
2881
|
if (isSeam && candidate) {
|
|
2743
2882
|
await takeScriptedSlot(request, info);
|
|
2744
2883
|
seamReached = true;
|
|
@@ -2747,15 +2886,19 @@ async function runSeam(machine, options) {
|
|
|
2747
2886
|
seamEventAt = liveEvents;
|
|
2748
2887
|
const result = await candidate(request, info);
|
|
2749
2888
|
seamOutput = await seamOutputOf(result, request);
|
|
2889
|
+
seamUsage = getCallUsage(result);
|
|
2890
|
+
ledger("candidate");
|
|
2750
2891
|
return result;
|
|
2751
2892
|
}
|
|
2752
2893
|
const scripted = await scriptedAnswer(request, info);
|
|
2894
|
+
ledger("script");
|
|
2753
2895
|
if (!isSeam) return scripted;
|
|
2754
2896
|
seamReached = true;
|
|
2755
2897
|
callsBeforeSeam = callIndex;
|
|
2756
2898
|
seamStateAt = statePath.length;
|
|
2757
2899
|
seamEventAt = liveEvents;
|
|
2758
2900
|
seamOutput = scripted.output;
|
|
2901
|
+
seamUsage = scripted.usage;
|
|
2759
2902
|
return scripted;
|
|
2760
2903
|
};
|
|
2761
2904
|
const executors = {
|
|
@@ -2817,7 +2960,9 @@ async function runSeam(machine, options) {
|
|
|
2817
2960
|
return {
|
|
2818
2961
|
result,
|
|
2819
2962
|
seamOutput,
|
|
2963
|
+
...seamUsage !== void 0 ? { seamUsage } : {},
|
|
2820
2964
|
callsBeforeSeam,
|
|
2965
|
+
calls: callLog,
|
|
2821
2966
|
before: {
|
|
2822
2967
|
statePath: statePath.slice(0, splitStateAt),
|
|
2823
2968
|
events: events.slice(0, splitAt)
|
|
@@ -2852,6 +2997,8 @@ function completionActorId(event) {
|
|
|
2852
2997
|
const actorId = event.actorId;
|
|
2853
2998
|
return typeof actorId === "string" ? actorId : void 0;
|
|
2854
2999
|
}
|
|
3000
|
+
/** Thrown by the adapter's `waitForEvent` when nothing can produce an event. */
|
|
3001
|
+
const IDLE = Symbol("agent.durable.idle");
|
|
2855
3002
|
function createMailbox() {
|
|
2856
3003
|
const queue = [];
|
|
2857
3004
|
const waiters = [];
|
|
@@ -2917,6 +3064,8 @@ async function runDurableAgent(machine, options = {}) {
|
|
|
2917
3064
|
const actorId = completionActorId(event);
|
|
2918
3065
|
if (actorId !== void 0) journaledCompletions.set(actorId, (journaledCompletions.get(actorId) ?? 0) + 1);
|
|
2919
3066
|
}
|
|
3067
|
+
const storedExecutionId = hasInit ? priorEntries[0].metadata?.executionId : void 0;
|
|
3068
|
+
const executionId = typeof storedExecutionId === "string" ? storedExecutionId : hasInit ? priorEntries[0].id : crypto.randomUUID();
|
|
2920
3069
|
const mailbox = createMailbox();
|
|
2921
3070
|
const rootAddress = machineId;
|
|
2922
3071
|
const suppressedChildren = /* @__PURE__ */ new WeakSet();
|
|
@@ -2931,7 +3080,10 @@ async function runDurableAgent(machine, options = {}) {
|
|
|
2931
3080
|
}
|
|
2932
3081
|
};
|
|
2933
3082
|
let replaying = journal.length > 0;
|
|
3083
|
+
let liveEventConsumed = false;
|
|
3084
|
+
let latestSnapshot;
|
|
2934
3085
|
const execution = createDurable(bound, {
|
|
3086
|
+
executionId,
|
|
2935
3087
|
sendEvent(source, target, event) {
|
|
2936
3088
|
if (target.address === rootAddress) {
|
|
2937
3089
|
mailbox.push(event);
|
|
@@ -2961,8 +3113,14 @@ async function runDurableAgent(machine, options = {}) {
|
|
|
2961
3113
|
if (replaying) return;
|
|
2962
3114
|
action.exec?.();
|
|
2963
3115
|
},
|
|
2964
|
-
waitForEvent() {
|
|
2965
|
-
return mailbox.take();
|
|
3116
|
+
async waitForEvent() {
|
|
3117
|
+
if (mailbox.size() > 0) return await mailbox.take();
|
|
3118
|
+
if (liveInFlight.size > 0 && !(options.isIdle?.(latestSnapshot) ?? false)) return await mailbox.take();
|
|
3119
|
+
if (!liveEventConsumed && options.event !== void 0) {
|
|
3120
|
+
liveEventConsumed = true;
|
|
3121
|
+
return options.event;
|
|
3122
|
+
}
|
|
3123
|
+
throw IDLE;
|
|
2966
3124
|
}
|
|
2967
3125
|
});
|
|
2968
3126
|
const entries = [...priorEntries];
|
|
@@ -2976,17 +3134,18 @@ async function runDurableAgent(machine, options = {}) {
|
|
|
2976
3134
|
options.onEntry?.(entry);
|
|
2977
3135
|
};
|
|
2978
3136
|
if (!hasInit) {
|
|
2979
|
-
const entry = initEntry(machine, input,
|
|
3137
|
+
const entry = initEntry(machine, input, {
|
|
3138
|
+
...entryOptions,
|
|
3139
|
+
metadata: { executionId }
|
|
3140
|
+
});
|
|
2980
3141
|
entries.push(entry);
|
|
2981
3142
|
options.onEntry?.(entry);
|
|
2982
3143
|
}
|
|
2983
|
-
const sessions = /* @__PURE__ */ new Map();
|
|
2984
3144
|
let journalIndex = 0;
|
|
2985
|
-
let liveEventConsumed = false;
|
|
2986
3145
|
let [snapshot, effects] = execution.initialTransition(input);
|
|
3146
|
+
latestSnapshot = snapshot;
|
|
2987
3147
|
for (;;) {
|
|
2988
|
-
|
|
2989
|
-
for (const rootEvent of captured) mailbox.push(rootEvent.event);
|
|
3148
|
+
await execution.executeEffects(effects);
|
|
2990
3149
|
const machineSnapshot = snapshot;
|
|
2991
3150
|
if (machineSnapshot.status === "done") return {
|
|
2992
3151
|
status: "done",
|
|
@@ -2998,25 +3157,26 @@ async function runDurableAgent(machine, options = {}) {
|
|
|
2998
3157
|
let event;
|
|
2999
3158
|
let fromJournal = false;
|
|
3000
3159
|
if (journalIndex < journal.length) {
|
|
3001
|
-
event =
|
|
3160
|
+
event = journal[journalIndex];
|
|
3002
3161
|
journalIndex++;
|
|
3003
3162
|
fromJournal = true;
|
|
3004
3163
|
replaying = journalIndex < journal.length;
|
|
3005
|
-
} else
|
|
3006
|
-
|
|
3007
|
-
|
|
3008
|
-
|
|
3009
|
-
|
|
3010
|
-
|
|
3011
|
-
|
|
3012
|
-
|
|
3013
|
-
|
|
3014
|
-
}
|
|
3164
|
+
} else try {
|
|
3165
|
+
event = await execution.waitForEvent();
|
|
3166
|
+
} catch (error) {
|
|
3167
|
+
if (error === IDLE) return {
|
|
3168
|
+
status: "idle",
|
|
3169
|
+
snapshot,
|
|
3170
|
+
entries
|
|
3171
|
+
};
|
|
3172
|
+
throw error;
|
|
3173
|
+
}
|
|
3015
3174
|
const completedId = completionActorId(event);
|
|
3016
3175
|
if (completedId !== void 0) liveInFlight.delete(completedId);
|
|
3017
3176
|
if (!fromJournal) appendEntry(event);
|
|
3018
3177
|
[snapshot, effects] = execution.transition(snapshot, event);
|
|
3178
|
+
latestSnapshot = snapshot;
|
|
3019
3179
|
}
|
|
3020
3180
|
}
|
|
3021
3181
|
//#endregion
|
|
3022
|
-
export { AGENT_EVENT_SCHEMA_VERSION, AGENT_INIT_EVENT_TYPE, AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, AgentDecisionExhaustedError, AgentError, AgentEventLogConflictError, AgentIdleError, AgentIllegalResumeEventError, AgentLintError, AgentMaxModelCallsExceededError, AgentReplayDivergenceError, AgentReplayMachineMismatchError, AgentSnapshotVersionMismatchError, NonSerializableAgentEventError, appendMessages, assertAgentLogEntry, assertEventLogStoreConformance, assertJsonSerializable, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentActor, createAgentRun, createAgentSchemas, createInMemoryEventLogStore, createReplayEntry, createScriptedExecutors, createTextLogic, diffEventLogs, executeAgentRequest, explorePaths, generateResult, getAcceptedEvents, getAgentEffects, getAgentMessages, getAgentOutputMode, getAgentSchemas, getCallUsage, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getSnapshotNodes, getSnapshotRequests, getStateMeta, initEntry, inspectTransitions, isStandardSchema, lintAgentMachine, matchesTrajectory, messagesSchema, parseAgentEvent, parseModelRef, parseOutput, parseStructuredEnvelope, provideExecutors, renderDecisionAttempts, replay, resolveDecision, runAgent, runDurableAgent, runSeam, serializeTraceEvent, setupAgent, simulateAgent, systemMessage, toolMessage, traceTransitions, userMessage };
|
|
3182
|
+
export { AGENT_EVENT_SCHEMA_VERSION, AGENT_INIT_EVENT_TYPE, AGENT_TRACE_SCHEMA_VERSION, AGENT_USAGE_EVENT_TYPE, AgentDecisionExhaustedError, AgentError, AgentEventLogConflictError, AgentIdleError, AgentIllegalResumeEventError, AgentLintError, AgentMaxModelCallsExceededError, AgentReplayDivergenceError, AgentReplayMachineMismatchError, AgentSnapshotVersionMismatchError, NonSerializableAgentEventError, appendMessages, assertAgentLogEntry, assertAgentMachine, assertEventLogStoreConformance, assertJsonSerializable, assistantMessage, bindRequestExecutor, buildEnvelopeSchema, canReach, createAgentActor, createAgentRun, createAgentSchemas, createInMemoryEventLogStore, createReplayEntry, createScriptedExecutors, createTextLogic, diffEventLogs, executeAgentRequest, explorePaths, generateResult, getAcceptedEvents, getAgentEffects, getAgentMessages, getAgentOutputMode, getAgentSchemas, getCallUsage, getJsonSchema, getJsonSchemaSync, getMachineStructuralHash, getSnapshotNodes, getSnapshotRequests, getStateMeta, initEntry, inspectTransitions, isStandardSchema, lintAgentMachine, matchesTrajectory, messagesSchema, parseAgentEvent, parseModelRef, parseOutput, parseStructuredEnvelope, provideExecutors, renderDecisionAttempts, replay, resolveDecision, runAgent, runDurableAgent, runSeam, serializeTraceEvent, setupAgent, simulateAgent, systemMessage, toolMessage, traceTransitions, userMessage };
|
package/dist/machines.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_setup_agent = require("./setup-agent-
|
|
2
|
+
const require_setup_agent = require("./setup-agent-91FSuZbB.cjs");
|
|
3
3
|
//#region src/machines/internal.ts
|
|
4
4
|
/** The builtin inline text request every preset lowers a request entry to. */
|
|
5
5
|
const GENERATE_TEXT_SRC = "agent.generateText";
|
package/dist/machines.d.cts
CHANGED
package/dist/machines.d.mts
CHANGED
package/dist/machines.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as setupAgent } from "./setup-agent-
|
|
1
|
+
import { r as setupAgent } from "./setup-agent-DqqdcdNh.mjs";
|
|
2
2
|
//#region src/machines/internal.ts
|
|
3
3
|
/** The builtin inline text request every preset lowers a request entry to. */
|
|
4
4
|
const GENERATE_TEXT_SRC = "agent.generateText";
|
package/dist/otel.d.cts
CHANGED
package/dist/otel.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { T as WithAgentInputSchema, c as AgentTools, d as ChosenEvent, h as InferInput, n as AgentMessage, v as StandardSchemaV1 } from "./types-
|
|
1
|
+
import { T as WithAgentInputSchema, c as AgentTools, d as ChosenEvent, h as InferInput, n as AgentMessage, v as StandardSchemaV1 } from "./types-CvWRGFxP.mjs";
|
|
2
2
|
import { t as AgentError } from "./errors-C9rxnWbX.mjs";
|
|
3
|
-
import { H as AgentRequestSource, N as AgentDecisionRequest, V as AgentRequestOptions, d as AgentTextRequest, f as AgentUsage, l as AgentRequestExecutors, p as AgentUserInput, t as AgentCallUsage, u as AgentRequestMode, z as AgentEventDescriptor } from "./text-logic-
|
|
3
|
+
import { H as AgentRequestSource, N as AgentDecisionRequest, V as AgentRequestOptions, d as AgentTextRequest, f as AgentUsage, l as AgentRequestExecutors, p as AgentUserInput, t as AgentCallUsage, u as AgentRequestMode, z as AgentEventDescriptor } from "./text-logic-BR5twXCv.mjs";
|
|
4
4
|
import { i as AgentLogEntry, o as JsonValue } from "./event-log-store-hrA1vqtN.mjs";
|
|
5
5
|
import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, ExecutableActionObject, InputFrom, InspectionEvent, OutputFrom, Snapshot, SnapshotFrom, createActor } from "xstate";
|
|
6
6
|
|
|
@@ -934,7 +934,7 @@ declare class AgentMaxModelCallsExceededError extends AgentError {
|
|
|
934
934
|
* declared input schema — and machines reached through `.provide(...)`, which
|
|
935
935
|
* drops the brand — fall back to xstate's `InputFrom`.
|
|
936
936
|
*/
|
|
937
|
-
type AgentInputFrom<TMachine extends AnyStateMachine> = InputFrom<TMachine
|
|
937
|
+
type AgentInputFrom<TMachine extends AnyStateMachine> = [NonNullable<InputFrom<TMachine>>] extends [WithAgentInputSchema<infer TInputSchema>] ? [TInputSchema] extends [StandardSchemaV1] ? InferInput<TInputSchema> : InputFrom<TMachine> : InputFrom<TMachine>;
|
|
938
938
|
/**
|
|
939
939
|
* Runs an agent machine to completion or idle: a `createActor` host that
|
|
940
940
|
* binds `options`' host executors onto the machine's `agent.*`/`TextLogic`/
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { T as WithAgentInputSchema, c as AgentTools, d as ChosenEvent, h as InferInput, n as AgentMessage, v as StandardSchemaV1 } from "./types-
|
|
1
|
+
import { T as WithAgentInputSchema, c as AgentTools, d as ChosenEvent, h as InferInput, n as AgentMessage, v as StandardSchemaV1 } from "./types-DSdj2tGs.cjs";
|
|
2
2
|
import { t as AgentError } from "./errors-BQRk9eiZ.cjs";
|
|
3
|
-
import { H as AgentRequestSource, N as AgentDecisionRequest, V as AgentRequestOptions, d as AgentTextRequest, f as AgentUsage, l as AgentRequestExecutors, p as AgentUserInput, t as AgentCallUsage, u as AgentRequestMode, z as AgentEventDescriptor } from "./text-logic-
|
|
3
|
+
import { H as AgentRequestSource, N as AgentDecisionRequest, V as AgentRequestOptions, d as AgentTextRequest, f as AgentUsage, l as AgentRequestExecutors, p as AgentUserInput, t as AgentCallUsage, u as AgentRequestMode, z as AgentEventDescriptor } from "./text-logic-Mmbgb2jy.cjs";
|
|
4
4
|
import { i as AgentLogEntry, o as JsonValue } from "./event-log-store-Bz7HDBkE.cjs";
|
|
5
5
|
import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, ExecutableActionObject, InputFrom, InspectionEvent, OutputFrom, Snapshot, SnapshotFrom, createActor } from "xstate";
|
|
6
6
|
|
|
@@ -934,7 +934,7 @@ declare class AgentMaxModelCallsExceededError extends AgentError {
|
|
|
934
934
|
* declared input schema — and machines reached through `.provide(...)`, which
|
|
935
935
|
* drops the brand — fall back to xstate's `InputFrom`.
|
|
936
936
|
*/
|
|
937
|
-
type AgentInputFrom<TMachine extends AnyStateMachine> = InputFrom<TMachine
|
|
937
|
+
type AgentInputFrom<TMachine extends AnyStateMachine> = [NonNullable<InputFrom<TMachine>>] extends [WithAgentInputSchema<infer TInputSchema>] ? [TInputSchema] extends [StandardSchemaV1] ? InferInput<TInputSchema> : InputFrom<TMachine> : InputFrom<TMachine>;
|
|
938
938
|
/**
|
|
939
939
|
* Runs an agent machine to completion or idle: a `createActor` host that
|
|
940
940
|
* binds `options`' host executors onto the machine's `agent.*`/`TextLogic`/
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const require_errors = require("./errors-DUBBzRLP.cjs");
|
|
2
|
-
const require_decision = require("./decision-
|
|
2
|
+
const require_decision = require("./decision-BnTCsuJv.cjs");
|
|
3
3
|
const require_event_log_store = require("./event-log-store-a_TKy1gk.cjs");
|
|
4
4
|
require("./validate.cjs");
|
|
5
5
|
let xstate = require("xstate");
|
|
@@ -374,13 +374,6 @@ function toEvents(history) {
|
|
|
374
374
|
return candidate && typeof candidate === "object" && "event" in candidate && candidate.event ? candidate.event : entry;
|
|
375
375
|
});
|
|
376
376
|
}
|
|
377
|
-
/**
|
|
378
|
-
* Rewrites a journaled actor event's per-incarnation `sessionId` to the
|
|
379
|
-
* current snapshot's child for the same stable `actorId`, so replayed
|
|
380
|
-
* completions match freshly restored children.
|
|
381
|
-
*
|
|
382
|
-
* @internal
|
|
383
|
-
*/
|
|
384
377
|
function rebindActorSession(event, snapshot, sessions) {
|
|
385
378
|
const actorEvent = event;
|
|
386
379
|
if (typeof actorEvent.actorId !== "string" || typeof actorEvent.sessionId !== "string") return event;
|
|
@@ -926,7 +919,7 @@ function createRequestsFromWorkflowConfig(config, compileSchema) {
|
|
|
926
919
|
messages: resolver(request.messages),
|
|
927
920
|
tools: request.tools,
|
|
928
921
|
toolChoice: request.toolChoice,
|
|
929
|
-
|
|
922
|
+
includeReasoning: request.includeReasoning,
|
|
930
923
|
temperature: resolver(request.temperature),
|
|
931
924
|
maxOutputTokens: resolver(request.maxOutputTokens),
|
|
932
925
|
topP: resolver(request.topP),
|
|
@@ -1616,12 +1609,6 @@ Object.defineProperty(exports, "messagesSchema", {
|
|
|
1616
1609
|
return messagesSchema;
|
|
1617
1610
|
}
|
|
1618
1611
|
});
|
|
1619
|
-
Object.defineProperty(exports, "rebindActorSession", {
|
|
1620
|
-
enumerable: true,
|
|
1621
|
-
get: function() {
|
|
1622
|
-
return rebindActorSession;
|
|
1623
|
-
}
|
|
1624
|
-
});
|
|
1625
1612
|
Object.defineProperty(exports, "replay", {
|
|
1626
1613
|
enumerable: true,
|
|
1627
1614
|
get: function() {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as AgentError } from "./errors-CeSXQx0v.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { D as agentExecutionOptions, E as userInputActor, F as missingActor, G as resolveMachineVersion, L as djb2Hex, N as machineIdlePredicates, P as machineStaticTransitionTargets, Y as validateSchemaSync, _ as createTextLogic, g as builtinTextActors, j as getRegisteredAgentExecutionOptions, l as DECIDE_ACTOR, n as createDecideActor, o as getAcceptedEvents, p as USER_INPUT_ACTOR, r as isDecisionLogic, v as executeAgentTextRequest, x as isTextLogic } from "./decision-JWx6n3xR.mjs";
|
|
3
3
|
import { a as assertJsonSerializable, i as assertAgentLogEntry } from "./event-log-store-DmIDosD6.mjs";
|
|
4
4
|
import { createMachineFromConfig, initialTransition, setup, transition } from "xstate";
|
|
5
5
|
//#region src/messages.ts
|
|
@@ -373,13 +373,6 @@ function toEvents(history) {
|
|
|
373
373
|
return candidate && typeof candidate === "object" && "event" in candidate && candidate.event ? candidate.event : entry;
|
|
374
374
|
});
|
|
375
375
|
}
|
|
376
|
-
/**
|
|
377
|
-
* Rewrites a journaled actor event's per-incarnation `sessionId` to the
|
|
378
|
-
* current snapshot's child for the same stable `actorId`, so replayed
|
|
379
|
-
* completions match freshly restored children.
|
|
380
|
-
*
|
|
381
|
-
* @internal
|
|
382
|
-
*/
|
|
383
376
|
function rebindActorSession(event, snapshot, sessions) {
|
|
384
377
|
const actorEvent = event;
|
|
385
378
|
if (typeof actorEvent.actorId !== "string" || typeof actorEvent.sessionId !== "string") return event;
|
|
@@ -925,7 +918,7 @@ function createRequestsFromWorkflowConfig(config, compileSchema) {
|
|
|
925
918
|
messages: resolver(request.messages),
|
|
926
919
|
tools: request.tools,
|
|
927
920
|
toolChoice: request.toolChoice,
|
|
928
|
-
|
|
921
|
+
includeReasoning: request.includeReasoning,
|
|
929
922
|
temperature: resolver(request.temperature),
|
|
930
923
|
maxOutputTokens: resolver(request.maxOutputTokens),
|
|
931
924
|
topP: resolver(request.topP),
|
|
@@ -1525,4 +1518,4 @@ function createAgentActors(actors, requestActors) {
|
|
|
1525
1518
|
};
|
|
1526
1519
|
}
|
|
1527
1520
|
//#endregion
|
|
1528
|
-
export {
|
|
1521
|
+
export { resolveAgentStep as _, AGENT_USAGE_EVENT_TYPE as a, messagesSchema as b, createReplayEntry as c, initEntry as d, replay as f, initialAgentStep as g, getInvokeEffectMetadata as h, AGENT_INIT_EVENT_TYPE as i, diffEventLogs as l, executeAgentRequest as m, getAgentSchemas as n, AgentReplayDivergenceError as o, validateReplayEntries as p, setupAgent as r, AgentReplayMachineMismatchError as s, createAgentSchemas as t, getAgentEffects as u, transitionAgentStep as v, appendMessages as y };
|
package/dist/sqlite.d.cts
CHANGED
package/dist/sqlite.d.mts
CHANGED