@statelyai/agent 2.0.0-alpha.33 → 2.0.0-alpha.34
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 +32 -0
- package/dist/ai-sdk.cjs +114 -63
- package/dist/ai-sdk.d.cts +11 -2
- package/dist/ai-sdk.d.mts +11 -2
- package/dist/ai-sdk.mjs +115 -64
- package/dist/{decision-BPdEaxPf.cjs → decision-BEsATcr1.cjs} +18 -2
- package/dist/{decision-CV7WiV5C.mjs → decision-COkJNjOW.mjs} +18 -2
- package/dist/{event-log-CKWeC7H-.cjs → event-log-BWSSLUff.cjs} +139 -10
- package/dist/{event-log-DAqsalT1.mjs → event-log-C7jeH0y8.mjs} +123 -12
- package/dist/{event-log-store-C2NjVlWU.d.mts → event-log-store-BzXehP7R.d.cts} +28 -3
- package/dist/{event-log-store-s73r1Hxf.d.cts → event-log-store-CWjN6lmM.d.mts} +28 -3
- package/dist/{event-log-store-DKyE7JKr.cjs → event-log-store-CleWpsp5.cjs} +1 -1
- package/dist/{event-log-store-BGehvVTb.mjs → event-log-store-W49TCJXi.mjs} +1 -1
- package/dist/index.cjs +5 -5
- package/dist/index.d.cts +7 -7
- package/dist/index.d.mts +7 -7
- package/dist/index.mjs +5 -5
- 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-BilDEyqk.mjs → model-source-CK3F4YuU.mjs} +1 -1
- package/dist/{model-source-BQ97_l1-.cjs → model-source-DmhTMK39.cjs} +1 -1
- package/dist/openai.cjs +377 -95
- package/dist/openai.d.cts +55 -20
- package/dist/openai.d.mts +55 -20
- package/dist/openai.mjs +375 -96
- package/dist/otel.d.cts +1 -1
- package/dist/otel.d.mts +1 -1
- package/dist/{run-agent-B5QhabdY.d.cts → run-agent-B1-Eqviq.d.cts} +13 -5
- package/dist/{run-agent-Atu-wEk7.d.mts → run-agent-BGdx5913.d.mts} +13 -5
- package/dist/{run-agent-2UnSUhDb.mjs → run-agent-Ct_GZw_f.mjs} +124 -38
- package/dist/{run-agent-Cg0xd3K-.cjs → run-agent-s5D32w99.cjs} +123 -37
- package/dist/{setup-agent-CmhB-U5P.mjs → setup-agent-05uw4dPZ.mjs} +2 -2
- package/dist/{setup-agent-BiF1N3td.d.cts → setup-agent-BtfeFfF6.d.cts} +2 -2
- package/dist/{setup-agent-J9f_Wu5T.d.mts → setup-agent-C6nqzv_X.d.mts} +2 -2
- package/dist/{setup-agent-CwUJyqKB.cjs → setup-agent-CXEBURdo.cjs} +2 -2
- package/dist/tanstack-ai.cjs +91 -59
- package/dist/tanstack-ai.d.cts +13 -2
- package/dist/tanstack-ai.d.mts +13 -2
- package/dist/tanstack-ai.mjs +91 -59
- package/dist/testing.cjs +539 -13
- package/dist/testing.d.cts +202 -6
- package/dist/testing.d.mts +202 -6
- package/dist/testing.mjs +536 -14
- package/dist/{text-logic-CYP502VT.d.cts → text-logic-CV_4KGr6.d.cts} +28 -3
- package/dist/{text-logic-DuK9HIFM.d.mts → text-logic-Ckh-rJFV.d.mts} +28 -3
- package/dist/{usage-D7JKAxLc.d.mts → usage-BDiJKyv9.d.cts} +11 -1
- package/dist/{usage-DVw-646x.d.cts → usage-DOoVUGVq.d.mts} +11 -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-Dk3Vwnha.d.cts → verify-BQpE8hUz.d.cts} +1 -1
- package/dist/{verify-DgB8P-Wx.mjs → verify-Bpahmr34.mjs} +2 -2
- package/dist/{verify-BVz4cURF.d.mts → verify-CqeuEmIk.d.mts} +1 -1
- package/dist/{verify-CS_WLRXn.cjs → verify-DCLZa9R0.cjs} +2 -2
- package/dist/with-model-calls-BXYdBdcu.cjs +45 -0
- package/dist/with-model-calls-Bv4V4EHC.mjs +34 -0
- package/package.json +5 -5
- package/readme.md +14 -13
- package/skills/loop-to-machine/SKILL.md +40 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { _ as StandardSchemaV1, m as InferInput, s as AgentTools, w as WithAgentInputSchema } from "./types-Dp5_Ru4R.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import { n as AgentUsageEvent } from "./usage-
|
|
4
|
-
import { c as AgentLogEntry, h as JsonValue$1, n as AgentEventLogStore } from "./event-log-store-
|
|
2
|
+
import { $ as AgentError, G as AgentEventDescriptor, J as AgentRequestSource, L as DecisionAttempt, P as AgentDecisionRequest, d as AgentRequestMode, f as AgentTextRequest, m as AgentUsage, r as AgentFinishReason, t as AgentCallUsage, u as AgentRequestExecutors } from "./text-logic-Ckh-rJFV.mjs";
|
|
3
|
+
import { n as AgentUsageEvent } from "./usage-DOoVUGVq.mjs";
|
|
4
|
+
import { c as AgentLogEntry, h as JsonValue$1, n as AgentEventLogStore } from "./event-log-store-CWjN6lmM.mjs";
|
|
5
5
|
import { AnyActorLogic, AnyActorRef, AnyMachineSnapshot, AnyStateMachine, AsyncActorLogic, EmittedFrom, EventFromLogic, EventObject, InputFrom, InspectionEvent, OutputFrom, Snapshot, SnapshotFrom, StateValue } from "xstate";
|
|
6
6
|
import { DurableExecution } from "xstate/durable";
|
|
7
7
|
//#region src/steps.d.ts
|
|
@@ -334,9 +334,16 @@ interface AgentRuntimeOptions<TMachine extends AnyStateMachine> {
|
|
|
334
334
|
* invoke that would have made the call, as an
|
|
335
335
|
* {@link AgentMaxModelCallsExceededError} with `code: 'max-model-calls'` — so
|
|
336
336
|
* an `onError` can branch on it and route to a degraded state. Unhandled, it
|
|
337
|
-
* settles `{ status: 'error', cause: 'max-model-calls' }`.
|
|
337
|
+
* settles `{ status: 'error', cause: 'max-model-calls' }`. A tool loop
|
|
338
|
+
* counts one call per step, so the call after it is the one refused.
|
|
338
339
|
*/
|
|
339
340
|
maxModelCalls?: number;
|
|
341
|
+
/**
|
|
342
|
+
* Model calls already spent against `maxModelCalls` before this run, such as
|
|
343
|
+
* earlier turns of the same conversation (sum their `usage.modelCalls`).
|
|
344
|
+
* Default 0. Not added to this run's `usage.modelCalls`.
|
|
345
|
+
*/
|
|
346
|
+
modelCallsSpent?: number;
|
|
340
347
|
/** Aborts the run; settles `{ status: 'error', cause: 'aborted' }` with `signal.reason` as the error. */
|
|
341
348
|
signal?: AbortSignal;
|
|
342
349
|
/** Where root `after` timers live. Default `"in-process"`. See {@link AgentTimerScheduler}. */
|
|
@@ -488,7 +495,8 @@ type AgentEffects = Parameters<DurableExecution<AnyStateMachine>["executeEffects
|
|
|
488
495
|
* durable timers (a Temporal timer, a Durable Object alarm, an Inngest sleep)
|
|
489
496
|
* passes `schedule`/`cancel`: the loop then treats a pending timer as the
|
|
490
497
|
* outside world's business, and the host delivers `{ type: "xstate.timer", id }`
|
|
491
|
-
* through {@link AgentRuntime.transition} when it fires.
|
|
498
|
+
* through {@link AgentRuntime.transition} when it fires. Only root timers go
|
|
499
|
+
* to the host: an invoked child machine's timers are always in-process.
|
|
492
500
|
*/
|
|
493
501
|
type AgentTimerScheduler = "in-process" | {
|
|
494
502
|
schedule(timer: {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { d as getAcceptedEvents, f as getHumanEventTypes, l as resolveDecision, n as acceptedDecisionOptions, s as isDecisionLogic, t as AgentDecisionExhaustedError } from "./decision-
|
|
3
|
-
import { t as AgentEventLogConflictError } from "./event-log-store-
|
|
4
|
-
import { createAsyncLogic, getNextTransitions, isMachineSnapshot, stopActor } from "xstate";
|
|
1
|
+
import { C as validateReplayEntries, F as getCallUsage, G as getRegisteredAgentExecutionOptions, H as responseMessagesOf, I as isTextLogic, K as isUnboundPlaceholder, L as normalizeGeneratorResult, N as getCallFinishReason, P as getCallModelCalls, S as replay, U as executorBoundLogics, X as findNonSerializableContextPaths, _ as getSnapshotStateHash, c as agentCallSite, ct as validateSchemaSync, d as canonicalEventJson, f as createReplayEntry, g as getLogExecutionId, i as AgentMachineVersionMismatchError, it as resolveMachineVersion, lt as canonicalJson, p as foldLog, pt as AgentError, rt as isStandardSchema, s as agentCallOccurrence, u as assertJsonSerializable, v as getUsageFromEvents, w as AGENT_USAGE_EVENT_TYPE, y as initEntry } from "./event-log-C7jeH0y8.mjs";
|
|
2
|
+
import { d as getAcceptedEvents, f as getHumanEventTypes, l as resolveDecision, n as acceptedDecisionOptions, s as isDecisionLogic, t as AgentDecisionExhaustedError } from "./decision-COkJNjOW.mjs";
|
|
3
|
+
import { t as AgentEventLogConflictError } from "./event-log-store-W49TCJXi.mjs";
|
|
4
|
+
import { createAsyncLogic, deliverEvent, getNextTransitions, isMachineSnapshot, stopActor } from "xstate";
|
|
5
5
|
import { createDurable } from "xstate/durable";
|
|
6
6
|
//#region src/run-agent.ts
|
|
7
7
|
/**
|
|
@@ -339,6 +339,22 @@ function selfIdAndSrc(self) {
|
|
|
339
339
|
};
|
|
340
340
|
}
|
|
341
341
|
/**
|
|
342
|
+
* The invoke ids from the root down to `actor` (`[]` for the root itself, or
|
|
343
|
+
* an actor outside the run's tree).
|
|
344
|
+
*/
|
|
345
|
+
function actorPathOf(actor) {
|
|
346
|
+
const path = [];
|
|
347
|
+
for (let at = actor; at?._parent !== void 0; at = at._parent) {
|
|
348
|
+
if (typeof at.id !== "string") return [];
|
|
349
|
+
path.unshift(at.id);
|
|
350
|
+
}
|
|
351
|
+
return path;
|
|
352
|
+
}
|
|
353
|
+
/** True for a request inside an invoked child machine rather than the root. */
|
|
354
|
+
function isChildRequest(self) {
|
|
355
|
+
return (self?._parent)?._parent !== void 0;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
342
358
|
* The machine actor that INVOKED a decision request — the actor whose
|
|
343
359
|
* live snapshot supplies the candidate events and drives `canTake`/`send`.
|
|
344
360
|
* For a top-level request this is the root actor (identity-equal to
|
|
@@ -349,7 +365,7 @@ function selfIdAndSrc(self) {
|
|
|
349
365
|
*/
|
|
350
366
|
function invokingActorOf(self, runCtx) {
|
|
351
367
|
const parent = self?._parent;
|
|
352
|
-
if (parent !== void 0 &&
|
|
368
|
+
if (parent !== void 0 && isChildRequest(self)) return parent;
|
|
353
369
|
return runCtx.actorHolder.actorRef ?? parent;
|
|
354
370
|
}
|
|
355
371
|
/**
|
|
@@ -406,6 +422,7 @@ function bindTextLogic(logic, runCtx) {
|
|
|
406
422
|
const output = await normalizeGeneratorResult(raw, id);
|
|
407
423
|
const rawReasoning = raw?.reasoning;
|
|
408
424
|
const reasoning = typeof rawReasoning === "string" ? rawReasoning : void 0;
|
|
425
|
+
runCtx.countModelCalls?.(getCallModelCalls(raw) - 1);
|
|
409
426
|
const usage = getCallUsage(raw);
|
|
410
427
|
const finishReason = getCallFinishReason(raw);
|
|
411
428
|
if (usage) runCtx.recordUsage?.(usage, {
|
|
@@ -429,6 +446,7 @@ function bindTextLogic(logic, runCtx) {
|
|
|
429
446
|
messages: responseMessagesOf(raw)
|
|
430
447
|
};
|
|
431
448
|
} catch (error) {
|
|
449
|
+
runCtx.countModelCalls?.(getCallModelCalls(error) - 1);
|
|
432
450
|
runCtx.emitTrace?.({
|
|
433
451
|
type: "request.error",
|
|
434
452
|
request: agentRequest,
|
|
@@ -438,7 +456,7 @@ function bindTextLogic(logic, runCtx) {
|
|
|
438
456
|
}
|
|
439
457
|
});
|
|
440
458
|
}
|
|
441
|
-
function createCountingDecide(runCtx, self) {
|
|
459
|
+
function createCountingDecide(runCtx, self, recordLater) {
|
|
442
460
|
return async (attemptRequest, info) => {
|
|
443
461
|
runCtx.consumeModelCall();
|
|
444
462
|
runCtx.emitTrace?.({
|
|
@@ -463,12 +481,12 @@ function createCountingDecide(runCtx, self) {
|
|
|
463
481
|
const finishReason = getCallFinishReason(result);
|
|
464
482
|
if (usage) {
|
|
465
483
|
const { src } = selfIdAndSrc(self);
|
|
466
|
-
runCtx.recordUsage?.(usage, {
|
|
484
|
+
recordLater(() => runCtx.recordUsage?.(usage, {
|
|
467
485
|
kind: "decision",
|
|
468
486
|
...attemptRequest.id ? { id: attemptRequest.id } : {},
|
|
469
487
|
...src !== "" ? { src } : {},
|
|
470
488
|
model: attemptRequest.model
|
|
471
|
-
}, self);
|
|
489
|
+
}, self));
|
|
472
490
|
}
|
|
473
491
|
runCtx.emitTrace?.({
|
|
474
492
|
type: "request.end",
|
|
@@ -562,18 +580,25 @@ function bindDecisionLogic(logic, runCtx) {
|
|
|
562
580
|
}, self);
|
|
563
581
|
throw error;
|
|
564
582
|
}
|
|
565
|
-
const
|
|
583
|
+
const usageRecords = [];
|
|
584
|
+
const decide = createCountingDecide(runCtx, self, (record) => usageRecords.push(record));
|
|
566
585
|
let priorAttempts = [];
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
586
|
+
let chosen;
|
|
587
|
+
try {
|
|
588
|
+
chosen = await resolveDecision(request, { decide: (attemptRequest, info) => {
|
|
589
|
+
priorAttempts = attemptRequest.attempts;
|
|
590
|
+
return decide(attemptRequest, info);
|
|
591
|
+
} }, {
|
|
592
|
+
maxRetries: lowered.maxRetries ?? logic.maxRetries,
|
|
593
|
+
signal,
|
|
594
|
+
canTake: agentCan
|
|
595
|
+
});
|
|
596
|
+
const callKey = id !== "" ? runCtx.callKey?.(id, self) : void 0;
|
|
597
|
+
runCtx.noteDecision?.(chosen, priorAttempts, callKey === void 0 ? void 0 : callKey.slice(callKey.indexOf(":") + 1));
|
|
598
|
+
actorRef?.send(chosen);
|
|
599
|
+
} finally {
|
|
600
|
+
for (const record of usageRecords) record();
|
|
601
|
+
}
|
|
577
602
|
await Promise.resolve();
|
|
578
603
|
return chosen;
|
|
579
604
|
} });
|
|
@@ -798,7 +823,20 @@ function rebindChildMachine(childMachine, runCtx, visited, ctxFor) {
|
|
|
798
823
|
continue;
|
|
799
824
|
}
|
|
800
825
|
}
|
|
801
|
-
|
|
826
|
+
const rebound = Object.keys(wrapped).length > 0 ? childMachine.provide({ actors: wrapped }) : childMachine;
|
|
827
|
+
return runCtx.onChildEvent ? journaledMachine(rebound, runCtx.onChildEvent) : rebound;
|
|
828
|
+
}
|
|
829
|
+
/**
|
|
830
|
+
* `machine`, reporting each event an actor of it starts processing. An actor
|
|
831
|
+
* calls its logic's `transition` once per event it processes (raised events
|
|
832
|
+
* stay inside that step), and before anything moves, so a parent that
|
|
833
|
+
* receives a child's completion mid-step is reported after the child.
|
|
834
|
+
*/
|
|
835
|
+
function journaledMachine(machine, onEvent) {
|
|
836
|
+
return Object.create(machine, { transition: { value: (...args) => {
|
|
837
|
+
onEvent(args[2].self, args[1]);
|
|
838
|
+
return machine.transition(...args);
|
|
839
|
+
} } });
|
|
802
840
|
}
|
|
803
841
|
const timerId = (timer) => JSON.stringify(timer);
|
|
804
842
|
function toTimerInput(event) {
|
|
@@ -856,21 +894,20 @@ async function runAgent(machine, options = {}) {
|
|
|
856
894
|
const { onIdle, ...rest } = options;
|
|
857
895
|
let result = await runToQuiescence(createAgentRuntime(machine, rest), rest);
|
|
858
896
|
if (!onIdle) return result;
|
|
859
|
-
|
|
860
|
-
let modelCalls = result.usage.modelCalls;
|
|
897
|
+
let modelCallsSpent = (rest.modelCallsSpent ?? 0) + result.usage.modelCalls;
|
|
861
898
|
const { input: _input, events: _events, attempts: _attempts, ...resumeOptions } = rest;
|
|
862
899
|
while (result.status === "idle" && result.ignored === void 0) {
|
|
863
900
|
const event = await onIdle(result.snapshot);
|
|
864
901
|
result = await runToQuiescence(createAgentRuntime(machine, {
|
|
865
902
|
...resumeOptions,
|
|
866
|
-
|
|
903
|
+
modelCallsSpent
|
|
867
904
|
}), {
|
|
868
905
|
...resumeOptions,
|
|
869
906
|
...rest.store === void 0 ? { events: result.events } : {},
|
|
870
907
|
snapshot: result.persist(),
|
|
871
908
|
event
|
|
872
909
|
});
|
|
873
|
-
|
|
910
|
+
modelCallsSpent += result.usage.modelCalls;
|
|
874
911
|
}
|
|
875
912
|
return result;
|
|
876
913
|
}
|
|
@@ -886,7 +923,7 @@ function assertThreadMatchesEvents(threadId, stored, events) {
|
|
|
886
923
|
const givenEntry = events[index];
|
|
887
924
|
const storedHash = storedEntry.verification?.stateHash;
|
|
888
925
|
const givenHash = givenEntry.verification?.stateHash;
|
|
889
|
-
if (!(storedEntry.id === givenEntry.id && storedEntry.index === givenEntry.index && canonicalEventJson(storedEntry.event) === canonicalEventJson(givenEntry.event) && (storedHash === void 0 || givenHash === void 0 || storedHash === givenHash) && (index > 0 || getLogExecutionId([storedEntry]) === getLogExecutionId([givenEntry])))) throw new AgentError("event-log-conflict", `createAgentRuntime: the given \`events\` diverge from thread "${threadId}" at index ${index} (stored entry '${storedEntry.id}', given '${givenEntry.id}') — the log passed in is not this thread's log.`);
|
|
926
|
+
if (!(storedEntry.id === givenEntry.id && storedEntry.index === givenEntry.index && canonicalEventJson(storedEntry.event) === canonicalEventJson(givenEntry.event) && storedEntry.decidedBy === givenEntry.decidedBy && storedEntry.actorPath?.join("\0") === givenEntry.actorPath?.join("\0") && (storedHash === void 0 || givenHash === void 0 || storedHash === givenHash) && (index > 0 || getLogExecutionId([storedEntry]) === getLogExecutionId([givenEntry])))) throw new AgentError("event-log-conflict", `createAgentRuntime: the given \`events\` diverge from thread "${threadId}" at index ${index} (stored entry '${storedEntry.id}', given '${givenEntry.id}') — the log passed in is not this thread's log.`);
|
|
890
927
|
}
|
|
891
928
|
}
|
|
892
929
|
const QUIESCENT = Symbol("quiescent");
|
|
@@ -927,6 +964,7 @@ const QUIESCENT = Symbol("quiescent");
|
|
|
927
964
|
*/
|
|
928
965
|
function createAgentRuntime(machine, options = {}) {
|
|
929
966
|
const maxModelCalls = options.maxModelCalls ?? 100;
|
|
967
|
+
const modelCallsSpent = options.modelCallsSpent ?? 0;
|
|
930
968
|
let modelCallCount = 0;
|
|
931
969
|
let budgetExceeded = false;
|
|
932
970
|
let warnedNonSerializable = false;
|
|
@@ -954,12 +992,15 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
954
992
|
});
|
|
955
993
|
const consumeModelCall = () => {
|
|
956
994
|
if (budgetExceeded) throw new AgentMaxModelCallsExceededError(maxModelCalls);
|
|
957
|
-
if (modelCallCount + 1 > maxModelCalls) {
|
|
995
|
+
if (modelCallsSpent + modelCallCount + 1 > maxModelCalls) {
|
|
958
996
|
budgetExceeded = true;
|
|
959
997
|
throw new AgentMaxModelCallsExceededError(maxModelCalls);
|
|
960
998
|
}
|
|
961
999
|
modelCallCount += 1;
|
|
962
1000
|
};
|
|
1001
|
+
const countModelCalls = (extra) => {
|
|
1002
|
+
modelCallCount += extra;
|
|
1003
|
+
};
|
|
963
1004
|
const logEntries = [];
|
|
964
1005
|
const store = options.store;
|
|
965
1006
|
const threadId = options.threadId;
|
|
@@ -1015,6 +1056,8 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1015
1056
|
let logMachine = machine;
|
|
1016
1057
|
let loggingEnabled = true;
|
|
1017
1058
|
const attemptsByEvent = /* @__PURE__ */ new WeakMap();
|
|
1059
|
+
const decidedByEvent = /* @__PURE__ */ new WeakMap();
|
|
1060
|
+
const openDecisions = /* @__PURE__ */ new Map();
|
|
1018
1061
|
let logFold;
|
|
1019
1062
|
const stopLogging = (error) => {
|
|
1020
1063
|
if (!loggingEnabled) return;
|
|
@@ -1029,25 +1072,39 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1029
1072
|
}
|
|
1030
1073
|
console.warn(`@statelyai/agent: this run's log stopped at entry ${logEntries.length}, so result.events is incomplete: ${error instanceof Error ? error.message : String(error)}. Pass input and events that JSON can hold.`);
|
|
1031
1074
|
};
|
|
1032
|
-
const
|
|
1075
|
+
const takeDecidedBy = (event, actorPath = []) => {
|
|
1076
|
+
const chosen = decidedByEvent.get(event);
|
|
1077
|
+
if (chosen !== void 0) return chosen;
|
|
1078
|
+
const { actorId } = event;
|
|
1079
|
+
if ((event.type === "xstate.done.actor" || event.type === "xstate.error.actor") && typeof actorId === "string") {
|
|
1080
|
+
const site = agentCallSite(actorPath, actorId);
|
|
1081
|
+
const settled = openDecisions.get(site);
|
|
1082
|
+
openDecisions.delete(site);
|
|
1083
|
+
return settled;
|
|
1084
|
+
}
|
|
1085
|
+
};
|
|
1086
|
+
const appendLogEntry = (event, attempts, decidedBy, actorPath) => {
|
|
1033
1087
|
if (!loggingEnabled) return;
|
|
1034
1088
|
let entry;
|
|
1035
1089
|
try {
|
|
1036
1090
|
entry = createReplayEntry(logMachine, logEntries, event, {
|
|
1037
1091
|
machineVersion,
|
|
1038
1092
|
verification: false,
|
|
1039
|
-
...attempts !== void 0 ? { attempts } : {}
|
|
1093
|
+
...attempts !== void 0 ? { attempts } : {},
|
|
1094
|
+
...decidedBy !== void 0 ? { decidedBy } : {},
|
|
1095
|
+
...actorPath !== void 0 ? { actorPath } : {}
|
|
1040
1096
|
});
|
|
1041
1097
|
} catch (error) {
|
|
1042
1098
|
stopLogging(error);
|
|
1043
1099
|
return;
|
|
1044
1100
|
}
|
|
1045
|
-
if (
|
|
1101
|
+
if (logFold !== null) try {
|
|
1046
1102
|
logFold ??= foldLog(logMachine, logEntries, {
|
|
1047
1103
|
machineVersion,
|
|
1048
1104
|
verify: false
|
|
1049
1105
|
});
|
|
1050
|
-
|
|
1106
|
+
const folded = logFold.apply(entry);
|
|
1107
|
+
if (verificationEnabled) entry.verification = { stateHash: getSnapshotStateHash(folded) };
|
|
1051
1108
|
} catch {
|
|
1052
1109
|
logFold = null;
|
|
1053
1110
|
}
|
|
@@ -1060,7 +1117,11 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1060
1117
|
const event = {
|
|
1061
1118
|
type: AGENT_USAGE_EVENT_TYPE,
|
|
1062
1119
|
...source,
|
|
1063
|
-
usage
|
|
1120
|
+
usage,
|
|
1121
|
+
budget: {
|
|
1122
|
+
modelCalls: modelCallsSpent + modelCallCount,
|
|
1123
|
+
maxModelCalls
|
|
1124
|
+
}
|
|
1064
1125
|
};
|
|
1065
1126
|
let delivered = false;
|
|
1066
1127
|
deliverUsageEvent(event, () => rootFacade(() => delivered = true), (dropped) => {
|
|
@@ -1109,12 +1170,24 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1109
1170
|
decide: executors.decide,
|
|
1110
1171
|
emitTrace: onTrace,
|
|
1111
1172
|
consumeModelCall,
|
|
1173
|
+
countModelCalls,
|
|
1112
1174
|
recordUsage,
|
|
1113
1175
|
actorHolder,
|
|
1114
1176
|
awaitJournal,
|
|
1115
1177
|
runId,
|
|
1116
1178
|
schemas: getRegisteredAgentExecutionOptions(machine).schemas,
|
|
1117
|
-
|
|
1179
|
+
onChildEvent: (self, event) => {
|
|
1180
|
+
if (finished || event.type === "xstate.stop") return;
|
|
1181
|
+
const actorPath = actorPathOf(self);
|
|
1182
|
+
if (actorPath.length === 0) return;
|
|
1183
|
+
appendLogEntry(event, attemptsByEvent.get(event), takeDecidedBy(event, actorPath), actorPath);
|
|
1184
|
+
},
|
|
1185
|
+
noteDecision: (event, attempts, decidedBy) => {
|
|
1186
|
+
if (decidedBy !== void 0) {
|
|
1187
|
+
decidedByEvent.set(event, decidedBy);
|
|
1188
|
+
openDecisions.set(decidedBy.slice(0, decidedBy.lastIndexOf("#")), decidedBy);
|
|
1189
|
+
}
|
|
1190
|
+
if (attempts.length === 0) return;
|
|
1118
1191
|
try {
|
|
1119
1192
|
assertJsonSerializable(attempts, "attempts");
|
|
1120
1193
|
} catch {
|
|
@@ -1177,7 +1250,7 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1177
1250
|
...timer
|
|
1178
1251
|
};
|
|
1179
1252
|
if (isRoot) enqueue(timerEvent);
|
|
1180
|
-
else source
|
|
1253
|
+
else if (source) deliverEvent(source, source, timerEvent);
|
|
1181
1254
|
recheck();
|
|
1182
1255
|
}, delay));
|
|
1183
1256
|
};
|
|
@@ -1186,7 +1259,7 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1186
1259
|
if (childSnapshot?.status !== "active") return false;
|
|
1187
1260
|
return isMachineSnapshot(childSnapshot) ? childrenBusy(childSnapshot) : true;
|
|
1188
1261
|
});
|
|
1189
|
-
const workInFlight = () => childrenBusy(current) ||
|
|
1262
|
+
const workInFlight = () => childrenBusy(current) || timerHandles.size > 0;
|
|
1190
1263
|
let recheckScheduled = false;
|
|
1191
1264
|
const recheck = () => {
|
|
1192
1265
|
if (wake === void 0 || recheckScheduled) return;
|
|
@@ -1451,9 +1524,21 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1451
1524
|
if (logExecutionId === void 0) return;
|
|
1452
1525
|
const memoized = self === void 0 ? void 0 : mintedCallKeys.get(self);
|
|
1453
1526
|
if (memoized !== void 0) return memoized;
|
|
1454
|
-
const
|
|
1455
|
-
|
|
1456
|
-
const
|
|
1527
|
+
const actorPath = actorPathOf(self?._parent);
|
|
1528
|
+
const site = agentCallSite(actorPath, siteId);
|
|
1529
|
+
const startedHere = siteCallCounts.get(site) ?? 0;
|
|
1530
|
+
siteCallCounts.set(site, startedHere + 1);
|
|
1531
|
+
openDecisions.delete(site);
|
|
1532
|
+
if (logFold === void 0 && loggingEnabled && logEntries.length > 0) try {
|
|
1533
|
+
logFold = foldLog(logMachine, logEntries, {
|
|
1534
|
+
machineVersion,
|
|
1535
|
+
verify: false
|
|
1536
|
+
});
|
|
1537
|
+
} catch {
|
|
1538
|
+
logFold = null;
|
|
1539
|
+
}
|
|
1540
|
+
const n = logFold && loggingEnabled ? logFold.starts(site) : agentCallOccurrence(resumedHistory, siteId, actorPath) + startedHere;
|
|
1541
|
+
const key = `${logExecutionId}:${site}#${n}`;
|
|
1457
1542
|
if (self !== void 0) mintedCallKeys.set(self, key);
|
|
1458
1543
|
return key;
|
|
1459
1544
|
};
|
|
@@ -1512,7 +1597,7 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1512
1597
|
const [next, effects] = execution.transition(state, event);
|
|
1513
1598
|
const ignored = !fromMailbox.has(event) && next === state && effects.length === 0;
|
|
1514
1599
|
if (ignored) ignoredEvent = event;
|
|
1515
|
-
appendLogEntry(event, attempts);
|
|
1600
|
+
appendLogEntry(event, attempts, takeDecidedBy(event));
|
|
1516
1601
|
if (stopReason !== void 0) return [state, []];
|
|
1517
1602
|
commit(next, event, ignored);
|
|
1518
1603
|
return [next, effects];
|
|
@@ -1540,6 +1625,7 @@ function createAgentRuntime(machine, options = {}) {
|
|
|
1540
1625
|
},
|
|
1541
1626
|
async finish() {
|
|
1542
1627
|
if (finished) throw new AgentError("runtime-finished", "createAgentRuntime: `finish` was already called.");
|
|
1628
|
+
for (const event of mailbox) if (event.type === "@agent.usage") appendLogEntry(event);
|
|
1543
1629
|
const snapshot = current;
|
|
1544
1630
|
let outcome;
|
|
1545
1631
|
if (stopReason !== void 0) outcome = {
|