@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
|
@@ -7,23 +7,74 @@ import { toStandardSchema } from "@mastra/core/schema";
|
|
|
7
7
|
import { Tool, createTool } from "@mastra/core/tools";
|
|
8
8
|
import * as coreWorkflows from "@mastra/core/workflows";
|
|
9
9
|
import { DefaultExecutionEngine, Run, Workflow, createStepFromAgent, createStepFromTool, createTimeTravelExecutionParams, getEntryWorkflow, hydrateSerializedStepErrors, isSingleStepEntry } from "@mastra/core/workflows";
|
|
10
|
-
import
|
|
10
|
+
import * as coreDurable from "@mastra/core/agent/durable";
|
|
11
|
+
import { AGENT_STREAM_TOPIC, AgentStreamBus, AgentStreamEventTypes, DURABLE_STOP_WHEN_ERROR_ID, DurableAgentDefaults, DurableStepIds, agentThreadStreamRuntime, applyReservedMemoryContextKeys, baseIterationStateSchema, createBaseIterationStateUpdate, createDurableAgentStream, createDurableBackgroundTaskCheckStep, createDurableGoalStep, createDurableIsTaskCompleteStep, createDurableLLMExecutionStep, createDurableLLMMappingStep, createDurableToolCallStep, createRunAbortController, deleteRunRegistryEntry, durableAgenticOutputSchema, emitAbortEvent, emitChunkEvent, emitErrorEvent, emitFinishEvent, emitSuspendedEvent, executeDurableAgentScorers, getRunRegistryEntry, getRunStreamSlot, getScopeStreamSlot, globalRunRegistry, loadRunStoredMessages, modelConfigSchema, modelListEntrySchema, normalizeResumeGenerateArgs, persistDurableRunInput, prepareForDurableExecution, pruneAgentLoopSnapshot, publishAbortRequest, requestAcknowledgedAbort, resolveDurableToolCallConcurrency, runDurableFinishSideEffects, runDurableStreamUntilIdle, runResumeDurableStreamUntilIdle, takeRunScorerInstances, validateModelTimeoutSettings } from "@mastra/core/agent/durable";
|
|
11
12
|
import { RequestContext } from "@mastra/core/di";
|
|
12
13
|
import { CachingPubSub, PubSub } from "@mastra/core/events";
|
|
13
14
|
import { NonRetriableError } from "inngest";
|
|
15
|
+
import { MASTRA_AUTH_TOKEN_KEY, RequestContext as RequestContext$1 } from "@mastra/core/request-context";
|
|
14
16
|
import { AsyncLocalStorage } from "async_hooks";
|
|
15
17
|
import { coreFeatures } from "@mastra/core/features";
|
|
16
18
|
import { subscribe } from "inngest/realtime";
|
|
17
19
|
import { ReadableStream as ReadableStream$1 } from "stream/web";
|
|
18
20
|
import { ChunkFrom, WorkflowRunOutput } from "@mastra/core/stream";
|
|
19
|
-
import { MASTRA_AUTH_TOKEN_KEY, RequestContext as RequestContext$1 } from "@mastra/core/request-context";
|
|
20
21
|
import { serve } from "inngest/hono";
|
|
21
|
-
import { InMemoryServerCache } from "@mastra/core/cache";
|
|
22
22
|
import { createTimeoutAbortSignal, isMastraTimeoutError } from "@mastra/core/loop";
|
|
23
|
+
import { matchesRunFence } from "@mastra/core/storage";
|
|
23
24
|
import { deepMerge, rebindProcessorTools } from "@mastra/core/utils";
|
|
24
25
|
import { MessageList as MessageList$1 } from "@mastra/core/agent/message-list";
|
|
25
26
|
import { PUBSUB_SYMBOL } from "@mastra/core/workflows/_constants";
|
|
26
27
|
import { z } from "zod";
|
|
28
|
+
// src/durable-event-payload.ts
|
|
29
|
+
/**
|
|
30
|
+
* Lease on an InngestAgent resume claim until its event starts. A claim whose event never started
|
|
31
|
+
* (its resume died before sending, or the send failed) lapses, and a later resume takes it over.
|
|
32
|
+
*/
|
|
33
|
+
const RESUME_CLAIM_DISPATCH_LEASE_MS = 6e4;
|
|
34
|
+
/**
|
|
35
|
+
* Flatten a `RequestContext` into the plain JSON object the event carries.
|
|
36
|
+
* Absent context serializes to `{}`, never `undefined`.
|
|
37
|
+
*/
|
|
38
|
+
function serializeRequestContext(requestContext) {
|
|
39
|
+
const obj = requestContext ? requestContext.toJSON() : {};
|
|
40
|
+
delete obj[MASTRA_AUTH_TOKEN_KEY];
|
|
41
|
+
return obj;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Resume request-context rule: values persisted in the snapshot are the base,
|
|
45
|
+
* and anything the caller supplies on this resume call overrides them.
|
|
46
|
+
*/
|
|
47
|
+
function mergeResumeRequestContext(snapshotRequestContext, requestContext) {
|
|
48
|
+
return {
|
|
49
|
+
...snapshotRequestContext ?? {},
|
|
50
|
+
...serializeRequestContext(requestContext)
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
function buildDurableTriggerEventData(args) {
|
|
54
|
+
const { requestContext, ...rest } = args;
|
|
55
|
+
return {
|
|
56
|
+
...rest,
|
|
57
|
+
requestContext: toRequestContextEntries(requestContext)
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function buildDurableResumeEventData(args) {
|
|
61
|
+
const { requestContext, ...rest } = args;
|
|
62
|
+
return {
|
|
63
|
+
...rest,
|
|
64
|
+
requestContext: toRequestContextEntries(requestContext)
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function buildDurableTimeTravelEventData(args) {
|
|
68
|
+
const { requestContext, ...rest } = args;
|
|
69
|
+
return {
|
|
70
|
+
...rest,
|
|
71
|
+
requestContext: toRequestContextEntries(requestContext)
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function toRequestContextEntries(requestContext) {
|
|
75
|
+
if (!requestContext) return {};
|
|
76
|
+
return typeof requestContext.toJSON === "function" ? serializeRequestContext(requestContext) : requestContext;
|
|
77
|
+
}
|
|
27
78
|
// src/nested-workflow-output.ts
|
|
28
79
|
const NESTED_WORKFLOW_OUTPUT_MODE = {
|
|
29
80
|
DEFAULT: "default",
|
|
@@ -84,6 +135,10 @@ function workflowTermination(...args) {
|
|
|
84
135
|
function agentLoopTermination(...args) {
|
|
85
136
|
return coreFeatures.has("execution-outcomes") ? coreObservability.agentLoopTermination?.(...args) ?? {} : {};
|
|
86
137
|
}
|
|
138
|
+
/** End the caller's live root spans with `error`; a no-op on cores without the helper. */
|
|
139
|
+
function endRunSpansWithError(...args) {
|
|
140
|
+
if (coreFeatures.has("execution-outcomes")) coreDurable.endRunSpansWithError?.(...args);
|
|
141
|
+
}
|
|
87
142
|
/** Keep completed-request usage when a failed request makes the total incomplete. */
|
|
88
143
|
function generationUsage(usage, steps) {
|
|
89
144
|
const usageIncomplete = coreFeatures.has("execution-outcomes") && coreObservability.isUsageIncomplete?.(usage);
|
|
@@ -443,7 +498,9 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
|
|
|
443
498
|
runId,
|
|
444
499
|
steps: nestedResumeSteps,
|
|
445
500
|
resumePayload: resume.resumePayload,
|
|
446
|
-
resumePath: nestedResumeStepId ? snapshot?.suspendedPaths?.[nestedResumeStepId] : void 0
|
|
501
|
+
resumePath: nestedResumeStepId ? snapshot?.suspendedPaths?.[nestedResumeStepId] : void 0,
|
|
502
|
+
label: resume.label,
|
|
503
|
+
forEachIndex: resume.label ? snapshot?.resumeLabels?.[resume.label]?.foreachIndex : void 0
|
|
447
504
|
} },
|
|
448
505
|
outputOptions: {
|
|
449
506
|
includeState: true,
|
|
@@ -561,6 +618,26 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
|
|
|
561
618
|
const suspendedSteps = Object.entries(result.steps).filter(([_stepName, stepResult]) => {
|
|
562
619
|
return stepResult?.status === "suspended";
|
|
563
620
|
});
|
|
621
|
+
const agentInput = stepResults.input;
|
|
622
|
+
const resumedCallFinished = isResume && !!resume?.label && !result.resumeLabels?.[resume.label];
|
|
623
|
+
const parked = (suspendedSteps[0]?.[1])?.suspendPayload;
|
|
624
|
+
const approval = parked?.requireToolApproval;
|
|
625
|
+
const parkedToolCallId = parked?.toolCallId ?? approval?.toolCallId;
|
|
626
|
+
let parkedBefore = false;
|
|
627
|
+
if (resumedCallFinished && agentInput?.__workflowKind === "durable-agent" && parkedToolCallId) parkedBefore = !!(await (await this.mastra?.getStorage()?.getStore("workflows"))?.loadWorkflowSnapshot({
|
|
628
|
+
workflowName: executionContext.workflowId,
|
|
629
|
+
runId: executionContext.runId
|
|
630
|
+
}))?.resumeLabels?.[parkedToolCallId];
|
|
631
|
+
if (parkedBefore && agentInput?.runId) {
|
|
632
|
+
const meta = parked?.__workflow_meta;
|
|
633
|
+
await emitSuspendedEvent(pubsub, agentInput.runId, {
|
|
634
|
+
toolCallId: parkedToolCallId,
|
|
635
|
+
toolName: approval?.toolName ?? parked?.toolName,
|
|
636
|
+
args: approval?.args ?? parked?.args ?? meta?.foreachOutput?.[meta.foreachIndex]?.payload?.args,
|
|
637
|
+
suspendPayload: parked?.toolCallSuspended,
|
|
638
|
+
type: parked?.type === "approval" ? "approval" : "suspension"
|
|
639
|
+
});
|
|
640
|
+
}
|
|
564
641
|
for (const [stepName, stepResult] of suspendedSteps) {
|
|
565
642
|
const suspendPath = [stepName, ...stepResult?.suspendPayload?.__workflow_meta?.path ?? []];
|
|
566
643
|
executionContext.suspendedPaths[step.id] = executionContext.executionPath;
|
|
@@ -1052,51 +1129,6 @@ var InngestPubSub = class extends PubSub {
|
|
|
1052
1129
|
this.subscriptions.clear();
|
|
1053
1130
|
}
|
|
1054
1131
|
};
|
|
1055
|
-
// src/durable-event-payload.ts
|
|
1056
|
-
/**
|
|
1057
|
-
* Flatten a `RequestContext` into the plain JSON object the event carries.
|
|
1058
|
-
* Absent context serializes to `{}`, never `undefined`.
|
|
1059
|
-
*/
|
|
1060
|
-
function serializeRequestContext(requestContext) {
|
|
1061
|
-
const obj = requestContext ? requestContext.toJSON() : {};
|
|
1062
|
-
delete obj[MASTRA_AUTH_TOKEN_KEY];
|
|
1063
|
-
return obj;
|
|
1064
|
-
}
|
|
1065
|
-
/**
|
|
1066
|
-
* Resume request-context rule: values persisted in the snapshot are the base,
|
|
1067
|
-
* and anything the caller supplies on this resume call overrides them.
|
|
1068
|
-
*/
|
|
1069
|
-
function mergeResumeRequestContext(snapshotRequestContext, requestContext) {
|
|
1070
|
-
return {
|
|
1071
|
-
...snapshotRequestContext ?? {},
|
|
1072
|
-
...serializeRequestContext(requestContext)
|
|
1073
|
-
};
|
|
1074
|
-
}
|
|
1075
|
-
function buildDurableTriggerEventData(args) {
|
|
1076
|
-
const { requestContext, ...rest } = args;
|
|
1077
|
-
return {
|
|
1078
|
-
...rest,
|
|
1079
|
-
requestContext: toRequestContextEntries(requestContext)
|
|
1080
|
-
};
|
|
1081
|
-
}
|
|
1082
|
-
function buildDurableResumeEventData(args) {
|
|
1083
|
-
const { requestContext, ...rest } = args;
|
|
1084
|
-
return {
|
|
1085
|
-
...rest,
|
|
1086
|
-
requestContext: toRequestContextEntries(requestContext)
|
|
1087
|
-
};
|
|
1088
|
-
}
|
|
1089
|
-
function buildDurableTimeTravelEventData(args) {
|
|
1090
|
-
const { requestContext, ...rest } = args;
|
|
1091
|
-
return {
|
|
1092
|
-
...rest,
|
|
1093
|
-
requestContext: toRequestContextEntries(requestContext)
|
|
1094
|
-
};
|
|
1095
|
-
}
|
|
1096
|
-
function toRequestContextEntries(requestContext) {
|
|
1097
|
-
if (!requestContext) return {};
|
|
1098
|
-
return typeof requestContext.toJSON === "function" ? serializeRequestContext(requestContext) : requestContext;
|
|
1099
|
-
}
|
|
1100
1132
|
// src/run.ts
|
|
1101
1133
|
var InngestRun = class extends Run {
|
|
1102
1134
|
inngest;
|
|
@@ -1817,6 +1849,8 @@ var InngestWorkflow = class extends Workflow {
|
|
|
1817
1849
|
*/
|
|
1818
1850
|
#pubsubFactory;
|
|
1819
1851
|
#emitWorkflowEvents = true;
|
|
1852
|
+
/** Functions a host (e.g. the durable agent loop) serves alongside this workflow's own. */
|
|
1853
|
+
#hostFunctions = [];
|
|
1820
1854
|
constructor(params, inngest) {
|
|
1821
1855
|
const { concurrency, rateLimit, throttle, debounce, priority, retries, cron, inputData, initialState, ...workflowParams } = params;
|
|
1822
1856
|
super(workflowParams);
|
|
@@ -1881,6 +1915,9 @@ var InngestWorkflow = class extends Workflow {
|
|
|
1881
1915
|
this.__setEmitWorkflowEvents(this.#emitWorkflowEvents);
|
|
1882
1916
|
return committed;
|
|
1883
1917
|
}
|
|
1918
|
+
__addHostFunctions(functions) {
|
|
1919
|
+
this.#hostFunctions.push(...functions);
|
|
1920
|
+
}
|
|
1884
1921
|
__setEmitWorkflowEvents(enabled) {
|
|
1885
1922
|
this.#emitWorkflowEvents = enabled;
|
|
1886
1923
|
const updateNested = (step) => {
|
|
@@ -2012,6 +2049,18 @@ var InngestWorkflow = class extends Workflow {
|
|
|
2012
2049
|
});
|
|
2013
2050
|
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.`);
|
|
2014
2051
|
}
|
|
2052
|
+
const resumeClaim = resume?.claim;
|
|
2053
|
+
if (resumeClaim) {
|
|
2054
|
+
if (!await step.run(`workflow.${this.id}.resume-claim`, async () => {
|
|
2055
|
+
return (await (await this.#mastra?.getStorage()?.getStore("workflows"))?.renewRunOwnership({
|
|
2056
|
+
...resumeClaim,
|
|
2057
|
+
leaseMs: 864e5
|
|
2058
|
+
}))?.renewed ?? true;
|
|
2059
|
+
})) return {
|
|
2060
|
+
result: void 0,
|
|
2061
|
+
runId
|
|
2062
|
+
};
|
|
2063
|
+
}
|
|
2015
2064
|
if (resume && (initialState === void 0 || resume.stepResults === void 0)) {
|
|
2016
2065
|
const snapshot = await (await this.#mastra?.getStorage()?.getStore("workflows"))?.loadWorkflowSnapshot({
|
|
2017
2066
|
workflowName: this.id,
|
|
@@ -2190,6 +2239,7 @@ var InngestWorkflow = class extends Workflow {
|
|
|
2190
2239
|
});
|
|
2191
2240
|
}
|
|
2192
2241
|
}
|
|
2242
|
+
if (resumeClaim) await (await mastra?.getStorage()?.getStore("workflows"))?.releaseRunOwnership(resumeClaim);
|
|
2193
2243
|
try {
|
|
2194
2244
|
await pubsub.publish(`workflow.events.v2.${runId}`, {
|
|
2195
2245
|
type: "watch",
|
|
@@ -2245,7 +2295,8 @@ var InngestWorkflow = class extends Workflow {
|
|
|
2245
2295
|
return [
|
|
2246
2296
|
this.getFunction(),
|
|
2247
2297
|
...this.cronConfig?.cron ? [this.createCronFunction()] : [],
|
|
2248
|
-
...this.getNestedFunctions(this.executionGraph.steps)
|
|
2298
|
+
...this.getNestedFunctions(this.executionGraph.steps),
|
|
2299
|
+
...this.#hostFunctions
|
|
2249
2300
|
];
|
|
2250
2301
|
}
|
|
2251
2302
|
};
|
|
@@ -2375,6 +2426,7 @@ const durableAgenticInputSchema = z.object({
|
|
|
2375
2426
|
* Iteration state schema - extends base with observability fields.
|
|
2376
2427
|
*/
|
|
2377
2428
|
const iterationStateSchema = baseIterationStateSchema.extend({
|
|
2429
|
+
accumulatedSteps: z.array(z.any()),
|
|
2378
2430
|
modelList: z.array(modelListEntrySchema).optional(),
|
|
2379
2431
|
agentSpanData: z.any().optional(),
|
|
2380
2432
|
modelSpanData: z.any().optional(),
|
|
@@ -2404,7 +2456,77 @@ const InngestDurableStepIds = {
|
|
|
2404
2456
|
AGENTIC_EXECUTION: `${INNGEST_ENGINE_PREFIX}:${DurableStepIds.AGENTIC_EXECUTION}`,
|
|
2405
2457
|
AGENTIC_LOOP: `${INNGEST_ENGINE_PREFIX}:${DurableStepIds.AGENTIC_LOOP}`
|
|
2406
2458
|
};
|
|
2459
|
+
/** Run ownership key of the claim an InngestAgent resume holds on the loop run. */
|
|
2460
|
+
const resumeClaimKey = (runId) => `${InngestDurableStepIds.AGENTIC_LOOP}:resume-claim:${runId}`;
|
|
2461
|
+
/**
|
|
2462
|
+
* The store a resume claim lives in. A claim needs an atomic status change and a lease, so a
|
|
2463
|
+
* claim whose resume died can be taken over; without both, resumes are not claimed at all.
|
|
2464
|
+
*/
|
|
2465
|
+
async function resumeClaimStore(mastra) {
|
|
2466
|
+
const store = await mastra?.getStorage()?.getStore("workflows");
|
|
2467
|
+
if (!store?.supportsConcurrentUpdates?.()) return void 0;
|
|
2468
|
+
return await Promise.resolve().then(() => store.supportsRunFencing()).catch(() => false) ? store : void 0;
|
|
2469
|
+
}
|
|
2470
|
+
const setLoopStatus = (store, runId, status, expectedStatus) => store.updateWorkflowState({
|
|
2471
|
+
workflowName: InngestDurableStepIds.AGENTIC_LOOP,
|
|
2472
|
+
runId,
|
|
2473
|
+
opts: {
|
|
2474
|
+
status,
|
|
2475
|
+
expectedStatus
|
|
2476
|
+
}
|
|
2477
|
+
});
|
|
2478
|
+
/**
|
|
2479
|
+
* Ends a resumed segment Inngest failed or cancelled, which never reaches the finalize step that
|
|
2480
|
+
* would: marks the run failed or canceled, ends its stream and releases its claim. The run is not
|
|
2481
|
+
* parked again, since a nested segment Inngest did not cancel can still be running its tools.
|
|
2482
|
+
*/
|
|
2483
|
+
function createResumeClaimReleaseFunction(inngest, workflow) {
|
|
2484
|
+
const loopEvent = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;
|
|
2485
|
+
return inngest.createFunction({
|
|
2486
|
+
id: `${loopEvent}.resume-claim-release`,
|
|
2487
|
+
triggers: [{
|
|
2488
|
+
event: "inngest/function.failed",
|
|
2489
|
+
if: `event.data.event.name == '${loopEvent}'`
|
|
2490
|
+
}, {
|
|
2491
|
+
event: "inngest/function.cancelled",
|
|
2492
|
+
if: `event.data.event.name == '${loopEvent}'`
|
|
2493
|
+
}]
|
|
2494
|
+
}, async ({ event }) => {
|
|
2495
|
+
const original = event.data.event?.data;
|
|
2496
|
+
const claim = original?.resume?.claim;
|
|
2497
|
+
const mastra = workflow.mastra;
|
|
2498
|
+
const store = await resumeClaimStore(mastra);
|
|
2499
|
+
if (!original?.runId || !claim || !store) return;
|
|
2500
|
+
if (!(await store.renewRunOwnership({
|
|
2501
|
+
...claim,
|
|
2502
|
+
leaseMs: 6e4
|
|
2503
|
+
})).renewed) return;
|
|
2504
|
+
const cancelled = event.name === "inngest/function.cancelled";
|
|
2505
|
+
await setLoopStatus(store, original.runId, cancelled ? "canceled" : "failed", "running");
|
|
2506
|
+
const defaultPubsub = new InngestPubSub(inngest, workflow.id, mastra?.getLogger?.());
|
|
2507
|
+
const pubsub = workflow.__getPubsubFactory()?.(defaultPubsub) ?? defaultPubsub;
|
|
2508
|
+
try {
|
|
2509
|
+
if (cancelled) await emitAbortEvent(pubsub, original.runId, {
|
|
2510
|
+
steps: [],
|
|
2511
|
+
text: ""
|
|
2512
|
+
});
|
|
2513
|
+
else {
|
|
2514
|
+
const message = event.data.error?.message;
|
|
2515
|
+
await emitErrorEvent(pubsub, original.runId, new Error(message ?? "The resumed agent run failed."));
|
|
2516
|
+
}
|
|
2517
|
+
} catch (error) {
|
|
2518
|
+
mastra?.getLogger?.()?.warn?.(`[InngestAgent] run ${original.runId} failed to publish its end`, error);
|
|
2519
|
+
}
|
|
2520
|
+
await store.releaseRunOwnership(claim);
|
|
2521
|
+
});
|
|
2522
|
+
}
|
|
2407
2523
|
function createInngestDurableAgenticWorkflow(options) {
|
|
2524
|
+
const workflow = createAgenticLoopWorkflow(options);
|
|
2525
|
+
const inngestWorkflow = workflow;
|
|
2526
|
+
inngestWorkflow.__addHostFunctions([createResumeClaimReleaseFunction(options.inngest, inngestWorkflow)]);
|
|
2527
|
+
return workflow;
|
|
2528
|
+
}
|
|
2529
|
+
function createAgenticLoopWorkflow(options) {
|
|
2408
2530
|
const { inngest, maxSteps = DurableAgentDefaults.MAX_STEPS, retries } = options;
|
|
2409
2531
|
const { createWorkflow } = init(inngest);
|
|
2410
2532
|
const llmExecutionStep = createDurableLLMExecutionStep();
|
|
@@ -2546,8 +2668,12 @@ function createInngestDurableAgenticWorkflow(options) {
|
|
|
2546
2668
|
});
|
|
2547
2669
|
}
|
|
2548
2670
|
};
|
|
2671
|
+
const recordStopCause = (cause) => {
|
|
2672
|
+
state.tracingStopCause = cause;
|
|
2673
|
+
if (tracingRegistry) tracingRegistry.tracingStopCause = cause;
|
|
2674
|
+
};
|
|
2549
2675
|
if (state.delegationBailed) {
|
|
2550
|
-
|
|
2676
|
+
recordStopCause(state.lastStepResult?.isContinued ? "delegation" : "model_finished");
|
|
2551
2677
|
await emitStepFinish(false);
|
|
2552
2678
|
return false;
|
|
2553
2679
|
}
|
|
@@ -2555,7 +2681,7 @@ function createInngestDurableAgenticWorkflow(options) {
|
|
|
2555
2681
|
const effectiveMaxSteps = state.options?.maxSteps ?? maxSteps;
|
|
2556
2682
|
const underMaxSteps = state.iterationCount < effectiveMaxSteps;
|
|
2557
2683
|
if (!shouldContinue || !underMaxSteps) {
|
|
2558
|
-
|
|
2684
|
+
recordStopCause(shouldContinue ? "max_steps" : "model_finished");
|
|
2559
2685
|
await emitStepFinish(false);
|
|
2560
2686
|
return false;
|
|
2561
2687
|
}
|
|
@@ -2581,7 +2707,7 @@ function createInngestDurableAgenticWorkflow(options) {
|
|
|
2581
2707
|
}
|
|
2582
2708
|
}))).some(Boolean);
|
|
2583
2709
|
});
|
|
2584
|
-
if (stopped
|
|
2710
|
+
if (stopped) recordStopCause("stop_condition");
|
|
2585
2711
|
await emitStepFinish(!stopped);
|
|
2586
2712
|
return !stopped;
|
|
2587
2713
|
}).map(async (params) => {
|
|
@@ -2662,6 +2788,17 @@ function createInngestDurableAgenticWorkflow(options) {
|
|
|
2662
2788
|
...completionClock ? { completionStartTime: new Date(completionClock) } : {},
|
|
2663
2789
|
...timeToFirstTokenMs !== void 0 ? { timeToFirstTokenMs } : {}
|
|
2664
2790
|
};
|
|
2791
|
+
const finishReason = finalOutput.stepResult?.reason;
|
|
2792
|
+
const stopCause = state.tracingStopCause ?? registry?.tracingStopCause;
|
|
2793
|
+
const recordedTermination = state.tracingTermination ?? registry?.tracingTermination;
|
|
2794
|
+
if (!stopCause && (finishReason === "stop" || finishReason === "tool-calls")) mastra?.getLogger?.()?.warn?.(`[InngestDurableAgent] Run ${state.runId} has no recorded stop cause; its span outcome is unknown`);
|
|
2795
|
+
const termination = ["tripwire", "error"].includes(finishReason ?? "") && recordedTermination ? recordedTermination : agentLoopTermination({
|
|
2796
|
+
stopCause,
|
|
2797
|
+
delegationFailure: state.tracingDelegationFailure ?? registry?.tracingDelegationFailure,
|
|
2798
|
+
finishReason,
|
|
2799
|
+
tripwire: tripwire ?? state.lastStepResult?.tripwire,
|
|
2800
|
+
maxSteps: state.options?.maxSteps ?? maxSteps
|
|
2801
|
+
});
|
|
2665
2802
|
if (state.modelSpanData) {
|
|
2666
2803
|
const modelSpan = registry?.resumeModelSpan ?? registry?.modelSpan ?? observability?.rebuildSpan(state.modelSpanData);
|
|
2667
2804
|
const toolCalls = state.accumulatedSteps.flatMap((step) => (step.toolCalls ?? []).map((tc) => ({
|
|
@@ -2671,13 +2808,7 @@ function createInngestDurableAgenticWorkflow(options) {
|
|
|
2671
2808
|
})));
|
|
2672
2809
|
const { usageIncomplete, usage } = generationUsage(state.accumulatedUsage, state.accumulatedSteps);
|
|
2673
2810
|
modelSpan?.createTracker()?.endGeneration({
|
|
2674
|
-
...
|
|
2675
|
-
stopCause: registry?.tracingStopCause,
|
|
2676
|
-
delegationFailure: registry?.tracingDelegationFailure,
|
|
2677
|
-
finishReason: finalOutput.stepResult?.reason,
|
|
2678
|
-
tripwire,
|
|
2679
|
-
maxSteps: state.options?.maxSteps ?? maxSteps
|
|
2680
|
-
}),
|
|
2811
|
+
...termination,
|
|
2681
2812
|
output: {
|
|
2682
2813
|
text: finalText,
|
|
2683
2814
|
...toolCalls.length ? { toolCalls } : {}
|
|
@@ -2693,13 +2824,7 @@ function createInngestDurableAgenticWorkflow(options) {
|
|
|
2693
2824
|
});
|
|
2694
2825
|
}
|
|
2695
2826
|
if (state.agentSpanData) (registry?.resumeAgentSpan ?? registry?.agentSpan ?? observability?.rebuildSpan(state.agentSpanData))?.end({
|
|
2696
|
-
...
|
|
2697
|
-
stopCause: registry?.tracingStopCause,
|
|
2698
|
-
delegationFailure: registry?.tracingDelegationFailure,
|
|
2699
|
-
finishReason: finalOutput.stepResult?.reason,
|
|
2700
|
-
tripwire,
|
|
2701
|
-
maxSteps: state.options?.maxSteps ?? maxSteps
|
|
2702
|
-
}),
|
|
2827
|
+
...termination,
|
|
2703
2828
|
output: { text: finalText },
|
|
2704
2829
|
...Object.keys(clocks).length ? { attributes: clocks } : {}
|
|
2705
2830
|
});
|
|
@@ -2814,6 +2939,43 @@ var InngestAgentPubSubRouter = class extends PubSub {
|
|
|
2814
2939
|
const STREAM_CLEANUP = Symbol("mastra.durable.inngest.streamCleanup");
|
|
2815
2940
|
const RESUME_SNAPSHOT_WAIT_MS = 1e4;
|
|
2816
2941
|
const RESUME_SNAPSHOT_POLL_MS = 100;
|
|
2942
|
+
/** runId -> toolCallId -> token of the resume of that tool call in flight in this process. */
|
|
2943
|
+
const inFlightToolCallResumes = /* @__PURE__ */ new Map();
|
|
2944
|
+
/** Names this process in resume claim owner ids, to recognize its own claims. */
|
|
2945
|
+
const RESUME_CLAIM_PROCESS_ID = crypto.randomUUID();
|
|
2946
|
+
/**
|
|
2947
|
+
* Marks a resume of `toolCallId` as in flight. Returns `undefined` when another resume already
|
|
2948
|
+
* holds the mark. The returned release only clears its own mark.
|
|
2949
|
+
*/
|
|
2950
|
+
function markToolCallResume(runId, toolCallId) {
|
|
2951
|
+
const token = Symbol(toolCallId);
|
|
2952
|
+
const marks = inFlightToolCallResumes.get(runId) ?? /* @__PURE__ */ new Map();
|
|
2953
|
+
if (marks.has(toolCallId)) return void 0;
|
|
2954
|
+
marks.set(toolCallId, token);
|
|
2955
|
+
inFlightToolCallResumes.set(runId, marks);
|
|
2956
|
+
return () => {
|
|
2957
|
+
if (marks.get(toolCallId) !== token) return;
|
|
2958
|
+
marks.delete(toolCallId);
|
|
2959
|
+
if (marks.size === 0) inFlightToolCallResumes.delete(runId);
|
|
2960
|
+
};
|
|
2961
|
+
}
|
|
2962
|
+
function resumeAlreadyClaimedError(agentName, runId, toolCallId) {
|
|
2963
|
+
return new MastraError({
|
|
2964
|
+
id: "AGENT_RESUME_ALREADY_CLAIMED",
|
|
2965
|
+
domain: ErrorDomain.AGENT,
|
|
2966
|
+
category: ErrorCategory.USER,
|
|
2967
|
+
text: `InngestAgent "${agentName}" resume(${runId}) cannot resume the run because another resume of it is already running.`,
|
|
2968
|
+
details: {
|
|
2969
|
+
agentName,
|
|
2970
|
+
runId,
|
|
2971
|
+
...toolCallId ? { toolCallId } : {}
|
|
2972
|
+
}
|
|
2973
|
+
});
|
|
2974
|
+
}
|
|
2975
|
+
/** A second approval of a tool call this process is already resuming fails right away (#27485). */
|
|
2976
|
+
function assertToolCallResumeNotInFlight(agentName, runId, toolCallId) {
|
|
2977
|
+
if (toolCallId && inFlightToolCallResumes.get(runId)?.has(toolCallId)) throw resumeAlreadyClaimedError(agentName, runId, toolCallId);
|
|
2978
|
+
}
|
|
2817
2979
|
/**
|
|
2818
2980
|
* Merges the wrapped agent's `defaultOptions` under the call options, matching
|
|
2819
2981
|
* core `DurableAgent`, so lifecycle callbacks configured as defaults fire unless
|
|
@@ -2861,21 +3023,23 @@ function createInngestAgent(options) {
|
|
|
2861
3023
|
retries
|
|
2862
3024
|
});
|
|
2863
3025
|
let _customCache = cache;
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
2867
|
-
|
|
2868
|
-
|
|
2869
|
-
|
|
2870
|
-
|
|
3026
|
+
const innerPubsub = customPubsub ?? new InngestPubSub(inngest, InngestDurableStepIds.AGENTIC_LOOP);
|
|
3027
|
+
const streams = new AgentStreamBus({
|
|
3028
|
+
pubsub: innerPubsub,
|
|
3029
|
+
cache
|
|
3030
|
+
}, {
|
|
3031
|
+
getMastra: () => mastra,
|
|
3032
|
+
usesSharedRunLog: () => false,
|
|
3033
|
+
warn: (message) => console.warn(`InngestAgent '${idOverride ?? agent.id}': ${message}`)
|
|
3034
|
+
});
|
|
3035
|
+
let busResolved = false;
|
|
2871
3036
|
function getPubsub() {
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
|
|
2875
|
-
|
|
2876
|
-
} else _cachingPubsub = new CachingPubSub(innerPubsub, resolveCache());
|
|
3037
|
+
const pubsub = streams.pubsub;
|
|
3038
|
+
if (!busResolved) {
|
|
3039
|
+
busResolved = true;
|
|
3040
|
+
_customCache ??= innerPubsub instanceof CachingPubSub ? mastra?.serverCache : streams.cache ?? void 0;
|
|
2877
3041
|
}
|
|
2878
|
-
return
|
|
3042
|
+
return pubsub;
|
|
2879
3043
|
}
|
|
2880
3044
|
async function getPubsubOffset(runId) {
|
|
2881
3045
|
return (await getPubsub().getHistory(AGENT_STREAM_TOPIC(runId))).length;
|
|
@@ -2925,18 +3089,30 @@ function createInngestAgent(options) {
|
|
|
2925
3089
|
async function deleteFencedSuspendedRun(runId) {
|
|
2926
3090
|
try {
|
|
2927
3091
|
const workflowsStore = await mastra?.getStorage()?.getStore("workflows");
|
|
2928
|
-
|
|
2929
|
-
runId,
|
|
2930
|
-
workflowName: InngestDurableStepIds.AGENTIC_LOOP
|
|
2931
|
-
}))?.status !== "suspended") return;
|
|
2932
|
-
await workflowsStore?.deleteWorkflowRunById({
|
|
3092
|
+
const snapshot = await workflowsStore?.loadWorkflowSnapshot({
|
|
2933
3093
|
runId,
|
|
2934
3094
|
workflowName: InngestDurableStepIds.AGENTIC_LOOP
|
|
2935
3095
|
});
|
|
2936
|
-
await
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
3096
|
+
const store = await resumeClaimStore(mastra);
|
|
3097
|
+
const owner = await store?.getRunOwnership({ runId: resumeClaimKey(runId) });
|
|
3098
|
+
const parked = !owner?.live && (snapshot?.status === "suspended" || snapshot?.status === "running" && Object.keys(snapshot.suspendedPaths ?? {}).length > 0);
|
|
3099
|
+
const fence = parked && store ? await store.claimRunOwnership({
|
|
3100
|
+
runId: resumeClaimKey(runId),
|
|
3101
|
+
ownerId: `${RESUME_CLAIM_PROCESS_ID}/${crypto.randomUUID()}/`,
|
|
3102
|
+
leaseMs: RESUME_CLAIM_DISPATCH_LEASE_MS,
|
|
3103
|
+
expectedGeneration: owner?.generation ?? 0
|
|
3104
|
+
}) : void 0;
|
|
3105
|
+
if (fence?.acquired) await store?.releaseRunOwnership(fence.record);
|
|
3106
|
+
if (parked && (!store || fence?.acquired)) {
|
|
3107
|
+
await workflowsStore?.deleteWorkflowRunById({
|
|
3108
|
+
runId,
|
|
3109
|
+
workflowName: InngestDurableStepIds.AGENTIC_LOOP
|
|
3110
|
+
});
|
|
3111
|
+
await workflowsStore?.deleteWorkflowRunById({
|
|
3112
|
+
runId,
|
|
3113
|
+
workflowName: InngestDurableStepIds.AGENTIC_EXECUTION
|
|
3114
|
+
});
|
|
3115
|
+
}
|
|
2940
3116
|
await emitAbortEvent(getPubsub(), runId, {
|
|
2941
3117
|
steps: [],
|
|
2942
3118
|
text: ""
|
|
@@ -3047,6 +3223,62 @@ function createInngestAgent(options) {
|
|
|
3047
3223
|
return false;
|
|
3048
3224
|
}
|
|
3049
3225
|
}
|
|
3226
|
+
/** The live lease of the resume holding the run's claim, if any. */
|
|
3227
|
+
async function liveResumeClaim(runId) {
|
|
3228
|
+
const owner = await (await resumeClaimStore(mastra))?.getRunOwnership({ runId: resumeClaimKey(runId) });
|
|
3229
|
+
return owner?.live ? owner : void 0;
|
|
3230
|
+
}
|
|
3231
|
+
/**
|
|
3232
|
+
* Claims a suspension read by `resume()` (`suspended` -> `running`) so no other resume, in this
|
|
3233
|
+
* process or another, dispatches it again (#27485, #27925). The lease is taken first and is the
|
|
3234
|
+
* mutex: a `running` snapshot without a live lease is a claim whose event never started, which
|
|
3235
|
+
* this resume takes over. Returns `undefined` when another resume got there first.
|
|
3236
|
+
*/
|
|
3237
|
+
async function claimSuspension(runId, snapshot, toolCallId) {
|
|
3238
|
+
const store = await resumeClaimStore(mastra);
|
|
3239
|
+
if (!store || !snapshot.status) return { release: async () => {} };
|
|
3240
|
+
const key = resumeClaimKey(runId);
|
|
3241
|
+
const owner = await store.getRunOwnership({ runId: key });
|
|
3242
|
+
if (owner?.live) return void 0;
|
|
3243
|
+
const ownerId = `${RESUME_CLAIM_PROCESS_ID}/${crypto.randomUUID()}/${toolCallId ?? ""}`;
|
|
3244
|
+
const lease = await store.claimRunOwnership({
|
|
3245
|
+
runId: key,
|
|
3246
|
+
ownerId,
|
|
3247
|
+
leaseMs: RESUME_CLAIM_DISPATCH_LEASE_MS,
|
|
3248
|
+
expectedGeneration: owner?.generation ?? 0
|
|
3249
|
+
});
|
|
3250
|
+
if (!lease.acquired) return void 0;
|
|
3251
|
+
const fence = {
|
|
3252
|
+
runId: key,
|
|
3253
|
+
generation: lease.record.generation,
|
|
3254
|
+
ownerId
|
|
3255
|
+
};
|
|
3256
|
+
const claimed = await setLoopStatus(store, runId, "running", snapshot.status);
|
|
3257
|
+
if (claimed?.timestamp !== snapshot.timestamp) {
|
|
3258
|
+
if (claimed && snapshot.status !== "running") await setLoopStatus(store, runId, "suspended", "running");
|
|
3259
|
+
await store.releaseRunOwnership(fence);
|
|
3260
|
+
return;
|
|
3261
|
+
}
|
|
3262
|
+
return {
|
|
3263
|
+
fence,
|
|
3264
|
+
release: async () => {
|
|
3265
|
+
if (!matchesRunFence(await store.getRunOwnership({ runId: key }), fence)) return;
|
|
3266
|
+
await setLoopStatus(store, runId, "suspended", "running");
|
|
3267
|
+
await store.releaseRunOwnership(fence);
|
|
3268
|
+
}
|
|
3269
|
+
};
|
|
3270
|
+
}
|
|
3271
|
+
/**
|
|
3272
|
+
* Throws unless this resume may wait for the live one holding the run: one resuming a different
|
|
3273
|
+
* call, or any resume once the holder's segment parked again in this process. Any other resume is a
|
|
3274
|
+
* duplicate, and waiting would hand its resume data to whatever the run suspends on next.
|
|
3275
|
+
*/
|
|
3276
|
+
function assertMayWaitFor(owner, runId, toolCallId) {
|
|
3277
|
+
const [ownerProcess, , ...label] = owner.ownerId.split("/");
|
|
3278
|
+
const ownerToolCallId = label.join("/");
|
|
3279
|
+
if (ownerProcess === RESUME_CLAIM_PROCESS_ID && !inFlightToolCallResumes.get(runId)?.has(ownerToolCallId) || toolCallId && ownerToolCallId !== toolCallId) return;
|
|
3280
|
+
throw resumeAlreadyClaimedError(agent.name, runId, toolCallId);
|
|
3281
|
+
}
|
|
3050
3282
|
/**
|
|
3051
3283
|
* Tool calls and text from before the suspension, seeded into the resumed stream
|
|
3052
3284
|
* so its `toolCalls` and `text` include them without replaying their chunks.
|
|
@@ -3151,15 +3383,6 @@ function createInngestAgent(options) {
|
|
|
3151
3383
|
* Best-effort: the local abort has already happened, and a caller asking to
|
|
3152
3384
|
* stop a run should not get a rejection because the publish failed.
|
|
3153
3385
|
*/
|
|
3154
|
-
function forwardExternalAbort(external, controller, runId) {
|
|
3155
|
-
const forward = () => {
|
|
3156
|
-
controller.abort(external.reason);
|
|
3157
|
-
requestRemoteAbort(runId);
|
|
3158
|
-
};
|
|
3159
|
-
if (external.aborted) forward();
|
|
3160
|
-
else external.addEventListener("abort", forward, { once: true });
|
|
3161
|
-
return () => external.removeEventListener("abort", forward);
|
|
3162
|
-
}
|
|
3163
3386
|
async function requestRemoteAbort(runId) {
|
|
3164
3387
|
try {
|
|
3165
3388
|
await publishAbortRequest(getPubsub(), runId);
|
|
@@ -3245,8 +3468,7 @@ function createInngestAgent(options) {
|
|
|
3245
3468
|
const { runId, messageId, workflowInput, registryEntry, threadId, resourceId } = preparation;
|
|
3246
3469
|
workflowInput.agentId = agentId;
|
|
3247
3470
|
workflowInput.agentName = agentName;
|
|
3248
|
-
const abortController =
|
|
3249
|
-
const stopForwardingAbort = streamOptions?.abortSignal ? forwardExternalAbort(streamOptions.abortSignal, abortController, runId) : void 0;
|
|
3471
|
+
const { controller: abortController, detach: stopForwardingAbort } = createRunAbortController(streamOptions?.abortSignal, { onExternalAbort: () => void requestRemoteAbort(runId) });
|
|
3250
3472
|
registryEntry.abortController = abortController;
|
|
3251
3473
|
const clearTotalTimeout = armTotalTimeout(registryEntry, abortController, runId, callbackOptions.modelSettings?.timeout?.totalMs);
|
|
3252
3474
|
registryEntry.messageList = preparation.messageList;
|
|
@@ -3345,6 +3567,7 @@ function createInngestAgent(options) {
|
|
|
3345
3567
|
throw error;
|
|
3346
3568
|
}
|
|
3347
3569
|
}).catch(async (error) => {
|
|
3570
|
+
endRunSpansWithError(runId, error);
|
|
3348
3571
|
await emitError(runId, error);
|
|
3349
3572
|
await failStream(error);
|
|
3350
3573
|
});
|
|
@@ -3397,6 +3620,11 @@ function createInngestAgent(options) {
|
|
|
3397
3620
|
bgManager: mastra?.backgroundTaskManager
|
|
3398
3621
|
});
|
|
3399
3622
|
}
|
|
3623
|
+
const markedToolCallId = resumeOptions?.toolCallId ?? "";
|
|
3624
|
+
if (inFlightToolCallResumes.get(runId)?.has(markedToolCallId)) {
|
|
3625
|
+
if (!await resumeClaimStore(mastra) || await liveResumeClaim(runId)) throw resumeAlreadyClaimedError(agent.name, runId, resumeOptions?.toolCallId);
|
|
3626
|
+
inFlightToolCallResumes.get(runId)?.delete(markedToolCallId);
|
|
3627
|
+
}
|
|
3400
3628
|
const existingRegistryEntry = getRunRegistryEntry(runId, mastra);
|
|
3401
3629
|
await (existingRegistryEntry?.workflowExecution)?.catch(() => {});
|
|
3402
3630
|
const resumableSnapshot = (async () => {
|
|
@@ -3408,9 +3636,21 @@ function createInngestAgent(options) {
|
|
|
3408
3636
|
});
|
|
3409
3637
|
const toolCallId = resumeOptions?.toolCallId;
|
|
3410
3638
|
let nestedSnapshot;
|
|
3639
|
+
let held = false;
|
|
3411
3640
|
const isReady = async (s) => {
|
|
3412
3641
|
nestedSnapshot = void 0;
|
|
3413
|
-
|
|
3642
|
+
held = false;
|
|
3643
|
+
const claimed = s?.status === "running" && Object.keys(s.suspendedPaths ?? {}).length > 0;
|
|
3644
|
+
if (s?.status !== "suspended" && !claimed) return false;
|
|
3645
|
+
const owner = await liveResumeClaim(runId);
|
|
3646
|
+
if (owner) {
|
|
3647
|
+
held = true;
|
|
3648
|
+
if (s.status !== "suspended") assertMayWaitFor(owner, runId, toolCallId);
|
|
3649
|
+
return false;
|
|
3650
|
+
}
|
|
3651
|
+
if (claimed && !await resumeClaimStore(mastra)) return false;
|
|
3652
|
+
if (toolCallId && !s.resumeLabels?.[toolCallId]) return false;
|
|
3653
|
+
if (s.activePaths?.length) return false;
|
|
3414
3654
|
const labelIds = Object.keys(s.resumeLabels ?? {});
|
|
3415
3655
|
if (labelIds.length === 0) return true;
|
|
3416
3656
|
nestedSnapshot = await workflowsStore.loadWorkflowSnapshot({
|
|
@@ -3421,14 +3661,18 @@ function createInngestAgent(options) {
|
|
|
3421
3661
|
};
|
|
3422
3662
|
let snapshot = await loadSnapshot();
|
|
3423
3663
|
const deadline = Date.now() + RESUME_SNAPSHOT_WAIT_MS;
|
|
3424
|
-
|
|
3664
|
+
let ready;
|
|
3665
|
+
while (!(ready = await isReady(snapshot)) && Date.now() < deadline) {
|
|
3666
|
+
assertToolCallResumeNotInFlight(agent.name, runId, toolCallId);
|
|
3425
3667
|
await new Promise((resolve) => setTimeout(resolve, RESUME_SNAPSHOT_POLL_MS));
|
|
3426
3668
|
snapshot = await loadSnapshot();
|
|
3427
3669
|
}
|
|
3428
3670
|
return {
|
|
3429
3671
|
hasStore: true,
|
|
3430
3672
|
snapshot,
|
|
3431
|
-
nestedSnapshot
|
|
3673
|
+
nestedSnapshot,
|
|
3674
|
+
ready,
|
|
3675
|
+
held
|
|
3432
3676
|
};
|
|
3433
3677
|
})();
|
|
3434
3678
|
resumableSnapshot.catch(() => {});
|
|
@@ -3438,8 +3682,10 @@ function createInngestAgent(options) {
|
|
|
3438
3682
|
requestContext: new RequestContext$1([...savedRequestContext, ...resumeOptions?.requestContext?.entries() ?? []])
|
|
3439
3683
|
});
|
|
3440
3684
|
validateModelTimeoutSettings(callbackOptions.modelSettings?.timeout);
|
|
3441
|
-
const { hasStore, snapshot: suspendedSnapshot, nestedSnapshot } = await resumableSnapshot;
|
|
3442
|
-
|
|
3685
|
+
const { hasStore, snapshot: suspendedSnapshot, nestedSnapshot, ready: snapshotReady, held } = await resumableSnapshot;
|
|
3686
|
+
const takeover = snapshotReady && suspendedSnapshot?.status === "running";
|
|
3687
|
+
if (held || !takeover && suspendedSnapshot?.status === "running" && Object.keys(suspendedSnapshot.suspendedPaths ?? {}).length) throw resumeAlreadyClaimedError(agent.name, runId, resumeOptions?.toolCallId);
|
|
3688
|
+
if (hasStore && !takeover && suspendedSnapshot?.status !== "suspended") throw new NonRetriableError(`Cannot resume run ${runId}: it is not suspended` + (suspendedSnapshot?.status ? ` (status: ${suspendedSnapshot.status}).` : " (no snapshot found)."));
|
|
3443
3689
|
const suspendedStepIds = suspendedSnapshot?.suspendedPaths ? Object.keys(suspendedSnapshot.suspendedPaths) : [];
|
|
3444
3690
|
const resumeLabels = suspendedSnapshot?.resumeLabels ?? {};
|
|
3445
3691
|
const expandToLeafPath = (stepId) => {
|
|
@@ -3450,7 +3696,7 @@ function createInngestAgent(options) {
|
|
|
3450
3696
|
let steps;
|
|
3451
3697
|
if (toolCallId) {
|
|
3452
3698
|
const targetStepId = resumeLabels[toolCallId]?.stepId;
|
|
3453
|
-
if (!targetStepId) {
|
|
3699
|
+
if (!targetStepId || nestedSnapshot && !nestedSnapshot.resumeLabels?.[toolCallId]) {
|
|
3454
3700
|
const available = Object.keys(resumeLabels);
|
|
3455
3701
|
throw new 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.`));
|
|
3456
3702
|
}
|
|
@@ -3462,8 +3708,16 @@ function createInngestAgent(options) {
|
|
|
3462
3708
|
}
|
|
3463
3709
|
const resumeOffset = await getPubsubOffset(runId);
|
|
3464
3710
|
const { toolCalls: initialToolCalls, resumedText } = await loadSuspendedIteration(runId, suspendedSnapshot, nestedSnapshot);
|
|
3465
|
-
const
|
|
3466
|
-
const
|
|
3711
|
+
const markKey = toolCallId ?? (await resumeClaimStore(mastra) ? "" : void 0);
|
|
3712
|
+
const releaseToolCallMarker = markKey === void 0 ? () => {} : markToolCallResume(runId, markKey);
|
|
3713
|
+
if (!releaseToolCallMarker) throw resumeAlreadyClaimedError(agent.name, runId, toolCallId);
|
|
3714
|
+
const claim = await claimSuspension(runId, suspendedSnapshot ?? {}, toolCallId);
|
|
3715
|
+
if (!claim) {
|
|
3716
|
+
releaseToolCallMarker();
|
|
3717
|
+
assertToolCallResumeNotInFlight(agent.name, runId, toolCallId);
|
|
3718
|
+
return proxyRef.resume(runId, resumeData, resumeOptions);
|
|
3719
|
+
}
|
|
3720
|
+
const { controller: abortController, detach: stopForwardingAbort } = createRunAbortController(resumeOptions?.abortSignal, { onExternalAbort: () => void requestRemoteAbort(runId) });
|
|
3467
3721
|
let existingEntry = existingRegistryEntry;
|
|
3468
3722
|
if (!existingEntry) {
|
|
3469
3723
|
existingEntry = {
|
|
@@ -3515,6 +3769,7 @@ function createInngestAgent(options) {
|
|
|
3515
3769
|
let resumeCleanedUp = false;
|
|
3516
3770
|
const finalizeResumeRegistry = () => {
|
|
3517
3771
|
clearTotalTimeout();
|
|
3772
|
+
releaseToolCallMarker();
|
|
3518
3773
|
if (resumeCleanedUp) return;
|
|
3519
3774
|
resumeCleanedUp = true;
|
|
3520
3775
|
stopForwardingAbort?.();
|
|
@@ -3543,7 +3798,10 @@ function createInngestAgent(options) {
|
|
|
3543
3798
|
requestContext: callbackOptions.requestContext,
|
|
3544
3799
|
onChunk: (chunk) => {
|
|
3545
3800
|
resumedChunkSeen = true;
|
|
3546
|
-
if (chunk.type === "tool-call-approval" || chunk.type === "tool-call-suspended")
|
|
3801
|
+
if (chunk.type === "tool-call-approval" || chunk.type === "tool-call-suspended") {
|
|
3802
|
+
stopForwardingAbort?.();
|
|
3803
|
+
if (!toolCallId || chunk.payload.toolCallId === toolCallId) releaseToolCallMarker();
|
|
3804
|
+
}
|
|
3547
3805
|
return callbackOptions.onChunk?.(chunk);
|
|
3548
3806
|
},
|
|
3549
3807
|
onStepFinish: callbackOptions.onStepFinish,
|
|
@@ -3564,6 +3822,7 @@ function createInngestAgent(options) {
|
|
|
3564
3822
|
onSuspended: async (data) => {
|
|
3565
3823
|
if (!resumedChunkSeen) return;
|
|
3566
3824
|
clearTotalTimeout();
|
|
3825
|
+
releaseToolCallMarker();
|
|
3567
3826
|
try {
|
|
3568
3827
|
await callbackOptions.onSuspended?.(data);
|
|
3569
3828
|
} finally {
|
|
@@ -3581,6 +3840,7 @@ function createInngestAgent(options) {
|
|
|
3581
3840
|
});
|
|
3582
3841
|
const eventName = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;
|
|
3583
3842
|
let notResumable = false;
|
|
3843
|
+
let sendStarted = false;
|
|
3584
3844
|
const didThreadRunPublishTerminal = agentThreadStreamRuntime.captureThreadRunTerminalPublish(runId, agent.getPubSub());
|
|
3585
3845
|
const dispatch = ready.then(async () => {
|
|
3586
3846
|
const snapshot = suspendedSnapshot;
|
|
@@ -3595,7 +3855,9 @@ function createInngestAgent(options) {
|
|
|
3595
3855
|
traceId: snapshot.tracingContext.traceId,
|
|
3596
3856
|
parentSpanId: snapshot.tracingContext.spanId
|
|
3597
3857
|
} : void 0;
|
|
3858
|
+
sendStarted = true;
|
|
3598
3859
|
await inngest.send({
|
|
3860
|
+
...snapshot?.timestamp && claim.fence ? { id: `${runId}:resume:${snapshot.timestamp}:${claim.fence.generation}` } : {},
|
|
3599
3861
|
name: eventName,
|
|
3600
3862
|
data: buildDurableResumeEventData({
|
|
3601
3863
|
inputData: resumeData,
|
|
@@ -3607,7 +3869,9 @@ function createInngestAgent(options) {
|
|
|
3607
3869
|
resume: {
|
|
3608
3870
|
steps,
|
|
3609
3871
|
resumePayload: resumeData,
|
|
3610
|
-
resumePath: steps[0] ? snapshot?.suspendedPaths?.[steps[0]] : void 0
|
|
3872
|
+
resumePath: steps[0] ? snapshot?.suspendedPaths?.[steps[0]] : void 0,
|
|
3873
|
+
label: toolCallId,
|
|
3874
|
+
claim: claim.fence
|
|
3611
3875
|
}
|
|
3612
3876
|
})
|
|
3613
3877
|
});
|
|
@@ -3621,6 +3885,7 @@ function createInngestAgent(options) {
|
|
|
3621
3885
|
} catch (error) {
|
|
3622
3886
|
streamCleanup();
|
|
3623
3887
|
finalizeResumeRegistry();
|
|
3888
|
+
if (!sendStarted) await claim.release().catch((releaseError) => mastra?.getLogger?.()?.warn?.(`[InngestAgent] resume(${runId}) failed to release its claim`, releaseError));
|
|
3624
3889
|
throw error;
|
|
3625
3890
|
}
|
|
3626
3891
|
const resumeMemory = resumeOptions?.memory;
|
|
@@ -4724,4 +4989,4 @@ function init(inngest) {
|
|
|
4724
4989
|
}
|
|
4725
4990
|
export { createServe as a, isInngestAgent as c, InngestRun as d, InngestPubSub as f, connect as i, createInngestDurableAgenticWorkflow as l, InngestExecutionEngine as m, init as n, serve$1 as o, OVERSIZED_EVENT_CHUNK_TYPE as p, _compatibilityCheck as r, createInngestAgent as s, createStep as t, InngestWorkflow as u };
|
|
4726
4991
|
|
|
4727
|
-
//# sourceMappingURL=src-
|
|
4992
|
+
//# sourceMappingURL=src-IbSX_hCm.js.map
|