@mastra/inngest 1.9.1 → 1.9.2-alpha.0

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.
@@ -1,16 +1,24 @@
1
- import { MastraNonRetryableError, getErrorFromUnknown } from "@mastra/core/error";
2
- import { EntityType, SpanType } from "@mastra/core/observability";
3
- import { DefaultExecutionEngine, Run, Workflow, createTimeTravelExecutionParams, getEntryWorkflow, hydrateSerializedStepErrors, isSingleStepEntry } from "@mastra/core/workflows";
1
+ import { Agent, MessageList, TripWire } from "@mastra/core/agent";
2
+ import { ErrorCategory, ErrorDomain, MastraError, MastraNonRetryableError, getErrorFromUnknown } from "@mastra/core/error";
3
+ import { EntityType, InternalSpans, SpanType } from "@mastra/core/observability";
4
+ import { ProcessorRunner, ProcessorState, ProcessorStepOutputSchema, ProcessorStepSchema } from "@mastra/core/processors";
5
+ import { toStandardSchema } from "@mastra/core/schema";
6
+ import { Tool, createTool } from "@mastra/core/tools";
7
+ import { DefaultExecutionEngine, Run, Workflow, createStepFromAgent, createStepFromTool, createTimeTravelExecutionParams, getEntryWorkflow, hydrateSerializedStepErrors, isSingleStepEntry } from "@mastra/core/workflows";
4
8
  import { randomUUID } from "crypto";
5
- import { emitErrorEvent } from "@mastra/core/agent/durable";
9
+ import { AGENT_STREAM_TOPIC, DurableAgentDefaults, DurableStepIds, agentThreadStreamRuntime, baseIterationStateSchema, createBaseIterationStateUpdate, createDurableAgentStream, createDurableBackgroundTaskCheckStep, createDurableLLMExecutionStep, createDurableLLMMappingStep, createDurableToolCallStep, durableAgenticOutputSchema, emitErrorEvent, emitFinishEvent, executeDurableAgentScorers, globalRunRegistry, modelConfigSchema, prepareForDurableExecution, publishAbortRequest, resolveDurableToolCallConcurrency, runDurableFinishSideEffects, runDurableStreamUntilIdle, runResumeDurableStreamUntilIdle } from "@mastra/core/agent/durable";
6
10
  import { RequestContext } from "@mastra/core/di";
7
11
  import { NonRetriableError } from "inngest";
8
12
  import { AsyncLocalStorage } from "async_hooks";
9
- import { PubSub } from "@mastra/core/events";
13
+ import { CachingPubSub, PubSub } from "@mastra/core/events";
10
14
  import { subscribe } from "inngest/realtime";
11
15
  import { ReadableStream } from "stream/web";
12
16
  import { ChunkFrom, WorkflowRunOutput } from "@mastra/core/stream";
13
17
  import { MASTRA_AUTH_TOKEN_KEY } from "@mastra/core/request-context";
18
+ import { serve } from "inngest/hono";
19
+ import { InMemoryServerCache } from "@mastra/core/cache";
20
+ import { PUBSUB_SYMBOL } from "@mastra/core/workflows/_constants";
21
+ import { z } from "zod";
14
22
  //#region src/nested-workflow-output.ts
15
23
  const NESTED_WORKFLOW_OUTPUT_MODE = {
16
24
  DEFAULT: "default",
@@ -77,6 +85,15 @@ function isNonRetryableStepFailure(error) {
77
85
  return false;
78
86
  }
79
87
  const retryCountStorage = new AsyncLocalStorage();
88
+ const BUILTIN_ERROR_TYPES = [
89
+ TypeError,
90
+ RangeError,
91
+ ReferenceError,
92
+ SyntaxError,
93
+ EvalError,
94
+ URIError,
95
+ AggregateError
96
+ ];
80
97
  var InngestExecutionEngine = class extends DefaultExecutionEngine {
81
98
  parentStream;
82
99
  inngestStep;
@@ -208,16 +225,20 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
208
225
  return await operationFn();
209
226
  } catch (e) {
210
227
  const errorInstance = getErrorFromUnknown(e, {
211
- serializeStack: false,
228
+ serializeStack: true,
212
229
  fallbackMessage: "Unknown step execution error"
213
230
  });
214
231
  const isNonRetryable = isNonRetryableStepFailure(e);
215
- throw new Error(errorInstance.message, { cause: {
232
+ const wrapped = new Error(errorInstance.message, { cause: {
216
233
  status: "failed",
217
234
  error: errorInstance,
218
235
  endedAt: Date.now(),
219
236
  ...isNonRetryable && { nonRetryable: true }
220
237
  } });
238
+ if (errorInstance.stack) wrapped.stack = errorInstance.stack;
239
+ const builtinErrorType = e instanceof Error ? BUILTIN_ERROR_TYPES.find((ErrorType) => Object.getPrototypeOf(e) === ErrorType.prototype) : void 0;
240
+ if (builtinErrorType) Object.setPrototypeOf(wrapped, builtinErrorType.prototype);
241
+ throw wrapped;
221
242
  }
222
243
  });
223
244
  }
@@ -245,6 +266,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
245
266
  async createStepSpan(params) {
246
267
  const { executionContext, operationId, options, parentSpan } = params;
247
268
  const parentSpanId = parentSpan?.id ?? executionContext.tracingIds?.workflowSpanId;
269
+ if (!this.mastra?.observability?.getSelectedInstance({})) return void 0;
248
270
  const exportedSpan = await this.wrapDurableOperation(operationId, async () => {
249
271
  const observability = this.mastra?.observability?.getSelectedInstance({});
250
272
  if (!observability) return void 0;
@@ -284,6 +306,7 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
284
306
  async createChildSpan(params) {
285
307
  const { executionContext, operationId, options, parentSpan } = params;
286
308
  const parentSpanId = parentSpan?.id ?? executionContext.tracingIds?.workflowSpanId;
309
+ if (!this.mastra?.observability?.getSelectedInstance({})) return void 0;
287
310
  const exportedSpan = await this.wrapDurableOperation(operationId, async () => {
288
311
  const observability = this.mastra?.observability?.getSelectedInstance({});
289
312
  if (!observability) return void 0;
@@ -1962,17 +1985,946 @@ function toSnapshotResult(output) {
1962
1985
  return output;
1963
1986
  }
1964
1987
  //#endregion
1988
+ //#region src/durable-agent/create-inngest-agentic-workflow.ts
1989
+ /**
1990
+ * Input schema for the durable agentic workflow.
1991
+ * Extends base with observability fields for Inngest.
1992
+ */
1993
+ const durableAgenticInputSchema = z.object({
1994
+ runId: z.string(),
1995
+ agentId: z.string(),
1996
+ agentName: z.string().optional(),
1997
+ messageListState: z.any(),
1998
+ toolsMetadata: z.array(z.any()),
1999
+ modelConfig: modelConfigSchema,
2000
+ options: z.any(),
2001
+ state: z.any(),
2002
+ messageId: z.string(),
2003
+ requestContextEntries: z.record(z.string(), z.any()).optional(),
2004
+ agentSpanData: z.any().optional(),
2005
+ modelSpanData: z.any().optional(),
2006
+ stepIndex: z.number().optional()
2007
+ });
2008
+ /**
2009
+ * Iteration state schema - extends base with observability fields.
2010
+ */
2011
+ const iterationStateSchema = baseIterationStateSchema.extend({
2012
+ agentSpanData: z.any().optional(),
2013
+ modelSpanData: z.any().optional(),
2014
+ stepIndex: z.number()
2015
+ });
2016
+ /**
2017
+ * Create a durable agentic workflow using Inngest.
2018
+ *
2019
+ * This workflow implements the agentic loop pattern in a durable way using
2020
+ * Inngest's execution engine:
2021
+ *
2022
+ * 1. LLM Execution Step - Calls the LLM and gets response/tool calls
2023
+ * 2. Tool Call Steps (foreach) - Executes each tool call individually with suspend support
2024
+ * 3. LLM Mapping Step - Merges tool results back into state
2025
+ * 4. Loop - Continues if more tool calls are needed (dowhile)
2026
+ *
2027
+ * All state flows through workflow input/output, making it durable across
2028
+ * process restarts and execution engine replays.
2029
+ *
2030
+ * @param options - Configuration options
2031
+ * @returns An InngestWorkflow instance that implements the agentic loop
2032
+ */
2033
+ /** Prefix for Inngest engine workflow IDs to avoid collision with other engines */
2034
+ const INNGEST_ENGINE_PREFIX = "inngest";
2035
+ /** Inngest-prefixed workflow IDs */
2036
+ const InngestDurableStepIds = {
2037
+ AGENTIC_EXECUTION: `${INNGEST_ENGINE_PREFIX}:${DurableStepIds.AGENTIC_EXECUTION}`,
2038
+ AGENTIC_LOOP: `${INNGEST_ENGINE_PREFIX}:${DurableStepIds.AGENTIC_LOOP}`
2039
+ };
2040
+ function createInngestDurableAgenticWorkflow(options) {
2041
+ const { inngest, maxSteps = DurableAgentDefaults.MAX_STEPS, retries } = options;
2042
+ const { createWorkflow } = init(inngest);
2043
+ const llmExecutionStep = createDurableLLMExecutionStep();
2044
+ const toolCallStep = createDurableToolCallStep();
2045
+ const llmMappingStep = createDurableLLMMappingStep();
2046
+ const backgroundTaskCheckStep = createDurableBackgroundTaskCheckStep();
2047
+ const singleIterationWorkflow = createWorkflow({
2048
+ id: InngestDurableStepIds.AGENTIC_EXECUTION,
2049
+ retries,
2050
+ inputSchema: iterationStateSchema,
2051
+ outputSchema: iterationStateSchema,
2052
+ options: {
2053
+ tracingPolicy: { internal: InternalSpans.WORKFLOW },
2054
+ shouldPersistSnapshot: ({ workflowStatus }) => workflowStatus === "suspended",
2055
+ evaluatePersistencePredicateBeforeDurableOperation: true,
2056
+ validateInputs: false,
2057
+ emitStepEvents: false
2058
+ },
2059
+ steps: []
2060
+ }).map(async ({ inputData }) => {
2061
+ const state = inputData;
2062
+ return {
2063
+ runId: state.runId,
2064
+ agentId: state.agentId,
2065
+ agentName: state.agentName,
2066
+ messageListState: state.messageListState,
2067
+ toolsMetadata: state.toolsMetadata,
2068
+ modelConfig: state.modelConfig,
2069
+ options: state.options,
2070
+ state: state.state,
2071
+ messageId: state.messageId,
2072
+ requestContextEntries: state.requestContextEntries,
2073
+ agentSpanData: state.agentSpanData,
2074
+ modelSpanData: state.modelSpanData,
2075
+ stepIndex: state.stepIndex
2076
+ };
2077
+ }, { id: "map-to-llm-input" }).then(llmExecutionStep).map(async ({ inputData }) => {
2078
+ const llmOutput = inputData;
2079
+ return (llmOutput.toolCalls ?? []).map((toolCall) => ({
2080
+ ...toolCall,
2081
+ stepSpanData: llmOutput.stepSpanData
2082
+ }));
2083
+ }, { id: "extract-tool-calls" }).foreach(toolCallStep, { concurrency: ({ inputData, getInitData }) => {
2084
+ const state = getInitData();
2085
+ return resolveDurableToolCallConcurrency({
2086
+ options: state?.options,
2087
+ toolsMetadata: state?.toolsMetadata,
2088
+ toolCalls: inputData
2089
+ });
2090
+ } }).map(async ({ inputData, getStepResult, getInitData }) => {
2091
+ const toolResults = inputData;
2092
+ const llmOutput = getStepResult(llmExecutionStep.id);
2093
+ const initData = getInitData();
2094
+ return {
2095
+ llmOutput,
2096
+ toolResults,
2097
+ runId: initData.runId,
2098
+ agentId: initData.agentId,
2099
+ messageId: initData.messageId,
2100
+ state: llmOutput?.state ?? initData.state
2101
+ };
2102
+ }, { id: "collect-tool-results" }).then(llmMappingStep).then(backgroundTaskCheckStep).map(async ({ inputData, getInitData }) => {
2103
+ const executionOutput = inputData;
2104
+ const initData = getInitData();
2105
+ return {
2106
+ ...createBaseIterationStateUpdate({
2107
+ currentState: initData,
2108
+ executionOutput
2109
+ }),
2110
+ agentSpanData: initData.agentSpanData,
2111
+ modelSpanData: initData.modelSpanData,
2112
+ stepIndex: initData.stepIndex + 1
2113
+ };
2114
+ }, { id: "update-iteration-state" }).commit();
2115
+ return createWorkflow({
2116
+ id: InngestDurableStepIds.AGENTIC_LOOP,
2117
+ retries,
2118
+ inputSchema: durableAgenticInputSchema,
2119
+ outputSchema: durableAgenticOutputSchema,
2120
+ options: {
2121
+ tracingPolicy: { internal: InternalSpans.WORKFLOW },
2122
+ shouldPersistSnapshot: ({ workflowStatus }) => workflowStatus === "suspended",
2123
+ evaluatePersistencePredicateBeforeDurableOperation: true,
2124
+ validateInputs: false,
2125
+ emitStepEvents: false
2126
+ },
2127
+ steps: []
2128
+ }).map(async ({ inputData }) => {
2129
+ const input = inputData;
2130
+ const agentSpanData = input.agentSpanData;
2131
+ const modelSpanData = input.modelSpanData;
2132
+ return {
2133
+ ...input,
2134
+ iterationCount: 0,
2135
+ accumulatedSteps: [],
2136
+ accumulatedUsage: {
2137
+ inputTokens: 0,
2138
+ outputTokens: 0,
2139
+ totalTokens: 0
2140
+ },
2141
+ lastStepResult: void 0,
2142
+ agentSpanData,
2143
+ modelSpanData,
2144
+ stepIndex: input.stepIndex ?? 0
2145
+ };
2146
+ }, { id: "init-iteration-state" }).dowhile(singleIterationWorkflow, async ({ inputData }) => {
2147
+ const state = inputData;
2148
+ const shouldContinue = state.lastStepResult?.isContinued === true;
2149
+ const effectiveMaxSteps = state.options?.maxSteps ?? maxSteps;
2150
+ const underMaxSteps = state.iterationCount < effectiveMaxSteps;
2151
+ return shouldContinue && underMaxSteps;
2152
+ }).map(async (params) => {
2153
+ const { inputData, mastra, requestContext, tracingContext } = params;
2154
+ const state = inputData;
2155
+ const initData = params.getInitData();
2156
+ const pubsub = params[PUBSUB_SYMBOL];
2157
+ const lastStep = state.accumulatedSteps[state.accumulatedSteps.length - 1];
2158
+ let finalText = lastStep?.text;
2159
+ const finishResult = await runDurableFinishSideEffects({
2160
+ runId: state.runId,
2161
+ initData,
2162
+ messageListState: state.messageListState,
2163
+ mastra,
2164
+ requestContext,
2165
+ tracingContext,
2166
+ logger: mastra?.getLogger?.(),
2167
+ outputResult: {
2168
+ text: finalText ?? "",
2169
+ usage: state.accumulatedUsage,
2170
+ finishReason: state.lastStepResult?.reason ?? "unknown",
2171
+ steps: state.accumulatedSteps
2172
+ }
2173
+ });
2174
+ if (lastStep && finishResult.outputText && finishResult.outputText !== (finalText ?? "")) {
2175
+ lastStep.text = finishResult.outputText;
2176
+ finalText = finishResult.outputText;
2177
+ }
2178
+ const finalOutput = {
2179
+ messageListState: finishResult.messageListState,
2180
+ messageId: state.messageId,
2181
+ stepResult: state.lastStepResult || {
2182
+ reason: "stop",
2183
+ warnings: [],
2184
+ isContinued: false
2185
+ },
2186
+ output: {
2187
+ text: finalText,
2188
+ usage: state.accumulatedUsage,
2189
+ steps: state.accumulatedSteps
2190
+ },
2191
+ state: state.state
2192
+ };
2193
+ const observability = mastra?.observability?.getSelectedInstance({});
2194
+ if (state.modelSpanData) (observability?.rebuildSpan(state.modelSpanData))?.createTracker()?.endGeneration({
2195
+ output: { text: finalText },
2196
+ attributes: { finishReason: state.lastStepResult?.reason || "stop" },
2197
+ usage: state.accumulatedUsage
2198
+ });
2199
+ if (state.agentSpanData) (observability?.rebuildSpan(state.agentSpanData))?.end({ output: { text: finalText } });
2200
+ if (pubsub) await emitFinishEvent(pubsub, state.runId, {
2201
+ output: finalOutput.output,
2202
+ stepResult: finalOutput.stepResult
2203
+ });
2204
+ return finalOutput;
2205
+ }, { id: "map-final-output" }).map(async ({ inputData, getInitData, mastra, requestContext, tracingContext }) => {
2206
+ executeDurableAgentScorers({
2207
+ initData: getInitData(),
2208
+ finalOutput: inputData,
2209
+ mastra,
2210
+ requestContext,
2211
+ tracingContext
2212
+ });
2213
+ return inputData;
2214
+ }, { id: "execute-scorers" }).commit();
2215
+ }
2216
+ //#endregion
2217
+ //#region src/durable-agent/create-inngest-agent.ts
2218
+ var InngestWorkflowCachingPubSub = class extends CachingPubSub {
2219
+ publish(topic, event, options) {
2220
+ if (topic.startsWith("workflow.events.v2.")) return super.publish(topic, event, {
2221
+ ...options,
2222
+ localOnly: true
2223
+ });
2224
+ return super.publish(topic, event, options);
2225
+ }
2226
+ };
2227
+ /**
2228
+ * Internal sentinel used by {@link InngestAgent.generate} and
2229
+ * {@link InngestAgent.resumeGenerate} to ask the underlying `stream()` /
2230
+ * `resume()` implementation to close the consumer stream on a SUSPENDED
2231
+ * event, so `getFullOutput()` resolves promptly with `finishReason:
2232
+ * 'suspended'` instead of waiting for FINISH/ERROR.
2233
+ *
2234
+ * Modelled on `CLOSE_ON_SUSPEND` in core `DurableAgent`.
2235
+ */
2236
+ const CLOSE_ON_SUSPEND = Symbol("mastra.durable.inngest.closeOnSuspend");
2237
+ /**
2238
+ * Internal symbol used by `generate()` / `resumeGenerate()` to tear down the
2239
+ * pubsub subscription on suspend without removing the run-registry entry.
2240
+ * The public `cleanup()` does both; this lets the generate wrappers keep the
2241
+ * registry alive across `suspend` → `resumeGenerate()` while still releasing
2242
+ * the local stream subscription.
2243
+ */
2244
+ const STREAM_CLEANUP = Symbol("mastra.durable.inngest.streamCleanup");
2245
+ const RESUME_SNAPSHOT_WAIT_MS = 1e4;
2246
+ const RESUME_SNAPSHOT_POLL_MS = 100;
2247
+ /**
2248
+ * Create an Inngest-powered durable agent from a Mastra Agent.
2249
+ *
2250
+ * This factory function wraps a regular Mastra Agent with Inngest's durable
2251
+ * execution capabilities. The returned InngestAgent can be registered with
2252
+ * Mastra, and the required workflow will be automatically registered.
2253
+ *
2254
+ * @param options - Configuration options
2255
+ * @returns An InngestAgent that can be registered with Mastra
2256
+ *
2257
+ * @example
2258
+ * ```typescript
2259
+ * const agent = new Agent({
2260
+ * id: 'my-agent',
2261
+ * instructions: 'You are helpful',
2262
+ * model: openai('gpt-4'),
2263
+ * });
2264
+ *
2265
+ * const durableAgent = createInngestAgent({ agent, inngest });
2266
+ *
2267
+ * const mastra = new Mastra({
2268
+ * agents: { myAgent: durableAgent },
2269
+ * });
2270
+ * ```
2271
+ */
2272
+ function createInngestAgent(options) {
2273
+ const { agent, inngest, id: idOverride, name: nameOverride, pubsub: customPubsub, cache, mastra: mastraOption, shouldPersistSnapshot, retries } = options;
2274
+ if (shouldPersistSnapshot) console.warn(`InngestAgent '${idOverride ?? agent.id}': ignoring the shouldPersistSnapshot option. Inngest's step memoization/replay owns durability, so InngestAgent always persists 'suspended' snapshots only (for human-in-the-loop resume).`);
2275
+ const agentId = idOverride ?? agent.id;
2276
+ const agentName = nameOverride ?? agent.name;
2277
+ let mastra = mastraOption;
2278
+ const activeStreamUntilIdle = /* @__PURE__ */ new Map();
2279
+ let proxyRef;
2280
+ const workflow = createInngestDurableAgenticWorkflow({
2281
+ inngest,
2282
+ retries
2283
+ });
2284
+ let _customCache = cache;
2285
+ let innerPubsub = customPubsub ?? new InngestPubSub(inngest, InngestDurableStepIds.AGENTIC_LOOP);
2286
+ let _cachingPubsub = null;
2287
+ function resolveCache() {
2288
+ const resolved = _customCache ?? mastra?.serverCache ?? new InMemoryServerCache();
2289
+ _customCache = resolved;
2290
+ return resolved;
2291
+ }
2292
+ function getPubsub() {
2293
+ if (!_cachingPubsub) if (innerPubsub instanceof CachingPubSub) {
2294
+ _cachingPubsub = innerPubsub;
2295
+ _customCache = _customCache ?? mastra?.serverCache;
2296
+ } else _cachingPubsub = new CachingPubSub(innerPubsub, resolveCache());
2297
+ return _cachingPubsub;
2298
+ }
2299
+ async function getPubsubOffset(runId) {
2300
+ return (await getPubsub().getHistory(AGENT_STREAM_TOPIC(runId))).length;
2301
+ }
2302
+ workflow.__setPubsubFactory((defaultPubsub) => {
2303
+ if (defaultPubsub instanceof CachingPubSub) return defaultPubsub;
2304
+ getPubsub();
2305
+ return new InngestWorkflowCachingPubSub(defaultPubsub, resolveCache());
2306
+ });
2307
+ function getCache() {
2308
+ getPubsub();
2309
+ return _customCache;
2310
+ }
2311
+ /**
2312
+ * Trigger the workflow via Inngest event
2313
+ */
2314
+ async function triggerWorkflow(runId, workflowInput, tracingOptions, actor) {
2315
+ const eventName = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;
2316
+ await inngest.send({
2317
+ name: eventName,
2318
+ data: buildDurableTriggerEventData({
2319
+ inputData: workflowInput,
2320
+ runId,
2321
+ resourceId: workflowInput.state?.resourceId,
2322
+ requestContext: workflowInput.requestContextEntries ?? {},
2323
+ tracingOptions,
2324
+ actor
2325
+ })
2326
+ });
2327
+ }
2328
+ /**
2329
+ * Emit an error event to pubsub.
2330
+ *
2331
+ * Best-effort: callers fire-and-forget this on paths that are already
2332
+ * failing, so an unreachable pubsub must not turn error reporting into an
2333
+ * unhandled rejection.
2334
+ */
2335
+ async function emitError(runId, error) {
2336
+ try {
2337
+ await emitErrorEvent(getPubsub(), runId, error);
2338
+ } catch (publishError) {
2339
+ mastra?.getLogger?.()?.warn?.("Failed to publish Inngest durable agent error event", {
2340
+ agentId,
2341
+ runId,
2342
+ error: publishError instanceof Error ? publishError.message : String(publishError)
2343
+ });
2344
+ }
2345
+ }
2346
+ /**
2347
+ * Stop a run in whichever worker is executing it.
2348
+ *
2349
+ * An Inngest agent's steps run on Inngest's infrastructure, essentially never
2350
+ * in the process that called `stream()`. The local `AbortController` is
2351
+ * therefore invisible to the step worker, and on its own `abort()` cannot
2352
+ * stop anything. Publishing an abort request lets the worker flip its own
2353
+ * controller and unwind the run gracefully, emitting the terminal stream
2354
+ * event consumers wait on — which a hard workflow cancel would skip.
2355
+ *
2356
+ * Best-effort: the local abort has already happened, and a caller asking to
2357
+ * stop a run should not get a rejection because the publish failed.
2358
+ */
2359
+ async function requestRemoteAbort(runId) {
2360
+ try {
2361
+ await publishAbortRequest(getPubsub(), runId);
2362
+ } catch (error) {
2363
+ mastra?.getLogger?.()?.warn?.("Failed to publish Inngest durable agent abort request", {
2364
+ agentId,
2365
+ runId,
2366
+ error: error instanceof Error ? error.message : String(error)
2367
+ });
2368
+ }
2369
+ }
2370
+ const result = new Proxy({
2371
+ get id() {
2372
+ return agentId;
2373
+ },
2374
+ get name() {
2375
+ return agentName;
2376
+ },
2377
+ get agent() {
2378
+ return agent;
2379
+ },
2380
+ get inngest() {
2381
+ return inngest;
2382
+ },
2383
+ get cache() {
2384
+ return getCache();
2385
+ },
2386
+ get pubsub() {
2387
+ return getPubsub();
2388
+ },
2389
+ async stream(messages, streamOptions) {
2390
+ if (streamOptions?.untilIdle) {
2391
+ const { untilIdle, ...rest } = streamOptions;
2392
+ const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
2393
+ return runDurableStreamUntilIdle(proxyRef, messages, {
2394
+ ...rest,
2395
+ maxIdleMs
2396
+ }, {
2397
+ activeStreams: activeStreamUntilIdle,
2398
+ bgManager: mastra?.backgroundTaskManager
2399
+ });
2400
+ }
2401
+ const { runId, messageId, workflowInput, registryEntry, threadId, resourceId } = await prepareForDurableExecution({
2402
+ agent,
2403
+ messages,
2404
+ options: streamOptions,
2405
+ runId: streamOptions?.runId,
2406
+ requestContext: streamOptions?.requestContext,
2407
+ methodType: streamOptions?.__methodType ?? "stream",
2408
+ mastra,
2409
+ durableAgentId: agentId,
2410
+ durableAgentName: agentName
2411
+ });
2412
+ workflowInput.agentId = agentId;
2413
+ workflowInput.agentName = agentName;
2414
+ const abortController = new AbortController();
2415
+ if (streamOptions?.abortSignal) {
2416
+ const external = streamOptions.abortSignal;
2417
+ if (external.aborted) abortController.abort(external.reason);
2418
+ else external.addEventListener("abort", () => abortController.abort(external.reason), { once: true });
2419
+ }
2420
+ registryEntry.abortController = abortController;
2421
+ registryEntry.abortSignal = abortController.signal;
2422
+ globalRunRegistry.set(runId, registryEntry);
2423
+ workflowInput.stepIndex = 0;
2424
+ let cleanedUp = false;
2425
+ const finalizeGlobalRegistry = () => {
2426
+ if (cleanedUp) return;
2427
+ cleanedUp = true;
2428
+ globalRunRegistry.delete(runId);
2429
+ };
2430
+ const { output, cleanup: streamCleanup, ready } = createDurableAgentStream({
2431
+ pubsub: getPubsub(),
2432
+ runId,
2433
+ messageId,
2434
+ model: {
2435
+ modelId: workflowInput.modelConfig.modelId,
2436
+ provider: workflowInput.modelConfig.provider,
2437
+ version: "v3"
2438
+ },
2439
+ threadId,
2440
+ resourceId,
2441
+ onChunk: streamOptions?.onChunk,
2442
+ onStepFinish: streamOptions?.onStepFinish,
2443
+ onFinish: async (result) => {
2444
+ try {
2445
+ await streamOptions?.onFinish?.(result);
2446
+ } finally {
2447
+ finalizeGlobalRegistry();
2448
+ }
2449
+ },
2450
+ onError: async (errorArg) => {
2451
+ try {
2452
+ await streamOptions?.onError?.(errorArg);
2453
+ } finally {
2454
+ finalizeGlobalRegistry();
2455
+ }
2456
+ },
2457
+ onSuspended: streamOptions?.onSuspended,
2458
+ onAbort: async (data) => {
2459
+ try {
2460
+ await (streamOptions?.onAbort)?.(data);
2461
+ } finally {
2462
+ finalizeGlobalRegistry();
2463
+ }
2464
+ },
2465
+ onIterationComplete: streamOptions?.onIterationComplete ? async (data) => {
2466
+ await streamOptions.onIterationComplete?.(data);
2467
+ } : void 0,
2468
+ closeOnSuspend: streamOptions?.[CLOSE_ON_SUSPEND] === true
2469
+ });
2470
+ const agentSpanData = workflowInput.agentSpanData;
2471
+ const tracingOptions = agentSpanData?.traceId && agentSpanData?.id ? {
2472
+ traceId: agentSpanData.traceId,
2473
+ parentSpanId: agentSpanData.id
2474
+ } : void 0;
2475
+ const workflowExecution = ready.then(() => triggerWorkflow(runId, workflowInput, tracingOptions, streamOptions?.actor)).catch((error) => {
2476
+ emitError(runId, error);
2477
+ });
2478
+ const trackedEntry = globalRunRegistry.get(runId);
2479
+ if (trackedEntry) trackedEntry.workflowExecution = workflowExecution;
2480
+ await agentThreadStreamRuntime.registerRun(proxyRef, output, streamOptions ?? {}, agent.getPubSub());
2481
+ const cleanup = () => {
2482
+ streamCleanup();
2483
+ finalizeGlobalRegistry();
2484
+ };
2485
+ const abort = async (reason) => {
2486
+ if (!abortController.signal.aborted) abortController.abort(reason);
2487
+ await requestRemoteAbort(runId);
2488
+ };
2489
+ return {
2490
+ output,
2491
+ runId,
2492
+ threadId,
2493
+ resourceId,
2494
+ cleanup,
2495
+ abort,
2496
+ get fullStream() {
2497
+ return output.fullStream;
2498
+ },
2499
+ [STREAM_CLEANUP]: streamCleanup
2500
+ };
2501
+ },
2502
+ async resume(runId, resumeData, resumeOptions) {
2503
+ if (resumeOptions?.untilIdle) {
2504
+ const { untilIdle, ...rest } = resumeOptions;
2505
+ const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
2506
+ return runResumeDurableStreamUntilIdle(proxyRef, runId, resumeData, {
2507
+ ...rest,
2508
+ maxIdleMs
2509
+ }, {
2510
+ activeStreams: activeStreamUntilIdle,
2511
+ bgManager: mastra?.backgroundTaskManager
2512
+ });
2513
+ }
2514
+ const existingRegistryEntry = globalRunRegistry.get(runId);
2515
+ await (existingRegistryEntry?.workflowExecution)?.catch(() => {});
2516
+ const resumeOffset = await getPubsubOffset(runId);
2517
+ const abortController = new AbortController();
2518
+ if (resumeOptions?.abortSignal) {
2519
+ const external = resumeOptions.abortSignal;
2520
+ if (external.aborted) abortController.abort(external.reason);
2521
+ else external.addEventListener("abort", () => abortController.abort(external.reason), { once: true });
2522
+ }
2523
+ let existingEntry = existingRegistryEntry;
2524
+ if (!existingEntry) {
2525
+ existingEntry = {
2526
+ isPlaceholder: true,
2527
+ tools: {},
2528
+ model: void 0
2529
+ };
2530
+ globalRunRegistry.set(runId, existingEntry);
2531
+ }
2532
+ existingEntry.abortController = abortController;
2533
+ existingEntry.abortSignal = abortController.signal;
2534
+ let resumeCleanedUp = false;
2535
+ const finalizeResumeRegistry = () => {
2536
+ if (resumeCleanedUp) return;
2537
+ resumeCleanedUp = true;
2538
+ globalRunRegistry.delete(runId);
2539
+ };
2540
+ const { output, cleanup: streamCleanup, ready } = createDurableAgentStream({
2541
+ pubsub: getPubsub(),
2542
+ runId,
2543
+ offset: resumeOffset,
2544
+ messageId: crypto.randomUUID(),
2545
+ model: {
2546
+ modelId: void 0,
2547
+ provider: void 0,
2548
+ version: "v3"
2549
+ },
2550
+ threadId: resumeOptions?.threadId,
2551
+ resourceId: resumeOptions?.resourceId,
2552
+ onChunk: resumeOptions?.onChunk,
2553
+ onStepFinish: resumeOptions?.onStepFinish,
2554
+ onFinish: async (result) => {
2555
+ try {
2556
+ await resumeOptions?.onFinish?.(result);
2557
+ } finally {
2558
+ finalizeResumeRegistry();
2559
+ }
2560
+ },
2561
+ onError: async (errorArg) => {
2562
+ try {
2563
+ await resumeOptions?.onError?.(errorArg);
2564
+ } finally {
2565
+ finalizeResumeRegistry();
2566
+ }
2567
+ },
2568
+ onSuspended: resumeOptions?.onSuspended,
2569
+ onAbort: async (data) => {
2570
+ try {
2571
+ await (resumeOptions?.onAbort)?.(data);
2572
+ } finally {
2573
+ finalizeResumeRegistry();
2574
+ }
2575
+ },
2576
+ closeOnSuspend: resumeOptions?.[CLOSE_ON_SUSPEND] === true
2577
+ });
2578
+ const eventName = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;
2579
+ let notResumable = false;
2580
+ const dispatch = ready.then(async () => {
2581
+ const workflowsStore = await mastra?.getStorage()?.getStore("workflows");
2582
+ const loadSnapshot = async () => workflowsStore?.loadWorkflowSnapshot({
2583
+ workflowName: InngestDurableStepIds.AGENTIC_LOOP,
2584
+ runId
2585
+ });
2586
+ let snapshot = await loadSnapshot();
2587
+ const deadline = Date.now() + RESUME_SNAPSHOT_WAIT_MS;
2588
+ while (workflowsStore && snapshot?.status !== "suspended" && Date.now() < deadline) {
2589
+ await new Promise((resolve) => setTimeout(resolve, RESUME_SNAPSHOT_POLL_MS));
2590
+ snapshot = await loadSnapshot();
2591
+ }
2592
+ if (workflowsStore && snapshot?.status !== "suspended") {
2593
+ notResumable = true;
2594
+ throw new NonRetriableError(`Cannot resume run ${runId}: it is not suspended` + (snapshot?.status ? ` (status: ${snapshot.status}).` : " (no snapshot found)."));
2595
+ }
2596
+ const suspendedStepIds = snapshot?.suspendedPaths ? Object.keys(snapshot.suspendedPaths) : [];
2597
+ const resumeLabels = snapshot?.resumeLabels ?? {};
2598
+ const toolCallId = resumeOptions?.toolCallId;
2599
+ const expandToLeafPath = (stepId) => {
2600
+ const nestedPath = (snapshot?.context ?? {})[stepId]?.suspendPayload?.__workflow_meta?.path;
2601
+ return Array.isArray(nestedPath) ? [stepId, ...nestedPath] : [stepId];
2602
+ };
2603
+ let steps;
2604
+ if (toolCallId) {
2605
+ const targetStepId = resumeLabels[toolCallId]?.stepId;
2606
+ if (!targetStepId) {
2607
+ const available = Object.keys(resumeLabels);
2608
+ 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.`));
2609
+ }
2610
+ steps = expandToLeafPath(targetStepId);
2611
+ } else {
2612
+ const available = Object.keys(resumeLabels);
2613
+ if (suspendedStepIds.length > 1 || available.length > 1) throw new NonRetriableError(`Cannot resume run ${runId}: more than one suspension is parked. Pass "toolCallId" to choose which suspended tool call to resume.` + (available.length > 0 ? ` Suspended tool call ids: ${available.join(", ")}.` : ""));
2614
+ steps = suspendedStepIds[0] ? expandToLeafPath(suspendedStepIds[0]) : [];
2615
+ }
2616
+ const requestContext = mergeResumeRequestContext(snapshot?.requestContext, resumeOptions?.requestContext);
2617
+ const tracingOptions = snapshot?.tracingContext ? {
2618
+ traceId: snapshot.tracingContext.traceId,
2619
+ parentSpanId: snapshot.tracingContext.spanId
2620
+ } : void 0;
2621
+ await inngest.send({
2622
+ name: eventName,
2623
+ data: buildDurableResumeEventData({
2624
+ inputData: resumeData,
2625
+ runId,
2626
+ resourceId: resumeOptions?.resourceId,
2627
+ requestContext,
2628
+ tracingOptions,
2629
+ actor: resumeOptions?.actor,
2630
+ resume: {
2631
+ steps,
2632
+ resumePayload: resumeData,
2633
+ resumePath: steps[0] ? snapshot?.suspendedPaths?.[steps[0]] : void 0
2634
+ }
2635
+ })
2636
+ });
2637
+ });
2638
+ const workflowExecution = dispatch.catch((error) => {
2639
+ if (!notResumable) emitError(runId, error);
2640
+ });
2641
+ existingEntry.workflowExecution = workflowExecution;
2642
+ try {
2643
+ await dispatch;
2644
+ } catch (error) {
2645
+ streamCleanup();
2646
+ finalizeResumeRegistry();
2647
+ throw error;
2648
+ }
2649
+ const abort = async (reason) => {
2650
+ if (!abortController.signal.aborted) abortController.abort(reason);
2651
+ await requestRemoteAbort(runId);
2652
+ };
2653
+ const cleanup = () => {
2654
+ streamCleanup();
2655
+ finalizeResumeRegistry();
2656
+ };
2657
+ return {
2658
+ output,
2659
+ get fullStream() {
2660
+ return output.fullStream;
2661
+ },
2662
+ runId,
2663
+ threadId: resumeOptions?.threadId,
2664
+ resourceId: resumeOptions?.resourceId,
2665
+ cleanup,
2666
+ abort,
2667
+ [STREAM_CLEANUP]: streamCleanup
2668
+ };
2669
+ },
2670
+ async prepare(messages, prepareOptions) {
2671
+ const preparation = await prepareForDurableExecution({
2672
+ agent,
2673
+ messages,
2674
+ options: prepareOptions,
2675
+ requestContext: prepareOptions?.requestContext,
2676
+ mastra,
2677
+ durableAgentId: agentId,
2678
+ durableAgentName: agentName
2679
+ });
2680
+ preparation.workflowInput.agentId = agentId;
2681
+ preparation.workflowInput.agentName = agentName;
2682
+ return {
2683
+ runId: preparation.runId,
2684
+ messageId: preparation.messageId,
2685
+ workflowInput: preparation.workflowInput,
2686
+ threadId: preparation.threadId,
2687
+ resourceId: preparation.resourceId
2688
+ };
2689
+ },
2690
+ async observe(runId, observeOptions) {
2691
+ const { output, cleanup: streamCleanup, ready } = createDurableAgentStream({
2692
+ pubsub: getPubsub(),
2693
+ runId,
2694
+ messageId: crypto.randomUUID(),
2695
+ model: {
2696
+ modelId: void 0,
2697
+ provider: void 0,
2698
+ version: "v3"
2699
+ },
2700
+ offset: observeOptions?.offset,
2701
+ onChunk: observeOptions?.onChunk,
2702
+ onStepFinish: observeOptions?.onStepFinish,
2703
+ onFinish: observeOptions?.onFinish,
2704
+ onError: observeOptions?.onError,
2705
+ onSuspended: observeOptions?.onSuspended
2706
+ });
2707
+ await ready;
2708
+ const abort = async (_reason) => {
2709
+ streamCleanup();
2710
+ await requestRemoteAbort(runId);
2711
+ };
2712
+ return {
2713
+ output,
2714
+ get fullStream() {
2715
+ return output.fullStream;
2716
+ },
2717
+ runId,
2718
+ cleanup: streamCleanup,
2719
+ abort
2720
+ };
2721
+ },
2722
+ async generate(messages, generateOptions) {
2723
+ const { untilIdle, ...rest } = generateOptions ?? {};
2724
+ const streamOpts = {
2725
+ ...rest,
2726
+ [CLOSE_ON_SUSPEND]: true,
2727
+ __methodType: "generate"
2728
+ };
2729
+ const result = await proxyRef.stream(messages, streamOpts);
2730
+ let suspended = false;
2731
+ try {
2732
+ const fullOutput = await result.output.getFullOutput();
2733
+ if (fullOutput.error) throw fullOutput.error;
2734
+ suspended = fullOutput.finishReason === "suspended";
2735
+ if (suspended) await globalRunRegistry.get(result.runId)?.workflowExecution;
2736
+ if (!fullOutput.runId) fullOutput.runId = result.runId;
2737
+ return fullOutput;
2738
+ } finally {
2739
+ if (suspended) {
2740
+ const streamOnlyCleanup = result[STREAM_CLEANUP];
2741
+ streamOnlyCleanup?.();
2742
+ } else result.cleanup();
2743
+ }
2744
+ },
2745
+ async resumeGenerate(runId, resumeData, resumeOptions) {
2746
+ const { untilIdle, ...rest } = resumeOptions ?? {};
2747
+ const result = await proxyRef.resume(runId, resumeData, {
2748
+ ...rest,
2749
+ [CLOSE_ON_SUSPEND]: true
2750
+ });
2751
+ let suspended = false;
2752
+ try {
2753
+ const fullOutput = await result.output.getFullOutput();
2754
+ if (fullOutput.error) throw fullOutput.error;
2755
+ suspended = fullOutput.finishReason === "suspended";
2756
+ if (suspended) await globalRunRegistry.get(result.runId)?.workflowExecution;
2757
+ if (!fullOutput.runId) fullOutput.runId = result.runId;
2758
+ return fullOutput;
2759
+ } finally {
2760
+ if (suspended) {
2761
+ const streamOnlyCleanup = result[STREAM_CLEANUP];
2762
+ streamOnlyCleanup?.();
2763
+ } else result.cleanup();
2764
+ }
2765
+ },
2766
+ async resumeStream(resumeData, streamOptions) {
2767
+ const runId = streamOptions?.runId;
2768
+ if (!runId) throw new Error("resumeStream() on InngestAgent requires a runId in streamOptions.");
2769
+ const { runId: _runId, ...resumeOptions } = streamOptions;
2770
+ return (await proxyRef.resume(runId, resumeData, {
2771
+ ...resumeOptions,
2772
+ [CLOSE_ON_SUSPEND]: true
2773
+ })).output;
2774
+ },
2775
+ async approveToolCall(options) {
2776
+ return proxyRef.resumeStream({ approved: true }, options);
2777
+ },
2778
+ async declineToolCall(options) {
2779
+ const { reason, ...resumeOptions } = options;
2780
+ return proxyRef.resumeStream({
2781
+ approved: false,
2782
+ ...reason !== void 0 ? { reason } : {}
2783
+ }, resumeOptions);
2784
+ },
2785
+ async approveToolCallGenerate(options) {
2786
+ const { runId, ...resumeOptions } = options;
2787
+ if (!runId) throw new Error("approveToolCallGenerate() on InngestAgent requires a runId.");
2788
+ return proxyRef.resumeGenerate(runId, { approved: true }, resumeOptions);
2789
+ },
2790
+ async declineToolCallGenerate(options) {
2791
+ const { runId, reason, ...resumeOptions } = options;
2792
+ if (!runId) throw new Error("declineToolCallGenerate() on InngestAgent requires a runId.");
2793
+ return proxyRef.resumeGenerate(runId, {
2794
+ approved: false,
2795
+ ...reason !== void 0 ? { reason } : {}
2796
+ }, resumeOptions);
2797
+ },
2798
+ __fork() {
2799
+ const { shouldPersistSnapshot: _ignored, ...forkOptions } = options;
2800
+ return createInngestAgent({
2801
+ ...forkOptions,
2802
+ agent: agent.__fork(),
2803
+ pubsub: innerPubsub,
2804
+ cache: _customCache,
2805
+ mastra
2806
+ });
2807
+ },
2808
+ getDurableWorkflows() {
2809
+ return [workflow];
2810
+ },
2811
+ __setMastra(mastraInstance) {
2812
+ mastra = mastraInstance;
2813
+ }
2814
+ }, {
2815
+ get(target, prop, receiver) {
2816
+ if (prop in target) return Reflect.get(target, prop, receiver);
2817
+ const agentValue = agent[prop];
2818
+ if (typeof agentValue === "function") return agentValue.bind(agent);
2819
+ return agentValue;
2820
+ },
2821
+ has(target, prop) {
2822
+ return prop in target || prop in agent;
2823
+ }
2824
+ });
2825
+ proxyRef = result;
2826
+ agent.__setThreadRuntimeAgent(result);
2827
+ return result;
2828
+ }
2829
+ /**
2830
+ * Check if an object is an InngestAgent
2831
+ */
2832
+ function isInngestAgent(obj) {
2833
+ if (!obj) return false;
2834
+ return typeof obj.id === "string" && typeof obj.name === "string" && "agent" in obj && "inngest" in obj && typeof obj.stream === "function" && typeof obj.getDurableWorkflows === "function";
2835
+ }
2836
+ //#endregion
1965
2837
  //#region src/functions.ts
1966
2838
  function collectInngestFunctions({ mastra, functions: userFunctions = [] }) {
1967
- const workflows = mastra.listWorkflows();
1968
- return [...Array.from(new Set(Object.values(workflows).flatMap((workflow) => {
1969
- if (workflow instanceof InngestWorkflow) {
1970
- workflow.__registerMastra(mastra);
1971
- return workflow.getFunctions();
2839
+ /**
2840
+ * Inngest agents share the same logical durable workflow IDs and resolve the
2841
+ * concrete agent from the workflow input, so only the first registered
2842
+ * agent's workflow needs to be served.
2843
+ */
2844
+ const durableAgent = Object.values(mastra.listAgents()).find((agent) => isInngestAgent(agent));
2845
+ const workflows = [...Object.values(mastra.listWorkflows()), ...durableAgent?.getDurableWorkflows() ?? []];
2846
+ const workflowFunctions = /* @__PURE__ */ new Map();
2847
+ for (const workflow of workflows) {
2848
+ if (!(workflow instanceof InngestWorkflow)) continue;
2849
+ workflow.__registerMastra(mastra);
2850
+ for (const fn of workflow.getFunctions()) {
2851
+ const functionId = fn.id();
2852
+ if (!workflowFunctions.has(functionId)) workflowFunctions.set(functionId, fn);
1972
2853
  }
1973
- return [];
1974
- }))), ...userFunctions];
2854
+ }
2855
+ return [...workflowFunctions.values(), ...userFunctions];
2856
+ }
2857
+ //#endregion
2858
+ //#region src/serve.ts
2859
+ /**
2860
+ * Collects workflow functions from Mastra and prepares serve options for inngest.
2861
+ */
2862
+ function prepareServeOptions({ mastra, inngest, functions: userFunctions = [], registerOptions }) {
2863
+ return {
2864
+ ...registerOptions,
2865
+ client: inngest,
2866
+ functions: collectInngestFunctions({
2867
+ mastra,
2868
+ functions: userFunctions
2869
+ })
2870
+ };
2871
+ }
2872
+ /**
2873
+ * Factory function to create a serve function with any inngest adapter.
2874
+ * Use this to integrate Mastra workflows with any framework supported by inngest.
2875
+ *
2876
+ * @example Express
2877
+ * ```ts
2878
+ * import { createServe } from '@mastra/inngest';
2879
+ * import { serve } from 'inngest/express';
2880
+ *
2881
+ * const serveExpress = createServe(serve);
2882
+ * app.use('/inngest/api', serveExpress({ mastra, inngest }));
2883
+ * ```
2884
+ *
2885
+ * @example Fastify
2886
+ * ```ts
2887
+ * import { createServe } from '@mastra/inngest';
2888
+ * import { serve } from 'inngest/fastify';
2889
+ *
2890
+ * const serveFastify = createServe(serve);
2891
+ * fastify.route({
2892
+ * method: ['GET', 'POST', 'PUT'],
2893
+ * handler: serveFastify({ mastra, inngest }),
2894
+ * url: '/inngest/api',
2895
+ * });
2896
+ * ```
2897
+ *
2898
+ * @example Next.js
2899
+ * ```ts
2900
+ * // app/inngest/api/route.ts — file path determines the route URL
2901
+ * import { createServe } from '@mastra/inngest';
2902
+ * import { serve } from 'inngest/next';
2903
+ *
2904
+ * const serveNext = createServe(serve);
2905
+ * export const { GET, POST, PUT } = serveNext({ mastra, inngest });
2906
+ * ```
2907
+ */
2908
+ function createServe(adapter) {
2909
+ return (options) => {
2910
+ return adapter(prepareServeOptions(options));
2911
+ };
1975
2912
  }
2913
+ /**
2914
+ * Serve Mastra workflows with Hono (default).
2915
+ *
2916
+ * For other frameworks, use `createServe` with the appropriate inngest adapter.
2917
+ *
2918
+ * @example
2919
+ * ```ts
2920
+ * import { serve } from '@mastra/inngest';
2921
+ *
2922
+ * app.use('/inngest/api', async (c) => {
2923
+ * return serve({ mastra, inngest })(c);
2924
+ * });
2925
+ * ```
2926
+ */
2927
+ const serve$1 = createServe(serve);
1976
2928
  //#endregion
1977
2929
  //#region src/connect.ts
1978
2930
  /**
@@ -2013,6 +2965,514 @@ async function connect(options) {
2013
2965
  });
2014
2966
  }
2015
2967
  //#endregion
2016
- export { buildDurableResumeEventData as a, InngestPubSub as c, InngestRun as i, InngestExecutionEngine as l, collectInngestFunctions as n, buildDurableTriggerEventData as o, InngestWorkflow as r, mergeResumeRequestContext as s, connect as t };
2968
+ //#region src/types.ts
2969
+ const _compatibilityCheck = true;
2970
+ //#endregion
2971
+ //#region src/index.ts
2972
+ function isInngestWorkflow(input) {
2973
+ return input instanceof InngestWorkflow;
2974
+ }
2975
+ /**
2976
+ * copied from @mastra/core/agent/subagent.ts for compatible
2977
+ */
2978
+ function isAgentCompatible(input) {
2979
+ return typeof input === "object" && input !== null && "generate" in input && typeof input.generate === "function" && "stream" in input && typeof input.stream === "function" && "getDescription" in input && typeof input.getDescription === "function" && "getModel" in input && typeof input.getModel === "function";
2980
+ }
2981
+ function isToolStep(input) {
2982
+ return input instanceof Tool;
2983
+ }
2984
+ function isStepParams(input) {
2985
+ return input !== null && typeof input === "object" && "id" in input && "execute" in input && !(input instanceof Agent) && !(input instanceof Tool) && !(input instanceof InngestWorkflow);
2986
+ }
2987
+ /**
2988
+ * Type guard to check if an object is a Processor.
2989
+ * A Processor must have an 'id' property and at least one processor method.
2990
+ */
2991
+ function isProcessor(obj) {
2992
+ return obj !== null && typeof obj === "object" && "id" in obj && typeof obj.id === "string" && !(obj instanceof Agent) && !(obj instanceof Tool) && !(obj instanceof InngestWorkflow) && (typeof obj.processInput === "function" || typeof obj.processInputStep === "function" || typeof obj.processOutputStream === "function" || typeof obj.processOutputResult === "function" || typeof obj.processOutputStep === "function");
2993
+ }
2994
+ function createStep(params, agentOrToolOptions) {
2995
+ if (isInngestWorkflow(params)) return params;
2996
+ if (isAgentCompatible(params)) return createStepFromAgent$1(params, agentOrToolOptions);
2997
+ if (isToolStep(params)) return createStepFromTool$1(params, agentOrToolOptions);
2998
+ if (isStepParams(params)) return createStepFromParams(params);
2999
+ if (isProcessor(params)) return createStepFromProcessor(params);
3000
+ throw new Error("Invalid input: expected StepParams, Agent, ToolStep, Processor, or InngestWorkflow");
3001
+ }
3002
+ function createStepFromParams(params) {
3003
+ return {
3004
+ id: params.id,
3005
+ description: params.description,
3006
+ inputSchema: toStandardSchema(params.inputSchema),
3007
+ stateSchema: params.stateSchema ? toStandardSchema(params.stateSchema) : void 0,
3008
+ outputSchema: toStandardSchema(params.outputSchema),
3009
+ resumeSchema: params.resumeSchema ? toStandardSchema(params.resumeSchema) : void 0,
3010
+ suspendSchema: params.suspendSchema ? toStandardSchema(params.suspendSchema) : void 0,
3011
+ scorers: params.scorers,
3012
+ retries: params.retries,
3013
+ metadata: params.metadata,
3014
+ execute: params.execute.bind(params)
3015
+ };
3016
+ }
3017
+ function createStepFromAgent$1(params, agentOrToolOptions) {
3018
+ return createStepFromAgent(params, agentOrToolOptions);
3019
+ }
3020
+ function createStepFromTool$1(params, agentOrToolOptions) {
3021
+ return createStepFromTool(params, agentOrToolOptions);
3022
+ }
3023
+ function createStepFromProcessor(processor) {
3024
+ const getProcessorEntityType = (phase) => {
3025
+ switch (phase) {
3026
+ case "input": return EntityType.INPUT_PROCESSOR;
3027
+ case "inputStep": return EntityType.INPUT_STEP_PROCESSOR;
3028
+ case "outputStream":
3029
+ case "outputResult": return EntityType.OUTPUT_PROCESSOR;
3030
+ case "outputStep": return EntityType.OUTPUT_STEP_PROCESSOR;
3031
+ default: return EntityType.OUTPUT_PROCESSOR;
3032
+ }
3033
+ };
3034
+ const getSpanNamePrefix = (phase) => {
3035
+ switch (phase) {
3036
+ case "input": return "input processor";
3037
+ case "inputStep": return "input step processor";
3038
+ case "outputStream": return "output stream processor";
3039
+ case "outputResult": return "output processor";
3040
+ case "outputStep": return "output step processor";
3041
+ default: return "processor";
3042
+ }
3043
+ };
3044
+ const hasPhaseMethod = (phase) => {
3045
+ switch (phase) {
3046
+ case "input": return !!processor.processInput;
3047
+ case "inputStep": return !!processor.processInputStep;
3048
+ case "outputStream": return !!processor.processOutputStream;
3049
+ case "outputResult": return !!processor.processOutputResult;
3050
+ case "outputStep": return !!processor.processOutputStep;
3051
+ default: return false;
3052
+ }
3053
+ };
3054
+ return {
3055
+ id: `processor:${processor.id}`,
3056
+ description: processor.name ?? `Processor ${processor.id}`,
3057
+ inputSchema: ProcessorStepSchema,
3058
+ outputSchema: ProcessorStepOutputSchema,
3059
+ execute: async ({ inputData, requestContext, tracingContext }) => {
3060
+ const input = inputData;
3061
+ const { phase, messages, messageList, stepNumber, systemMessages, part, streamParts, processorStates, result, finishReason, toolCalls, text, retryCount, model, tools, toolChoice, activeTools, providerOptions, modelSettings, structuredOutput, steps, usage } = input;
3062
+ const abort = (reason, options) => {
3063
+ throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
3064
+ };
3065
+ if (!hasPhaseMethod(phase)) return input;
3066
+ const currentSpan = tracingContext?.currentSpan;
3067
+ const parentSpan = phase === "inputStep" || phase === "outputStep" ? currentSpan?.findParent(SpanType.MODEL_STEP) || currentSpan : currentSpan?.findParent(SpanType.AGENT_RUN) || currentSpan;
3068
+ const processorSpan = phase !== "outputStream" ? parentSpan?.createChildSpan({
3069
+ type: SpanType.PROCESSOR_RUN,
3070
+ name: `${getSpanNamePrefix(phase)}: ${processor.id}`,
3071
+ entityType: getProcessorEntityType(phase),
3072
+ entityId: processor.id,
3073
+ entityName: processor.name ?? processor.id,
3074
+ input: {
3075
+ phase,
3076
+ messageCount: messages?.length
3077
+ },
3078
+ attributes: {
3079
+ processorExecutor: "workflow",
3080
+ processorIndex: processor.processorIndex
3081
+ }
3082
+ }) : void 0;
3083
+ const processorTracingContext = processorSpan ? { currentSpan: processorSpan } : tracingContext;
3084
+ let processorState = {};
3085
+ if (processorStates) {
3086
+ let ps = processorStates.get(processor.id);
3087
+ if (!ps) {
3088
+ ps = new ProcessorState(processor.id);
3089
+ processorStates.set(processor.id, ps);
3090
+ }
3091
+ processorState = ps.customState;
3092
+ }
3093
+ const baseContext = {
3094
+ abort,
3095
+ retryCount: retryCount ?? 0,
3096
+ requestContext,
3097
+ tracingContext: processorTracingContext
3098
+ };
3099
+ const passThrough = {
3100
+ phase,
3101
+ messageList: messageList ?? (Array.isArray(messages) ? new MessageList().add(messages, "input").addSystem(systemMessages ?? []) : void 0),
3102
+ stepNumber,
3103
+ systemMessages,
3104
+ streamParts,
3105
+ state: processorState,
3106
+ processorStates,
3107
+ result,
3108
+ finishReason,
3109
+ toolCalls,
3110
+ text,
3111
+ retryCount,
3112
+ model,
3113
+ tools,
3114
+ toolChoice,
3115
+ activeTools,
3116
+ providerOptions,
3117
+ modelSettings,
3118
+ structuredOutput,
3119
+ steps,
3120
+ usage
3121
+ };
3122
+ const executePhaseWithSpan = async (fn) => {
3123
+ try {
3124
+ const result = await fn();
3125
+ processorSpan?.end({ output: result });
3126
+ return result;
3127
+ } catch (error) {
3128
+ if (error instanceof TripWire) processorSpan?.end({ output: { tripwire: error.message } });
3129
+ else processorSpan?.error({
3130
+ error,
3131
+ endSpan: true
3132
+ });
3133
+ throw error;
3134
+ }
3135
+ };
3136
+ return executePhaseWithSpan(async () => {
3137
+ switch (phase) {
3138
+ case "input":
3139
+ if (processor.processInput) {
3140
+ if (!passThrough.messageList) throw new MastraError({
3141
+ category: ErrorCategory.USER,
3142
+ domain: ErrorDomain.MASTRA_WORKFLOW,
3143
+ id: "PROCESSOR_MISSING_MESSAGE_LIST",
3144
+ text: `Processor ${processor.id} requires messageList or messages for processInput phase`
3145
+ });
3146
+ const idsBeforeProcessing = messages.map((m) => m.id);
3147
+ const check = passThrough.messageList.makeMessageSourceChecker();
3148
+ const result = await processor.processInput({
3149
+ ...baseContext,
3150
+ messages,
3151
+ messageList: passThrough.messageList,
3152
+ systemMessages: systemMessages ?? [],
3153
+ state: processorState
3154
+ });
3155
+ if (result instanceof MessageList) {
3156
+ if (result !== passThrough.messageList) throw new MastraError({
3157
+ category: ErrorCategory.USER,
3158
+ domain: ErrorDomain.MASTRA_WORKFLOW,
3159
+ id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
3160
+ text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`
3161
+ });
3162
+ return {
3163
+ ...passThrough,
3164
+ messages: result.get.all.db(),
3165
+ systemMessages: result.getSystemMessages()
3166
+ };
3167
+ } else if (Array.isArray(result)) {
3168
+ ProcessorRunner.applyMessagesToMessageList(result, passThrough.messageList, idsBeforeProcessing, check, "input");
3169
+ return {
3170
+ ...passThrough,
3171
+ messages: result
3172
+ };
3173
+ } else if (result && "messages" in result && "systemMessages" in result) {
3174
+ const typedResult = result;
3175
+ ProcessorRunner.applyMessagesToMessageList(typedResult.messages, passThrough.messageList, idsBeforeProcessing, check, "input");
3176
+ passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);
3177
+ return {
3178
+ ...passThrough,
3179
+ messages: typedResult.messages,
3180
+ systemMessages: passThrough.messageList.getSystemMessages()
3181
+ };
3182
+ }
3183
+ return {
3184
+ ...passThrough,
3185
+ messages
3186
+ };
3187
+ }
3188
+ return {
3189
+ ...passThrough,
3190
+ messages
3191
+ };
3192
+ case "inputStep":
3193
+ if (processor.processInputStep) {
3194
+ if (!passThrough.messageList) throw new MastraError({
3195
+ category: ErrorCategory.USER,
3196
+ domain: ErrorDomain.MASTRA_WORKFLOW,
3197
+ id: "PROCESSOR_MISSING_MESSAGE_LIST",
3198
+ text: `Processor ${processor.id} requires messageList or messages for processInputStep phase`
3199
+ });
3200
+ const idsBeforeProcessing = messages.map((m) => m.id);
3201
+ const check = passThrough.messageList.makeMessageSourceChecker();
3202
+ const result = await processor.processInputStep({
3203
+ ...baseContext,
3204
+ messages,
3205
+ messageList: passThrough.messageList,
3206
+ stepNumber: stepNumber ?? 0,
3207
+ systemMessages: systemMessages ?? [],
3208
+ model,
3209
+ tools,
3210
+ toolChoice,
3211
+ activeTools,
3212
+ providerOptions,
3213
+ modelSettings,
3214
+ structuredOutput,
3215
+ steps: steps ?? [],
3216
+ state: processorState
3217
+ });
3218
+ const validatedResult = await ProcessorRunner.validateAndFormatProcessInputStepResult(result, {
3219
+ messageList: passThrough.messageList,
3220
+ processor,
3221
+ stepNumber: stepNumber ?? 0
3222
+ });
3223
+ if (validatedResult.messages) ProcessorRunner.applyMessagesToMessageList(validatedResult.messages, passThrough.messageList, idsBeforeProcessing, check);
3224
+ if (validatedResult.systemMessages) passThrough.messageList.replaceAllSystemMessages(validatedResult.systemMessages);
3225
+ return {
3226
+ ...passThrough,
3227
+ messages,
3228
+ ...validatedResult,
3229
+ systemMessages: passThrough.messageList.getSystemMessages()
3230
+ };
3231
+ }
3232
+ return {
3233
+ ...passThrough,
3234
+ messages
3235
+ };
3236
+ case "outputStream":
3237
+ if (processor.processOutputStream) {
3238
+ const spanKey = `__outputStreamSpan_${processor.id}`;
3239
+ const mutableState = processorState;
3240
+ let processorSpan = mutableState[spanKey];
3241
+ if (!processorSpan && parentSpan) {
3242
+ processorSpan = parentSpan.createChildSpan({
3243
+ type: SpanType.PROCESSOR_RUN,
3244
+ name: `output stream processor: ${processor.id}`,
3245
+ entityType: EntityType.OUTPUT_PROCESSOR,
3246
+ entityId: processor.id,
3247
+ entityName: processor.name ?? processor.id,
3248
+ input: {
3249
+ phase,
3250
+ streamParts: []
3251
+ },
3252
+ attributes: {
3253
+ processorExecutor: "workflow",
3254
+ processorIndex: processor.processorIndex
3255
+ }
3256
+ });
3257
+ mutableState[spanKey] = processorSpan;
3258
+ }
3259
+ if (processorSpan) processorSpan.input = {
3260
+ phase,
3261
+ streamParts: streamParts ?? [],
3262
+ totalChunks: (streamParts ?? []).length
3263
+ };
3264
+ const processorTracingContext = processorSpan ? { currentSpan: processorSpan } : baseContext.tracingContext;
3265
+ let result;
3266
+ try {
3267
+ result = await processor.processOutputStream({
3268
+ ...baseContext,
3269
+ tracingContext: processorTracingContext,
3270
+ part,
3271
+ streamParts: streamParts ?? [],
3272
+ state: mutableState,
3273
+ messageList: passThrough.messageList
3274
+ });
3275
+ if (part && part.type === "finish") {
3276
+ processorSpan?.end({ output: result });
3277
+ delete mutableState[spanKey];
3278
+ }
3279
+ } catch (error) {
3280
+ if (error instanceof TripWire) processorSpan?.end({ output: { tripwire: error.message } });
3281
+ else processorSpan?.error({
3282
+ error,
3283
+ endSpan: true
3284
+ });
3285
+ delete mutableState[spanKey];
3286
+ throw error;
3287
+ }
3288
+ return {
3289
+ ...passThrough,
3290
+ state: mutableState,
3291
+ part: result
3292
+ };
3293
+ }
3294
+ return {
3295
+ ...passThrough,
3296
+ part
3297
+ };
3298
+ case "outputResult":
3299
+ if (processor.processOutputResult) {
3300
+ if (!passThrough.messageList) throw new MastraError({
3301
+ category: ErrorCategory.USER,
3302
+ domain: ErrorDomain.MASTRA_WORKFLOW,
3303
+ id: "PROCESSOR_MISSING_MESSAGE_LIST",
3304
+ text: `Processor ${processor.id} requires messageList or messages for processOutputResult phase`
3305
+ });
3306
+ const idsBeforeProcessing = messages.map((m) => m.id);
3307
+ const check = passThrough.messageList.makeMessageSourceChecker();
3308
+ const outputResult = passThrough.result ?? {
3309
+ text: "",
3310
+ usage: {
3311
+ inputTokens: 0,
3312
+ outputTokens: 0,
3313
+ totalTokens: 0
3314
+ },
3315
+ finishReason: "unknown",
3316
+ steps: []
3317
+ };
3318
+ const processResult = await processor.processOutputResult({
3319
+ ...baseContext,
3320
+ messages,
3321
+ messageList: passThrough.messageList,
3322
+ state: processorState,
3323
+ result: outputResult
3324
+ });
3325
+ if (processResult instanceof MessageList) {
3326
+ if (processResult !== passThrough.messageList) throw new MastraError({
3327
+ category: ErrorCategory.USER,
3328
+ domain: ErrorDomain.MASTRA_WORKFLOW,
3329
+ id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
3330
+ text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`
3331
+ });
3332
+ return {
3333
+ ...passThrough,
3334
+ messages: processResult.get.all.db(),
3335
+ systemMessages: processResult.getSystemMessages()
3336
+ };
3337
+ } else if (Array.isArray(processResult)) {
3338
+ ProcessorRunner.applyMessagesToMessageList(processResult, passThrough.messageList, idsBeforeProcessing, check, "response");
3339
+ return {
3340
+ ...passThrough,
3341
+ messages: processResult
3342
+ };
3343
+ } else if (processResult && "messages" in processResult && "systemMessages" in processResult) {
3344
+ const typedResult = processResult;
3345
+ ProcessorRunner.applyMessagesToMessageList(typedResult.messages, passThrough.messageList, idsBeforeProcessing, check, "response");
3346
+ passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);
3347
+ return {
3348
+ ...passThrough,
3349
+ messages: typedResult.messages,
3350
+ systemMessages: passThrough.messageList.getSystemMessages()
3351
+ };
3352
+ }
3353
+ return {
3354
+ ...passThrough,
3355
+ messages
3356
+ };
3357
+ }
3358
+ return {
3359
+ ...passThrough,
3360
+ messages
3361
+ };
3362
+ case "outputStep":
3363
+ if (processor.processOutputStep) {
3364
+ if (!passThrough.messageList) throw new MastraError({
3365
+ category: ErrorCategory.USER,
3366
+ domain: ErrorDomain.MASTRA_WORKFLOW,
3367
+ id: "PROCESSOR_MISSING_MESSAGE_LIST",
3368
+ text: `Processor ${processor.id} requires messageList or messages for processOutputStep phase`
3369
+ });
3370
+ const idsBeforeProcessing = messages.map((m) => m.id);
3371
+ const check = passThrough.messageList.makeMessageSourceChecker();
3372
+ const defaultUsage = {
3373
+ inputTokens: void 0,
3374
+ outputTokens: void 0,
3375
+ totalTokens: void 0
3376
+ };
3377
+ const result = await processor.processOutputStep({
3378
+ ...baseContext,
3379
+ messages,
3380
+ messageList: passThrough.messageList,
3381
+ stepNumber: stepNumber ?? 0,
3382
+ finishReason,
3383
+ toolCalls,
3384
+ text,
3385
+ usage: usage ?? defaultUsage,
3386
+ systemMessages: systemMessages ?? [],
3387
+ steps: steps ?? [],
3388
+ state: processorState
3389
+ });
3390
+ if (result instanceof MessageList) {
3391
+ if (result !== passThrough.messageList) throw new MastraError({
3392
+ category: ErrorCategory.USER,
3393
+ domain: ErrorDomain.MASTRA_WORKFLOW,
3394
+ id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
3395
+ text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`
3396
+ });
3397
+ return {
3398
+ ...passThrough,
3399
+ messages: result.get.all.db(),
3400
+ systemMessages: result.getSystemMessages()
3401
+ };
3402
+ } else if (Array.isArray(result)) {
3403
+ ProcessorRunner.applyMessagesToMessageList(result, passThrough.messageList, idsBeforeProcessing, check, "response");
3404
+ return {
3405
+ ...passThrough,
3406
+ messages: result
3407
+ };
3408
+ } else if (result && "messages" in result && "systemMessages" in result) {
3409
+ const typedResult = result;
3410
+ ProcessorRunner.applyMessagesToMessageList(typedResult.messages, passThrough.messageList, idsBeforeProcessing, check, "response");
3411
+ passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);
3412
+ return {
3413
+ ...passThrough,
3414
+ messages: typedResult.messages,
3415
+ systemMessages: passThrough.messageList.getSystemMessages()
3416
+ };
3417
+ }
3418
+ return {
3419
+ ...passThrough,
3420
+ messages
3421
+ };
3422
+ }
3423
+ return {
3424
+ ...passThrough,
3425
+ messages
3426
+ };
3427
+ default: return {
3428
+ ...passThrough,
3429
+ messages
3430
+ };
3431
+ }
3432
+ });
3433
+ },
3434
+ component: "PROCESSOR"
3435
+ };
3436
+ }
3437
+ function init(inngest) {
3438
+ return {
3439
+ createTool,
3440
+ createWorkflow(params) {
3441
+ return new InngestWorkflow(params, inngest);
3442
+ },
3443
+ createStep,
3444
+ cloneStep(step, opts) {
3445
+ return {
3446
+ id: opts.id,
3447
+ description: step.description,
3448
+ inputSchema: step.inputSchema,
3449
+ outputSchema: step.outputSchema,
3450
+ resumeSchema: step.resumeSchema,
3451
+ suspendSchema: step.suspendSchema,
3452
+ stateSchema: step.stateSchema,
3453
+ metadata: step.metadata,
3454
+ execute: step.execute,
3455
+ retries: step.retries,
3456
+ scorers: step.scorers,
3457
+ component: step.component
3458
+ };
3459
+ },
3460
+ cloneWorkflow(workflow, opts) {
3461
+ const wf = new Workflow({
3462
+ id: opts.id,
3463
+ inputSchema: workflow.inputSchema,
3464
+ outputSchema: workflow.outputSchema,
3465
+ steps: workflow.stepDefs,
3466
+ mastra: workflow.mastra,
3467
+ options: workflow.options
3468
+ });
3469
+ wf.setStepFlow(workflow.stepGraph);
3470
+ wf.commit();
3471
+ return wf;
3472
+ }
3473
+ };
3474
+ }
3475
+ //#endregion
3476
+ export { createServe as a, isInngestAgent as c, InngestRun as d, InngestPubSub as f, connect as i, createInngestDurableAgenticWorkflow as l, init as n, serve$1 as o, InngestExecutionEngine as p, _compatibilityCheck as r, createInngestAgent as s, createStep as t, InngestWorkflow as u };
2017
3477
 
2018
- //# sourceMappingURL=connect-DbsoIp0h.js.map
3478
+ //# sourceMappingURL=src-iZ1vJU4r.js.map