@mastra/inngest 1.11.5 → 1.11.6-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/connect.cjs CHANGED
@@ -1,3 +1,3 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_src = require("./src-D-mqQKT7.cjs");
2
+ const require_src = require("./src-apDn0X9g.cjs");
3
3
  exports.connect = require_src.connect;
package/dist/connect.js CHANGED
@@ -1 +1 @@
1
- export { i as connect } from "./src-zXJQpJbZ.js";
1
+ export { i as connect } from "./src-DasTihK7.js";
@@ -15,6 +15,8 @@ export declare class InngestExecutionEngine extends DefaultExecutionEngine {
15
15
  private workflowSpan?;
16
16
  private inngestStep;
17
17
  private inngestAttempts;
18
+ /** A suspension in the failed nested run already ended the spans of the durable agent's segment. */
19
+ segmentEnded: boolean;
18
20
  constructor(mastra: Mastra, inngestStep: BaseContext<Inngest>['step'], inngestAttempts: number | undefined, options: ExecutionEngineOptions, parentStream?: {
19
21
  workflowId: string;
20
22
  runId: string;
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_src = require("./src-D-mqQKT7.cjs");
2
+ const require_src = require("./src-apDn0X9g.cjs");
3
3
  exports.InngestExecutionEngine = require_src.InngestExecutionEngine;
4
4
  exports.InngestPubSub = require_src.InngestPubSub;
5
5
  exports.InngestRun = require_src.InngestRun;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { m as InngestExecutionEngine, f as InngestPubSub, d as InngestRun, u as InngestWorkflow, p as OVERSIZED_EVENT_CHUNK_TYPE, r as _compatibilityCheck, i as connect, s as createInngestAgent, l as createInngestDurableAgenticWorkflow, a as createServe, t as createStep, n as init, c as isInngestAgent, o as serve } from "./src-zXJQpJbZ.js";
1
+ export { m as InngestExecutionEngine, f as InngestPubSub, d as InngestRun, u as InngestWorkflow, p as OVERSIZED_EVENT_CHUNK_TYPE, r as _compatibilityCheck, i as connect, s as createInngestAgent, l as createInngestDurableAgenticWorkflow, a as createServe, t as createStep, n as init, c as isInngestAgent, o as serve } from "./src-DasTihK7.js";
@@ -9,11 +9,18 @@ export declare function workflowTermination(...args: Parameters<typeof coreWorkf
9
9
  export declare function agentLoopTermination(...args: Parameters<typeof coreObservability.agentLoopTermination>): SpanOutcomeFields;
10
10
  /** End the caller's live root spans with `error`; a no-op on cores without the helper. */
11
11
  export declare function endRunSpansWithError(...args: Parameters<typeof coreDurable.endRunSpansWithError>): void;
12
+ /** End the spans a failed execution left open; an older core leaves them open. */
13
+ export declare function endFailedSegmentSpans(...args: Parameters<typeof coreDurable.endFailedSegmentSpans>): void;
14
+ /** Whether a suspension beside the failed tool call already ended the spans of the segment. */
15
+ export declare function segmentEndedBySuspension(...args: Parameters<typeof coreDurable.segmentEndedBySuspension>): boolean;
12
16
  export declare function executionFailureTermination(...args: Parameters<typeof coreObservability.executionFailureTermination>): SpanOutcomeFields;
13
- /** Keep completed-request usage when a failed request makes the total incomplete. */
17
+ /**
18
+ * Keep completed-request usage when a failed request makes the total incomplete, less what the
19
+ * MODEL_GENERATION spans of suspended segments already recorded; an older core recorded none.
20
+ */
14
21
  export declare function generationUsage(usage: LanguageModelUsage, steps: Array<{
15
22
  usage?: LanguageModelUsage;
16
- }>): {
23
+ }>, reported?: LanguageModelUsage): {
17
24
  usageIncomplete: boolean;
18
25
  usage: LanguageModelUsage;
19
26
  };
@@ -142,15 +142,27 @@ function agentLoopTermination(...args) {
142
142
  function endRunSpansWithError(...args) {
143
143
  if (coreFeatures.has("execution-outcomes")) coreDurable.endRunSpansWithError?.(...args);
144
144
  }
145
+ /** End the spans a failed execution left open; an older core leaves them open. */
146
+ function endFailedSegmentSpans(...args) {
147
+ if (carriesSegmentSpans()) coreDurable.endFailedSegmentSpans?.(...args);
148
+ }
149
+ /** Whether a suspension beside the failed tool call already ended the spans of the segment. */
150
+ function segmentEndedBySuspension(...args) {
151
+ return carriesSegmentSpans() && !!coreDurable.segmentEndedBySuspension?.(...args);
152
+ }
145
153
  function executionFailureTermination(...args) {
146
154
  return coreFeatures.has("execution-outcomes") ? coreObservability.executionFailureTermination?.(...args) ?? {} : {};
147
155
  }
148
- /** Keep completed-request usage when a failed request makes the total incomplete. */
149
- function generationUsage(usage, steps) {
156
+ /**
157
+ * Keep completed-request usage when a failed request makes the total incomplete, less what the
158
+ * MODEL_GENERATION spans of suspended segments already recorded; an older core recorded none.
159
+ */
160
+ function generationUsage(usage, steps, reported) {
150
161
  const usageIncomplete = coreFeatures.has("execution-outcomes") && coreObservability.isUsageIncomplete?.(usage);
162
+ const observed = usageIncomplete ? coreObservability.calculateObservedUsage?.(steps) ?? usage : usage;
151
163
  return {
152
164
  usageIncomplete,
153
- usage: usageIncomplete ? coreObservability.calculateObservedUsage?.(steps) ?? usage : usage
165
+ usage: coreObservability.subtractReportedUsage?.(observed, reported) ?? observed
154
166
  };
155
167
  }
156
168
  /**
@@ -214,6 +226,8 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
214
226
  workflowSpan;
215
227
  inngestStep;
216
228
  inngestAttempts;
229
+ /** A suspension in the failed nested run already ended the spans of the durable agent's segment. */
230
+ segmentEnded = false;
217
231
  constructor(mastra, inngestStep, inngestAttempts = 0, options, parentStream, inngestRunId, workflowSpan) {
218
232
  super({
219
233
  mastra,
@@ -663,7 +677,8 @@ var InngestExecutionEngine = class extends DefaultExecutionEngine {
663
677
  const errorCause = e && typeof e === "object" && "cause" in e ? e.cause : void 0;
664
678
  if (errorCause && typeof errorCause === "object" && "status" in errorCause && errorCause.status === "failed") {
665
679
  nestedErrorOrigin = coreObservability.getSpanErrorOrigin?.(errorCause);
666
- const { __mastraSpanErrorOrigin: _transportOrigin, ...publicResult } = errorCause;
680
+ const { __mastraSpanErrorOrigin: _transportOrigin, __mastraSegmentEnded: segmentEnded, ...publicResult } = errorCause;
681
+ this.segmentEnded ||= !!segmentEnded;
667
682
  result = publicResult;
668
683
  runId = "runId" in errorCause && typeof errorCause.runId === "string" ? errorCause.runId : globalThis.crypto.randomUUID();
669
684
  } else {
@@ -2482,12 +2497,28 @@ var InngestWorkflow = class extends Workflow {
2482
2497
  } catch (publishError) {
2483
2498
  this.logger.debug?.("Failed to publish workflow-finish event:", publishError);
2484
2499
  }
2500
+ const agentState = durableAgentInput ?? [inputData, resume?.stepResults?.input].find((input) => input?.iterationCount !== void 0 && input.runId);
2501
+ let segmentEnded = false;
2502
+ if (result.status === "failed" && agentState && !engine.segmentEnded) {
2503
+ const steps = result.steps;
2504
+ segmentEnded = segmentEndedBySuspension(segmentSpanData(requestContext, agentState.runId, agentState), steps);
2505
+ endFailedSegmentSpans({
2506
+ mastra,
2507
+ requestContext,
2508
+ runId: agentState.runId,
2509
+ state: agentState,
2510
+ steps,
2511
+ error: durableAgentWorkflowError(result.error).error,
2512
+ live: getRunRegistryEntry(agentState.runId, mastra)
2513
+ });
2514
+ }
2485
2515
  if (result.status === "failed") throw new NonRetriableError(`Workflow failed`, { cause: {
2486
2516
  ...shouldCompactNestedWorkflowOutput ? {
2487
2517
  ...returnedResult,
2488
2518
  runId
2489
2519
  } : result,
2490
- __mastraSpanErrorOrigin: coreObservability.getSpanErrorOrigin?.(result.error)
2520
+ __mastraSpanErrorOrigin: coreObservability.getSpanErrorOrigin?.(result.error),
2521
+ ...segmentEnded ? { __mastraSegmentEnded: true } : {}
2491
2522
  } });
2492
2523
  return shouldCompactNestedWorkflowOutput ? { status: result.status } : result;
2493
2524
  };
@@ -2830,14 +2861,23 @@ function createAgenticLoopWorkflow(options) {
2830
2861
  stepIndex: state.stepIndex,
2831
2862
  accumulatedSteps: state.accumulatedSteps
2832
2863
  };
2833
- }, { id: "map-to-llm-input" }).then(llmExecutionStep).map(async ({ inputData }) => {
2864
+ }, { id: "map-to-llm-input" }).then(llmExecutionStep).map(async ({ inputData, getInitData }) => {
2834
2865
  const llmOutput = inputData;
2835
- return (llmOutput.toolCalls ?? []).map((toolCall) => ({
2866
+ const toolCalls = llmOutput.toolCalls ?? [];
2867
+ const state = getInitData();
2868
+ const sideBySide = toolCalls.length > 1 && resolveDurableToolCallConcurrency({
2869
+ options: state?.options,
2870
+ toolsMetadata: state?.toolsMetadata,
2871
+ toolCalls
2872
+ }) > 1;
2873
+ return toolCalls.map((toolCall) => ({
2836
2874
  ...toolCall,
2837
2875
  stepSpanData: llmOutput.stepSpanData,
2838
2876
  completionStartTime: llmOutput.completionStartTime,
2839
2877
  timeToFirstTokenMs: llmOutput.timeToFirstTokenMs,
2840
- stepUsage: llmOutput.stepResult?.totalUsage
2878
+ stepUsage: llmOutput.stepResult?.totalUsage,
2879
+ response: llmOutput.response,
2880
+ ...sideBySide ? { sideBySide } : {}
2841
2881
  }));
2842
2882
  }, { id: "extract-tool-calls" }).foreach(toolCallStep, { concurrency: ({ inputData, getInitData }) => {
2843
2883
  const state = getInitData();
@@ -2901,6 +2941,11 @@ function createAgenticLoopWorkflow(options) {
2901
2941
  outputTokens: 0,
2902
2942
  totalTokens: 0
2903
2943
  },
2944
+ generationReportedUsage: {
2945
+ inputTokens: 0,
2946
+ outputTokens: 0,
2947
+ totalTokens: 0
2948
+ },
2904
2949
  lastStepResult: void 0,
2905
2950
  agentSpanData,
2906
2951
  modelSpanData,
@@ -3136,25 +3181,31 @@ function createAgenticLoopWorkflow(options) {
3136
3181
  const stopCause = state.tracingStopCause ?? registry?.tracingStopCause;
3137
3182
  const recordedTermination = state.tracingTermination ?? registry?.tracingTermination;
3138
3183
  if (!stopCause && (finishReason === "stop" || finishReason === "tool-calls")) mastra?.getLogger?.()?.warn?.(`[InngestDurableAgent] Run ${state.runId} has no recorded stop cause; its span outcome is unknown`);
3184
+ const runTripwire = tripwire ?? state.lastStepResult?.tripwire ?? initData.inputTripwire;
3139
3185
  const termination = deadlineTermination ? deadlineTermination : ["tripwire", "error"].includes(finishReason ?? "") && recordedTermination ? recordedTermination : agentLoopTermination({
3140
3186
  stopCause,
3141
3187
  delegationFailure: state.tracingDelegationFailure ?? registry?.tracingDelegationFailure,
3142
3188
  finishReason,
3143
- tripwire: tripwire ?? state.lastStepResult?.tripwire,
3189
+ tripwire: runTripwire,
3144
3190
  maxSteps: state.options?.maxSteps ?? maxSteps
3145
3191
  });
3146
3192
  if (modelSpanData) {
3147
3193
  const modelSpan = liveSegmentSpan(modelSpanData, registry?.resumeModelSpan, registry?.modelSpan) ?? observability?.rebuildSpan(modelSpanData);
3194
+ if (modelSpan?.isInternal) modelSpan.parent ??= agentSpan;
3148
3195
  const toolCalls = state.accumulatedSteps.flatMap((step) => (step.toolCalls ?? []).map((tc) => ({
3149
3196
  toolCallId: tc.toolCallId,
3150
3197
  toolName: tc.toolName,
3151
3198
  args: tc.args
3152
3199
  })));
3153
- const { usageIncomplete, usage } = generationUsage(state.accumulatedUsage, state.accumulatedSteps);
3200
+ const { usageIncomplete, usage } = generationUsage(state.accumulatedUsage, state.accumulatedSteps, state.generationReportedUsage);
3201
+ const servedBy = state.lastResponse?.servedBy;
3202
+ const servedName = servedBy && `llm: '${servedBy.modelId}'`;
3203
+ if (servedName && modelSpan && modelSpan.name !== servedName) modelSpan.update({ name: servedName });
3154
3204
  modelSpan?.createTracker()?.endGeneration({
3155
3205
  ...termination,
3156
3206
  output: {
3157
3207
  text: finalText,
3208
+ object: finishResult.object,
3158
3209
  ...toolCalls.length ? { toolCalls } : {}
3159
3210
  },
3160
3211
  attributes: {
@@ -3162,15 +3213,32 @@ function createAgenticLoopWorkflow(options) {
3162
3213
  ...usageIncomplete ? { usageIncomplete: true } : {},
3163
3214
  ...clocks,
3164
3215
  responseId: state.lastResponse?.id,
3165
- responseModel: state.lastResponse?.modelId
3216
+ responseModel: state.lastResponse?.modelId,
3217
+ ...servedBy ? {
3218
+ model: servedBy.modelId,
3219
+ provider: servedBy.provider
3220
+ } : {}
3166
3221
  },
3167
- usage
3222
+ usage,
3223
+ stepProviderMetadata: state.reportedCosts?.slice(state.generationReportedSteps ?? 0).map((cost) => cost ?? void 0)
3168
3224
  });
3169
3225
  }
3170
- if (agentSpanData) (liveSegmentSpan(agentSpanData, registry?.resumeAgentSpan, registry?.agentSpan) ?? observability?.rebuildSpan(agentSpanData))?.end({
3226
+ if (agentSpanData) agentSpan?.end({
3171
3227
  ...termination,
3172
- output: { text: finalText },
3173
- ...Object.keys(clocks).length ? { attributes: clocks } : {}
3228
+ output: {
3229
+ text: finalText,
3230
+ object: finishResult.object,
3231
+ ...runTripwire ? { tripwire: runTripwire } : {}
3232
+ },
3233
+ attributes: {
3234
+ ...clocks,
3235
+ ...runTripwire ? { tripwireAbort: {
3236
+ reason: runTripwire.reason,
3237
+ processorId: runTripwire.processorId,
3238
+ retry: runTripwire.retry,
3239
+ metadata: runTripwire.metadata
3240
+ } } : {}
3241
+ }
3174
3242
  });
3175
3243
  if (pubsub && deadlineError) await emitErrorEvent(pubsub, state.runId, deadlineError);
3176
3244
  else if (pubsub) await emitFinishEvent(pubsub, state.runId, {
@@ -3230,6 +3298,7 @@ function keepSuspendedRunScopes(snapshot, requestContext, resumeOptions) {
3230
3298
  requestContext[SCOPES_KEY] = saved;
3231
3299
  }
3232
3300
  // src/durable-agent/create-inngest-agent.ts
3301
+ const DURABLE_CONTEXT_SEGMENT_KEY = "__mastra_durableContextSegment";
3233
3302
  var InngestAgentPubSubRouter = class extends PubSub {
3234
3303
  defaultPubsub;
3235
3304
  getAgentPubsub;
@@ -3577,6 +3646,7 @@ function createInngestAgent(options) {
3577
3646
  runId,
3578
3647
  resumed: true
3579
3648
  },
3649
+ tracingPolicy: agent.getTracingPolicy?.(),
3580
3650
  requestContext
3581
3651
  });
3582
3652
  return {
@@ -3796,7 +3866,7 @@ function createInngestAgent(options) {
3796
3866
  /**
3797
3867
  * Trigger the workflow via Inngest event
3798
3868
  */
3799
- async function triggerWorkflow(runId, workflowInput, tracingOptions, actor, deadline) {
3869
+ async function triggerWorkflow(runId, workflowInput, tracingOptions, actor, deadline, contextSegment) {
3800
3870
  const eventName = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;
3801
3871
  await inngest.send({
3802
3872
  name: eventName,
@@ -3804,7 +3874,10 @@ function createInngestAgent(options) {
3804
3874
  inputData: workflowInput,
3805
3875
  runId,
3806
3876
  resourceId: workflowInput.state?.resourceId,
3807
- requestContext: withSegmentDeadline(workflowInput.requestContextEntries ?? {}, deadline),
3877
+ requestContext: withSegmentDeadline({
3878
+ ...workflowInput.requestContextEntries,
3879
+ [DURABLE_CONTEXT_SEGMENT_KEY]: contextSegment
3880
+ }, deadline),
3808
3881
  tracingOptions,
3809
3882
  actor
3810
3883
  })
@@ -3931,6 +4004,8 @@ function createInngestAgent(options) {
3931
4004
  workflowInput.agentName = agentName;
3932
4005
  const { controller: abortController, detach: stopForwardingAbort } = createRunAbortController(streamOptions?.abortSignal, { onExternalAbort: () => void requestRemoteAbort(runId) });
3933
4006
  registryEntry.abortController = abortController;
4007
+ const contextSegment = crypto.randomUUID();
4008
+ registryEntry.requestContextSegment = contextSegment;
3934
4009
  const { clear: clearTotalTimeout, deadline: segmentDeadline } = armTotalTimeout(registryEntry, abortController, runId, callbackOptions.modelSettings?.timeout?.totalMs);
3935
4010
  registryEntry.messageList = preparation.messageList;
3936
4011
  globalRunRegistry.set(runId, registryEntry);
@@ -4016,14 +4091,16 @@ function createInngestAgent(options) {
4016
4091
  const reason = registryEntry.abortSignal?.reason;
4017
4092
  return isMastraTimeoutError(reason) && reason !== abortController.signal.reason;
4018
4093
  };
4019
- if (deadlineFired()) return;
4094
+ const endTimedOutSpans = () => endRunSpansWithError(runId, registryEntry.abortSignal.reason);
4095
+ if (deadlineFired()) return endTimedOutSpans();
4020
4096
  const persistedRunning = await persistRunningSnapshot(runId, workflowInput);
4021
4097
  if (deadlineFired()) {
4098
+ endTimedOutSpans();
4022
4099
  if (persistedRunning) await deleteRunSnapshots(runId);
4023
4100
  return;
4024
4101
  }
4025
4102
  try {
4026
- await triggerWorkflow(runId, workflowInput, tracingOptions, streamOptions?.actor, segmentDeadline);
4103
+ await triggerWorkflow(runId, workflowInput, tracingOptions, streamOptions?.actor, segmentDeadline, contextSegment);
4027
4104
  } catch (error) {
4028
4105
  if (persistedRunning) await deleteRunSnapshots(runId);
4029
4106
  throw error;
@@ -4194,6 +4271,9 @@ function createInngestAgent(options) {
4194
4271
  }
4195
4272
  existingEntry.abortController = abortController;
4196
4273
  existingEntry.requestContext = callbackOptions.requestContext;
4274
+ existingEntry.requestContextRebuilt = false;
4275
+ const contextSegment = crypto.randomUUID();
4276
+ existingEntry.requestContextSegment = contextSegment;
4197
4277
  const resumeSegment = openResumeSegment(runId, suspendedSnapshot, callbackOptions.requestContext);
4198
4278
  existingEntry.resumeAgentSpan = resumeSegment?.agentSpan;
4199
4279
  existingEntry.resumeModelSpan = resumeSegment?.modelSpan;
@@ -4336,7 +4416,10 @@ function createInngestAgent(options) {
4336
4416
  inputData: resumeData,
4337
4417
  runId,
4338
4418
  resourceId: resumeOptions?.resourceId,
4339
- requestContext: withSegmentDeadline(requestContext, segmentDeadline),
4419
+ requestContext: withSegmentDeadline({
4420
+ ...requestContext,
4421
+ [DURABLE_CONTEXT_SEGMENT_KEY]: contextSegment
4422
+ }, segmentDeadline),
4340
4423
  tracingOptions,
4341
4424
  actor: resumeOptions?.actor,
4342
4425
  resume: {
@@ -164,15 +164,27 @@ function agentLoopTermination(...args) {
164
164
  function endRunSpansWithError(...args) {
165
165
  if (_mastra_core_features.coreFeatures.has("execution-outcomes")) _mastra_core_agent_durable.endRunSpansWithError?.(...args);
166
166
  }
167
+ /** End the spans a failed execution left open; an older core leaves them open. */
168
+ function endFailedSegmentSpans(...args) {
169
+ if (carriesSegmentSpans()) _mastra_core_agent_durable.endFailedSegmentSpans?.(...args);
170
+ }
171
+ /** Whether a suspension beside the failed tool call already ended the spans of the segment. */
172
+ function segmentEndedBySuspension(...args) {
173
+ return carriesSegmentSpans() && !!_mastra_core_agent_durable.segmentEndedBySuspension?.(...args);
174
+ }
167
175
  function executionFailureTermination(...args) {
168
176
  return _mastra_core_features.coreFeatures.has("execution-outcomes") ? _mastra_core_observability.executionFailureTermination?.(...args) ?? {} : {};
169
177
  }
170
- /** Keep completed-request usage when a failed request makes the total incomplete. */
171
- function generationUsage(usage, steps) {
178
+ /**
179
+ * Keep completed-request usage when a failed request makes the total incomplete, less what the
180
+ * MODEL_GENERATION spans of suspended segments already recorded; an older core recorded none.
181
+ */
182
+ function generationUsage(usage, steps, reported) {
172
183
  const usageIncomplete = _mastra_core_features.coreFeatures.has("execution-outcomes") && _mastra_core_observability.isUsageIncomplete?.(usage);
184
+ const observed = usageIncomplete ? _mastra_core_observability.calculateObservedUsage?.(steps) ?? usage : usage;
173
185
  return {
174
186
  usageIncomplete,
175
- usage: usageIncomplete ? _mastra_core_observability.calculateObservedUsage?.(steps) ?? usage : usage
187
+ usage: _mastra_core_observability.subtractReportedUsage?.(observed, reported) ?? observed
176
188
  };
177
189
  }
178
190
  /**
@@ -236,6 +248,8 @@ var InngestExecutionEngine = class extends _mastra_core_workflows.DefaultExecuti
236
248
  workflowSpan;
237
249
  inngestStep;
238
250
  inngestAttempts;
251
+ /** A suspension in the failed nested run already ended the spans of the durable agent's segment. */
252
+ segmentEnded = false;
239
253
  constructor(mastra, inngestStep, inngestAttempts = 0, options, parentStream, inngestRunId, workflowSpan) {
240
254
  super({
241
255
  mastra,
@@ -685,7 +699,8 @@ var InngestExecutionEngine = class extends _mastra_core_workflows.DefaultExecuti
685
699
  const errorCause = e && typeof e === "object" && "cause" in e ? e.cause : void 0;
686
700
  if (errorCause && typeof errorCause === "object" && "status" in errorCause && errorCause.status === "failed") {
687
701
  nestedErrorOrigin = _mastra_core_observability.getSpanErrorOrigin?.(errorCause);
688
- const { __mastraSpanErrorOrigin: _transportOrigin, ...publicResult } = errorCause;
702
+ const { __mastraSpanErrorOrigin: _transportOrigin, __mastraSegmentEnded: segmentEnded, ...publicResult } = errorCause;
703
+ this.segmentEnded ||= !!segmentEnded;
689
704
  result = publicResult;
690
705
  runId = "runId" in errorCause && typeof errorCause.runId === "string" ? errorCause.runId : globalThis.crypto.randomUUID();
691
706
  } else {
@@ -2504,12 +2519,28 @@ var InngestWorkflow = class extends _mastra_core_workflows.Workflow {
2504
2519
  } catch (publishError) {
2505
2520
  this.logger.debug?.("Failed to publish workflow-finish event:", publishError);
2506
2521
  }
2522
+ const agentState = durableAgentInput ?? [inputData, resume?.stepResults?.input].find((input) => input?.iterationCount !== void 0 && input.runId);
2523
+ let segmentEnded = false;
2524
+ if (result.status === "failed" && agentState && !engine.segmentEnded) {
2525
+ const steps = result.steps;
2526
+ segmentEnded = segmentEndedBySuspension(segmentSpanData(requestContext, agentState.runId, agentState), steps);
2527
+ endFailedSegmentSpans({
2528
+ mastra,
2529
+ requestContext,
2530
+ runId: agentState.runId,
2531
+ state: agentState,
2532
+ steps,
2533
+ error: durableAgentWorkflowError(result.error).error,
2534
+ live: (0, _mastra_core_agent_durable.getRunRegistryEntry)(agentState.runId, mastra)
2535
+ });
2536
+ }
2507
2537
  if (result.status === "failed") throw new inngest.NonRetriableError(`Workflow failed`, { cause: {
2508
2538
  ...shouldCompactNestedWorkflowOutput ? {
2509
2539
  ...returnedResult,
2510
2540
  runId
2511
2541
  } : result,
2512
- __mastraSpanErrorOrigin: _mastra_core_observability.getSpanErrorOrigin?.(result.error)
2542
+ __mastraSpanErrorOrigin: _mastra_core_observability.getSpanErrorOrigin?.(result.error),
2543
+ ...segmentEnded ? { __mastraSegmentEnded: true } : {}
2513
2544
  } });
2514
2545
  return shouldCompactNestedWorkflowOutput ? { status: result.status } : result;
2515
2546
  };
@@ -2852,14 +2883,23 @@ function createAgenticLoopWorkflow(options) {
2852
2883
  stepIndex: state.stepIndex,
2853
2884
  accumulatedSteps: state.accumulatedSteps
2854
2885
  };
2855
- }, { id: "map-to-llm-input" }).then(llmExecutionStep).map(async ({ inputData }) => {
2886
+ }, { id: "map-to-llm-input" }).then(llmExecutionStep).map(async ({ inputData, getInitData }) => {
2856
2887
  const llmOutput = inputData;
2857
- return (llmOutput.toolCalls ?? []).map((toolCall) => ({
2888
+ const toolCalls = llmOutput.toolCalls ?? [];
2889
+ const state = getInitData();
2890
+ const sideBySide = toolCalls.length > 1 && (0, _mastra_core_agent_durable.resolveDurableToolCallConcurrency)({
2891
+ options: state?.options,
2892
+ toolsMetadata: state?.toolsMetadata,
2893
+ toolCalls
2894
+ }) > 1;
2895
+ return toolCalls.map((toolCall) => ({
2858
2896
  ...toolCall,
2859
2897
  stepSpanData: llmOutput.stepSpanData,
2860
2898
  completionStartTime: llmOutput.completionStartTime,
2861
2899
  timeToFirstTokenMs: llmOutput.timeToFirstTokenMs,
2862
- stepUsage: llmOutput.stepResult?.totalUsage
2900
+ stepUsage: llmOutput.stepResult?.totalUsage,
2901
+ response: llmOutput.response,
2902
+ ...sideBySide ? { sideBySide } : {}
2863
2903
  }));
2864
2904
  }, { id: "extract-tool-calls" }).foreach(toolCallStep, { concurrency: ({ inputData, getInitData }) => {
2865
2905
  const state = getInitData();
@@ -2923,6 +2963,11 @@ function createAgenticLoopWorkflow(options) {
2923
2963
  outputTokens: 0,
2924
2964
  totalTokens: 0
2925
2965
  },
2966
+ generationReportedUsage: {
2967
+ inputTokens: 0,
2968
+ outputTokens: 0,
2969
+ totalTokens: 0
2970
+ },
2926
2971
  lastStepResult: void 0,
2927
2972
  agentSpanData,
2928
2973
  modelSpanData,
@@ -3158,25 +3203,31 @@ function createAgenticLoopWorkflow(options) {
3158
3203
  const stopCause = state.tracingStopCause ?? registry?.tracingStopCause;
3159
3204
  const recordedTermination = state.tracingTermination ?? registry?.tracingTermination;
3160
3205
  if (!stopCause && (finishReason === "stop" || finishReason === "tool-calls")) mastra?.getLogger?.()?.warn?.(`[InngestDurableAgent] Run ${state.runId} has no recorded stop cause; its span outcome is unknown`);
3206
+ const runTripwire = tripwire ?? state.lastStepResult?.tripwire ?? initData.inputTripwire;
3161
3207
  const termination = deadlineTermination ? deadlineTermination : ["tripwire", "error"].includes(finishReason ?? "") && recordedTermination ? recordedTermination : agentLoopTermination({
3162
3208
  stopCause,
3163
3209
  delegationFailure: state.tracingDelegationFailure ?? registry?.tracingDelegationFailure,
3164
3210
  finishReason,
3165
- tripwire: tripwire ?? state.lastStepResult?.tripwire,
3211
+ tripwire: runTripwire,
3166
3212
  maxSteps: state.options?.maxSteps ?? maxSteps
3167
3213
  });
3168
3214
  if (modelSpanData) {
3169
3215
  const modelSpan = liveSegmentSpan(modelSpanData, registry?.resumeModelSpan, registry?.modelSpan) ?? observability?.rebuildSpan(modelSpanData);
3216
+ if (modelSpan?.isInternal) modelSpan.parent ??= agentSpan;
3170
3217
  const toolCalls = state.accumulatedSteps.flatMap((step) => (step.toolCalls ?? []).map((tc) => ({
3171
3218
  toolCallId: tc.toolCallId,
3172
3219
  toolName: tc.toolName,
3173
3220
  args: tc.args
3174
3221
  })));
3175
- const { usageIncomplete, usage } = generationUsage(state.accumulatedUsage, state.accumulatedSteps);
3222
+ const { usageIncomplete, usage } = generationUsage(state.accumulatedUsage, state.accumulatedSteps, state.generationReportedUsage);
3223
+ const servedBy = state.lastResponse?.servedBy;
3224
+ const servedName = servedBy && `llm: '${servedBy.modelId}'`;
3225
+ if (servedName && modelSpan && modelSpan.name !== servedName) modelSpan.update({ name: servedName });
3176
3226
  modelSpan?.createTracker()?.endGeneration({
3177
3227
  ...termination,
3178
3228
  output: {
3179
3229
  text: finalText,
3230
+ object: finishResult.object,
3180
3231
  ...toolCalls.length ? { toolCalls } : {}
3181
3232
  },
3182
3233
  attributes: {
@@ -3184,15 +3235,32 @@ function createAgenticLoopWorkflow(options) {
3184
3235
  ...usageIncomplete ? { usageIncomplete: true } : {},
3185
3236
  ...clocks,
3186
3237
  responseId: state.lastResponse?.id,
3187
- responseModel: state.lastResponse?.modelId
3238
+ responseModel: state.lastResponse?.modelId,
3239
+ ...servedBy ? {
3240
+ model: servedBy.modelId,
3241
+ provider: servedBy.provider
3242
+ } : {}
3188
3243
  },
3189
- usage
3244
+ usage,
3245
+ stepProviderMetadata: state.reportedCosts?.slice(state.generationReportedSteps ?? 0).map((cost) => cost ?? void 0)
3190
3246
  });
3191
3247
  }
3192
- if (agentSpanData) (liveSegmentSpan(agentSpanData, registry?.resumeAgentSpan, registry?.agentSpan) ?? observability?.rebuildSpan(agentSpanData))?.end({
3248
+ if (agentSpanData) agentSpan?.end({
3193
3249
  ...termination,
3194
- output: { text: finalText },
3195
- ...Object.keys(clocks).length ? { attributes: clocks } : {}
3250
+ output: {
3251
+ text: finalText,
3252
+ object: finishResult.object,
3253
+ ...runTripwire ? { tripwire: runTripwire } : {}
3254
+ },
3255
+ attributes: {
3256
+ ...clocks,
3257
+ ...runTripwire ? { tripwireAbort: {
3258
+ reason: runTripwire.reason,
3259
+ processorId: runTripwire.processorId,
3260
+ retry: runTripwire.retry,
3261
+ metadata: runTripwire.metadata
3262
+ } } : {}
3263
+ }
3196
3264
  });
3197
3265
  if (pubsub && deadlineError) await (0, _mastra_core_agent_durable.emitErrorEvent)(pubsub, state.runId, deadlineError);
3198
3266
  else if (pubsub) await (0, _mastra_core_agent_durable.emitFinishEvent)(pubsub, state.runId, {
@@ -3252,6 +3320,7 @@ function keepSuspendedRunScopes(snapshot, requestContext, resumeOptions) {
3252
3320
  requestContext[SCOPES_KEY] = saved;
3253
3321
  }
3254
3322
  // src/durable-agent/create-inngest-agent.ts
3323
+ const DURABLE_CONTEXT_SEGMENT_KEY = "__mastra_durableContextSegment";
3255
3324
  var InngestAgentPubSubRouter = class extends _mastra_core_events.PubSub {
3256
3325
  defaultPubsub;
3257
3326
  getAgentPubsub;
@@ -3599,6 +3668,7 @@ function createInngestAgent(options) {
3599
3668
  runId,
3600
3669
  resumed: true
3601
3670
  },
3671
+ tracingPolicy: agent.getTracingPolicy?.(),
3602
3672
  requestContext
3603
3673
  });
3604
3674
  return {
@@ -3818,7 +3888,7 @@ function createInngestAgent(options) {
3818
3888
  /**
3819
3889
  * Trigger the workflow via Inngest event
3820
3890
  */
3821
- async function triggerWorkflow(runId, workflowInput, tracingOptions, actor, deadline) {
3891
+ async function triggerWorkflow(runId, workflowInput, tracingOptions, actor, deadline, contextSegment) {
3822
3892
  const eventName = `workflow.${InngestDurableStepIds.AGENTIC_LOOP}`;
3823
3893
  await inngest$1.send({
3824
3894
  name: eventName,
@@ -3826,7 +3896,10 @@ function createInngestAgent(options) {
3826
3896
  inputData: workflowInput,
3827
3897
  runId,
3828
3898
  resourceId: workflowInput.state?.resourceId,
3829
- requestContext: withSegmentDeadline(workflowInput.requestContextEntries ?? {}, deadline),
3899
+ requestContext: withSegmentDeadline({
3900
+ ...workflowInput.requestContextEntries,
3901
+ [DURABLE_CONTEXT_SEGMENT_KEY]: contextSegment
3902
+ }, deadline),
3830
3903
  tracingOptions,
3831
3904
  actor
3832
3905
  })
@@ -3953,6 +4026,8 @@ function createInngestAgent(options) {
3953
4026
  workflowInput.agentName = agentName;
3954
4027
  const { controller: abortController, detach: stopForwardingAbort } = (0, _mastra_core_agent_durable.createRunAbortController)(streamOptions?.abortSignal, { onExternalAbort: () => void requestRemoteAbort(runId) });
3955
4028
  registryEntry.abortController = abortController;
4029
+ const contextSegment = crypto.randomUUID();
4030
+ registryEntry.requestContextSegment = contextSegment;
3956
4031
  const { clear: clearTotalTimeout, deadline: segmentDeadline } = armTotalTimeout(registryEntry, abortController, runId, callbackOptions.modelSettings?.timeout?.totalMs);
3957
4032
  registryEntry.messageList = preparation.messageList;
3958
4033
  _mastra_core_agent_durable.globalRunRegistry.set(runId, registryEntry);
@@ -4038,14 +4113,16 @@ function createInngestAgent(options) {
4038
4113
  const reason = registryEntry.abortSignal?.reason;
4039
4114
  return (0, _mastra_core_loop.isMastraTimeoutError)(reason) && reason !== abortController.signal.reason;
4040
4115
  };
4041
- if (deadlineFired()) return;
4116
+ const endTimedOutSpans = () => endRunSpansWithError(runId, registryEntry.abortSignal.reason);
4117
+ if (deadlineFired()) return endTimedOutSpans();
4042
4118
  const persistedRunning = await persistRunningSnapshot(runId, workflowInput);
4043
4119
  if (deadlineFired()) {
4120
+ endTimedOutSpans();
4044
4121
  if (persistedRunning) await deleteRunSnapshots(runId);
4045
4122
  return;
4046
4123
  }
4047
4124
  try {
4048
- await triggerWorkflow(runId, workflowInput, tracingOptions, streamOptions?.actor, segmentDeadline);
4125
+ await triggerWorkflow(runId, workflowInput, tracingOptions, streamOptions?.actor, segmentDeadline, contextSegment);
4049
4126
  } catch (error) {
4050
4127
  if (persistedRunning) await deleteRunSnapshots(runId);
4051
4128
  throw error;
@@ -4216,6 +4293,9 @@ function createInngestAgent(options) {
4216
4293
  }
4217
4294
  existingEntry.abortController = abortController;
4218
4295
  existingEntry.requestContext = callbackOptions.requestContext;
4296
+ existingEntry.requestContextRebuilt = false;
4297
+ const contextSegment = crypto.randomUUID();
4298
+ existingEntry.requestContextSegment = contextSegment;
4219
4299
  const resumeSegment = openResumeSegment(runId, suspendedSnapshot, callbackOptions.requestContext);
4220
4300
  existingEntry.resumeAgentSpan = resumeSegment?.agentSpan;
4221
4301
  existingEntry.resumeModelSpan = resumeSegment?.modelSpan;
@@ -4358,7 +4438,10 @@ function createInngestAgent(options) {
4358
4438
  inputData: resumeData,
4359
4439
  runId,
4360
4440
  resourceId: resumeOptions?.resourceId,
4361
- requestContext: withSegmentDeadline(requestContext, segmentDeadline),
4441
+ requestContext: withSegmentDeadline({
4442
+ ...requestContext,
4443
+ [DURABLE_CONTEXT_SEGMENT_KEY]: contextSegment
4444
+ }, segmentDeadline),
4362
4445
  tracingOptions,
4363
4446
  actor: resumeOptions?.actor,
4364
4447
  resume: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/inngest",
3
- "version": "1.11.5",
3
+ "version": "1.11.6-alpha.1",
4
4
  "description": "Mastra Inngest integration",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -66,12 +66,12 @@
66
66
  "@internal/lint": "0.0.152",
67
67
  "@internal/types-builder": "0.0.127",
68
68
  "@internal/workflow-test-utils": "0.0.31",
69
- "@mastra/core": "1.86.0",
70
- "@mastra/deployer": "1.86.0",
71
- "@mastra/libsql": "1.32.0",
69
+ "@mastra/core": "1.87.0-alpha.1",
70
+ "@mastra/deployer": "1.87.0-alpha.1",
71
+ "@mastra/libsql": "1.33.0-alpha.0",
72
72
  "@mastra/memory": "1.41.3",
73
- "@mastra/observability": "1.24.3",
74
- "@mastra/pg": "1.38.0"
73
+ "@mastra/observability": "1.24.4-alpha.0",
74
+ "@mastra/pg": "1.39.0-alpha.0"
75
75
  },
76
76
  "peerDependencies": {
77
77
  "@mastra/core": ">=1.83.0-0 <2.0.0-0",