@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,6 +1,6 @@
|
|
|
1
|
-
const require_event_log = require("./event-log-
|
|
2
|
-
const require_decision = require("./decision-
|
|
3
|
-
const require_event_log_store = require("./event-log-store-
|
|
1
|
+
const require_event_log = require("./event-log-BWSSLUff.cjs");
|
|
2
|
+
const require_decision = require("./decision-BEsATcr1.cjs");
|
|
3
|
+
const require_event_log_store = require("./event-log-store-CleWpsp5.cjs");
|
|
4
4
|
let xstate = require("xstate");
|
|
5
5
|
let xstate_durable = require("xstate/durable");
|
|
6
6
|
//#region src/run-agent.ts
|
|
@@ -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 require_event_log.normalizeGeneratorResult(raw, id);
|
|
407
423
|
const rawReasoning = raw?.reasoning;
|
|
408
424
|
const reasoning = typeof rawReasoning === "string" ? rawReasoning : void 0;
|
|
425
|
+
runCtx.countModelCalls?.(require_event_log.getCallModelCalls(raw) - 1);
|
|
409
426
|
const usage = require_event_log.getCallUsage(raw);
|
|
410
427
|
const finishReason = require_event_log.getCallFinishReason(raw);
|
|
411
428
|
if (usage) runCtx.recordUsage?.(usage, {
|
|
@@ -429,6 +446,7 @@ function bindTextLogic(logic, runCtx) {
|
|
|
429
446
|
messages: require_event_log.responseMessagesOf(raw)
|
|
430
447
|
};
|
|
431
448
|
} catch (error) {
|
|
449
|
+
runCtx.countModelCalls?.(require_event_log.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 = require_event_log.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 require_decision.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 && require_event_log.canonicalEventJson(storedEntry.event) === require_event_log.canonicalEventJson(givenEntry.event) && (storedHash === void 0 || givenHash === void 0 || storedHash === givenHash) && (index > 0 || require_event_log.getLogExecutionId([storedEntry]) === require_event_log.getLogExecutionId([givenEntry])))) throw new require_event_log.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 && require_event_log.canonicalEventJson(storedEntry.event) === require_event_log.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 || require_event_log.getLogExecutionId([storedEntry]) === require_event_log.getLogExecutionId([givenEntry])))) throw new require_event_log.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 = require_event_log.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 = require_event_log.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 ??= require_event_log.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: require_event_log.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: require_event_log.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: require_event_log.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
|
require_event_log.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) (0, xstate.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 (0, xstate.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 = require_event_log.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 = require_event_log.foldLog(logMachine, logEntries, {
|
|
1534
|
+
machineVersion,
|
|
1535
|
+
verify: false
|
|
1536
|
+
});
|
|
1537
|
+
} catch {
|
|
1538
|
+
logFold = null;
|
|
1539
|
+
}
|
|
1540
|
+
const n = logFold && loggingEnabled ? logFold.starts(site) : require_event_log.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 require_event_log.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 = {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
import { r as createDecideActor } from "./decision-
|
|
1
|
+
import { A as builtinTextActors, E as DECIDE_ACTOR, J as setAgentExecutionOptions, W as getAgentExecutionOptions, ct as validateSchemaSync, dt as isPlainObject, j as createTextLogic, pt as AgentError, q as missingActor, w as AGENT_USAGE_EVENT_TYPE } from "./event-log-C7jeH0y8.mjs";
|
|
2
|
+
import { r as createDecideActor } from "./decision-COkJNjOW.mjs";
|
|
3
3
|
import { machineFromJSON, setup } from "xstate";
|
|
4
4
|
//#region src/workflow-config.ts
|
|
5
5
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { _ as StandardSchemaV1, d as EventUnion, g as NormalizedEventSchemas, h as InferOutput, i as AgentToolChoice, m as InferInput, s as AgentTools, t as AgentEventSchemaInputMap, w as WithAgentInputSchema } from "./types-Dp5_Ru4R.cjs";
|
|
2
|
-
import {
|
|
3
|
-
import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-
|
|
2
|
+
import { X as EventFromSnapshot, Y as AgentSchemas, _ as TextLogic, a as AgentModelRef, d as AgentRequestMode, h as BuiltinAgentActors, i as AgentModelMap, v as TextLogicConfig } from "./text-logic-CV_4KGr6.cjs";
|
|
3
|
+
import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-BDiJKyv9.cjs";
|
|
4
4
|
import { AnyActorLogic, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, EventObject, MachineContext, MetaObject, NonReducibleUnknown, SetupReturnFromConfig, SetupStateSchema } from "xstate";
|
|
5
5
|
//#region src/interaction.d.ts
|
|
6
6
|
interface AgentInteractionEvent<TType extends string = string> {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { _ as StandardSchemaV1, d as EventUnion, g as NormalizedEventSchemas, h as InferOutput, i as AgentToolChoice, m as InferInput, s as AgentTools, t as AgentEventSchemaInputMap, w as WithAgentInputSchema } from "./types-Dp5_Ru4R.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-
|
|
2
|
+
import { X as EventFromSnapshot, Y as AgentSchemas, _ as TextLogic, a as AgentModelRef, d as AgentRequestMode, h as BuiltinAgentActors, i as AgentModelMap, v as TextLogicConfig } from "./text-logic-Ckh-rJFV.mjs";
|
|
3
|
+
import { n as AgentUsageEvent, t as AGENT_USAGE_EVENT_TYPE } from "./usage-DOoVUGVq.mjs";
|
|
4
4
|
import { AnyActorLogic, AnyMachineSnapshot, AnySetupConfig, AnyStateMachine, AsyncActorLogic, EventObject, MachineContext, MetaObject, NonReducibleUnknown, SetupReturnFromConfig, SetupStateSchema } from "xstate";
|
|
5
5
|
//#region src/interaction.d.ts
|
|
6
6
|
interface AgentInteractionEvent<TType extends string = string> {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const require_event_log = require("./event-log-
|
|
2
|
-
const require_decision = require("./decision-
|
|
1
|
+
const require_event_log = require("./event-log-BWSSLUff.cjs");
|
|
2
|
+
const require_decision = require("./decision-BEsATcr1.cjs");
|
|
3
3
|
let xstate = require("xstate");
|
|
4
4
|
//#region src/workflow-config.ts
|
|
5
5
|
/**
|
package/dist/tanstack-ai.cjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
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_model_source = require("./model-source-
|
|
2
|
+
const require_event_log = require("./event-log-BWSSLUff.cjs");
|
|
3
|
+
const require_decision = require("./decision-BEsATcr1.cjs");
|
|
4
|
+
const require_model_source = require("./model-source-DmhTMK39.cjs");
|
|
5
|
+
const require_with_model_calls = require("./with-model-calls-BXYdBdcu.cjs");
|
|
5
6
|
let _tanstack_ai = require("@tanstack/ai");
|
|
6
7
|
//#region src/tanstack-ai/index.ts
|
|
7
8
|
/**
|
|
@@ -324,6 +325,7 @@ async function readRun(stream, onDelta) {
|
|
|
324
325
|
structured: void 0,
|
|
325
326
|
usage: void 0,
|
|
326
327
|
finishReason: "other",
|
|
328
|
+
modelCalls: 0,
|
|
327
329
|
toolCalls: [],
|
|
328
330
|
messages: [],
|
|
329
331
|
chunks: []
|
|
@@ -349,66 +351,78 @@ async function readRun(stream, onDelta) {
|
|
|
349
351
|
flushResults();
|
|
350
352
|
return assistant ??= [];
|
|
351
353
|
};
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
354
|
+
try {
|
|
355
|
+
for await (const chunk of stream) {
|
|
356
|
+
summary.chunks.push(chunk);
|
|
357
|
+
switch (chunk.type) {
|
|
358
|
+
case "TEXT_MESSAGE_CONTENT": {
|
|
359
|
+
summary.text += chunk.delta;
|
|
360
|
+
onDelta?.(chunk.delta);
|
|
361
|
+
const parts = assistantParts();
|
|
362
|
+
const last = parts.at(-1);
|
|
363
|
+
if (last?.type === "text") last.text += chunk.delta;
|
|
364
|
+
else parts.push({
|
|
365
|
+
type: "text",
|
|
366
|
+
text: chunk.delta
|
|
367
|
+
});
|
|
368
|
+
break;
|
|
369
|
+
}
|
|
370
|
+
case "TOOL_CALL_START": {
|
|
371
|
+
const part = {
|
|
372
|
+
type: "tool-call",
|
|
373
|
+
toolCallId: chunk.toolCallId,
|
|
374
|
+
toolName: chunk.toolCallName,
|
|
375
|
+
input: {}
|
|
376
|
+
};
|
|
377
|
+
assistantParts().push(part);
|
|
378
|
+
args.set(chunk.toolCallId, {
|
|
379
|
+
part,
|
|
380
|
+
json: ""
|
|
381
|
+
});
|
|
382
|
+
break;
|
|
383
|
+
}
|
|
384
|
+
case "TOOL_CALL_ARGS": {
|
|
385
|
+
const call = args.get(chunk.toolCallId);
|
|
386
|
+
if (call) call.json += chunk.delta;
|
|
387
|
+
break;
|
|
388
|
+
}
|
|
389
|
+
case "TOOL_CALL_RESULT":
|
|
390
|
+
flushAssistant();
|
|
391
|
+
(results ??= []).push({
|
|
392
|
+
type: "tool-result",
|
|
393
|
+
toolCallId: chunk.toolCallId,
|
|
394
|
+
toolName: args.get(chunk.toolCallId)?.part.toolName ?? "",
|
|
395
|
+
output: toToolResultOutput(chunk.content)
|
|
396
|
+
});
|
|
397
|
+
break;
|
|
398
|
+
case "CUSTOM":
|
|
399
|
+
if (chunk.name === "structured-output.complete") summary.structured = chunk.value?.object;
|
|
400
|
+
break;
|
|
401
|
+
case "RUN_FINISHED":
|
|
402
|
+
summary.finishReason = toAgentFinishReason(chunk.finishReason ?? (chunk.metadata?.tanstack)?.finishReason);
|
|
403
|
+
summary.modelCalls++;
|
|
404
|
+
if (chunk.usage && !Array.isArray(chunk.usage)) summary.usage = addUsage(summary.usage, toAgentCallUsage(chunk.usage));
|
|
405
|
+
break;
|
|
406
|
+
case "RUN_ERROR": throw new TanStackAiRunError(chunk.message, chunk.code ?? chunk.error?.code);
|
|
385
407
|
}
|
|
386
|
-
case "TOOL_CALL_RESULT":
|
|
387
|
-
flushAssistant();
|
|
388
|
-
(results ??= []).push({
|
|
389
|
-
type: "tool-result",
|
|
390
|
-
toolCallId: chunk.toolCallId,
|
|
391
|
-
toolName: args.get(chunk.toolCallId)?.part.toolName ?? "",
|
|
392
|
-
output: toToolResultOutput(chunk.content)
|
|
393
|
-
});
|
|
394
|
-
break;
|
|
395
|
-
case "CUSTOM":
|
|
396
|
-
if (chunk.name === "structured-output.complete") summary.structured = chunk.value?.object;
|
|
397
|
-
break;
|
|
398
|
-
case "RUN_FINISHED":
|
|
399
|
-
summary.finishReason = toAgentFinishReason(chunk.finishReason ?? (chunk.metadata?.tanstack)?.finishReason);
|
|
400
|
-
if (chunk.usage && !Array.isArray(chunk.usage)) summary.usage = addUsage(summary.usage, toAgentCallUsage(chunk.usage));
|
|
401
|
-
break;
|
|
402
|
-
case "RUN_ERROR": throw new TanStackAiRunError(chunk.message, chunk.code ?? chunk.error?.code);
|
|
403
408
|
}
|
|
409
|
+
} catch (error) {
|
|
410
|
+
throw require_with_model_calls.withModelCalls(error, summary.modelCalls + 1);
|
|
411
|
+
}
|
|
412
|
+
const invalid = /* @__PURE__ */ new Set();
|
|
413
|
+
for (const { part, json } of args.values()) try {
|
|
414
|
+
part.input = json ? JSON.parse(json) : {};
|
|
415
|
+
} catch {
|
|
416
|
+
part.input = json;
|
|
417
|
+
invalid.add(part.toolCallId);
|
|
404
418
|
}
|
|
405
|
-
for (const { part, json } of args.values()) part.input = json ? JSON.parse(json) : {};
|
|
406
419
|
flushAssistant();
|
|
407
420
|
flushResults();
|
|
408
421
|
summary.toolCalls = [...args.values()].map(({ part }) => ({
|
|
409
422
|
toolCallId: part.toolCallId,
|
|
410
423
|
toolName: part.toolName,
|
|
411
|
-
input: part.input
|
|
424
|
+
input: part.input,
|
|
425
|
+
...invalid.has(part.toolCallId) ? { invalid: true } : {}
|
|
412
426
|
}));
|
|
413
427
|
return summary;
|
|
414
428
|
}
|
|
@@ -543,13 +557,19 @@ function createTanStackAiExecutors(source) {
|
|
|
543
557
|
throw structured && isTruncationError(error) ? truncated(request, info, void 0, error) : error;
|
|
544
558
|
}
|
|
545
559
|
if (outputSchema) {
|
|
546
|
-
if (run.finishReason === "length") throw truncated(request, info, run.structured ?? run.text);
|
|
547
|
-
|
|
560
|
+
if (run.finishReason === "length") throw require_with_model_calls.withModelCalls(truncated(request, info, run.structured ?? run.text), run.modelCalls);
|
|
561
|
+
let parsed;
|
|
562
|
+
try {
|
|
563
|
+
parsed = require_event_log.parseProviderOutput(request, run.structured !== void 0 ? run.structured : JSON.parse(run.text));
|
|
564
|
+
} catch (error) {
|
|
565
|
+
throw require_with_model_calls.withModelCalls(error, run.modelCalls);
|
|
566
|
+
}
|
|
548
567
|
return {
|
|
549
568
|
result: parsed.result,
|
|
550
569
|
...typeof parsed.reasoning === "string" ? { reasoning: parsed.reasoning } : {},
|
|
551
570
|
...usageField(run.usage),
|
|
552
571
|
finishReason: run.finishReason,
|
|
572
|
+
modelCalls: run.modelCalls,
|
|
553
573
|
toolCalls: run.toolCalls,
|
|
554
574
|
messages: run.messages,
|
|
555
575
|
raw: run.chunks
|
|
@@ -559,6 +579,7 @@ function createTanStackAiExecutors(source) {
|
|
|
559
579
|
result: run.text,
|
|
560
580
|
...usageField(run.usage),
|
|
561
581
|
finishReason: run.finishReason,
|
|
582
|
+
modelCalls: run.modelCalls,
|
|
562
583
|
toolCalls: run.toolCalls,
|
|
563
584
|
messages: run.messages,
|
|
564
585
|
raw: run.chunks
|
|
@@ -579,6 +600,7 @@ function createTanStackAiExecutors(source) {
|
|
|
579
600
|
result: run.text,
|
|
580
601
|
...usageField(run.usage),
|
|
581
602
|
finishReason: run.finishReason,
|
|
603
|
+
modelCalls: run.modelCalls,
|
|
582
604
|
messages: run.messages,
|
|
583
605
|
raw: run.chunks
|
|
584
606
|
};
|
|
@@ -596,9 +618,19 @@ function createTanStackAiExecutors(source) {
|
|
|
596
618
|
agentLoopStrategy: (0, _tanstack_ai.maxIterations)(1)
|
|
597
619
|
}, info?.signal);
|
|
598
620
|
const toolCall = run.toolCalls[0];
|
|
599
|
-
|
|
621
|
+
const unnamed = (call) => ({
|
|
622
|
+
rejected: require_with_model_calls.rejectedAnswer(call, request.events.map((event) => event.toolName)),
|
|
623
|
+
...usageField(run.usage),
|
|
624
|
+
finishReason: run.finishReason,
|
|
625
|
+
raw: run.chunks
|
|
626
|
+
});
|
|
627
|
+
if (!toolCall) return unnamed();
|
|
600
628
|
const chosenEvent = request.events.find((event) => event.toolName === toolCall.toolName);
|
|
601
|
-
if (!chosenEvent)
|
|
629
|
+
if (!chosenEvent) return unnamed(toolCall);
|
|
630
|
+
if (toolCall.invalid) return unnamed({
|
|
631
|
+
toolName: toolCall.toolName,
|
|
632
|
+
invalidJson: true
|
|
633
|
+
});
|
|
602
634
|
return {
|
|
603
635
|
event: {
|
|
604
636
|
...toolCall.input && typeof toolCall.input === "object" ? toolCall.input : {},
|
package/dist/tanstack-ai.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as AgentToolChoice, n as AgentMessage, s as AgentTools, u as ChosenEvent } from "./types-Dp5_Ru4R.cjs";
|
|
2
|
-
import { N as
|
|
2
|
+
import { G as AgentEventDescriptor, N as AgentDecisionRejection, P as AgentDecisionRequest, c as AgentRequestExecutorInfo, f as AgentTextRequest, r as AgentFinishReason, t as AgentCallUsage } from "./text-logic-CV_4KGr6.cjs";
|
|
3
3
|
import { AnyStateMachine } from "xstate";
|
|
4
4
|
import { AnyTextAdapter, ModelMessage, StreamChunk, TokenUsage, Tool } from "@tanstack/ai";
|
|
5
5
|
import { TextActivityOptions } from "@tanstack/ai/adapters";
|
|
@@ -72,6 +72,8 @@ export type TanStackAiToolCall = {
|
|
|
72
72
|
toolCallId: string;
|
|
73
73
|
toolName: string;
|
|
74
74
|
input: unknown;
|
|
75
|
+
/** The arguments were not JSON; `input` is their raw text. */
|
|
76
|
+
invalid?: true;
|
|
75
77
|
};
|
|
76
78
|
/**
|
|
77
79
|
* Per-call `chat()` options a host can apply on top of what the machine asked
|
|
@@ -132,6 +134,8 @@ export type TanStackAiGenerateResult = {
|
|
|
132
134
|
usage?: AgentCallUsage;
|
|
133
135
|
/** Why the run stopped, normalized to the portable {@link AgentFinishReason}. */
|
|
134
136
|
finishReason: AgentFinishReason;
|
|
137
|
+
/** Model turns the run made: one per tool-loop iteration. */
|
|
138
|
+
modelCalls: number;
|
|
135
139
|
/** Every tool call the model made during the run. */
|
|
136
140
|
toolCalls: TanStackAiToolCall[];
|
|
137
141
|
/** The run's response messages — each turn's assistant text and tool
|
|
@@ -148,14 +152,21 @@ export type TanStackAiStreamResult = {
|
|
|
148
152
|
result: string;
|
|
149
153
|
usage?: AgentCallUsage;
|
|
150
154
|
finishReason: AgentFinishReason;
|
|
155
|
+
/** Model turns the run made, as on {@link TanStackAiGenerateResult}. */
|
|
156
|
+
modelCalls: number;
|
|
151
157
|
/** The run's response messages, as on {@link TanStackAiGenerateResult}. */
|
|
152
158
|
messages: AgentMessage[];
|
|
153
159
|
raw: StreamChunk[];
|
|
154
160
|
};
|
|
155
161
|
/** Raw result shape from {@link TanStackAiExecutors.decide} — the chosen event
|
|
156
162
|
* plus the call metadata, delivered per decision attempt to `onResult`. */
|
|
157
|
-
export type TanStackAiDecideResult = {
|
|
163
|
+
export type TanStackAiDecideResult = ({
|
|
158
164
|
event: ChosenEvent;
|
|
165
|
+
rejected?: undefined;
|
|
166
|
+
} | {
|
|
167
|
+
event?: undefined;
|
|
168
|
+
rejected: AgentDecisionRejection;
|
|
169
|
+
}) & {
|
|
159
170
|
usage?: AgentCallUsage;
|
|
160
171
|
finishReason: AgentFinishReason;
|
|
161
172
|
raw: StreamChunk[];
|