@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.
package/dist/index.js CHANGED
@@ -1,1421 +1,2 @@
1
- import { a as buildDurableResumeEventData, c as InngestPubSub, i as InngestRun, l as InngestExecutionEngine, n as collectInngestFunctions, o as buildDurableTriggerEventData, r as InngestWorkflow, s as mergeResumeRequestContext, t as connect } from "./connect-DbsoIp0h.js";
2
- import { Agent, MessageList, TripWire } from "@mastra/core/agent";
3
- import { ErrorCategory, ErrorDomain, MastraError } from "@mastra/core/error";
4
- import { EntityType, InternalSpans, SpanType } from "@mastra/core/observability";
5
- import { ProcessorRunner, ProcessorState, ProcessorStepOutputSchema, ProcessorStepSchema } from "@mastra/core/processors";
6
- import { toStandardSchema } from "@mastra/core/schema";
7
- import { Tool, createTool } from "@mastra/core/tools";
8
- import { Workflow, createStepFromAgent, createStepFromTool } from "@mastra/core/workflows";
9
- import { 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";
10
- import { NonRetriableError } from "inngest";
11
- import { CachingPubSub } from "@mastra/core/events";
12
- import { serve as serve$1 } from "inngest/hono";
13
- import { InMemoryServerCache } from "@mastra/core/cache";
14
- import { PUBSUB_SYMBOL } from "@mastra/core/workflows/_constants";
15
- import { z } from "zod";
16
- //#region src/serve.ts
17
- /**
18
- * Collects workflow functions from Mastra and prepares serve options for inngest.
19
- */
20
- function prepareServeOptions({ mastra, inngest, functions: userFunctions = [], registerOptions }) {
21
- return {
22
- ...registerOptions,
23
- client: inngest,
24
- functions: collectInngestFunctions({
25
- mastra,
26
- functions: userFunctions
27
- })
28
- };
29
- }
30
- /**
31
- * Factory function to create a serve function with any inngest adapter.
32
- * Use this to integrate Mastra workflows with any framework supported by inngest.
33
- *
34
- * @example Express
35
- * ```ts
36
- * import { createServe } from '@mastra/inngest';
37
- * import { serve } from 'inngest/express';
38
- *
39
- * const serveExpress = createServe(serve);
40
- * app.use('/inngest/api', serveExpress({ mastra, inngest }));
41
- * ```
42
- *
43
- * @example Fastify
44
- * ```ts
45
- * import { createServe } from '@mastra/inngest';
46
- * import { serve } from 'inngest/fastify';
47
- *
48
- * const serveFastify = createServe(serve);
49
- * fastify.route({
50
- * method: ['GET', 'POST', 'PUT'],
51
- * handler: serveFastify({ mastra, inngest }),
52
- * url: '/inngest/api',
53
- * });
54
- * ```
55
- *
56
- * @example Next.js
57
- * ```ts
58
- * // app/inngest/api/route.ts — file path determines the route URL
59
- * import { createServe } from '@mastra/inngest';
60
- * import { serve } from 'inngest/next';
61
- *
62
- * const serveNext = createServe(serve);
63
- * export const { GET, POST, PUT } = serveNext({ mastra, inngest });
64
- * ```
65
- */
66
- function createServe(adapter) {
67
- return (options) => {
68
- return adapter(prepareServeOptions(options));
69
- };
70
- }
71
- /**
72
- * Serve Mastra workflows with Hono (default).
73
- *
74
- * For other frameworks, use `createServe` with the appropriate inngest adapter.
75
- *
76
- * @example
77
- * ```ts
78
- * import { serve } from '@mastra/inngest';
79
- *
80
- * app.use('/inngest/api', async (c) => {
81
- * return serve({ mastra, inngest })(c);
82
- * });
83
- * ```
84
- */
85
- const serve = createServe(serve$1);
86
- //#endregion
87
- //#region src/types.ts
88
- const _compatibilityCheck = true;
89
- //#endregion
90
- //#region src/durable-agent/create-inngest-agentic-workflow.ts
91
- /**
92
- * Input schema for the durable agentic workflow.
93
- * Extends base with observability fields for Inngest.
94
- */
95
- const durableAgenticInputSchema = z.object({
96
- runId: z.string(),
97
- agentId: z.string(),
98
- agentName: z.string().optional(),
99
- messageListState: z.any(),
100
- toolsMetadata: z.array(z.any()),
101
- modelConfig: modelConfigSchema,
102
- options: z.any(),
103
- state: z.any(),
104
- messageId: z.string(),
105
- requestContextEntries: z.record(z.string(), z.any()).optional(),
106
- agentSpanData: z.any().optional(),
107
- modelSpanData: z.any().optional(),
108
- stepIndex: z.number().optional()
109
- });
110
- /**
111
- * Iteration state schema - extends base with observability fields.
112
- */
113
- const iterationStateSchema = baseIterationStateSchema.extend({
114
- agentSpanData: z.any().optional(),
115
- modelSpanData: z.any().optional(),
116
- stepIndex: z.number()
117
- });
118
- /**
119
- * Create a durable agentic workflow using Inngest.
120
- *
121
- * This workflow implements the agentic loop pattern in a durable way using
122
- * Inngest's execution engine:
123
- *
124
- * 1. LLM Execution Step - Calls the LLM and gets response/tool calls
125
- * 2. Tool Call Steps (foreach) - Executes each tool call individually with suspend support
126
- * 3. LLM Mapping Step - Merges tool results back into state
127
- * 4. Loop - Continues if more tool calls are needed (dowhile)
128
- *
129
- * All state flows through workflow input/output, making it durable across
130
- * process restarts and execution engine replays.
131
- *
132
- * @param options - Configuration options
133
- * @returns An InngestWorkflow instance that implements the agentic loop
134
- */
135
- /** Prefix for Inngest engine workflow IDs to avoid collision with other engines */
136
- const INNGEST_ENGINE_PREFIX = "inngest";
137
- /** Inngest-prefixed workflow IDs */
138
- const InngestDurableStepIds = {
139
- AGENTIC_EXECUTION: `${INNGEST_ENGINE_PREFIX}:${DurableStepIds.AGENTIC_EXECUTION}`,
140
- AGENTIC_LOOP: `${INNGEST_ENGINE_PREFIX}:${DurableStepIds.AGENTIC_LOOP}`
141
- };
142
- function createInngestDurableAgenticWorkflow(options) {
143
- const { inngest, maxSteps = DurableAgentDefaults.MAX_STEPS, retries } = options;
144
- const { createWorkflow } = init(inngest);
145
- const llmExecutionStep = createDurableLLMExecutionStep();
146
- const toolCallStep = createDurableToolCallStep();
147
- const llmMappingStep = createDurableLLMMappingStep();
148
- const backgroundTaskCheckStep = createDurableBackgroundTaskCheckStep();
149
- const singleIterationWorkflow = createWorkflow({
150
- id: InngestDurableStepIds.AGENTIC_EXECUTION,
151
- retries,
152
- inputSchema: iterationStateSchema,
153
- outputSchema: iterationStateSchema,
154
- options: {
155
- tracingPolicy: { internal: InternalSpans.WORKFLOW },
156
- shouldPersistSnapshot: ({ workflowStatus }) => workflowStatus === "suspended",
157
- validateInputs: false
158
- },
159
- steps: []
160
- }).map(async ({ inputData }) => {
161
- const state = inputData;
162
- return {
163
- runId: state.runId,
164
- agentId: state.agentId,
165
- agentName: state.agentName,
166
- messageListState: state.messageListState,
167
- toolsMetadata: state.toolsMetadata,
168
- modelConfig: state.modelConfig,
169
- options: state.options,
170
- state: state.state,
171
- messageId: state.messageId,
172
- requestContextEntries: state.requestContextEntries,
173
- agentSpanData: state.agentSpanData,
174
- modelSpanData: state.modelSpanData,
175
- stepIndex: state.stepIndex
176
- };
177
- }, { id: "map-to-llm-input" }).then(llmExecutionStep).map(async ({ inputData }) => {
178
- const llmOutput = inputData;
179
- return (llmOutput.toolCalls ?? []).map((toolCall) => ({
180
- ...toolCall,
181
- stepSpanData: llmOutput.stepSpanData
182
- }));
183
- }, { id: "extract-tool-calls" }).foreach(toolCallStep, { concurrency: ({ inputData, getInitData }) => {
184
- const state = getInitData();
185
- return resolveDurableToolCallConcurrency({
186
- options: state?.options,
187
- toolsMetadata: state?.toolsMetadata,
188
- toolCalls: inputData
189
- });
190
- } }).map(async ({ inputData, getStepResult, getInitData }) => {
191
- const toolResults = inputData;
192
- const llmOutput = getStepResult(llmExecutionStep.id);
193
- const initData = getInitData();
194
- return {
195
- llmOutput,
196
- toolResults,
197
- runId: initData.runId,
198
- agentId: initData.agentId,
199
- messageId: initData.messageId,
200
- state: llmOutput?.state ?? initData.state
201
- };
202
- }, { id: "collect-tool-results" }).then(llmMappingStep).then(backgroundTaskCheckStep).map(async ({ inputData, getInitData }) => {
203
- const executionOutput = inputData;
204
- const initData = getInitData();
205
- return {
206
- ...createBaseIterationStateUpdate({
207
- currentState: initData,
208
- executionOutput
209
- }),
210
- agentSpanData: initData.agentSpanData,
211
- modelSpanData: initData.modelSpanData,
212
- stepIndex: initData.stepIndex + 1
213
- };
214
- }, { id: "update-iteration-state" }).commit();
215
- return createWorkflow({
216
- id: InngestDurableStepIds.AGENTIC_LOOP,
217
- retries,
218
- inputSchema: durableAgenticInputSchema,
219
- outputSchema: durableAgenticOutputSchema,
220
- options: {
221
- tracingPolicy: { internal: InternalSpans.WORKFLOW },
222
- shouldPersistSnapshot: ({ workflowStatus }) => workflowStatus === "suspended",
223
- validateInputs: false
224
- },
225
- steps: []
226
- }).map(async ({ inputData }) => {
227
- const input = inputData;
228
- const agentSpanData = input.agentSpanData;
229
- const modelSpanData = input.modelSpanData;
230
- return {
231
- ...input,
232
- iterationCount: 0,
233
- accumulatedSteps: [],
234
- accumulatedUsage: {
235
- inputTokens: 0,
236
- outputTokens: 0,
237
- totalTokens: 0
238
- },
239
- lastStepResult: void 0,
240
- agentSpanData,
241
- modelSpanData,
242
- stepIndex: input.stepIndex ?? 0
243
- };
244
- }, { id: "init-iteration-state" }).dowhile(singleIterationWorkflow, async ({ inputData }) => {
245
- const state = inputData;
246
- const shouldContinue = state.lastStepResult?.isContinued === true;
247
- const effectiveMaxSteps = state.options?.maxSteps ?? maxSteps;
248
- const underMaxSteps = state.iterationCount < effectiveMaxSteps;
249
- return shouldContinue && underMaxSteps;
250
- }).map(async (params) => {
251
- const { inputData, mastra, requestContext, tracingContext } = params;
252
- const state = inputData;
253
- const initData = params.getInitData();
254
- const pubsub = params[PUBSUB_SYMBOL];
255
- const lastStep = state.accumulatedSteps[state.accumulatedSteps.length - 1];
256
- let finalText = lastStep?.text;
257
- const finishResult = await runDurableFinishSideEffects({
258
- runId: state.runId,
259
- initData,
260
- messageListState: state.messageListState,
261
- mastra,
262
- requestContext,
263
- tracingContext,
264
- logger: mastra?.getLogger?.(),
265
- outputResult: {
266
- text: finalText ?? "",
267
- usage: state.accumulatedUsage,
268
- finishReason: state.lastStepResult?.reason ?? "unknown",
269
- steps: state.accumulatedSteps
270
- }
271
- });
272
- if (lastStep && finishResult.outputText && finishResult.outputText !== (finalText ?? "")) {
273
- lastStep.text = finishResult.outputText;
274
- finalText = finishResult.outputText;
275
- }
276
- const finalOutput = {
277
- messageListState: finishResult.messageListState,
278
- messageId: state.messageId,
279
- stepResult: state.lastStepResult || {
280
- reason: "stop",
281
- warnings: [],
282
- isContinued: false
283
- },
284
- output: {
285
- text: finalText,
286
- usage: state.accumulatedUsage,
287
- steps: state.accumulatedSteps
288
- },
289
- state: state.state
290
- };
291
- const observability = mastra?.observability?.getSelectedInstance({});
292
- if (state.modelSpanData) (observability?.rebuildSpan(state.modelSpanData))?.createTracker()?.endGeneration({
293
- output: { text: finalText },
294
- attributes: { finishReason: state.lastStepResult?.reason || "stop" },
295
- usage: state.accumulatedUsage
296
- });
297
- if (state.agentSpanData) (observability?.rebuildSpan(state.agentSpanData))?.end({ output: { text: finalText } });
298
- if (pubsub) await emitFinishEvent(pubsub, state.runId, {
299
- output: finalOutput.output,
300
- stepResult: finalOutput.stepResult
301
- });
302
- return finalOutput;
303
- }, { id: "map-final-output" }).map(async ({ inputData, getInitData, mastra, requestContext, tracingContext }) => {
304
- executeDurableAgentScorers({
305
- initData: getInitData(),
306
- finalOutput: inputData,
307
- mastra,
308
- requestContext,
309
- tracingContext
310
- });
311
- return inputData;
312
- }, { id: "execute-scorers" }).commit();
313
- }
314
- //#endregion
315
- //#region src/durable-agent/create-inngest-agent.ts
316
- var InngestWorkflowCachingPubSub = class extends CachingPubSub {
317
- publish(topic, event, options) {
318
- if (topic.startsWith("workflow.events.v2.")) return super.publish(topic, event, {
319
- ...options,
320
- localOnly: true
321
- });
322
- return super.publish(topic, event, options);
323
- }
324
- };
325
- /**
326
- * Internal sentinel used by {@link InngestAgent.generate} and
327
- * {@link InngestAgent.resumeGenerate} to ask the underlying `stream()` /
328
- * `resume()` implementation to close the consumer stream on a SUSPENDED
329
- * event, so `getFullOutput()` resolves promptly with `finishReason:
330
- * 'suspended'` instead of waiting for FINISH/ERROR.
331
- *
332
- * Modelled on `CLOSE_ON_SUSPEND` in core `DurableAgent`.
333
- */
334
- const CLOSE_ON_SUSPEND = Symbol("mastra.durable.inngest.closeOnSuspend");
335
- /**
336
- * Internal symbol used by `generate()` / `resumeGenerate()` to tear down the
337
- * pubsub subscription on suspend without removing the run-registry entry.
338
- * The public `cleanup()` does both; this lets the generate wrappers keep the
339
- * registry alive across `suspend` → `resumeGenerate()` while still releasing
340
- * the local stream subscription.
341
- */
342
- const STREAM_CLEANUP = Symbol("mastra.durable.inngest.streamCleanup");
343
- /**
344
- * Create an Inngest-powered durable agent from a Mastra Agent.
345
- *
346
- * This factory function wraps a regular Mastra Agent with Inngest's durable
347
- * execution capabilities. The returned InngestAgent can be registered with
348
- * Mastra, and the required workflow will be automatically registered.
349
- *
350
- * @param options - Configuration options
351
- * @returns An InngestAgent that can be registered with Mastra
352
- *
353
- * @example
354
- * ```typescript
355
- * const agent = new Agent({
356
- * id: 'my-agent',
357
- * instructions: 'You are helpful',
358
- * model: openai('gpt-4'),
359
- * });
360
- *
361
- * const durableAgent = createInngestAgent({ agent, inngest });
362
- *
363
- * const mastra = new Mastra({
364
- * agents: { myAgent: durableAgent },
365
- * });
366
- * ```
367
- */
368
- function createInngestAgent(options) {
369
- const { agent, inngest, id: idOverride, name: nameOverride, pubsub: customPubsub, cache, mastra: mastraOption, shouldPersistSnapshot, retries } = options;
370
- 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).`);
371
- const agentId = idOverride ?? agent.id;
372
- const agentName = nameOverride ?? agent.name;
373
- let mastra = mastraOption;
374
- const activeStreamUntilIdle = /* @__PURE__ */ new Map();
375
- let proxyRef;
376
- const workflow = createInngestDurableAgenticWorkflow({
377
- inngest,
378
- retries
379
- });
380
- let _customCache = cache;
381
- let innerPubsub = customPubsub ?? new InngestPubSub(inngest, InngestDurableStepIds.AGENTIC_LOOP);
382
- let _cachingPubsub = null;
383
- function resolveCache() {
384
- const resolved = _customCache ?? mastra?.serverCache ?? new InMemoryServerCache();
385
- _customCache = resolved;
386
- return resolved;
387
- }
388
- function getPubsub() {
389
- if (!_cachingPubsub) if (innerPubsub instanceof CachingPubSub) {
390
- _cachingPubsub = innerPubsub;
391
- _customCache = _customCache ?? mastra?.serverCache;
392
- } else _cachingPubsub = new CachingPubSub(innerPubsub, resolveCache());
393
- return _cachingPubsub;
394
- }
395
- workflow.__setPubsubFactory((defaultPubsub) => {
396
- if (defaultPubsub instanceof CachingPubSub) return defaultPubsub;
397
- getPubsub();
398
- return new InngestWorkflowCachingPubSub(defaultPubsub, resolveCache());
399
- });
400
- function getCache() {
401
- getPubsub();
402
- return _customCache;
403
- }
404
- /**
405
- * Trigger the workflow via Inngest event
406
- */
407
- async function triggerWorkflow(runId, workflowInput, tracingOptions, actor) {
408
- const eventName = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;
409
- await inngest.send({
410
- name: eventName,
411
- data: buildDurableTriggerEventData({
412
- inputData: workflowInput,
413
- runId,
414
- resourceId: workflowInput.state?.resourceId,
415
- requestContext: workflowInput.requestContextEntries ?? {},
416
- tracingOptions,
417
- actor
418
- })
419
- });
420
- }
421
- /**
422
- * Emit an error event to pubsub.
423
- *
424
- * Best-effort: callers fire-and-forget this on paths that are already
425
- * failing, so an unreachable pubsub must not turn error reporting into an
426
- * unhandled rejection.
427
- */
428
- async function emitError(runId, error) {
429
- try {
430
- await emitErrorEvent(getPubsub(), runId, error);
431
- } catch (publishError) {
432
- mastra?.getLogger?.()?.warn?.("Failed to publish Inngest durable agent error event", {
433
- agentId,
434
- runId,
435
- error: publishError instanceof Error ? publishError.message : String(publishError)
436
- });
437
- }
438
- }
439
- /**
440
- * Stop a run in whichever worker is executing it.
441
- *
442
- * An Inngest agent's steps run on Inngest's infrastructure, essentially never
443
- * in the process that called `stream()`. The local `AbortController` is
444
- * therefore invisible to the step worker, and on its own `abort()` cannot
445
- * stop anything. Publishing an abort request lets the worker flip its own
446
- * controller and unwind the run gracefully, emitting the terminal stream
447
- * event consumers wait on — which a hard workflow cancel would skip.
448
- *
449
- * Best-effort: the local abort has already happened, and a caller asking to
450
- * stop a run should not get a rejection because the publish failed.
451
- */
452
- async function requestRemoteAbort(runId) {
453
- try {
454
- await publishAbortRequest(getPubsub(), runId);
455
- } catch (error) {
456
- mastra?.getLogger?.()?.warn?.("Failed to publish Inngest durable agent abort request", {
457
- agentId,
458
- runId,
459
- error: error instanceof Error ? error.message : String(error)
460
- });
461
- }
462
- }
463
- const result = new Proxy({
464
- get id() {
465
- return agentId;
466
- },
467
- get name() {
468
- return agentName;
469
- },
470
- get agent() {
471
- return agent;
472
- },
473
- get inngest() {
474
- return inngest;
475
- },
476
- get cache() {
477
- return getCache();
478
- },
479
- get pubsub() {
480
- return getPubsub();
481
- },
482
- async stream(messages, streamOptions) {
483
- if (streamOptions?.untilIdle) {
484
- const { untilIdle, ...rest } = streamOptions;
485
- const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
486
- return runDurableStreamUntilIdle(proxyRef, messages, {
487
- ...rest,
488
- maxIdleMs
489
- }, {
490
- activeStreams: activeStreamUntilIdle,
491
- bgManager: mastra?.backgroundTaskManager
492
- });
493
- }
494
- const { runId, messageId, workflowInput, registryEntry, threadId, resourceId } = await prepareForDurableExecution({
495
- agent,
496
- messages,
497
- options: streamOptions,
498
- runId: streamOptions?.runId,
499
- requestContext: streamOptions?.requestContext,
500
- methodType: streamOptions?.__methodType ?? "stream",
501
- mastra,
502
- durableAgentId: agentId,
503
- durableAgentName: agentName
504
- });
505
- workflowInput.agentId = agentId;
506
- workflowInput.agentName = agentName;
507
- const abortController = new AbortController();
508
- if (streamOptions?.abortSignal) {
509
- const external = streamOptions.abortSignal;
510
- if (external.aborted) abortController.abort(external.reason);
511
- else external.addEventListener("abort", () => abortController.abort(external.reason), { once: true });
512
- }
513
- registryEntry.abortController = abortController;
514
- registryEntry.abortSignal = abortController.signal;
515
- globalRunRegistry.set(runId, registryEntry);
516
- workflowInput.stepIndex = 0;
517
- let cleanedUp = false;
518
- const finalizeGlobalRegistry = () => {
519
- if (cleanedUp) return;
520
- cleanedUp = true;
521
- globalRunRegistry.delete(runId);
522
- };
523
- const { output, cleanup: streamCleanup, ready } = createDurableAgentStream({
524
- pubsub: getPubsub(),
525
- runId,
526
- messageId,
527
- model: {
528
- modelId: workflowInput.modelConfig.modelId,
529
- provider: workflowInput.modelConfig.provider,
530
- version: "v3"
531
- },
532
- threadId,
533
- resourceId,
534
- onChunk: streamOptions?.onChunk,
535
- onStepFinish: streamOptions?.onStepFinish,
536
- onFinish: async (result) => {
537
- try {
538
- await streamOptions?.onFinish?.(result);
539
- } finally {
540
- finalizeGlobalRegistry();
541
- }
542
- },
543
- onError: async (errorArg) => {
544
- try {
545
- await streamOptions?.onError?.(errorArg);
546
- } finally {
547
- finalizeGlobalRegistry();
548
- }
549
- },
550
- onSuspended: streamOptions?.onSuspended,
551
- onAbort: async (data) => {
552
- try {
553
- await (streamOptions?.onAbort)?.(data);
554
- } finally {
555
- finalizeGlobalRegistry();
556
- }
557
- },
558
- onIterationComplete: streamOptions?.onIterationComplete ? async (data) => {
559
- await streamOptions.onIterationComplete?.(data);
560
- } : void 0,
561
- closeOnSuspend: streamOptions?.[CLOSE_ON_SUSPEND] === true
562
- });
563
- const agentSpanData = workflowInput.agentSpanData;
564
- const tracingOptions = agentSpanData?.traceId && agentSpanData?.id ? {
565
- traceId: agentSpanData.traceId,
566
- parentSpanId: agentSpanData.id
567
- } : void 0;
568
- const workflowExecution = ready.then(() => triggerWorkflow(runId, workflowInput, tracingOptions, streamOptions?.actor)).catch((error) => {
569
- emitError(runId, error);
570
- });
571
- const trackedEntry = globalRunRegistry.get(runId);
572
- if (trackedEntry) trackedEntry.workflowExecution = workflowExecution;
573
- await agentThreadStreamRuntime.registerRun(proxyRef, output, streamOptions ?? {}, agent.getPubSub());
574
- const cleanup = () => {
575
- streamCleanup();
576
- finalizeGlobalRegistry();
577
- };
578
- const abort = async (reason) => {
579
- if (!abortController.signal.aborted) abortController.abort(reason);
580
- await requestRemoteAbort(runId);
581
- };
582
- return {
583
- output,
584
- runId,
585
- threadId,
586
- resourceId,
587
- cleanup,
588
- abort,
589
- get fullStream() {
590
- return output.fullStream;
591
- },
592
- [STREAM_CLEANUP]: streamCleanup
593
- };
594
- },
595
- async resume(runId, resumeData, resumeOptions) {
596
- if (resumeOptions?.untilIdle) {
597
- const { untilIdle, ...rest } = resumeOptions;
598
- const maxIdleMs = typeof untilIdle === "object" ? untilIdle.maxIdleMs : void 0;
599
- return runResumeDurableStreamUntilIdle(proxyRef, runId, resumeData, {
600
- ...rest,
601
- maxIdleMs
602
- }, {
603
- activeStreams: activeStreamUntilIdle,
604
- bgManager: mastra?.backgroundTaskManager
605
- });
606
- }
607
- const abortController = new AbortController();
608
- if (resumeOptions?.abortSignal) {
609
- const external = resumeOptions.abortSignal;
610
- if (external.aborted) abortController.abort(external.reason);
611
- else external.addEventListener("abort", () => abortController.abort(external.reason), { once: true });
612
- }
613
- let existingEntry = globalRunRegistry.get(runId);
614
- if (!existingEntry) {
615
- existingEntry = {
616
- isPlaceholder: true,
617
- tools: {},
618
- model: void 0
619
- };
620
- globalRunRegistry.set(runId, existingEntry);
621
- }
622
- existingEntry.abortController = abortController;
623
- existingEntry.abortSignal = abortController.signal;
624
- let resumeCleanedUp = false;
625
- const finalizeResumeRegistry = () => {
626
- if (resumeCleanedUp) return;
627
- resumeCleanedUp = true;
628
- globalRunRegistry.delete(runId);
629
- };
630
- const { output, cleanup: streamCleanup, ready } = createDurableAgentStream({
631
- pubsub: getPubsub(),
632
- runId,
633
- messageId: crypto.randomUUID(),
634
- model: {
635
- modelId: void 0,
636
- provider: void 0,
637
- version: "v3"
638
- },
639
- threadId: resumeOptions?.threadId,
640
- resourceId: resumeOptions?.resourceId,
641
- onChunk: resumeOptions?.onChunk,
642
- onStepFinish: resumeOptions?.onStepFinish,
643
- onFinish: async (result) => {
644
- try {
645
- await resumeOptions?.onFinish?.(result);
646
- } finally {
647
- finalizeResumeRegistry();
648
- }
649
- },
650
- onError: async (errorArg) => {
651
- try {
652
- await resumeOptions?.onError?.(errorArg);
653
- } finally {
654
- finalizeResumeRegistry();
655
- }
656
- },
657
- onSuspended: resumeOptions?.onSuspended,
658
- onAbort: async (data) => {
659
- try {
660
- await (resumeOptions?.onAbort)?.(data);
661
- } finally {
662
- finalizeResumeRegistry();
663
- }
664
- },
665
- closeOnSuspend: resumeOptions?.[CLOSE_ON_SUSPEND] === true
666
- });
667
- const eventName = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;
668
- const dispatch = ready.then(async () => {
669
- const snapshot = await (await mastra?.getStorage()?.getStore("workflows"))?.loadWorkflowSnapshot({
670
- workflowName: InngestDurableStepIds.AGENTIC_LOOP,
671
- runId
672
- });
673
- const suspendedStepIds = snapshot?.suspendedPaths ? Object.keys(snapshot.suspendedPaths) : [];
674
- const resumeLabels = snapshot?.resumeLabels ?? {};
675
- const toolCallId = resumeOptions?.toolCallId;
676
- const expandToLeafPath = (stepId) => {
677
- const nestedPath = (snapshot?.context ?? {})[stepId]?.suspendPayload?.__workflow_meta?.path;
678
- return Array.isArray(nestedPath) ? [stepId, ...nestedPath] : [stepId];
679
- };
680
- let steps;
681
- if (toolCallId) {
682
- const targetStepId = resumeLabels[toolCallId]?.stepId;
683
- if (!targetStepId) {
684
- const available = Object.keys(resumeLabels);
685
- 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.`));
686
- }
687
- steps = expandToLeafPath(targetStepId);
688
- } else {
689
- const available = Object.keys(resumeLabels);
690
- 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(", ")}.` : ""));
691
- steps = suspendedStepIds[0] ? expandToLeafPath(suspendedStepIds[0]) : [];
692
- }
693
- const requestContext = mergeResumeRequestContext(snapshot?.requestContext, resumeOptions?.requestContext);
694
- const tracingOptions = snapshot?.tracingContext ? {
695
- traceId: snapshot.tracingContext.traceId,
696
- parentSpanId: snapshot.tracingContext.spanId
697
- } : void 0;
698
- await inngest.send({
699
- name: eventName,
700
- data: buildDurableResumeEventData({
701
- inputData: resumeData,
702
- runId,
703
- resourceId: resumeOptions?.resourceId,
704
- requestContext,
705
- tracingOptions,
706
- actor: resumeOptions?.actor,
707
- resume: {
708
- steps,
709
- resumePayload: resumeData,
710
- resumePath: steps[0] ? snapshot?.suspendedPaths?.[steps[0]] : void 0
711
- }
712
- })
713
- });
714
- });
715
- const workflowExecution = dispatch.catch((error) => {
716
- emitError(runId, error);
717
- });
718
- existingEntry.workflowExecution = workflowExecution;
719
- try {
720
- await dispatch;
721
- } catch (error) {
722
- streamCleanup();
723
- finalizeResumeRegistry();
724
- throw error;
725
- }
726
- const abort = async (reason) => {
727
- if (!abortController.signal.aborted) abortController.abort(reason);
728
- await requestRemoteAbort(runId);
729
- };
730
- const cleanup = () => {
731
- streamCleanup();
732
- finalizeResumeRegistry();
733
- };
734
- return {
735
- output,
736
- get fullStream() {
737
- return output.fullStream;
738
- },
739
- runId,
740
- threadId: resumeOptions?.threadId,
741
- resourceId: resumeOptions?.resourceId,
742
- cleanup,
743
- abort,
744
- [STREAM_CLEANUP]: streamCleanup
745
- };
746
- },
747
- async prepare(messages, prepareOptions) {
748
- const preparation = await prepareForDurableExecution({
749
- agent,
750
- messages,
751
- options: prepareOptions,
752
- requestContext: prepareOptions?.requestContext,
753
- mastra,
754
- durableAgentId: agentId,
755
- durableAgentName: agentName
756
- });
757
- preparation.workflowInput.agentId = agentId;
758
- preparation.workflowInput.agentName = agentName;
759
- return {
760
- runId: preparation.runId,
761
- messageId: preparation.messageId,
762
- workflowInput: preparation.workflowInput,
763
- threadId: preparation.threadId,
764
- resourceId: preparation.resourceId
765
- };
766
- },
767
- async observe(runId, observeOptions) {
768
- const { output, cleanup: streamCleanup, ready } = createDurableAgentStream({
769
- pubsub: getPubsub(),
770
- runId,
771
- messageId: crypto.randomUUID(),
772
- model: {
773
- modelId: void 0,
774
- provider: void 0,
775
- version: "v3"
776
- },
777
- offset: observeOptions?.offset,
778
- onChunk: observeOptions?.onChunk,
779
- onStepFinish: observeOptions?.onStepFinish,
780
- onFinish: observeOptions?.onFinish,
781
- onError: observeOptions?.onError,
782
- onSuspended: observeOptions?.onSuspended
783
- });
784
- await ready;
785
- const abort = async (_reason) => {
786
- streamCleanup();
787
- await requestRemoteAbort(runId);
788
- };
789
- return {
790
- output,
791
- get fullStream() {
792
- return output.fullStream;
793
- },
794
- runId,
795
- cleanup: streamCleanup,
796
- abort
797
- };
798
- },
799
- async generate(messages, generateOptions) {
800
- const { untilIdle, ...rest } = generateOptions ?? {};
801
- const streamOpts = {
802
- ...rest,
803
- [CLOSE_ON_SUSPEND]: true,
804
- __methodType: "generate"
805
- };
806
- const result = await proxyRef.stream(messages, streamOpts);
807
- let suspended = false;
808
- try {
809
- const fullOutput = await result.output.getFullOutput();
810
- if (fullOutput.error) throw fullOutput.error;
811
- suspended = fullOutput.finishReason === "suspended";
812
- if (suspended) await globalRunRegistry.get(result.runId)?.workflowExecution;
813
- if (!fullOutput.runId) fullOutput.runId = result.runId;
814
- return fullOutput;
815
- } finally {
816
- if (suspended) {
817
- const streamOnlyCleanup = result[STREAM_CLEANUP];
818
- streamOnlyCleanup?.();
819
- } else result.cleanup();
820
- }
821
- },
822
- async resumeGenerate(runId, resumeData, resumeOptions) {
823
- const { untilIdle, ...rest } = resumeOptions ?? {};
824
- const result = await proxyRef.resume(runId, resumeData, {
825
- ...rest,
826
- [CLOSE_ON_SUSPEND]: true
827
- });
828
- let suspended = false;
829
- try {
830
- const fullOutput = await result.output.getFullOutput();
831
- if (fullOutput.error) throw fullOutput.error;
832
- suspended = fullOutput.finishReason === "suspended";
833
- if (suspended) await globalRunRegistry.get(result.runId)?.workflowExecution;
834
- if (!fullOutput.runId) fullOutput.runId = result.runId;
835
- return fullOutput;
836
- } finally {
837
- if (suspended) {
838
- const streamOnlyCleanup = result[STREAM_CLEANUP];
839
- streamOnlyCleanup?.();
840
- } else result.cleanup();
841
- }
842
- },
843
- async resumeStream(resumeData, streamOptions) {
844
- const runId = streamOptions?.runId;
845
- if (!runId) throw new Error("resumeStream() on InngestAgent requires a runId in streamOptions.");
846
- const { runId: _runId, ...resumeOptions } = streamOptions;
847
- return (await proxyRef.resume(runId, resumeData, {
848
- ...resumeOptions,
849
- [CLOSE_ON_SUSPEND]: true
850
- })).output;
851
- },
852
- async approveToolCall(options) {
853
- return proxyRef.resumeStream({ approved: true }, options);
854
- },
855
- async declineToolCall(options) {
856
- const { reason, ...resumeOptions } = options;
857
- return proxyRef.resumeStream({
858
- approved: false,
859
- ...reason !== void 0 ? { reason } : {}
860
- }, resumeOptions);
861
- },
862
- async approveToolCallGenerate(options) {
863
- const { runId, ...resumeOptions } = options;
864
- if (!runId) throw new Error("approveToolCallGenerate() on InngestAgent requires a runId.");
865
- return proxyRef.resumeGenerate(runId, { approved: true }, resumeOptions);
866
- },
867
- async declineToolCallGenerate(options) {
868
- const { runId, reason, ...resumeOptions } = options;
869
- if (!runId) throw new Error("declineToolCallGenerate() on InngestAgent requires a runId.");
870
- return proxyRef.resumeGenerate(runId, {
871
- approved: false,
872
- ...reason !== void 0 ? { reason } : {}
873
- }, resumeOptions);
874
- },
875
- __fork() {
876
- const { shouldPersistSnapshot: _ignored, ...forkOptions } = options;
877
- return createInngestAgent({
878
- ...forkOptions,
879
- agent: agent.__fork(),
880
- pubsub: innerPubsub,
881
- cache: _customCache,
882
- mastra
883
- });
884
- },
885
- getDurableWorkflows() {
886
- return [workflow];
887
- },
888
- __setMastra(mastraInstance) {
889
- mastra = mastraInstance;
890
- }
891
- }, {
892
- get(target, prop, receiver) {
893
- if (prop in target) return Reflect.get(target, prop, receiver);
894
- const agentValue = agent[prop];
895
- if (typeof agentValue === "function") return agentValue.bind(agent);
896
- return agentValue;
897
- },
898
- has(target, prop) {
899
- return prop in target || prop in agent;
900
- }
901
- });
902
- proxyRef = result;
903
- agent.__setThreadRuntimeAgent(result);
904
- return result;
905
- }
906
- /**
907
- * Check if an object is an InngestAgent
908
- */
909
- function isInngestAgent(obj) {
910
- if (!obj) return false;
911
- return typeof obj.id === "string" && typeof obj.name === "string" && "agent" in obj && "inngest" in obj && typeof obj.stream === "function" && typeof obj.getDurableWorkflows === "function";
912
- }
913
- //#endregion
914
- //#region src/index.ts
915
- function isInngestWorkflow(input) {
916
- return input instanceof InngestWorkflow;
917
- }
918
- /**
919
- * copied from @mastra/core/agent/subagent.ts for compatible
920
- */
921
- function isAgentCompatible(input) {
922
- 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";
923
- }
924
- function isToolStep(input) {
925
- return input instanceof Tool;
926
- }
927
- function isStepParams(input) {
928
- return input !== null && typeof input === "object" && "id" in input && "execute" in input && !(input instanceof Agent) && !(input instanceof Tool) && !(input instanceof InngestWorkflow);
929
- }
930
- /**
931
- * Type guard to check if an object is a Processor.
932
- * A Processor must have an 'id' property and at least one processor method.
933
- */
934
- function isProcessor(obj) {
935
- 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");
936
- }
937
- function createStep(params, agentOrToolOptions) {
938
- if (isInngestWorkflow(params)) return params;
939
- if (isAgentCompatible(params)) return createStepFromAgent$1(params, agentOrToolOptions);
940
- if (isToolStep(params)) return createStepFromTool$1(params, agentOrToolOptions);
941
- if (isStepParams(params)) return createStepFromParams(params);
942
- if (isProcessor(params)) return createStepFromProcessor(params);
943
- throw new Error("Invalid input: expected StepParams, Agent, ToolStep, Processor, or InngestWorkflow");
944
- }
945
- function createStepFromParams(params) {
946
- return {
947
- id: params.id,
948
- description: params.description,
949
- inputSchema: toStandardSchema(params.inputSchema),
950
- stateSchema: params.stateSchema ? toStandardSchema(params.stateSchema) : void 0,
951
- outputSchema: toStandardSchema(params.outputSchema),
952
- resumeSchema: params.resumeSchema ? toStandardSchema(params.resumeSchema) : void 0,
953
- suspendSchema: params.suspendSchema ? toStandardSchema(params.suspendSchema) : void 0,
954
- scorers: params.scorers,
955
- retries: params.retries,
956
- metadata: params.metadata,
957
- execute: params.execute.bind(params)
958
- };
959
- }
960
- function createStepFromAgent$1(params, agentOrToolOptions) {
961
- return createStepFromAgent(params, agentOrToolOptions);
962
- }
963
- function createStepFromTool$1(params, agentOrToolOptions) {
964
- return createStepFromTool(params, agentOrToolOptions);
965
- }
966
- function createStepFromProcessor(processor) {
967
- const getProcessorEntityType = (phase) => {
968
- switch (phase) {
969
- case "input": return EntityType.INPUT_PROCESSOR;
970
- case "inputStep": return EntityType.INPUT_STEP_PROCESSOR;
971
- case "outputStream":
972
- case "outputResult": return EntityType.OUTPUT_PROCESSOR;
973
- case "outputStep": return EntityType.OUTPUT_STEP_PROCESSOR;
974
- default: return EntityType.OUTPUT_PROCESSOR;
975
- }
976
- };
977
- const getSpanNamePrefix = (phase) => {
978
- switch (phase) {
979
- case "input": return "input processor";
980
- case "inputStep": return "input step processor";
981
- case "outputStream": return "output stream processor";
982
- case "outputResult": return "output processor";
983
- case "outputStep": return "output step processor";
984
- default: return "processor";
985
- }
986
- };
987
- const hasPhaseMethod = (phase) => {
988
- switch (phase) {
989
- case "input": return !!processor.processInput;
990
- case "inputStep": return !!processor.processInputStep;
991
- case "outputStream": return !!processor.processOutputStream;
992
- case "outputResult": return !!processor.processOutputResult;
993
- case "outputStep": return !!processor.processOutputStep;
994
- default: return false;
995
- }
996
- };
997
- return {
998
- id: `processor:${processor.id}`,
999
- description: processor.name ?? `Processor ${processor.id}`,
1000
- inputSchema: ProcessorStepSchema,
1001
- outputSchema: ProcessorStepOutputSchema,
1002
- execute: async ({ inputData, requestContext, tracingContext }) => {
1003
- const input = inputData;
1004
- const { phase, messages, messageList, stepNumber, systemMessages, part, streamParts, processorStates, result, finishReason, toolCalls, text, retryCount, model, tools, toolChoice, activeTools, providerOptions, modelSettings, structuredOutput, steps, usage } = input;
1005
- const abort = (reason, options) => {
1006
- throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
1007
- };
1008
- if (!hasPhaseMethod(phase)) return input;
1009
- const currentSpan = tracingContext?.currentSpan;
1010
- const parentSpan = phase === "inputStep" || phase === "outputStep" ? currentSpan?.findParent(SpanType.MODEL_STEP) || currentSpan : currentSpan?.findParent(SpanType.AGENT_RUN) || currentSpan;
1011
- const processorSpan = phase !== "outputStream" ? parentSpan?.createChildSpan({
1012
- type: SpanType.PROCESSOR_RUN,
1013
- name: `${getSpanNamePrefix(phase)}: ${processor.id}`,
1014
- entityType: getProcessorEntityType(phase),
1015
- entityId: processor.id,
1016
- entityName: processor.name ?? processor.id,
1017
- input: {
1018
- phase,
1019
- messageCount: messages?.length
1020
- },
1021
- attributes: {
1022
- processorExecutor: "workflow",
1023
- processorIndex: processor.processorIndex
1024
- }
1025
- }) : void 0;
1026
- const processorTracingContext = processorSpan ? { currentSpan: processorSpan } : tracingContext;
1027
- let processorState = {};
1028
- if (processorStates) {
1029
- let ps = processorStates.get(processor.id);
1030
- if (!ps) {
1031
- ps = new ProcessorState(processor.id);
1032
- processorStates.set(processor.id, ps);
1033
- }
1034
- processorState = ps.customState;
1035
- }
1036
- const baseContext = {
1037
- abort,
1038
- retryCount: retryCount ?? 0,
1039
- requestContext,
1040
- tracingContext: processorTracingContext
1041
- };
1042
- const passThrough = {
1043
- phase,
1044
- messageList: messageList ?? (Array.isArray(messages) ? new MessageList().add(messages, "input").addSystem(systemMessages ?? []) : void 0),
1045
- stepNumber,
1046
- systemMessages,
1047
- streamParts,
1048
- state: processorState,
1049
- processorStates,
1050
- result,
1051
- finishReason,
1052
- toolCalls,
1053
- text,
1054
- retryCount,
1055
- model,
1056
- tools,
1057
- toolChoice,
1058
- activeTools,
1059
- providerOptions,
1060
- modelSettings,
1061
- structuredOutput,
1062
- steps,
1063
- usage
1064
- };
1065
- const executePhaseWithSpan = async (fn) => {
1066
- try {
1067
- const result = await fn();
1068
- processorSpan?.end({ output: result });
1069
- return result;
1070
- } catch (error) {
1071
- if (error instanceof TripWire) processorSpan?.end({ output: { tripwire: error.message } });
1072
- else processorSpan?.error({
1073
- error,
1074
- endSpan: true
1075
- });
1076
- throw error;
1077
- }
1078
- };
1079
- return executePhaseWithSpan(async () => {
1080
- switch (phase) {
1081
- case "input":
1082
- if (processor.processInput) {
1083
- if (!passThrough.messageList) throw new MastraError({
1084
- category: ErrorCategory.USER,
1085
- domain: ErrorDomain.MASTRA_WORKFLOW,
1086
- id: "PROCESSOR_MISSING_MESSAGE_LIST",
1087
- text: `Processor ${processor.id} requires messageList or messages for processInput phase`
1088
- });
1089
- const idsBeforeProcessing = messages.map((m) => m.id);
1090
- const check = passThrough.messageList.makeMessageSourceChecker();
1091
- const result = await processor.processInput({
1092
- ...baseContext,
1093
- messages,
1094
- messageList: passThrough.messageList,
1095
- systemMessages: systemMessages ?? [],
1096
- state: processorState
1097
- });
1098
- if (result instanceof MessageList) {
1099
- if (result !== passThrough.messageList) throw new MastraError({
1100
- category: ErrorCategory.USER,
1101
- domain: ErrorDomain.MASTRA_WORKFLOW,
1102
- id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
1103
- text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`
1104
- });
1105
- return {
1106
- ...passThrough,
1107
- messages: result.get.all.db(),
1108
- systemMessages: result.getSystemMessages()
1109
- };
1110
- } else if (Array.isArray(result)) {
1111
- ProcessorRunner.applyMessagesToMessageList(result, passThrough.messageList, idsBeforeProcessing, check, "input");
1112
- return {
1113
- ...passThrough,
1114
- messages: result
1115
- };
1116
- } else if (result && "messages" in result && "systemMessages" in result) {
1117
- const typedResult = result;
1118
- ProcessorRunner.applyMessagesToMessageList(typedResult.messages, passThrough.messageList, idsBeforeProcessing, check, "input");
1119
- passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);
1120
- return {
1121
- ...passThrough,
1122
- messages: typedResult.messages,
1123
- systemMessages: passThrough.messageList.getSystemMessages()
1124
- };
1125
- }
1126
- return {
1127
- ...passThrough,
1128
- messages
1129
- };
1130
- }
1131
- return {
1132
- ...passThrough,
1133
- messages
1134
- };
1135
- case "inputStep":
1136
- if (processor.processInputStep) {
1137
- if (!passThrough.messageList) throw new MastraError({
1138
- category: ErrorCategory.USER,
1139
- domain: ErrorDomain.MASTRA_WORKFLOW,
1140
- id: "PROCESSOR_MISSING_MESSAGE_LIST",
1141
- text: `Processor ${processor.id} requires messageList or messages for processInputStep phase`
1142
- });
1143
- const idsBeforeProcessing = messages.map((m) => m.id);
1144
- const check = passThrough.messageList.makeMessageSourceChecker();
1145
- const result = await processor.processInputStep({
1146
- ...baseContext,
1147
- messages,
1148
- messageList: passThrough.messageList,
1149
- stepNumber: stepNumber ?? 0,
1150
- systemMessages: systemMessages ?? [],
1151
- model,
1152
- tools,
1153
- toolChoice,
1154
- activeTools,
1155
- providerOptions,
1156
- modelSettings,
1157
- structuredOutput,
1158
- steps: steps ?? [],
1159
- state: processorState
1160
- });
1161
- const validatedResult = await ProcessorRunner.validateAndFormatProcessInputStepResult(result, {
1162
- messageList: passThrough.messageList,
1163
- processor,
1164
- stepNumber: stepNumber ?? 0
1165
- });
1166
- if (validatedResult.messages) ProcessorRunner.applyMessagesToMessageList(validatedResult.messages, passThrough.messageList, idsBeforeProcessing, check);
1167
- if (validatedResult.systemMessages) passThrough.messageList.replaceAllSystemMessages(validatedResult.systemMessages);
1168
- return {
1169
- ...passThrough,
1170
- messages,
1171
- ...validatedResult,
1172
- systemMessages: passThrough.messageList.getSystemMessages()
1173
- };
1174
- }
1175
- return {
1176
- ...passThrough,
1177
- messages
1178
- };
1179
- case "outputStream":
1180
- if (processor.processOutputStream) {
1181
- const spanKey = `__outputStreamSpan_${processor.id}`;
1182
- const mutableState = processorState;
1183
- let processorSpan = mutableState[spanKey];
1184
- if (!processorSpan && parentSpan) {
1185
- processorSpan = parentSpan.createChildSpan({
1186
- type: SpanType.PROCESSOR_RUN,
1187
- name: `output stream processor: ${processor.id}`,
1188
- entityType: EntityType.OUTPUT_PROCESSOR,
1189
- entityId: processor.id,
1190
- entityName: processor.name ?? processor.id,
1191
- input: {
1192
- phase,
1193
- streamParts: []
1194
- },
1195
- attributes: {
1196
- processorExecutor: "workflow",
1197
- processorIndex: processor.processorIndex
1198
- }
1199
- });
1200
- mutableState[spanKey] = processorSpan;
1201
- }
1202
- if (processorSpan) processorSpan.input = {
1203
- phase,
1204
- streamParts: streamParts ?? [],
1205
- totalChunks: (streamParts ?? []).length
1206
- };
1207
- const processorTracingContext = processorSpan ? { currentSpan: processorSpan } : baseContext.tracingContext;
1208
- let result;
1209
- try {
1210
- result = await processor.processOutputStream({
1211
- ...baseContext,
1212
- tracingContext: processorTracingContext,
1213
- part,
1214
- streamParts: streamParts ?? [],
1215
- state: mutableState,
1216
- messageList: passThrough.messageList
1217
- });
1218
- if (part && part.type === "finish") {
1219
- processorSpan?.end({ output: result });
1220
- delete mutableState[spanKey];
1221
- }
1222
- } catch (error) {
1223
- if (error instanceof TripWire) processorSpan?.end({ output: { tripwire: error.message } });
1224
- else processorSpan?.error({
1225
- error,
1226
- endSpan: true
1227
- });
1228
- delete mutableState[spanKey];
1229
- throw error;
1230
- }
1231
- return {
1232
- ...passThrough,
1233
- state: mutableState,
1234
- part: result
1235
- };
1236
- }
1237
- return {
1238
- ...passThrough,
1239
- part
1240
- };
1241
- case "outputResult":
1242
- if (processor.processOutputResult) {
1243
- if (!passThrough.messageList) throw new MastraError({
1244
- category: ErrorCategory.USER,
1245
- domain: ErrorDomain.MASTRA_WORKFLOW,
1246
- id: "PROCESSOR_MISSING_MESSAGE_LIST",
1247
- text: `Processor ${processor.id} requires messageList or messages for processOutputResult phase`
1248
- });
1249
- const idsBeforeProcessing = messages.map((m) => m.id);
1250
- const check = passThrough.messageList.makeMessageSourceChecker();
1251
- const outputResult = passThrough.result ?? {
1252
- text: "",
1253
- usage: {
1254
- inputTokens: 0,
1255
- outputTokens: 0,
1256
- totalTokens: 0
1257
- },
1258
- finishReason: "unknown",
1259
- steps: []
1260
- };
1261
- const processResult = await processor.processOutputResult({
1262
- ...baseContext,
1263
- messages,
1264
- messageList: passThrough.messageList,
1265
- state: processorState,
1266
- result: outputResult
1267
- });
1268
- if (processResult instanceof MessageList) {
1269
- if (processResult !== passThrough.messageList) throw new MastraError({
1270
- category: ErrorCategory.USER,
1271
- domain: ErrorDomain.MASTRA_WORKFLOW,
1272
- id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
1273
- text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`
1274
- });
1275
- return {
1276
- ...passThrough,
1277
- messages: processResult.get.all.db(),
1278
- systemMessages: processResult.getSystemMessages()
1279
- };
1280
- } else if (Array.isArray(processResult)) {
1281
- ProcessorRunner.applyMessagesToMessageList(processResult, passThrough.messageList, idsBeforeProcessing, check, "response");
1282
- return {
1283
- ...passThrough,
1284
- messages: processResult
1285
- };
1286
- } else if (processResult && "messages" in processResult && "systemMessages" in processResult) {
1287
- const typedResult = processResult;
1288
- ProcessorRunner.applyMessagesToMessageList(typedResult.messages, passThrough.messageList, idsBeforeProcessing, check, "response");
1289
- passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);
1290
- return {
1291
- ...passThrough,
1292
- messages: typedResult.messages,
1293
- systemMessages: passThrough.messageList.getSystemMessages()
1294
- };
1295
- }
1296
- return {
1297
- ...passThrough,
1298
- messages
1299
- };
1300
- }
1301
- return {
1302
- ...passThrough,
1303
- messages
1304
- };
1305
- case "outputStep":
1306
- if (processor.processOutputStep) {
1307
- if (!passThrough.messageList) throw new MastraError({
1308
- category: ErrorCategory.USER,
1309
- domain: ErrorDomain.MASTRA_WORKFLOW,
1310
- id: "PROCESSOR_MISSING_MESSAGE_LIST",
1311
- text: `Processor ${processor.id} requires messageList or messages for processOutputStep phase`
1312
- });
1313
- const idsBeforeProcessing = messages.map((m) => m.id);
1314
- const check = passThrough.messageList.makeMessageSourceChecker();
1315
- const defaultUsage = {
1316
- inputTokens: void 0,
1317
- outputTokens: void 0,
1318
- totalTokens: void 0
1319
- };
1320
- const result = await processor.processOutputStep({
1321
- ...baseContext,
1322
- messages,
1323
- messageList: passThrough.messageList,
1324
- stepNumber: stepNumber ?? 0,
1325
- finishReason,
1326
- toolCalls,
1327
- text,
1328
- usage: usage ?? defaultUsage,
1329
- systemMessages: systemMessages ?? [],
1330
- steps: steps ?? [],
1331
- state: processorState
1332
- });
1333
- if (result instanceof MessageList) {
1334
- if (result !== passThrough.messageList) throw new MastraError({
1335
- category: ErrorCategory.USER,
1336
- domain: ErrorDomain.MASTRA_WORKFLOW,
1337
- id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
1338
- text: `Processor ${processor.id} returned a MessageList instance other than the one passed in. Use the messageList argument instead.`
1339
- });
1340
- return {
1341
- ...passThrough,
1342
- messages: result.get.all.db(),
1343
- systemMessages: result.getSystemMessages()
1344
- };
1345
- } else if (Array.isArray(result)) {
1346
- ProcessorRunner.applyMessagesToMessageList(result, passThrough.messageList, idsBeforeProcessing, check, "response");
1347
- return {
1348
- ...passThrough,
1349
- messages: result
1350
- };
1351
- } else if (result && "messages" in result && "systemMessages" in result) {
1352
- const typedResult = result;
1353
- ProcessorRunner.applyMessagesToMessageList(typedResult.messages, passThrough.messageList, idsBeforeProcessing, check, "response");
1354
- passThrough.messageList.replaceAllSystemMessages(typedResult.systemMessages);
1355
- return {
1356
- ...passThrough,
1357
- messages: typedResult.messages,
1358
- systemMessages: passThrough.messageList.getSystemMessages()
1359
- };
1360
- }
1361
- return {
1362
- ...passThrough,
1363
- messages
1364
- };
1365
- }
1366
- return {
1367
- ...passThrough,
1368
- messages
1369
- };
1370
- default: return {
1371
- ...passThrough,
1372
- messages
1373
- };
1374
- }
1375
- });
1376
- },
1377
- component: "PROCESSOR"
1378
- };
1379
- }
1380
- function init(inngest) {
1381
- return {
1382
- createTool,
1383
- createWorkflow(params) {
1384
- return new InngestWorkflow(params, inngest);
1385
- },
1386
- createStep,
1387
- cloneStep(step, opts) {
1388
- return {
1389
- id: opts.id,
1390
- description: step.description,
1391
- inputSchema: step.inputSchema,
1392
- outputSchema: step.outputSchema,
1393
- resumeSchema: step.resumeSchema,
1394
- suspendSchema: step.suspendSchema,
1395
- stateSchema: step.stateSchema,
1396
- metadata: step.metadata,
1397
- execute: step.execute,
1398
- retries: step.retries,
1399
- scorers: step.scorers,
1400
- component: step.component
1401
- };
1402
- },
1403
- cloneWorkflow(workflow, opts) {
1404
- const wf = new Workflow({
1405
- id: opts.id,
1406
- inputSchema: workflow.inputSchema,
1407
- outputSchema: workflow.outputSchema,
1408
- steps: workflow.stepDefs,
1409
- mastra: workflow.mastra,
1410
- options: workflow.options
1411
- });
1412
- wf.setStepFlow(workflow.stepGraph);
1413
- wf.commit();
1414
- return wf;
1415
- }
1416
- };
1417
- }
1418
- //#endregion
1
+ import { a as createServe, c as isInngestAgent, d as InngestRun, f as InngestPubSub, i as connect, l as createInngestDurableAgenticWorkflow, n as init, o as serve, p as InngestExecutionEngine, r as _compatibilityCheck, s as createInngestAgent, t as createStep, u as InngestWorkflow } from "./src-iZ1vJU4r.js";
1419
2
  export { InngestExecutionEngine, InngestPubSub, InngestRun, InngestWorkflow, _compatibilityCheck, connect, createInngestAgent, createInngestDurableAgenticWorkflow, createServe, createStep, init, isInngestAgent, serve };
1420
-
1421
- //# sourceMappingURL=index.js.map