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