@mastra/inngest 1.11.2-alpha.0 → 1.11.2-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/connect.cjs +1 -1
- package/dist/connect.js +1 -1
- package/dist/durable-agent/create-inngest-agent.d.ts.map +1 -1
- package/dist/durable-agent/create-inngest-agentic-workflow.d.ts +10 -0
- package/dist/durable-agent/create-inngest-agentic-workflow.d.ts.map +1 -1
- package/dist/durable-event-payload.d.ts +16 -0
- package/dist/durable-event-payload.d.ts.map +1 -1
- package/dist/execution-engine.d.ts +1 -0
- package/dist/execution-engine.d.ts.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/observability-compat.d.ts +3 -0
- package/dist/observability-compat.d.ts.map +1 -1
- package/dist/{src-BS8BwrvL.js → src-IbSX_hCm.js} +376 -111
- package/dist/src-IbSX_hCm.js.map +1 -0
- package/dist/{src-SSvfovM3.cjs → src-zS6LvTK1.cjs} +375 -110
- package/dist/src-zS6LvTK1.cjs.map +1 -0
- package/dist/workflow.d.ts +1 -0
- package/dist/workflow.d.ts.map +1 -1
- package/package.json +6 -6
- package/dist/src-BS8BwrvL.js.map +0 -1
- package/dist/src-SSvfovM3.cjs.map +0 -1
|
@@ -29,22 +29,73 @@ let _mastra_core_tools = require("@mastra/core/tools");
|
|
|
29
29
|
let _mastra_core_workflows = require("@mastra/core/workflows");
|
|
30
30
|
_mastra_core_workflows = __toESM(_mastra_core_workflows, 1);
|
|
31
31
|
let _mastra_core_agent_durable = require("@mastra/core/agent/durable");
|
|
32
|
+
_mastra_core_agent_durable = __toESM(_mastra_core_agent_durable, 1);
|
|
32
33
|
let _mastra_core_di = require("@mastra/core/di");
|
|
33
34
|
let _mastra_core_events = require("@mastra/core/events");
|
|
34
35
|
let inngest = require("inngest");
|
|
36
|
+
let _mastra_core_request_context = require("@mastra/core/request-context");
|
|
35
37
|
let async_hooks = require("async_hooks");
|
|
36
38
|
let _mastra_core_features = require("@mastra/core/features");
|
|
37
39
|
let inngest_realtime = require("inngest/realtime");
|
|
38
40
|
let stream_web = require("stream/web");
|
|
39
41
|
let _mastra_core_stream = require("@mastra/core/stream");
|
|
40
|
-
let _mastra_core_request_context = require("@mastra/core/request-context");
|
|
41
42
|
let inngest_hono = require("inngest/hono");
|
|
42
|
-
let _mastra_core_cache = require("@mastra/core/cache");
|
|
43
43
|
let _mastra_core_loop = require("@mastra/core/loop");
|
|
44
|
+
let _mastra_core_storage = require("@mastra/core/storage");
|
|
44
45
|
let _mastra_core_utils = require("@mastra/core/utils");
|
|
45
46
|
let _mastra_core_agent_message_list = require("@mastra/core/agent/message-list");
|
|
46
47
|
let _mastra_core_workflows__constants = require("@mastra/core/workflows/_constants");
|
|
47
48
|
let zod = require("zod");
|
|
49
|
+
// src/durable-event-payload.ts
|
|
50
|
+
/**
|
|
51
|
+
* Lease on an InngestAgent resume claim until its event starts. A claim whose event never started
|
|
52
|
+
* (its resume died before sending, or the send failed) lapses, and a later resume takes it over.
|
|
53
|
+
*/
|
|
54
|
+
const RESUME_CLAIM_DISPATCH_LEASE_MS = 6e4;
|
|
55
|
+
/**
|
|
56
|
+
* Flatten a `RequestContext` into the plain JSON object the event carries.
|
|
57
|
+
* Absent context serializes to `{}`, never `undefined`.
|
|
58
|
+
*/
|
|
59
|
+
function serializeRequestContext(requestContext) {
|
|
60
|
+
const obj = requestContext ? requestContext.toJSON() : {};
|
|
61
|
+
delete obj[_mastra_core_request_context.MASTRA_AUTH_TOKEN_KEY];
|
|
62
|
+
return obj;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Resume request-context rule: values persisted in the snapshot are the base,
|
|
66
|
+
* and anything the caller supplies on this resume call overrides them.
|
|
67
|
+
*/
|
|
68
|
+
function mergeResumeRequestContext(snapshotRequestContext, requestContext) {
|
|
69
|
+
return {
|
|
70
|
+
...snapshotRequestContext ?? {},
|
|
71
|
+
...serializeRequestContext(requestContext)
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function buildDurableTriggerEventData(args) {
|
|
75
|
+
const { requestContext, ...rest } = args;
|
|
76
|
+
return {
|
|
77
|
+
...rest,
|
|
78
|
+
requestContext: toRequestContextEntries(requestContext)
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function buildDurableResumeEventData(args) {
|
|
82
|
+
const { requestContext, ...rest } = args;
|
|
83
|
+
return {
|
|
84
|
+
...rest,
|
|
85
|
+
requestContext: toRequestContextEntries(requestContext)
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function buildDurableTimeTravelEventData(args) {
|
|
89
|
+
const { requestContext, ...rest } = args;
|
|
90
|
+
return {
|
|
91
|
+
...rest,
|
|
92
|
+
requestContext: toRequestContextEntries(requestContext)
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
function toRequestContextEntries(requestContext) {
|
|
96
|
+
if (!requestContext) return {};
|
|
97
|
+
return typeof requestContext.toJSON === "function" ? serializeRequestContext(requestContext) : requestContext;
|
|
98
|
+
}
|
|
48
99
|
// src/nested-workflow-output.ts
|
|
49
100
|
const NESTED_WORKFLOW_OUTPUT_MODE = {
|
|
50
101
|
DEFAULT: "default",
|
|
@@ -105,6 +156,10 @@ function workflowTermination(...args) {
|
|
|
105
156
|
function agentLoopTermination(...args) {
|
|
106
157
|
return _mastra_core_features.coreFeatures.has("execution-outcomes") ? _mastra_core_observability.agentLoopTermination?.(...args) ?? {} : {};
|
|
107
158
|
}
|
|
159
|
+
/** End the caller's live root spans with `error`; a no-op on cores without the helper. */
|
|
160
|
+
function endRunSpansWithError(...args) {
|
|
161
|
+
if (_mastra_core_features.coreFeatures.has("execution-outcomes")) _mastra_core_agent_durable.endRunSpansWithError?.(...args);
|
|
162
|
+
}
|
|
108
163
|
/** Keep completed-request usage when a failed request makes the total incomplete. */
|
|
109
164
|
function generationUsage(usage, steps) {
|
|
110
165
|
const usageIncomplete = _mastra_core_features.coreFeatures.has("execution-outcomes") && _mastra_core_observability.isUsageIncomplete?.(usage);
|
|
@@ -464,7 +519,9 @@ var InngestExecutionEngine = class extends _mastra_core_workflows.DefaultExecuti
|
|
|
464
519
|
runId,
|
|
465
520
|
steps: nestedResumeSteps,
|
|
466
521
|
resumePayload: resume.resumePayload,
|
|
467
|
-
resumePath: nestedResumeStepId ? snapshot?.suspendedPaths?.[nestedResumeStepId] : void 0
|
|
522
|
+
resumePath: nestedResumeStepId ? snapshot?.suspendedPaths?.[nestedResumeStepId] : void 0,
|
|
523
|
+
label: resume.label,
|
|
524
|
+
forEachIndex: resume.label ? snapshot?.resumeLabels?.[resume.label]?.foreachIndex : void 0
|
|
468
525
|
} },
|
|
469
526
|
outputOptions: {
|
|
470
527
|
includeState: true,
|
|
@@ -582,6 +639,26 @@ var InngestExecutionEngine = class extends _mastra_core_workflows.DefaultExecuti
|
|
|
582
639
|
const suspendedSteps = Object.entries(result.steps).filter(([_stepName, stepResult]) => {
|
|
583
640
|
return stepResult?.status === "suspended";
|
|
584
641
|
});
|
|
642
|
+
const agentInput = stepResults.input;
|
|
643
|
+
const resumedCallFinished = isResume && !!resume?.label && !result.resumeLabels?.[resume.label];
|
|
644
|
+
const parked = (suspendedSteps[0]?.[1])?.suspendPayload;
|
|
645
|
+
const approval = parked?.requireToolApproval;
|
|
646
|
+
const parkedToolCallId = parked?.toolCallId ?? approval?.toolCallId;
|
|
647
|
+
let parkedBefore = false;
|
|
648
|
+
if (resumedCallFinished && agentInput?.__workflowKind === "durable-agent" && parkedToolCallId) parkedBefore = !!(await (await this.mastra?.getStorage()?.getStore("workflows"))?.loadWorkflowSnapshot({
|
|
649
|
+
workflowName: executionContext.workflowId,
|
|
650
|
+
runId: executionContext.runId
|
|
651
|
+
}))?.resumeLabels?.[parkedToolCallId];
|
|
652
|
+
if (parkedBefore && agentInput?.runId) {
|
|
653
|
+
const meta = parked?.__workflow_meta;
|
|
654
|
+
await (0, _mastra_core_agent_durable.emitSuspendedEvent)(pubsub, agentInput.runId, {
|
|
655
|
+
toolCallId: parkedToolCallId,
|
|
656
|
+
toolName: approval?.toolName ?? parked?.toolName,
|
|
657
|
+
args: approval?.args ?? parked?.args ?? meta?.foreachOutput?.[meta.foreachIndex]?.payload?.args,
|
|
658
|
+
suspendPayload: parked?.toolCallSuspended,
|
|
659
|
+
type: parked?.type === "approval" ? "approval" : "suspension"
|
|
660
|
+
});
|
|
661
|
+
}
|
|
585
662
|
for (const [stepName, stepResult] of suspendedSteps) {
|
|
586
663
|
const suspendPath = [stepName, ...stepResult?.suspendPayload?.__workflow_meta?.path ?? []];
|
|
587
664
|
executionContext.suspendedPaths[step.id] = executionContext.executionPath;
|
|
@@ -1073,51 +1150,6 @@ var InngestPubSub = class extends _mastra_core_events.PubSub {
|
|
|
1073
1150
|
this.subscriptions.clear();
|
|
1074
1151
|
}
|
|
1075
1152
|
};
|
|
1076
|
-
// src/durable-event-payload.ts
|
|
1077
|
-
/**
|
|
1078
|
-
* Flatten a `RequestContext` into the plain JSON object the event carries.
|
|
1079
|
-
* Absent context serializes to `{}`, never `undefined`.
|
|
1080
|
-
*/
|
|
1081
|
-
function serializeRequestContext(requestContext) {
|
|
1082
|
-
const obj = requestContext ? requestContext.toJSON() : {};
|
|
1083
|
-
delete obj[_mastra_core_request_context.MASTRA_AUTH_TOKEN_KEY];
|
|
1084
|
-
return obj;
|
|
1085
|
-
}
|
|
1086
|
-
/**
|
|
1087
|
-
* Resume request-context rule: values persisted in the snapshot are the base,
|
|
1088
|
-
* and anything the caller supplies on this resume call overrides them.
|
|
1089
|
-
*/
|
|
1090
|
-
function mergeResumeRequestContext(snapshotRequestContext, requestContext) {
|
|
1091
|
-
return {
|
|
1092
|
-
...snapshotRequestContext ?? {},
|
|
1093
|
-
...serializeRequestContext(requestContext)
|
|
1094
|
-
};
|
|
1095
|
-
}
|
|
1096
|
-
function buildDurableTriggerEventData(args) {
|
|
1097
|
-
const { requestContext, ...rest } = args;
|
|
1098
|
-
return {
|
|
1099
|
-
...rest,
|
|
1100
|
-
requestContext: toRequestContextEntries(requestContext)
|
|
1101
|
-
};
|
|
1102
|
-
}
|
|
1103
|
-
function buildDurableResumeEventData(args) {
|
|
1104
|
-
const { requestContext, ...rest } = args;
|
|
1105
|
-
return {
|
|
1106
|
-
...rest,
|
|
1107
|
-
requestContext: toRequestContextEntries(requestContext)
|
|
1108
|
-
};
|
|
1109
|
-
}
|
|
1110
|
-
function buildDurableTimeTravelEventData(args) {
|
|
1111
|
-
const { requestContext, ...rest } = args;
|
|
1112
|
-
return {
|
|
1113
|
-
...rest,
|
|
1114
|
-
requestContext: toRequestContextEntries(requestContext)
|
|
1115
|
-
};
|
|
1116
|
-
}
|
|
1117
|
-
function toRequestContextEntries(requestContext) {
|
|
1118
|
-
if (!requestContext) return {};
|
|
1119
|
-
return typeof requestContext.toJSON === "function" ? serializeRequestContext(requestContext) : requestContext;
|
|
1120
|
-
}
|
|
1121
1153
|
// src/run.ts
|
|
1122
1154
|
var InngestRun = class extends _mastra_core_workflows.Run {
|
|
1123
1155
|
inngest;
|
|
@@ -1838,6 +1870,8 @@ var InngestWorkflow = class extends _mastra_core_workflows.Workflow {
|
|
|
1838
1870
|
*/
|
|
1839
1871
|
#pubsubFactory;
|
|
1840
1872
|
#emitWorkflowEvents = true;
|
|
1873
|
+
/** Functions a host (e.g. the durable agent loop) serves alongside this workflow's own. */
|
|
1874
|
+
#hostFunctions = [];
|
|
1841
1875
|
constructor(params, inngest) {
|
|
1842
1876
|
const { concurrency, rateLimit, throttle, debounce, priority, retries, cron, inputData, initialState, ...workflowParams } = params;
|
|
1843
1877
|
super(workflowParams);
|
|
@@ -1902,6 +1936,9 @@ var InngestWorkflow = class extends _mastra_core_workflows.Workflow {
|
|
|
1902
1936
|
this.__setEmitWorkflowEvents(this.#emitWorkflowEvents);
|
|
1903
1937
|
return committed;
|
|
1904
1938
|
}
|
|
1939
|
+
__addHostFunctions(functions) {
|
|
1940
|
+
this.#hostFunctions.push(...functions);
|
|
1941
|
+
}
|
|
1905
1942
|
__setEmitWorkflowEvents(enabled) {
|
|
1906
1943
|
this.#emitWorkflowEvents = enabled;
|
|
1907
1944
|
const updateNested = (step) => {
|
|
@@ -2033,6 +2070,18 @@ var InngestWorkflow = class extends _mastra_core_workflows.Workflow {
|
|
|
2033
2070
|
});
|
|
2034
2071
|
this.logger.warn?.(`Workflow "${this.id}" was triggered without a runId, so run "${runId}" cannot be cancelled by id. Send \`data.runId\` on the trigger event (or start the run with createRun()) to make it cancellable.`);
|
|
2035
2072
|
}
|
|
2073
|
+
const resumeClaim = resume?.claim;
|
|
2074
|
+
if (resumeClaim) {
|
|
2075
|
+
if (!await step.run(`workflow.${this.id}.resume-claim`, async () => {
|
|
2076
|
+
return (await (await this.#mastra?.getStorage()?.getStore("workflows"))?.renewRunOwnership({
|
|
2077
|
+
...resumeClaim,
|
|
2078
|
+
leaseMs: 864e5
|
|
2079
|
+
}))?.renewed ?? true;
|
|
2080
|
+
})) return {
|
|
2081
|
+
result: void 0,
|
|
2082
|
+
runId
|
|
2083
|
+
};
|
|
2084
|
+
}
|
|
2036
2085
|
if (resume && (initialState === void 0 || resume.stepResults === void 0)) {
|
|
2037
2086
|
const snapshot = await (await this.#mastra?.getStorage()?.getStore("workflows"))?.loadWorkflowSnapshot({
|
|
2038
2087
|
workflowName: this.id,
|
|
@@ -2211,6 +2260,7 @@ var InngestWorkflow = class extends _mastra_core_workflows.Workflow {
|
|
|
2211
2260
|
});
|
|
2212
2261
|
}
|
|
2213
2262
|
}
|
|
2263
|
+
if (resumeClaim) await (await mastra?.getStorage()?.getStore("workflows"))?.releaseRunOwnership(resumeClaim);
|
|
2214
2264
|
try {
|
|
2215
2265
|
await pubsub.publish(`workflow.events.v2.${runId}`, {
|
|
2216
2266
|
type: "watch",
|
|
@@ -2266,7 +2316,8 @@ var InngestWorkflow = class extends _mastra_core_workflows.Workflow {
|
|
|
2266
2316
|
return [
|
|
2267
2317
|
this.getFunction(),
|
|
2268
2318
|
...this.cronConfig?.cron ? [this.createCronFunction()] : [],
|
|
2269
|
-
...this.getNestedFunctions(this.executionGraph.steps)
|
|
2319
|
+
...this.getNestedFunctions(this.executionGraph.steps),
|
|
2320
|
+
...this.#hostFunctions
|
|
2270
2321
|
];
|
|
2271
2322
|
}
|
|
2272
2323
|
};
|
|
@@ -2396,6 +2447,7 @@ const durableAgenticInputSchema = zod.z.object({
|
|
|
2396
2447
|
* Iteration state schema - extends base with observability fields.
|
|
2397
2448
|
*/
|
|
2398
2449
|
const iterationStateSchema = _mastra_core_agent_durable.baseIterationStateSchema.extend({
|
|
2450
|
+
accumulatedSteps: zod.z.array(zod.z.any()),
|
|
2399
2451
|
modelList: zod.z.array(_mastra_core_agent_durable.modelListEntrySchema).optional(),
|
|
2400
2452
|
agentSpanData: zod.z.any().optional(),
|
|
2401
2453
|
modelSpanData: zod.z.any().optional(),
|
|
@@ -2425,7 +2477,77 @@ const InngestDurableStepIds = {
|
|
|
2425
2477
|
AGENTIC_EXECUTION: `${INNGEST_ENGINE_PREFIX}:${_mastra_core_agent_durable.DurableStepIds.AGENTIC_EXECUTION}`,
|
|
2426
2478
|
AGENTIC_LOOP: `${INNGEST_ENGINE_PREFIX}:${_mastra_core_agent_durable.DurableStepIds.AGENTIC_LOOP}`
|
|
2427
2479
|
};
|
|
2480
|
+
/** Run ownership key of the claim an InngestAgent resume holds on the loop run. */
|
|
2481
|
+
const resumeClaimKey = (runId) => `${InngestDurableStepIds.AGENTIC_LOOP}:resume-claim:${runId}`;
|
|
2482
|
+
/**
|
|
2483
|
+
* The store a resume claim lives in. A claim needs an atomic status change and a lease, so a
|
|
2484
|
+
* claim whose resume died can be taken over; without both, resumes are not claimed at all.
|
|
2485
|
+
*/
|
|
2486
|
+
async function resumeClaimStore(mastra) {
|
|
2487
|
+
const store = await mastra?.getStorage()?.getStore("workflows");
|
|
2488
|
+
if (!store?.supportsConcurrentUpdates?.()) return void 0;
|
|
2489
|
+
return await Promise.resolve().then(() => store.supportsRunFencing()).catch(() => false) ? store : void 0;
|
|
2490
|
+
}
|
|
2491
|
+
const setLoopStatus = (store, runId, status, expectedStatus) => store.updateWorkflowState({
|
|
2492
|
+
workflowName: InngestDurableStepIds.AGENTIC_LOOP,
|
|
2493
|
+
runId,
|
|
2494
|
+
opts: {
|
|
2495
|
+
status,
|
|
2496
|
+
expectedStatus
|
|
2497
|
+
}
|
|
2498
|
+
});
|
|
2499
|
+
/**
|
|
2500
|
+
* Ends a resumed segment Inngest failed or cancelled, which never reaches the finalize step that
|
|
2501
|
+
* would: marks the run failed or canceled, ends its stream and releases its claim. The run is not
|
|
2502
|
+
* parked again, since a nested segment Inngest did not cancel can still be running its tools.
|
|
2503
|
+
*/
|
|
2504
|
+
function createResumeClaimReleaseFunction(inngest, workflow) {
|
|
2505
|
+
const loopEvent = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;
|
|
2506
|
+
return inngest.createFunction({
|
|
2507
|
+
id: `${loopEvent}.resume-claim-release`,
|
|
2508
|
+
triggers: [{
|
|
2509
|
+
event: "inngest/function.failed",
|
|
2510
|
+
if: `event.data.event.name == '${loopEvent}'`
|
|
2511
|
+
}, {
|
|
2512
|
+
event: "inngest/function.cancelled",
|
|
2513
|
+
if: `event.data.event.name == '${loopEvent}'`
|
|
2514
|
+
}]
|
|
2515
|
+
}, async ({ event }) => {
|
|
2516
|
+
const original = event.data.event?.data;
|
|
2517
|
+
const claim = original?.resume?.claim;
|
|
2518
|
+
const mastra = workflow.mastra;
|
|
2519
|
+
const store = await resumeClaimStore(mastra);
|
|
2520
|
+
if (!original?.runId || !claim || !store) return;
|
|
2521
|
+
if (!(await store.renewRunOwnership({
|
|
2522
|
+
...claim,
|
|
2523
|
+
leaseMs: 6e4
|
|
2524
|
+
})).renewed) return;
|
|
2525
|
+
const cancelled = event.name === "inngest/function.cancelled";
|
|
2526
|
+
await setLoopStatus(store, original.runId, cancelled ? "canceled" : "failed", "running");
|
|
2527
|
+
const defaultPubsub = new InngestPubSub(inngest, workflow.id, mastra?.getLogger?.());
|
|
2528
|
+
const pubsub = workflow.__getPubsubFactory()?.(defaultPubsub) ?? defaultPubsub;
|
|
2529
|
+
try {
|
|
2530
|
+
if (cancelled) await (0, _mastra_core_agent_durable.emitAbortEvent)(pubsub, original.runId, {
|
|
2531
|
+
steps: [],
|
|
2532
|
+
text: ""
|
|
2533
|
+
});
|
|
2534
|
+
else {
|
|
2535
|
+
const message = event.data.error?.message;
|
|
2536
|
+
await (0, _mastra_core_agent_durable.emitErrorEvent)(pubsub, original.runId, new Error(message ?? "The resumed agent run failed."));
|
|
2537
|
+
}
|
|
2538
|
+
} catch (error) {
|
|
2539
|
+
mastra?.getLogger?.()?.warn?.(`[InngestAgent] run ${original.runId} failed to publish its end`, error);
|
|
2540
|
+
}
|
|
2541
|
+
await store.releaseRunOwnership(claim);
|
|
2542
|
+
});
|
|
2543
|
+
}
|
|
2428
2544
|
function createInngestDurableAgenticWorkflow(options) {
|
|
2545
|
+
const workflow = createAgenticLoopWorkflow(options);
|
|
2546
|
+
const inngestWorkflow = workflow;
|
|
2547
|
+
inngestWorkflow.__addHostFunctions([createResumeClaimReleaseFunction(options.inngest, inngestWorkflow)]);
|
|
2548
|
+
return workflow;
|
|
2549
|
+
}
|
|
2550
|
+
function createAgenticLoopWorkflow(options) {
|
|
2429
2551
|
const { inngest, maxSteps = _mastra_core_agent_durable.DurableAgentDefaults.MAX_STEPS, retries } = options;
|
|
2430
2552
|
const { createWorkflow } = init(inngest);
|
|
2431
2553
|
const llmExecutionStep = (0, _mastra_core_agent_durable.createDurableLLMExecutionStep)();
|
|
@@ -2567,8 +2689,12 @@ function createInngestDurableAgenticWorkflow(options) {
|
|
|
2567
2689
|
});
|
|
2568
2690
|
}
|
|
2569
2691
|
};
|
|
2692
|
+
const recordStopCause = (cause) => {
|
|
2693
|
+
state.tracingStopCause = cause;
|
|
2694
|
+
if (tracingRegistry) tracingRegistry.tracingStopCause = cause;
|
|
2695
|
+
};
|
|
2570
2696
|
if (state.delegationBailed) {
|
|
2571
|
-
|
|
2697
|
+
recordStopCause(state.lastStepResult?.isContinued ? "delegation" : "model_finished");
|
|
2572
2698
|
await emitStepFinish(false);
|
|
2573
2699
|
return false;
|
|
2574
2700
|
}
|
|
@@ -2576,7 +2702,7 @@ function createInngestDurableAgenticWorkflow(options) {
|
|
|
2576
2702
|
const effectiveMaxSteps = state.options?.maxSteps ?? maxSteps;
|
|
2577
2703
|
const underMaxSteps = state.iterationCount < effectiveMaxSteps;
|
|
2578
2704
|
if (!shouldContinue || !underMaxSteps) {
|
|
2579
|
-
|
|
2705
|
+
recordStopCause(shouldContinue ? "max_steps" : "model_finished");
|
|
2580
2706
|
await emitStepFinish(false);
|
|
2581
2707
|
return false;
|
|
2582
2708
|
}
|
|
@@ -2602,7 +2728,7 @@ function createInngestDurableAgenticWorkflow(options) {
|
|
|
2602
2728
|
}
|
|
2603
2729
|
}))).some(Boolean);
|
|
2604
2730
|
});
|
|
2605
|
-
if (stopped
|
|
2731
|
+
if (stopped) recordStopCause("stop_condition");
|
|
2606
2732
|
await emitStepFinish(!stopped);
|
|
2607
2733
|
return !stopped;
|
|
2608
2734
|
}).map(async (params) => {
|
|
@@ -2683,6 +2809,17 @@ function createInngestDurableAgenticWorkflow(options) {
|
|
|
2683
2809
|
...completionClock ? { completionStartTime: new Date(completionClock) } : {},
|
|
2684
2810
|
...timeToFirstTokenMs !== void 0 ? { timeToFirstTokenMs } : {}
|
|
2685
2811
|
};
|
|
2812
|
+
const finishReason = finalOutput.stepResult?.reason;
|
|
2813
|
+
const stopCause = state.tracingStopCause ?? registry?.tracingStopCause;
|
|
2814
|
+
const recordedTermination = state.tracingTermination ?? registry?.tracingTermination;
|
|
2815
|
+
if (!stopCause && (finishReason === "stop" || finishReason === "tool-calls")) mastra?.getLogger?.()?.warn?.(`[InngestDurableAgent] Run ${state.runId} has no recorded stop cause; its span outcome is unknown`);
|
|
2816
|
+
const termination = ["tripwire", "error"].includes(finishReason ?? "") && recordedTermination ? recordedTermination : agentLoopTermination({
|
|
2817
|
+
stopCause,
|
|
2818
|
+
delegationFailure: state.tracingDelegationFailure ?? registry?.tracingDelegationFailure,
|
|
2819
|
+
finishReason,
|
|
2820
|
+
tripwire: tripwire ?? state.lastStepResult?.tripwire,
|
|
2821
|
+
maxSteps: state.options?.maxSteps ?? maxSteps
|
|
2822
|
+
});
|
|
2686
2823
|
if (state.modelSpanData) {
|
|
2687
2824
|
const modelSpan = registry?.resumeModelSpan ?? registry?.modelSpan ?? observability?.rebuildSpan(state.modelSpanData);
|
|
2688
2825
|
const toolCalls = state.accumulatedSteps.flatMap((step) => (step.toolCalls ?? []).map((tc) => ({
|
|
@@ -2692,13 +2829,7 @@ function createInngestDurableAgenticWorkflow(options) {
|
|
|
2692
2829
|
})));
|
|
2693
2830
|
const { usageIncomplete, usage } = generationUsage(state.accumulatedUsage, state.accumulatedSteps);
|
|
2694
2831
|
modelSpan?.createTracker()?.endGeneration({
|
|
2695
|
-
...
|
|
2696
|
-
stopCause: registry?.tracingStopCause,
|
|
2697
|
-
delegationFailure: registry?.tracingDelegationFailure,
|
|
2698
|
-
finishReason: finalOutput.stepResult?.reason,
|
|
2699
|
-
tripwire,
|
|
2700
|
-
maxSteps: state.options?.maxSteps ?? maxSteps
|
|
2701
|
-
}),
|
|
2832
|
+
...termination,
|
|
2702
2833
|
output: {
|
|
2703
2834
|
text: finalText,
|
|
2704
2835
|
...toolCalls.length ? { toolCalls } : {}
|
|
@@ -2714,13 +2845,7 @@ function createInngestDurableAgenticWorkflow(options) {
|
|
|
2714
2845
|
});
|
|
2715
2846
|
}
|
|
2716
2847
|
if (state.agentSpanData) (registry?.resumeAgentSpan ?? registry?.agentSpan ?? observability?.rebuildSpan(state.agentSpanData))?.end({
|
|
2717
|
-
...
|
|
2718
|
-
stopCause: registry?.tracingStopCause,
|
|
2719
|
-
delegationFailure: registry?.tracingDelegationFailure,
|
|
2720
|
-
finishReason: finalOutput.stepResult?.reason,
|
|
2721
|
-
tripwire,
|
|
2722
|
-
maxSteps: state.options?.maxSteps ?? maxSteps
|
|
2723
|
-
}),
|
|
2848
|
+
...termination,
|
|
2724
2849
|
output: { text: finalText },
|
|
2725
2850
|
...Object.keys(clocks).length ? { attributes: clocks } : {}
|
|
2726
2851
|
});
|
|
@@ -2835,6 +2960,43 @@ var InngestAgentPubSubRouter = class extends _mastra_core_events.PubSub {
|
|
|
2835
2960
|
const STREAM_CLEANUP = Symbol("mastra.durable.inngest.streamCleanup");
|
|
2836
2961
|
const RESUME_SNAPSHOT_WAIT_MS = 1e4;
|
|
2837
2962
|
const RESUME_SNAPSHOT_POLL_MS = 100;
|
|
2963
|
+
/** runId -> toolCallId -> token of the resume of that tool call in flight in this process. */
|
|
2964
|
+
const inFlightToolCallResumes = /* @__PURE__ */ new Map();
|
|
2965
|
+
/** Names this process in resume claim owner ids, to recognize its own claims. */
|
|
2966
|
+
const RESUME_CLAIM_PROCESS_ID = crypto.randomUUID();
|
|
2967
|
+
/**
|
|
2968
|
+
* Marks a resume of `toolCallId` as in flight. Returns `undefined` when another resume already
|
|
2969
|
+
* holds the mark. The returned release only clears its own mark.
|
|
2970
|
+
*/
|
|
2971
|
+
function markToolCallResume(runId, toolCallId) {
|
|
2972
|
+
const token = Symbol(toolCallId);
|
|
2973
|
+
const marks = inFlightToolCallResumes.get(runId) ?? /* @__PURE__ */ new Map();
|
|
2974
|
+
if (marks.has(toolCallId)) return void 0;
|
|
2975
|
+
marks.set(toolCallId, token);
|
|
2976
|
+
inFlightToolCallResumes.set(runId, marks);
|
|
2977
|
+
return () => {
|
|
2978
|
+
if (marks.get(toolCallId) !== token) return;
|
|
2979
|
+
marks.delete(toolCallId);
|
|
2980
|
+
if (marks.size === 0) inFlightToolCallResumes.delete(runId);
|
|
2981
|
+
};
|
|
2982
|
+
}
|
|
2983
|
+
function resumeAlreadyClaimedError(agentName, runId, toolCallId) {
|
|
2984
|
+
return new _mastra_core_error.MastraError({
|
|
2985
|
+
id: "AGENT_RESUME_ALREADY_CLAIMED",
|
|
2986
|
+
domain: _mastra_core_error.ErrorDomain.AGENT,
|
|
2987
|
+
category: _mastra_core_error.ErrorCategory.USER,
|
|
2988
|
+
text: `InngestAgent "${agentName}" resume(${runId}) cannot resume the run because another resume of it is already running.`,
|
|
2989
|
+
details: {
|
|
2990
|
+
agentName,
|
|
2991
|
+
runId,
|
|
2992
|
+
...toolCallId ? { toolCallId } : {}
|
|
2993
|
+
}
|
|
2994
|
+
});
|
|
2995
|
+
}
|
|
2996
|
+
/** A second approval of a tool call this process is already resuming fails right away (#27485). */
|
|
2997
|
+
function assertToolCallResumeNotInFlight(agentName, runId, toolCallId) {
|
|
2998
|
+
if (toolCallId && inFlightToolCallResumes.get(runId)?.has(toolCallId)) throw resumeAlreadyClaimedError(agentName, runId, toolCallId);
|
|
2999
|
+
}
|
|
2838
3000
|
/**
|
|
2839
3001
|
* Merges the wrapped agent's `defaultOptions` under the call options, matching
|
|
2840
3002
|
* core `DurableAgent`, so lifecycle callbacks configured as defaults fire unless
|
|
@@ -2882,21 +3044,23 @@ function createInngestAgent(options) {
|
|
|
2882
3044
|
retries
|
|
2883
3045
|
});
|
|
2884
3046
|
let _customCache = cache;
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
|
|
2891
|
-
|
|
3047
|
+
const innerPubsub = customPubsub ?? new InngestPubSub(inngest$1, InngestDurableStepIds.AGENTIC_LOOP);
|
|
3048
|
+
const streams = new _mastra_core_agent_durable.AgentStreamBus({
|
|
3049
|
+
pubsub: innerPubsub,
|
|
3050
|
+
cache
|
|
3051
|
+
}, {
|
|
3052
|
+
getMastra: () => mastra,
|
|
3053
|
+
usesSharedRunLog: () => false,
|
|
3054
|
+
warn: (message) => console.warn(`InngestAgent '${idOverride ?? agent.id}': ${message}`)
|
|
3055
|
+
});
|
|
3056
|
+
let busResolved = false;
|
|
2892
3057
|
function getPubsub() {
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
} else _cachingPubsub = new _mastra_core_events.CachingPubSub(innerPubsub, resolveCache());
|
|
3058
|
+
const pubsub = streams.pubsub;
|
|
3059
|
+
if (!busResolved) {
|
|
3060
|
+
busResolved = true;
|
|
3061
|
+
_customCache ??= innerPubsub instanceof _mastra_core_events.CachingPubSub ? mastra?.serverCache : streams.cache ?? void 0;
|
|
2898
3062
|
}
|
|
2899
|
-
return
|
|
3063
|
+
return pubsub;
|
|
2900
3064
|
}
|
|
2901
3065
|
async function getPubsubOffset(runId) {
|
|
2902
3066
|
return (await getPubsub().getHistory((0, _mastra_core_agent_durable.AGENT_STREAM_TOPIC)(runId))).length;
|
|
@@ -2946,18 +3110,30 @@ function createInngestAgent(options) {
|
|
|
2946
3110
|
async function deleteFencedSuspendedRun(runId) {
|
|
2947
3111
|
try {
|
|
2948
3112
|
const workflowsStore = await mastra?.getStorage()?.getStore("workflows");
|
|
2949
|
-
|
|
2950
|
-
runId,
|
|
2951
|
-
workflowName: InngestDurableStepIds.AGENTIC_LOOP
|
|
2952
|
-
}))?.status !== "suspended") return;
|
|
2953
|
-
await workflowsStore?.deleteWorkflowRunById({
|
|
3113
|
+
const snapshot = await workflowsStore?.loadWorkflowSnapshot({
|
|
2954
3114
|
runId,
|
|
2955
3115
|
workflowName: InngestDurableStepIds.AGENTIC_LOOP
|
|
2956
3116
|
});
|
|
2957
|
-
await
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
3117
|
+
const store = await resumeClaimStore(mastra);
|
|
3118
|
+
const owner = await store?.getRunOwnership({ runId: resumeClaimKey(runId) });
|
|
3119
|
+
const parked = !owner?.live && (snapshot?.status === "suspended" || snapshot?.status === "running" && Object.keys(snapshot.suspendedPaths ?? {}).length > 0);
|
|
3120
|
+
const fence = parked && store ? await store.claimRunOwnership({
|
|
3121
|
+
runId: resumeClaimKey(runId),
|
|
3122
|
+
ownerId: `${RESUME_CLAIM_PROCESS_ID}/${crypto.randomUUID()}/`,
|
|
3123
|
+
leaseMs: RESUME_CLAIM_DISPATCH_LEASE_MS,
|
|
3124
|
+
expectedGeneration: owner?.generation ?? 0
|
|
3125
|
+
}) : void 0;
|
|
3126
|
+
if (fence?.acquired) await store?.releaseRunOwnership(fence.record);
|
|
3127
|
+
if (parked && (!store || fence?.acquired)) {
|
|
3128
|
+
await workflowsStore?.deleteWorkflowRunById({
|
|
3129
|
+
runId,
|
|
3130
|
+
workflowName: InngestDurableStepIds.AGENTIC_LOOP
|
|
3131
|
+
});
|
|
3132
|
+
await workflowsStore?.deleteWorkflowRunById({
|
|
3133
|
+
runId,
|
|
3134
|
+
workflowName: InngestDurableStepIds.AGENTIC_EXECUTION
|
|
3135
|
+
});
|
|
3136
|
+
}
|
|
2961
3137
|
await (0, _mastra_core_agent_durable.emitAbortEvent)(getPubsub(), runId, {
|
|
2962
3138
|
steps: [],
|
|
2963
3139
|
text: ""
|
|
@@ -3068,6 +3244,62 @@ function createInngestAgent(options) {
|
|
|
3068
3244
|
return false;
|
|
3069
3245
|
}
|
|
3070
3246
|
}
|
|
3247
|
+
/** The live lease of the resume holding the run's claim, if any. */
|
|
3248
|
+
async function liveResumeClaim(runId) {
|
|
3249
|
+
const owner = await (await resumeClaimStore(mastra))?.getRunOwnership({ runId: resumeClaimKey(runId) });
|
|
3250
|
+
return owner?.live ? owner : void 0;
|
|
3251
|
+
}
|
|
3252
|
+
/**
|
|
3253
|
+
* Claims a suspension read by `resume()` (`suspended` -> `running`) so no other resume, in this
|
|
3254
|
+
* process or another, dispatches it again (#27485, #27925). The lease is taken first and is the
|
|
3255
|
+
* mutex: a `running` snapshot without a live lease is a claim whose event never started, which
|
|
3256
|
+
* this resume takes over. Returns `undefined` when another resume got there first.
|
|
3257
|
+
*/
|
|
3258
|
+
async function claimSuspension(runId, snapshot, toolCallId) {
|
|
3259
|
+
const store = await resumeClaimStore(mastra);
|
|
3260
|
+
if (!store || !snapshot.status) return { release: async () => {} };
|
|
3261
|
+
const key = resumeClaimKey(runId);
|
|
3262
|
+
const owner = await store.getRunOwnership({ runId: key });
|
|
3263
|
+
if (owner?.live) return void 0;
|
|
3264
|
+
const ownerId = `${RESUME_CLAIM_PROCESS_ID}/${crypto.randomUUID()}/${toolCallId ?? ""}`;
|
|
3265
|
+
const lease = await store.claimRunOwnership({
|
|
3266
|
+
runId: key,
|
|
3267
|
+
ownerId,
|
|
3268
|
+
leaseMs: RESUME_CLAIM_DISPATCH_LEASE_MS,
|
|
3269
|
+
expectedGeneration: owner?.generation ?? 0
|
|
3270
|
+
});
|
|
3271
|
+
if (!lease.acquired) return void 0;
|
|
3272
|
+
const fence = {
|
|
3273
|
+
runId: key,
|
|
3274
|
+
generation: lease.record.generation,
|
|
3275
|
+
ownerId
|
|
3276
|
+
};
|
|
3277
|
+
const claimed = await setLoopStatus(store, runId, "running", snapshot.status);
|
|
3278
|
+
if (claimed?.timestamp !== snapshot.timestamp) {
|
|
3279
|
+
if (claimed && snapshot.status !== "running") await setLoopStatus(store, runId, "suspended", "running");
|
|
3280
|
+
await store.releaseRunOwnership(fence);
|
|
3281
|
+
return;
|
|
3282
|
+
}
|
|
3283
|
+
return {
|
|
3284
|
+
fence,
|
|
3285
|
+
release: async () => {
|
|
3286
|
+
if (!(0, _mastra_core_storage.matchesRunFence)(await store.getRunOwnership({ runId: key }), fence)) return;
|
|
3287
|
+
await setLoopStatus(store, runId, "suspended", "running");
|
|
3288
|
+
await store.releaseRunOwnership(fence);
|
|
3289
|
+
}
|
|
3290
|
+
};
|
|
3291
|
+
}
|
|
3292
|
+
/**
|
|
3293
|
+
* Throws unless this resume may wait for the live one holding the run: one resuming a different
|
|
3294
|
+
* call, or any resume once the holder's segment parked again in this process. Any other resume is a
|
|
3295
|
+
* duplicate, and waiting would hand its resume data to whatever the run suspends on next.
|
|
3296
|
+
*/
|
|
3297
|
+
function assertMayWaitFor(owner, runId, toolCallId) {
|
|
3298
|
+
const [ownerProcess, , ...label] = owner.ownerId.split("/");
|
|
3299
|
+
const ownerToolCallId = label.join("/");
|
|
3300
|
+
if (ownerProcess === RESUME_CLAIM_PROCESS_ID && !inFlightToolCallResumes.get(runId)?.has(ownerToolCallId) || toolCallId && ownerToolCallId !== toolCallId) return;
|
|
3301
|
+
throw resumeAlreadyClaimedError(agent.name, runId, toolCallId);
|
|
3302
|
+
}
|
|
3071
3303
|
/**
|
|
3072
3304
|
* Tool calls and text from before the suspension, seeded into the resumed stream
|
|
3073
3305
|
* so its `toolCalls` and `text` include them without replaying their chunks.
|
|
@@ -3172,15 +3404,6 @@ function createInngestAgent(options) {
|
|
|
3172
3404
|
* Best-effort: the local abort has already happened, and a caller asking to
|
|
3173
3405
|
* stop a run should not get a rejection because the publish failed.
|
|
3174
3406
|
*/
|
|
3175
|
-
function forwardExternalAbort(external, controller, runId) {
|
|
3176
|
-
const forward = () => {
|
|
3177
|
-
controller.abort(external.reason);
|
|
3178
|
-
requestRemoteAbort(runId);
|
|
3179
|
-
};
|
|
3180
|
-
if (external.aborted) forward();
|
|
3181
|
-
else external.addEventListener("abort", forward, { once: true });
|
|
3182
|
-
return () => external.removeEventListener("abort", forward);
|
|
3183
|
-
}
|
|
3184
3407
|
async function requestRemoteAbort(runId) {
|
|
3185
3408
|
try {
|
|
3186
3409
|
await (0, _mastra_core_agent_durable.publishAbortRequest)(getPubsub(), runId);
|
|
@@ -3266,8 +3489,7 @@ function createInngestAgent(options) {
|
|
|
3266
3489
|
const { runId, messageId, workflowInput, registryEntry, threadId, resourceId } = preparation;
|
|
3267
3490
|
workflowInput.agentId = agentId;
|
|
3268
3491
|
workflowInput.agentName = agentName;
|
|
3269
|
-
const abortController =
|
|
3270
|
-
const stopForwardingAbort = streamOptions?.abortSignal ? forwardExternalAbort(streamOptions.abortSignal, abortController, runId) : void 0;
|
|
3492
|
+
const { controller: abortController, detach: stopForwardingAbort } = (0, _mastra_core_agent_durable.createRunAbortController)(streamOptions?.abortSignal, { onExternalAbort: () => void requestRemoteAbort(runId) });
|
|
3271
3493
|
registryEntry.abortController = abortController;
|
|
3272
3494
|
const clearTotalTimeout = armTotalTimeout(registryEntry, abortController, runId, callbackOptions.modelSettings?.timeout?.totalMs);
|
|
3273
3495
|
registryEntry.messageList = preparation.messageList;
|
|
@@ -3366,6 +3588,7 @@ function createInngestAgent(options) {
|
|
|
3366
3588
|
throw error;
|
|
3367
3589
|
}
|
|
3368
3590
|
}).catch(async (error) => {
|
|
3591
|
+
endRunSpansWithError(runId, error);
|
|
3369
3592
|
await emitError(runId, error);
|
|
3370
3593
|
await failStream(error);
|
|
3371
3594
|
});
|
|
@@ -3418,6 +3641,11 @@ function createInngestAgent(options) {
|
|
|
3418
3641
|
bgManager: mastra?.backgroundTaskManager
|
|
3419
3642
|
});
|
|
3420
3643
|
}
|
|
3644
|
+
const markedToolCallId = resumeOptions?.toolCallId ?? "";
|
|
3645
|
+
if (inFlightToolCallResumes.get(runId)?.has(markedToolCallId)) {
|
|
3646
|
+
if (!await resumeClaimStore(mastra) || await liveResumeClaim(runId)) throw resumeAlreadyClaimedError(agent.name, runId, resumeOptions?.toolCallId);
|
|
3647
|
+
inFlightToolCallResumes.get(runId)?.delete(markedToolCallId);
|
|
3648
|
+
}
|
|
3421
3649
|
const existingRegistryEntry = (0, _mastra_core_agent_durable.getRunRegistryEntry)(runId, mastra);
|
|
3422
3650
|
await (existingRegistryEntry?.workflowExecution)?.catch(() => {});
|
|
3423
3651
|
const resumableSnapshot = (async () => {
|
|
@@ -3429,9 +3657,21 @@ function createInngestAgent(options) {
|
|
|
3429
3657
|
});
|
|
3430
3658
|
const toolCallId = resumeOptions?.toolCallId;
|
|
3431
3659
|
let nestedSnapshot;
|
|
3660
|
+
let held = false;
|
|
3432
3661
|
const isReady = async (s) => {
|
|
3433
3662
|
nestedSnapshot = void 0;
|
|
3434
|
-
|
|
3663
|
+
held = false;
|
|
3664
|
+
const claimed = s?.status === "running" && Object.keys(s.suspendedPaths ?? {}).length > 0;
|
|
3665
|
+
if (s?.status !== "suspended" && !claimed) return false;
|
|
3666
|
+
const owner = await liveResumeClaim(runId);
|
|
3667
|
+
if (owner) {
|
|
3668
|
+
held = true;
|
|
3669
|
+
if (s.status !== "suspended") assertMayWaitFor(owner, runId, toolCallId);
|
|
3670
|
+
return false;
|
|
3671
|
+
}
|
|
3672
|
+
if (claimed && !await resumeClaimStore(mastra)) return false;
|
|
3673
|
+
if (toolCallId && !s.resumeLabels?.[toolCallId]) return false;
|
|
3674
|
+
if (s.activePaths?.length) return false;
|
|
3435
3675
|
const labelIds = Object.keys(s.resumeLabels ?? {});
|
|
3436
3676
|
if (labelIds.length === 0) return true;
|
|
3437
3677
|
nestedSnapshot = await workflowsStore.loadWorkflowSnapshot({
|
|
@@ -3442,14 +3682,18 @@ function createInngestAgent(options) {
|
|
|
3442
3682
|
};
|
|
3443
3683
|
let snapshot = await loadSnapshot();
|
|
3444
3684
|
const deadline = Date.now() + RESUME_SNAPSHOT_WAIT_MS;
|
|
3445
|
-
|
|
3685
|
+
let ready;
|
|
3686
|
+
while (!(ready = await isReady(snapshot)) && Date.now() < deadline) {
|
|
3687
|
+
assertToolCallResumeNotInFlight(agent.name, runId, toolCallId);
|
|
3446
3688
|
await new Promise((resolve) => setTimeout(resolve, RESUME_SNAPSHOT_POLL_MS));
|
|
3447
3689
|
snapshot = await loadSnapshot();
|
|
3448
3690
|
}
|
|
3449
3691
|
return {
|
|
3450
3692
|
hasStore: true,
|
|
3451
3693
|
snapshot,
|
|
3452
|
-
nestedSnapshot
|
|
3694
|
+
nestedSnapshot,
|
|
3695
|
+
ready,
|
|
3696
|
+
held
|
|
3453
3697
|
};
|
|
3454
3698
|
})();
|
|
3455
3699
|
resumableSnapshot.catch(() => {});
|
|
@@ -3459,8 +3703,10 @@ function createInngestAgent(options) {
|
|
|
3459
3703
|
requestContext: new _mastra_core_request_context.RequestContext([...savedRequestContext, ...resumeOptions?.requestContext?.entries() ?? []])
|
|
3460
3704
|
});
|
|
3461
3705
|
(0, _mastra_core_agent_durable.validateModelTimeoutSettings)(callbackOptions.modelSettings?.timeout);
|
|
3462
|
-
const { hasStore, snapshot: suspendedSnapshot, nestedSnapshot } = await resumableSnapshot;
|
|
3463
|
-
|
|
3706
|
+
const { hasStore, snapshot: suspendedSnapshot, nestedSnapshot, ready: snapshotReady, held } = await resumableSnapshot;
|
|
3707
|
+
const takeover = snapshotReady && suspendedSnapshot?.status === "running";
|
|
3708
|
+
if (held || !takeover && suspendedSnapshot?.status === "running" && Object.keys(suspendedSnapshot.suspendedPaths ?? {}).length) throw resumeAlreadyClaimedError(agent.name, runId, resumeOptions?.toolCallId);
|
|
3709
|
+
if (hasStore && !takeover && suspendedSnapshot?.status !== "suspended") throw new inngest.NonRetriableError(`Cannot resume run ${runId}: it is not suspended` + (suspendedSnapshot?.status ? ` (status: ${suspendedSnapshot.status}).` : " (no snapshot found)."));
|
|
3464
3710
|
const suspendedStepIds = suspendedSnapshot?.suspendedPaths ? Object.keys(suspendedSnapshot.suspendedPaths) : [];
|
|
3465
3711
|
const resumeLabels = suspendedSnapshot?.resumeLabels ?? {};
|
|
3466
3712
|
const expandToLeafPath = (stepId) => {
|
|
@@ -3471,7 +3717,7 @@ function createInngestAgent(options) {
|
|
|
3471
3717
|
let steps;
|
|
3472
3718
|
if (toolCallId) {
|
|
3473
3719
|
const targetStepId = resumeLabels[toolCallId]?.stepId;
|
|
3474
|
-
if (!targetStepId) {
|
|
3720
|
+
if (!targetStepId || nestedSnapshot && !nestedSnapshot.resumeLabels?.[toolCallId]) {
|
|
3475
3721
|
const available = Object.keys(resumeLabels);
|
|
3476
3722
|
throw new inngest.NonRetriableError(`Cannot resume run ${runId}: no suspended tool call with id "${toolCallId}". ` + (available.length > 0 ? `Suspended tool call ids: ${available.join(", ")}.` : `No tool calls are currently suspended.`));
|
|
3477
3723
|
}
|
|
@@ -3483,8 +3729,16 @@ function createInngestAgent(options) {
|
|
|
3483
3729
|
}
|
|
3484
3730
|
const resumeOffset = await getPubsubOffset(runId);
|
|
3485
3731
|
const { toolCalls: initialToolCalls, resumedText } = await loadSuspendedIteration(runId, suspendedSnapshot, nestedSnapshot);
|
|
3486
|
-
const
|
|
3487
|
-
const
|
|
3732
|
+
const markKey = toolCallId ?? (await resumeClaimStore(mastra) ? "" : void 0);
|
|
3733
|
+
const releaseToolCallMarker = markKey === void 0 ? () => {} : markToolCallResume(runId, markKey);
|
|
3734
|
+
if (!releaseToolCallMarker) throw resumeAlreadyClaimedError(agent.name, runId, toolCallId);
|
|
3735
|
+
const claim = await claimSuspension(runId, suspendedSnapshot ?? {}, toolCallId);
|
|
3736
|
+
if (!claim) {
|
|
3737
|
+
releaseToolCallMarker();
|
|
3738
|
+
assertToolCallResumeNotInFlight(agent.name, runId, toolCallId);
|
|
3739
|
+
return proxyRef.resume(runId, resumeData, resumeOptions);
|
|
3740
|
+
}
|
|
3741
|
+
const { controller: abortController, detach: stopForwardingAbort } = (0, _mastra_core_agent_durable.createRunAbortController)(resumeOptions?.abortSignal, { onExternalAbort: () => void requestRemoteAbort(runId) });
|
|
3488
3742
|
let existingEntry = existingRegistryEntry;
|
|
3489
3743
|
if (!existingEntry) {
|
|
3490
3744
|
existingEntry = {
|
|
@@ -3536,6 +3790,7 @@ function createInngestAgent(options) {
|
|
|
3536
3790
|
let resumeCleanedUp = false;
|
|
3537
3791
|
const finalizeResumeRegistry = () => {
|
|
3538
3792
|
clearTotalTimeout();
|
|
3793
|
+
releaseToolCallMarker();
|
|
3539
3794
|
if (resumeCleanedUp) return;
|
|
3540
3795
|
resumeCleanedUp = true;
|
|
3541
3796
|
stopForwardingAbort?.();
|
|
@@ -3564,7 +3819,10 @@ function createInngestAgent(options) {
|
|
|
3564
3819
|
requestContext: callbackOptions.requestContext,
|
|
3565
3820
|
onChunk: (chunk) => {
|
|
3566
3821
|
resumedChunkSeen = true;
|
|
3567
|
-
if (chunk.type === "tool-call-approval" || chunk.type === "tool-call-suspended")
|
|
3822
|
+
if (chunk.type === "tool-call-approval" || chunk.type === "tool-call-suspended") {
|
|
3823
|
+
stopForwardingAbort?.();
|
|
3824
|
+
if (!toolCallId || chunk.payload.toolCallId === toolCallId) releaseToolCallMarker();
|
|
3825
|
+
}
|
|
3568
3826
|
return callbackOptions.onChunk?.(chunk);
|
|
3569
3827
|
},
|
|
3570
3828
|
onStepFinish: callbackOptions.onStepFinish,
|
|
@@ -3585,6 +3843,7 @@ function createInngestAgent(options) {
|
|
|
3585
3843
|
onSuspended: async (data) => {
|
|
3586
3844
|
if (!resumedChunkSeen) return;
|
|
3587
3845
|
clearTotalTimeout();
|
|
3846
|
+
releaseToolCallMarker();
|
|
3588
3847
|
try {
|
|
3589
3848
|
await callbackOptions.onSuspended?.(data);
|
|
3590
3849
|
} finally {
|
|
@@ -3602,6 +3861,7 @@ function createInngestAgent(options) {
|
|
|
3602
3861
|
});
|
|
3603
3862
|
const eventName = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;
|
|
3604
3863
|
let notResumable = false;
|
|
3864
|
+
let sendStarted = false;
|
|
3605
3865
|
const didThreadRunPublishTerminal = _mastra_core_agent_durable.agentThreadStreamRuntime.captureThreadRunTerminalPublish(runId, agent.getPubSub());
|
|
3606
3866
|
const dispatch = ready.then(async () => {
|
|
3607
3867
|
const snapshot = suspendedSnapshot;
|
|
@@ -3616,7 +3876,9 @@ function createInngestAgent(options) {
|
|
|
3616
3876
|
traceId: snapshot.tracingContext.traceId,
|
|
3617
3877
|
parentSpanId: snapshot.tracingContext.spanId
|
|
3618
3878
|
} : void 0;
|
|
3879
|
+
sendStarted = true;
|
|
3619
3880
|
await inngest$1.send({
|
|
3881
|
+
...snapshot?.timestamp && claim.fence ? { id: `${runId}:resume:${snapshot.timestamp}:${claim.fence.generation}` } : {},
|
|
3620
3882
|
name: eventName,
|
|
3621
3883
|
data: buildDurableResumeEventData({
|
|
3622
3884
|
inputData: resumeData,
|
|
@@ -3628,7 +3890,9 @@ function createInngestAgent(options) {
|
|
|
3628
3890
|
resume: {
|
|
3629
3891
|
steps,
|
|
3630
3892
|
resumePayload: resumeData,
|
|
3631
|
-
resumePath: steps[0] ? snapshot?.suspendedPaths?.[steps[0]] : void 0
|
|
3893
|
+
resumePath: steps[0] ? snapshot?.suspendedPaths?.[steps[0]] : void 0,
|
|
3894
|
+
label: toolCallId,
|
|
3895
|
+
claim: claim.fence
|
|
3632
3896
|
}
|
|
3633
3897
|
})
|
|
3634
3898
|
});
|
|
@@ -3642,6 +3906,7 @@ function createInngestAgent(options) {
|
|
|
3642
3906
|
} catch (error) {
|
|
3643
3907
|
streamCleanup();
|
|
3644
3908
|
finalizeResumeRegistry();
|
|
3909
|
+
if (!sendStarted) await claim.release().catch((releaseError) => mastra?.getLogger?.()?.warn?.(`[InngestAgent] resume(${runId}) failed to release its claim`, releaseError));
|
|
3645
3910
|
throw error;
|
|
3646
3911
|
}
|
|
3647
3912
|
const resumeMemory = resumeOptions?.memory;
|
|
@@ -4828,4 +5093,4 @@ Object.defineProperty(exports, "serve", {
|
|
|
4828
5093
|
}
|
|
4829
5094
|
});
|
|
4830
5095
|
|
|
4831
|
-
//# sourceMappingURL=src-
|
|
5096
|
+
//# sourceMappingURL=src-zS6LvTK1.cjs.map
|