@statelyai/agent 2.0.0-alpha.33 → 2.0.0-alpha.35
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 +45 -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 +629 -13
- package/dist/testing.d.cts +278 -6
- package/dist/testing.d.mts +278 -6
- package/dist/testing.mjs +626 -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 +42 -2
package/dist/ai-sdk.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { c as renderDecisionAttempts, o as decisionOptionIds } from "./decision-
|
|
3
|
-
import { t as resolveModelSource } from "./model-source-
|
|
4
|
-
import {
|
|
1
|
+
import { B as providerOutputSchema, M as getAgentOutputMode, ft as isRecord, mt as AgentTruncatedError, rt as isStandardSchema } from "./event-log-C7jeH0y8.mjs";
|
|
2
|
+
import { c as renderDecisionAttempts, o as decisionOptionIds } from "./decision-COkJNjOW.mjs";
|
|
3
|
+
import { t as resolveModelSource } from "./model-source-CK3F4YuU.mjs";
|
|
4
|
+
import { n as rejectedAnswer, t as withModelCalls } from "./with-model-calls-Bv4V4EHC.mjs";
|
|
5
|
+
import { InvalidResponseDataError, NoObjectGeneratedError, Output, ToolChoiceViolationError, experimental_decide, generateText, jsonSchema, stepCountIs, streamText, tool } from "ai";
|
|
5
6
|
//#region src/ai-sdk/mappers.ts
|
|
6
7
|
/**
|
|
7
8
|
* Maps an {@link AgentTools} map onto AI SDK `tool()` definitions. A tool that
|
|
@@ -203,23 +204,24 @@ function toAiSdkOptionTool(options) {
|
|
|
203
204
|
}
|
|
204
205
|
/**
|
|
205
206
|
* The event a closed-choice tool call names: the offered option whose id is
|
|
206
|
-
* `input.option`. A call to another tool, or an id that is not offered,
|
|
207
|
-
*
|
|
207
|
+
* `input.option`. A call to another tool, or an id that is not offered, is
|
|
208
|
+
* rejected with {@link unofferedOption}, so the choice is retried instead of thrown.
|
|
208
209
|
*/
|
|
209
210
|
function fromAiSdkOptionCall(toolCall, options, ids) {
|
|
210
|
-
if (toolCall.toolName !== OPTION_TOOL_NAME) return unofferedOption(`tool '${toolCall.toolName}'`, ids);
|
|
211
|
+
if (toolCall.toolName !== OPTION_TOOL_NAME) return { rejected: unofferedOption(`tool '${toolCall.toolName}'`, ids) };
|
|
211
212
|
const id = isRecord(toolCall.input) ? toolCall.input.option : void 0;
|
|
212
213
|
const option = typeof id === "string" ? options[ids.indexOf(id)] : void 0;
|
|
213
|
-
return option ? option.event : unofferedOption(`option ${JSON.stringify(id)}`, ids);
|
|
214
|
+
return option ? { event: option.event } : { rejected: unofferedOption(`option ${JSON.stringify(id)}`, ids) };
|
|
214
215
|
}
|
|
215
216
|
/**
|
|
216
|
-
*
|
|
217
|
-
*
|
|
218
|
-
* failed `'unknown-event'` attempt (the type, which names the answer and the
|
|
219
|
-
* valid ids, is the attempt's reason) and asks again.
|
|
217
|
+
* The rejection for a closed-choice answer that names no offered option, so
|
|
218
|
+
* `resolveDecision` records a failed `'unknown-event'` attempt and asks again.
|
|
220
219
|
*/
|
|
221
220
|
function unofferedOption(answer, ids) {
|
|
222
|
-
return {
|
|
221
|
+
return {
|
|
222
|
+
failure: "unknown-event",
|
|
223
|
+
reason: `${answer} was not offered; valid ids: ${ids.join(", ") || "none"}`
|
|
224
|
+
};
|
|
223
225
|
}
|
|
224
226
|
/**
|
|
225
227
|
* Messages for a decision request, with prior failed `attempts` (§2.6)
|
|
@@ -331,71 +333,98 @@ function createAiSdkExecutors(source) {
|
|
|
331
333
|
const options = resolveModelSource("createAiSdkExecutors", source);
|
|
332
334
|
const generateText$1 = async (request, info) => {
|
|
333
335
|
const { model, settings: modelSettings } = resolveLanguageModel(options, request);
|
|
336
|
+
const settings = {
|
|
337
|
+
...callSettings(options, request),
|
|
338
|
+
...defined(modelSettings ?? {})
|
|
339
|
+
};
|
|
340
|
+
let calls = 0;
|
|
334
341
|
const common = {
|
|
335
342
|
model,
|
|
336
343
|
abortSignal: info?.signal,
|
|
337
|
-
...
|
|
338
|
-
|
|
344
|
+
...settings,
|
|
345
|
+
onLanguageModelCallStart: (event) => {
|
|
346
|
+
calls++;
|
|
347
|
+
return settings.onLanguageModelCallStart?.(event);
|
|
348
|
+
},
|
|
339
349
|
...toAiSdkCallSettings(request),
|
|
340
350
|
...maxStepsSetting(request)
|
|
341
351
|
};
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
352
|
+
try {
|
|
353
|
+
if (isStructuredOutputRequest(request)) {
|
|
354
|
+
const outputSchema = providerOutputSchema(request.outputSchema, { reasoning: request.includeReasoning });
|
|
355
|
+
const structuredOutput = withJsonRepair(Output.object({ schema: outputSchema }));
|
|
356
|
+
const result = await generateText({
|
|
357
|
+
...common,
|
|
358
|
+
output: structuredOutput
|
|
359
|
+
}).catch((error) => {
|
|
360
|
+
throw NoObjectGeneratedError.isInstance(error) && error.finishReason === "length" ? truncated(request, info, error.text, error) : error;
|
|
361
|
+
});
|
|
362
|
+
const parsed = (() => {
|
|
363
|
+
try {
|
|
364
|
+
return result.output;
|
|
365
|
+
} catch (error) {
|
|
366
|
+
throw result.finishReason === "length" ? truncated(request, info, result.text, error) : error;
|
|
367
|
+
}
|
|
368
|
+
})();
|
|
369
|
+
if (result.finishReason === "length") throw truncated(request, info, parsed.result);
|
|
370
|
+
return {
|
|
371
|
+
result: parsed.result,
|
|
372
|
+
...parsed.reasoning !== void 0 ? { reasoning: parsed.reasoning } : {},
|
|
373
|
+
usage: toAgentCallUsage(result.usage),
|
|
374
|
+
finishReason: toAgentFinishReason(result.finishReason),
|
|
375
|
+
modelCalls: result.steps.length,
|
|
376
|
+
toolCalls: result.toolCalls,
|
|
377
|
+
toolResults: result.toolResults,
|
|
378
|
+
messages: result.responseMessages,
|
|
379
|
+
raw: result
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
const result = await generateText(common);
|
|
359
383
|
return {
|
|
360
|
-
result:
|
|
361
|
-
...parsed.reasoning !== void 0 ? { reasoning: parsed.reasoning } : {},
|
|
384
|
+
result: result.text,
|
|
362
385
|
usage: toAgentCallUsage(result.usage),
|
|
363
386
|
finishReason: toAgentFinishReason(result.finishReason),
|
|
387
|
+
modelCalls: result.steps.length,
|
|
364
388
|
toolCalls: result.toolCalls,
|
|
365
389
|
toolResults: result.toolResults,
|
|
366
390
|
messages: result.responseMessages,
|
|
367
391
|
raw: result
|
|
368
392
|
};
|
|
393
|
+
} catch (error) {
|
|
394
|
+
throw withModelCalls(error, calls);
|
|
369
395
|
}
|
|
370
|
-
const result = await generateText(common);
|
|
371
|
-
return {
|
|
372
|
-
result: result.text,
|
|
373
|
-
usage: toAgentCallUsage(result.usage),
|
|
374
|
-
finishReason: toAgentFinishReason(result.finishReason),
|
|
375
|
-
toolCalls: result.toolCalls,
|
|
376
|
-
toolResults: result.toolResults,
|
|
377
|
-
messages: result.responseMessages,
|
|
378
|
-
raw: result
|
|
379
|
-
};
|
|
380
396
|
};
|
|
381
397
|
const streamText$1 = async (request, info) => {
|
|
382
398
|
const { model, settings: modelSettings } = resolveLanguageModel(options, request);
|
|
399
|
+
const settings = {
|
|
400
|
+
...callSettings(options, request),
|
|
401
|
+
...defined(modelSettings ?? {})
|
|
402
|
+
};
|
|
403
|
+
let calls = 0;
|
|
383
404
|
const result = streamText({
|
|
384
405
|
model,
|
|
385
406
|
abortSignal: info?.signal,
|
|
386
|
-
...
|
|
387
|
-
|
|
407
|
+
...settings,
|
|
408
|
+
onLanguageModelCallStart: (event) => {
|
|
409
|
+
calls++;
|
|
410
|
+
return settings.onLanguageModelCallStart?.(event);
|
|
411
|
+
},
|
|
388
412
|
...toAiSdkCallSettings(request),
|
|
389
413
|
...maxStepsSetting(request)
|
|
390
414
|
});
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
415
|
+
try {
|
|
416
|
+
for await (const chunk of result.textStream) info?.onChunk?.(chunk);
|
|
417
|
+
return {
|
|
418
|
+
result: await result.text,
|
|
419
|
+
usage: toAgentCallUsage(await result.usage),
|
|
420
|
+
finishReason: toAgentFinishReason(await result.finishReason),
|
|
421
|
+
modelCalls: (await result.steps).length,
|
|
422
|
+
messages: await result.responseMessages,
|
|
423
|
+
raw: result
|
|
424
|
+
};
|
|
425
|
+
} catch (error) {
|
|
426
|
+
throw withModelCalls(error, calls);
|
|
427
|
+
}
|
|
399
428
|
};
|
|
400
429
|
const decide = async (request, info) => {
|
|
401
430
|
const { model, settings: modelSettings } = resolveAiSdkModel(options, request.model);
|
|
@@ -403,11 +432,25 @@ function createAiSdkExecutors(source) {
|
|
|
403
432
|
const choice = request.options ? toAiSdkOptionTool(request.options) : void 0;
|
|
404
433
|
const tools = choice ? choice.tools : toAiSdkEventTools(request.events);
|
|
405
434
|
const messages = toDecisionMessages(request);
|
|
435
|
+
const settings = {
|
|
436
|
+
...callSettings(options, request),
|
|
437
|
+
...defined(modelSettings ?? {})
|
|
438
|
+
};
|
|
439
|
+
const toolNames = Object.keys(tools);
|
|
440
|
+
let callEnd;
|
|
441
|
+
const unnamed = (ended, call) => ({
|
|
442
|
+
rejected: rejectedAnswer(call, toolNames),
|
|
443
|
+
usage: toAgentCallUsage(ended.usage),
|
|
444
|
+
finishReason: ended.finishReason
|
|
445
|
+
});
|
|
406
446
|
const result = await generateText({
|
|
407
447
|
model,
|
|
408
448
|
abortSignal: info?.signal,
|
|
409
|
-
...
|
|
410
|
-
|
|
449
|
+
...settings,
|
|
450
|
+
onLanguageModelCallEnd: (event) => {
|
|
451
|
+
callEnd = event;
|
|
452
|
+
return settings.onLanguageModelCallEnd?.(event);
|
|
453
|
+
},
|
|
411
454
|
system: request.system,
|
|
412
455
|
...messages ? {
|
|
413
456
|
messages,
|
|
@@ -417,16 +460,24 @@ function createAiSdkExecutors(source) {
|
|
|
417
460
|
toolChoice: "required",
|
|
418
461
|
stopWhen: stepCountIs(1),
|
|
419
462
|
...toAiSdkGenerationSettings(request)
|
|
463
|
+
}).catch((error) => {
|
|
464
|
+
if (ToolChoiceViolationError.isInstance(error) && callEnd) return void 0;
|
|
465
|
+
throw error;
|
|
420
466
|
});
|
|
467
|
+
if (!result) return unnamed(callEnd);
|
|
421
468
|
const toolCall = result.toolCalls[0];
|
|
422
|
-
if (!toolCall)
|
|
469
|
+
if (!toolCall) return unnamed(result);
|
|
470
|
+
if (toolCall.invalid && typeof toolCall.input === "string" && toolNames.includes(toolCall.toolName)) return unnamed(result, {
|
|
471
|
+
toolName: toolCall.toolName,
|
|
472
|
+
invalidJson: true
|
|
473
|
+
});
|
|
423
474
|
if (choice) return {
|
|
424
|
-
|
|
475
|
+
...fromAiSdkOptionCall(toolCall, request.options, choice.ids),
|
|
425
476
|
usage: toAgentCallUsage(result.usage),
|
|
426
477
|
finishReason: result.finishReason
|
|
427
478
|
};
|
|
428
479
|
const chosenEvent = request.events.find((event) => event.toolName === toolCall.toolName);
|
|
429
|
-
if (!chosenEvent)
|
|
480
|
+
if (!chosenEvent) return unnamed(result, toolCall);
|
|
430
481
|
return {
|
|
431
482
|
event: {
|
|
432
483
|
...toolCall.input && typeof toolCall.input === "object" ? toolCall.input : {},
|
|
@@ -466,18 +517,18 @@ async function decideWithDecisionModel(model, request, info) {
|
|
|
466
517
|
} catch (error) {
|
|
467
518
|
const chosen = unofferedChoice(error, ids);
|
|
468
519
|
if (chosen === void 0) throw error;
|
|
469
|
-
return decisionResult(unofferedOption(`option ${JSON.stringify(chosen)}`, ids));
|
|
520
|
+
return decisionResult({ rejected: unofferedOption(`option ${JSON.stringify(chosen)}`, ids) });
|
|
470
521
|
}
|
|
471
522
|
const answer = result.answers[DECISION_QUESTION_ID];
|
|
472
523
|
const option = offered[ids.indexOf(answer.choice)];
|
|
473
|
-
if (!option) return decisionResult(unofferedOption(`option ${JSON.stringify(answer.choice)}`, ids));
|
|
524
|
+
if (!option) return decisionResult({ rejected: unofferedOption(`option ${JSON.stringify(answer.choice)}`, ids) });
|
|
474
525
|
const reported = (result.providerMetadata?.typesafe?.confidence)?.[DECISION_QUESTION_ID];
|
|
475
526
|
const confidence = typeof reported === "number" ? reported : answer.probabilities?.[answer.choice];
|
|
476
|
-
return decisionResult(option.event, result.usage, confidence);
|
|
527
|
+
return decisionResult({ event: option.event }, result.usage, confidence);
|
|
477
528
|
}
|
|
478
|
-
function decisionResult(
|
|
529
|
+
function decisionResult(answer, usage = {}, confidence) {
|
|
479
530
|
return {
|
|
480
|
-
|
|
531
|
+
...answer,
|
|
481
532
|
usage: toAgentCallUsage({
|
|
482
533
|
inputTokens: usage.inputTokens,
|
|
483
534
|
outputTokens: usage.outputTokens,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const require_event_log = require("./event-log-
|
|
1
|
+
const require_event_log = require("./event-log-BWSSLUff.cjs");
|
|
2
2
|
let xstate = require("xstate");
|
|
3
3
|
//#region src/events.ts
|
|
4
4
|
/**
|
|
@@ -400,6 +400,11 @@ function dedupeToolNames(candidates) {
|
|
|
400
400
|
};
|
|
401
401
|
});
|
|
402
402
|
}
|
|
403
|
+
const DECISION_FAILURES = /* @__PURE__ */ new Set([
|
|
404
|
+
"unknown-event",
|
|
405
|
+
"invalid-payload",
|
|
406
|
+
"rejected-by-guard"
|
|
407
|
+
]);
|
|
403
408
|
/**
|
|
404
409
|
* Thrown by {@link resolveDecision} when every attempt (up to
|
|
405
410
|
* `maxRetries + 1` of them) fails one of the three checks recorded in
|
|
@@ -481,8 +486,19 @@ async function resolveDecision(request, executors, options = {}) {
|
|
|
481
486
|
...options.signal !== void 0 ? { signal: options.signal } : {},
|
|
482
487
|
...request.id ? { requestId: request.id } : {}
|
|
483
488
|
});
|
|
489
|
+
const rejected = result?.rejected;
|
|
490
|
+
if (rejected !== void 0) {
|
|
491
|
+
if (!require_event_log.isRecord(rejected) || typeof rejected.reason !== "string" || !DECISION_FAILURES.has(rejected.failure) || rejected.event !== void 0 && (!require_event_log.isRecord(rejected.event) || typeof rejected.event.type !== "string")) throw new Error(`decide executor's \`rejected\` must be { failure: 'unknown-event' | 'invalid-payload' | 'rejected-by-guard', reason: string, event?: { type: string } }; got ${JSON.stringify(rejected)}.`);
|
|
492
|
+
const { failure, reason, event } = rejected;
|
|
493
|
+
attempts.push({
|
|
494
|
+
...event ? { event } : {},
|
|
495
|
+
failure,
|
|
496
|
+
reason
|
|
497
|
+
});
|
|
498
|
+
continue;
|
|
499
|
+
}
|
|
484
500
|
if (!result || typeof result !== "object" || typeof result.event !== "object" || result.event === null || typeof result.event.type !== "string") throw new Error(`decide executor must return { event: { type: string, ... } }; got ${JSON.stringify(result)}. Wrap the chosen event: return { event: { type: 'SAFE' } }.`);
|
|
485
|
-
const
|
|
501
|
+
const event = result.event;
|
|
486
502
|
const descriptor = eventsByType.get(event.type);
|
|
487
503
|
if (!descriptor) {
|
|
488
504
|
attempts.push({
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { E as DECIDE_ACTOR, U as executorBoundLogics, V as resolveTextLogicValue, W as getAgentExecutionOptions, ct as validateSchemaSync, d as canonicalEventJson, ft as isRecord, pt as AgentError, st as userMessage } from "./event-log-C7jeH0y8.mjs";
|
|
2
2
|
import { createAsyncLogic, getNextTransitions } from "xstate";
|
|
3
3
|
//#region src/events.ts
|
|
4
4
|
/**
|
|
@@ -400,6 +400,11 @@ function dedupeToolNames(candidates) {
|
|
|
400
400
|
};
|
|
401
401
|
});
|
|
402
402
|
}
|
|
403
|
+
const DECISION_FAILURES = /* @__PURE__ */ new Set([
|
|
404
|
+
"unknown-event",
|
|
405
|
+
"invalid-payload",
|
|
406
|
+
"rejected-by-guard"
|
|
407
|
+
]);
|
|
403
408
|
/**
|
|
404
409
|
* Thrown by {@link resolveDecision} when every attempt (up to
|
|
405
410
|
* `maxRetries + 1` of them) fails one of the three checks recorded in
|
|
@@ -481,8 +486,19 @@ async function resolveDecision(request, executors, options = {}) {
|
|
|
481
486
|
...options.signal !== void 0 ? { signal: options.signal } : {},
|
|
482
487
|
...request.id ? { requestId: request.id } : {}
|
|
483
488
|
});
|
|
489
|
+
const rejected = result?.rejected;
|
|
490
|
+
if (rejected !== void 0) {
|
|
491
|
+
if (!isRecord(rejected) || typeof rejected.reason !== "string" || !DECISION_FAILURES.has(rejected.failure) || rejected.event !== void 0 && (!isRecord(rejected.event) || typeof rejected.event.type !== "string")) throw new Error(`decide executor's \`rejected\` must be { failure: 'unknown-event' | 'invalid-payload' | 'rejected-by-guard', reason: string, event?: { type: string } }; got ${JSON.stringify(rejected)}.`);
|
|
492
|
+
const { failure, reason, event } = rejected;
|
|
493
|
+
attempts.push({
|
|
494
|
+
...event ? { event } : {},
|
|
495
|
+
failure,
|
|
496
|
+
reason
|
|
497
|
+
});
|
|
498
|
+
continue;
|
|
499
|
+
}
|
|
484
500
|
if (!result || typeof result !== "object" || typeof result.event !== "object" || result.event === null || typeof result.event.type !== "string") throw new Error(`decide executor must return { event: { type: string, ... } }; got ${JSON.stringify(result)}. Wrap the chosen event: return { event: { type: 'SAFE' } }.`);
|
|
485
|
-
const
|
|
501
|
+
const event = result.event;
|
|
486
502
|
const descriptor = eventsByType.get(event.type);
|
|
487
503
|
if (!descriptor) {
|
|
488
504
|
attempts.push({
|
|
@@ -167,6 +167,7 @@ function getMachineStructuralHash(machine) {
|
|
|
167
167
|
function resolveMachineVersion(machine) {
|
|
168
168
|
return machine.version ?? getMachineStructuralHash(machine);
|
|
169
169
|
}
|
|
170
|
+
const STRUCTURAL_CACHE_KEYS = /* @__PURE__ */ new Set(["_candidateCache"]);
|
|
170
171
|
function stableStructuralString(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
171
172
|
if (value === null) return "null";
|
|
172
173
|
const type = typeof value;
|
|
@@ -184,7 +185,7 @@ function stableStructuralString(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
|
184
185
|
for (const key of Object.keys(obj).sort()) {
|
|
185
186
|
const child = obj[key];
|
|
186
187
|
const childType = typeof child;
|
|
187
|
-
if (childType === "function" || childType === "undefined" || childType === "symbol") continue;
|
|
188
|
+
if (childType === "function" || childType === "undefined" || childType === "symbol" || STRUCTURAL_CACHE_KEYS.has(key)) continue;
|
|
188
189
|
parts.push(`${JSON.stringify(key)}:${stableStructuralString(child, seen)}`);
|
|
189
190
|
}
|
|
190
191
|
out = `{${parts.join(",")}}`;
|
|
@@ -428,6 +429,11 @@ function getCallFinishReason(raw) {
|
|
|
428
429
|
if (value === "error") return "other";
|
|
429
430
|
return AGENT_FINISH_REASONS.has(value) ? value : void 0;
|
|
430
431
|
}
|
|
432
|
+
/** Provider calls a raw executor result reports (`modelCalls`, a whole number of at least 1), else 1. @internal */
|
|
433
|
+
function getCallModelCalls(raw) {
|
|
434
|
+
const value = raw?.modelCalls;
|
|
435
|
+
return typeof value === "number" && Number.isInteger(value) && value > 1 ? value : 1;
|
|
436
|
+
}
|
|
431
437
|
/** The token fields {@link AgentUsage} aggregates. @internal */
|
|
432
438
|
const AGENT_USAGE_TOKEN_FIELDS = [
|
|
433
439
|
"inputTokens",
|
|
@@ -984,6 +990,8 @@ function assertAgentLogEntry(entry) {
|
|
|
984
990
|
if (candidate.metadata !== void 0 && (candidate.metadata === null || typeof candidate.metadata !== "object" || Array.isArray(candidate.metadata))) throw new AgentEventLogError("Agent event entry.metadata must be an object when present.");
|
|
985
991
|
if (candidate.verification !== void 0 && (candidate.verification === null || typeof candidate.verification !== "object" || typeof candidate.verification.stateHash !== "string" || !candidate.verification.stateHash)) throw new AgentEventLogError("Agent event entry.verification requires a non-empty stateHash string.");
|
|
986
992
|
if (candidate.attempts !== void 0) assertLogAttempts(candidate.attempts);
|
|
993
|
+
if (candidate.decidedBy !== void 0) requireNonEmptyString(candidate.decidedBy, "entry.decidedBy", " when present");
|
|
994
|
+
if (candidate.actorPath !== void 0 && (!Array.isArray(candidate.actorPath) || candidate.actorPath.length === 0 || !candidate.actorPath.every((id) => typeof id === "string" && id !== ""))) throw new AgentEventLogError("Agent event entry.actorPath must be a non-empty array of invoke ids when present.");
|
|
987
995
|
}
|
|
988
996
|
function assertLogAttempts(attempts) {
|
|
989
997
|
if (!Array.isArray(attempts) || !attempts.every((attempt) => attempt !== null && typeof attempt === "object" && typeof attempt.failure === "string" && typeof attempt.reason === "string")) throw new AgentEventLogError("Agent event entry.attempts requires an array of { failure, reason } objects.");
|
|
@@ -1098,7 +1106,7 @@ function canonicalizeForHash(value, seen = /* @__PURE__ */ new WeakSet(), positi
|
|
|
1098
1106
|
if (value instanceof Map) return [...value.entries()].map(([key, item]) => [canonicalizeForHash(key, seen, "data"), canonicalizeForHash(item, seen, "data")]).sort(([a], [b]) => stableJson(a).localeCompare(stableJson(b)));
|
|
1099
1107
|
if (Array.isArray(value)) return value.map((item) => canonicalizeForHash(item, seen, "data"));
|
|
1100
1108
|
const volatileKeys = position === "snapshot" ? SNAPSHOT_VOLATILE_KEYS : position === "child" ? CHILD_VOLATILE_KEYS : void 0;
|
|
1101
|
-
const result =
|
|
1109
|
+
const result = Object.create(null);
|
|
1102
1110
|
for (const key of Object.keys(value).sort()) {
|
|
1103
1111
|
if (volatileKeys?.has(key)) continue;
|
|
1104
1112
|
const child = value[key];
|
|
@@ -1176,7 +1184,9 @@ function createReplayEntry(machine, entries, event, options = {}) {
|
|
|
1176
1184
|
event: normalizeDoneActorEvent(pruneUndefined(normalizeEventErrors(event))),
|
|
1177
1185
|
...options.causationId !== void 0 ? { causationId: options.causationId } : {},
|
|
1178
1186
|
...options.metadata !== void 0 ? { metadata: options.metadata } : {},
|
|
1179
|
-
...options.attempts !== void 0 && options.attempts.length > 0 ? { attempts: options.attempts } : {}
|
|
1187
|
+
...options.attempts !== void 0 && options.attempts.length > 0 ? { attempts: options.attempts } : {},
|
|
1188
|
+
...options.decidedBy !== void 0 ? { decidedBy: options.decidedBy } : {},
|
|
1189
|
+
...options.actorPath !== void 0 ? { actorPath: [...options.actorPath] } : {}
|
|
1180
1190
|
};
|
|
1181
1191
|
assertAgentLogEntry(entry);
|
|
1182
1192
|
if (entry.attempts !== void 0) entry.attempts = structuredClone(entry.attempts);
|
|
@@ -1325,16 +1335,40 @@ function toEvents(history) {
|
|
|
1325
1335
|
});
|
|
1326
1336
|
}
|
|
1327
1337
|
/**
|
|
1338
|
+
* An invoke site as call keys name it: the invoke ids from the root down,
|
|
1339
|
+
* joined with `/`, each id escaped so an id holding a `/` cannot read as a
|
|
1340
|
+
* child path. @internal
|
|
1341
|
+
*/
|
|
1342
|
+
function agentCallSite(actorPath, siteId) {
|
|
1343
|
+
return [...actorPath, siteId].map((id) => id.replaceAll("%", "%25").replaceAll("/", "%2F")).join("/");
|
|
1344
|
+
}
|
|
1345
|
+
/**
|
|
1328
1346
|
* The 1-based occurrence `n` for the NEXT call at invoke site `siteId`:
|
|
1329
1347
|
* `1 + completions`, where a completion is a journaled `xstate.done.actor` OR
|
|
1330
|
-
* `xstate.error.actor` for that `actorId` (an error is a semantic completion)
|
|
1348
|
+
* `xstate.error.actor` for that `actorId` (an error is a semantic completion),
|
|
1349
|
+
* or a distinct `entry.decidedBy` call at that site: a decision settles by
|
|
1350
|
+
* sending its chosen event, which usually ends the invoke before it completes.
|
|
1351
|
+
* Entries marked `decidedBy` are counted once per call, never as completions.
|
|
1352
|
+
* A site inside an invoked child machine is named by that child's
|
|
1353
|
+
* `actorPath` too, and only entries delivered to that child count.
|
|
1331
1354
|
* The one counting rule behind every `${siteId}#${n}` call key, so a live run
|
|
1332
1355
|
* and a replay derive the same `n` by construction.
|
|
1333
1356
|
*/
|
|
1334
|
-
function agentCallOccurrence(history, siteId) {
|
|
1357
|
+
function agentCallOccurrence(history, siteId, actorPath = []) {
|
|
1335
1358
|
let count = 0;
|
|
1336
|
-
|
|
1337
|
-
|
|
1359
|
+
const decided = /* @__PURE__ */ new Set();
|
|
1360
|
+
const site = agentCallSite(actorPath, siteId);
|
|
1361
|
+
for (const item of history ?? []) {
|
|
1362
|
+
const event = toEvents([item])[0];
|
|
1363
|
+
const entry = event === item ? void 0 : item;
|
|
1364
|
+
if (entry?.decidedBy !== void 0) {
|
|
1365
|
+
const { decidedBy } = entry;
|
|
1366
|
+
if (decidedBy.slice(0, decidedBy.lastIndexOf("#")) === site) decided.add(decidedBy);
|
|
1367
|
+
continue;
|
|
1368
|
+
}
|
|
1369
|
+
if ((event.type === DONE_ACTOR_EVENT_TYPE || event.type === ERROR_ACTOR_EVENT_TYPE) && event.actorId === siteId && (entry?.actorPath ?? []).join("\0") === actorPath.join("\0")) count++;
|
|
1370
|
+
}
|
|
1371
|
+
return count + decided.size + 1;
|
|
1338
1372
|
}
|
|
1339
1373
|
/**
|
|
1340
1374
|
* Folds the reserved `@agent.usage` entries of a log into one cumulative usage
|
|
@@ -1446,6 +1480,39 @@ function toError(normalized) {
|
|
|
1446
1480
|
error.name = name;
|
|
1447
1481
|
return Object.assign(error, rest);
|
|
1448
1482
|
}
|
|
1483
|
+
function countStarts(before, after, path, starts) {
|
|
1484
|
+
const known = /* @__PURE__ */ new Set();
|
|
1485
|
+
const collect = (snapshot) => {
|
|
1486
|
+
for (const ref of Object.values(snapshot.children ?? {})) {
|
|
1487
|
+
if (ref === void 0) continue;
|
|
1488
|
+
known.add(ref.sessionId);
|
|
1489
|
+
const childSnapshot = ref.getSnapshot();
|
|
1490
|
+
if ((0, xstate.isMachineSnapshot)(childSnapshot)) collect(childSnapshot);
|
|
1491
|
+
}
|
|
1492
|
+
};
|
|
1493
|
+
if (before !== void 0) collect(before);
|
|
1494
|
+
const walk = (snapshot, at) => {
|
|
1495
|
+
for (const [id, ref] of Object.entries(snapshot.children ?? {})) {
|
|
1496
|
+
if (ref === void 0) continue;
|
|
1497
|
+
const site = agentCallSite(at, id);
|
|
1498
|
+
if (!known.has(ref.sessionId)) starts.set(site, (starts.get(site) ?? 0) + 1);
|
|
1499
|
+
const childSnapshot = ref.getSnapshot();
|
|
1500
|
+
if ((0, xstate.isMachineSnapshot)(childSnapshot)) walk(childSnapshot, [...at, id]);
|
|
1501
|
+
}
|
|
1502
|
+
};
|
|
1503
|
+
walk(after, path);
|
|
1504
|
+
}
|
|
1505
|
+
function collectSessionRemints(before, after, out) {
|
|
1506
|
+
const afterChildren = after.children ?? {};
|
|
1507
|
+
for (const [id, old] of Object.entries(before.children ?? {})) {
|
|
1508
|
+
const now = afterChildren[id];
|
|
1509
|
+
if (old === void 0 || now === void 0) continue;
|
|
1510
|
+
out.set(old.sessionId, now.sessionId);
|
|
1511
|
+
const oldSnapshot = old.getSnapshot();
|
|
1512
|
+
const nowSnapshot = now.getSnapshot();
|
|
1513
|
+
if (oldSnapshot?.children && nowSnapshot?.children) collectSessionRemints(oldSnapshot, nowSnapshot, out);
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1449
1516
|
function verifyEntry(entry, persisted, mode) {
|
|
1450
1517
|
if (mode === false) return;
|
|
1451
1518
|
if (!entry.verification) {
|
|
@@ -1490,13 +1557,56 @@ function foldLog(machine, entries, options = {}) {
|
|
|
1490
1557
|
let snapshot = initEvent.snapshot !== void 0 ? machine.restoreSnapshot(initEvent.snapshot) : (0, xstate.initialTransition)(machine, initEvent.input)[0];
|
|
1491
1558
|
let persisted = machine.getPersistedSnapshot(snapshot);
|
|
1492
1559
|
verifyEntry(entries[0], persisted, options.verify);
|
|
1560
|
+
const starts = /* @__PURE__ */ new Map();
|
|
1561
|
+
countStarts(void 0, snapshot, [], starts);
|
|
1493
1562
|
const sessions = /* @__PURE__ */ new Map();
|
|
1563
|
+
const sessionsOf = (path) => {
|
|
1564
|
+
const key = path.join("\0");
|
|
1565
|
+
let map = sessions.get(key);
|
|
1566
|
+
if (map === void 0) sessions.set(key, map = /* @__PURE__ */ new Map());
|
|
1567
|
+
return map;
|
|
1568
|
+
};
|
|
1494
1569
|
const apply = (entry) => {
|
|
1495
|
-
|
|
1496
|
-
|
|
1570
|
+
if (entry.actorPath !== void 0) applyToChild(entry, entry.actorPath);
|
|
1571
|
+
else {
|
|
1572
|
+
const event = restoreJournaledEvent(rebindActorSession(entry.event, snapshot, sessionsOf([])));
|
|
1573
|
+
const before = snapshot;
|
|
1574
|
+
[snapshot] = (0, xstate.transition)(machine, snapshot, event);
|
|
1575
|
+
countStarts(before, snapshot, [], starts);
|
|
1576
|
+
}
|
|
1497
1577
|
persisted = machine.getPersistedSnapshot(snapshot);
|
|
1498
1578
|
return persisted;
|
|
1499
1579
|
};
|
|
1580
|
+
const applyToChild = (entry, path) => {
|
|
1581
|
+
let child;
|
|
1582
|
+
let owner = snapshot;
|
|
1583
|
+
for (const id of path) {
|
|
1584
|
+
child = owner.children[id];
|
|
1585
|
+
const childSnapshot = child?.getSnapshot();
|
|
1586
|
+
if (child === void 0 || !(0, xstate.isMachineSnapshot)(childSnapshot)) throw new AgentEventLogError(`Agent event entry '${entry.id}' (index ${entry.index}) is addressed to child machine '${path.join(" > ")}', which the fold has no machine actor for at that point.`);
|
|
1587
|
+
owner = childSnapshot;
|
|
1588
|
+
}
|
|
1589
|
+
const event = restoreJournaledEvent(rebindActorSession(entry.event, owner, sessionsOf(path)));
|
|
1590
|
+
let next;
|
|
1591
|
+
try {
|
|
1592
|
+
[next] = (0, xstate.transition)(child.logic, owner, event);
|
|
1593
|
+
} catch {
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1596
|
+
countStarts(owner, next, path, starts);
|
|
1597
|
+
const root = machine.getPersistedSnapshot(snapshot);
|
|
1598
|
+
let holder = root;
|
|
1599
|
+
for (const id of path.slice(0, -1)) holder = holder.children[id].snapshot;
|
|
1600
|
+
holder.children[path[path.length - 1]].snapshot = child.logic.getPersistedSnapshot(next);
|
|
1601
|
+
const before = snapshot;
|
|
1602
|
+
snapshot = machine.restoreSnapshot(root);
|
|
1603
|
+
const reminted = /* @__PURE__ */ new Map();
|
|
1604
|
+
collectSessionRemints(before, snapshot, reminted);
|
|
1605
|
+
for (const map of sessions.values()) for (const [recorded, current] of map) {
|
|
1606
|
+
const now = reminted.get(current);
|
|
1607
|
+
if (now !== void 0) map.set(recorded, now);
|
|
1608
|
+
}
|
|
1609
|
+
};
|
|
1500
1610
|
for (let index = 1; index < entries.length; index++) {
|
|
1501
1611
|
const entry = entries[index];
|
|
1502
1612
|
verifyEntry(entry, apply(entry), options.verify);
|
|
@@ -1508,7 +1618,8 @@ function foldLog(machine, entries, options = {}) {
|
|
|
1508
1618
|
get persistedSnapshot() {
|
|
1509
1619
|
return persisted;
|
|
1510
1620
|
},
|
|
1511
|
-
apply
|
|
1621
|
+
apply,
|
|
1622
|
+
starts: (site) => starts.get(site) ?? 0
|
|
1512
1623
|
};
|
|
1513
1624
|
}
|
|
1514
1625
|
/**
|
|
@@ -1654,6 +1765,12 @@ Object.defineProperty(exports, "agentCallOccurrence", {
|
|
|
1654
1765
|
return agentCallOccurrence;
|
|
1655
1766
|
}
|
|
1656
1767
|
});
|
|
1768
|
+
Object.defineProperty(exports, "agentCallSite", {
|
|
1769
|
+
enumerable: true,
|
|
1770
|
+
get: function() {
|
|
1771
|
+
return agentCallSite;
|
|
1772
|
+
}
|
|
1773
|
+
});
|
|
1657
1774
|
Object.defineProperty(exports, "assertAgentLogEntry", {
|
|
1658
1775
|
enumerable: true,
|
|
1659
1776
|
get: function() {
|
|
@@ -1750,6 +1867,12 @@ Object.defineProperty(exports, "getCallFinishReason", {
|
|
|
1750
1867
|
return getCallFinishReason;
|
|
1751
1868
|
}
|
|
1752
1869
|
});
|
|
1870
|
+
Object.defineProperty(exports, "getCallModelCalls", {
|
|
1871
|
+
enumerable: true,
|
|
1872
|
+
get: function() {
|
|
1873
|
+
return getCallModelCalls;
|
|
1874
|
+
}
|
|
1875
|
+
});
|
|
1753
1876
|
Object.defineProperty(exports, "getCallUsage", {
|
|
1754
1877
|
enumerable: true,
|
|
1755
1878
|
get: function() {
|
|
@@ -1828,6 +1951,12 @@ Object.defineProperty(exports, "initEntry", {
|
|
|
1828
1951
|
return initEntry;
|
|
1829
1952
|
}
|
|
1830
1953
|
});
|
|
1954
|
+
Object.defineProperty(exports, "isError", {
|
|
1955
|
+
enumerable: true,
|
|
1956
|
+
get: function() {
|
|
1957
|
+
return isError;
|
|
1958
|
+
}
|
|
1959
|
+
});
|
|
1831
1960
|
Object.defineProperty(exports, "isPlainObject", {
|
|
1832
1961
|
enumerable: true,
|
|
1833
1962
|
get: function() {
|