@mastra/inngest 1.11.5-alpha.0 → 1.11.5-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/connect.cjs CHANGED
@@ -1,3 +1,3 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_src = require("./src-Crbi-9ud.cjs");
2
+ const require_src = require("./src-F0jsXKoi.cjs");
3
3
  exports.connect = require_src.connect;
package/dist/connect.js CHANGED
@@ -1 +1 @@
1
- export { i as connect } from "./src-D5Qvqymw.js";
1
+ export { i as connect } from "./src-CNBlIex4.js";
@@ -240,6 +240,10 @@ export interface InngestAgentStreamResult<OUTPUT = undefined> {
240
240
  threadId?: string;
241
241
  /** Resource ID if using memory */
242
242
  resourceId?: string;
243
+ /** Trace ID of the run, when the run is traced */
244
+ traceId?: string;
245
+ /** ID of the agent run span, when the run is traced */
246
+ spanId?: string;
243
247
  /** Cleanup function */
244
248
  cleanup: () => void;
245
249
  /**
@@ -77,6 +77,7 @@ export declare function createInngestDurableAgenticWorkflow(options: InngestDura
77
77
  };
78
78
  state: any;
79
79
  tracingTermination?: import("@mastra/core/observability").SpanTermination | undefined;
80
+ stopCause?: "delegation" | "feedback_complete" | "iteration_hook" | "max_steps" | "model_finished" | "stop_condition" | undefined;
80
81
  }, {
81
82
  messageListState: any;
82
83
  messageId: string;
@@ -88,5 +89,6 @@ export declare function createInngestDurableAgenticWorkflow(options: InngestDura
88
89
  };
89
90
  state: any;
90
91
  tracingTermination?: import("@mastra/core/observability").SpanTermination | undefined;
92
+ stopCause?: "delegation" | "feedback_complete" | "iteration_hook" | "max_steps" | "model_finished" | "stop_condition" | undefined;
91
93
  }, unknown, any>;
92
94
  //# sourceMappingURL=create-inngest-agentic-workflow.d.ts.map
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_src = require("./src-Crbi-9ud.cjs");
2
+ const require_src = require("./src-F0jsXKoi.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-D5Qvqymw.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-CNBlIex4.js";
@@ -1006,10 +1006,12 @@ function fitAgentEvent(event) {
1006
1006
  }
1007
1007
  const data = event.data ?? {};
1008
1008
  const output = data.output ?? {};
1009
+ const stopCause = typeof data.stopCause === "string" ? data.stopCause : void 0;
1009
1010
  const reduced = {
1010
1011
  ...event,
1011
1012
  data: {
1012
1013
  stepResult: data.stepResult,
1014
+ ...stopCause ? { stopCause } : {},
1013
1015
  output: {
1014
1016
  text: output.text,
1015
1017
  usage: output.usage,
@@ -1023,6 +1025,7 @@ function fitAgentEvent(event) {
1023
1025
  ...event,
1024
1026
  data: {
1025
1027
  stepResult: typeof reason === "string" ? { reason } : void 0,
1028
+ ...stopCause ? { stopCause } : {},
1026
1029
  output: { steps: [] }
1027
1030
  }
1028
1031
  };
@@ -1033,6 +1036,75 @@ function fitAgentEvent(event) {
1033
1036
  }
1034
1037
  return fallback;
1035
1038
  }
1039
+ /** Read a complete JSON string literal starting at `start` (pointing at `"`), returning `[value, nextIndex]` or `null` if truncated. */
1040
+ function readJsonString(raw, start) {
1041
+ if (raw[start] !== "\"") return null;
1042
+ let i = start + 1;
1043
+ while (i < raw.length) {
1044
+ const ch = raw[i];
1045
+ if (ch === "\\") {
1046
+ i += 2;
1047
+ continue;
1048
+ }
1049
+ if (ch === "\"") try {
1050
+ return [JSON.parse(raw.slice(start, i + 1)), i + 1];
1051
+ } catch {
1052
+ return null;
1053
+ }
1054
+ i++;
1055
+ }
1056
+ return null;
1057
+ }
1058
+ /**
1059
+ * Extract a direct string property of the top-level `data` object from a possibly
1060
+ * truncated JSON event string, ignoring keys nested inside `output`, tool results, etc.
1061
+ */
1062
+ function extractDirectDataStringField(raw, field) {
1063
+ let i = 0;
1064
+ const skipWs = () => {
1065
+ while (i < raw.length && /\s/.test(raw[i])) i++;
1066
+ };
1067
+ skipWs();
1068
+ if (raw[i] !== "{") return void 0;
1069
+ i++;
1070
+ let depth = 1;
1071
+ let inDataObject = false;
1072
+ let dataDepth = -1;
1073
+ while (i < raw.length && depth > 0) {
1074
+ skipWs();
1075
+ if (i >= raw.length) break;
1076
+ const ch = raw[i];
1077
+ if (ch === "\"") {
1078
+ const parsed = readJsonString(raw, i);
1079
+ if (!parsed) return void 0;
1080
+ const [str, next] = parsed;
1081
+ i = next;
1082
+ skipWs();
1083
+ if (raw[i] === ":") {
1084
+ i++;
1085
+ skipWs();
1086
+ if (depth === 1 && str === "data" && raw[i] === "{") {
1087
+ inDataObject = true;
1088
+ dataDepth = 2;
1089
+ depth = 2;
1090
+ i++;
1091
+ continue;
1092
+ }
1093
+ if (inDataObject && depth === dataDepth && str === field) {
1094
+ const val = readJsonString(raw, i);
1095
+ return val ? val[0] : void 0;
1096
+ }
1097
+ }
1098
+ continue;
1099
+ }
1100
+ if (ch === "{" || ch === "[") depth++;
1101
+ else if (ch === "}" || ch === "]") {
1102
+ if (inDataObject && depth === dataDepth) inDataObject = false;
1103
+ depth--;
1104
+ }
1105
+ i++;
1106
+ }
1107
+ }
1036
1108
  /**
1037
1109
  * Recover an agent event Realtime truncated into a raw string. Terminal events are
1038
1110
  * salvaged into a minimal envelope so attached streams close; anything else becomes
@@ -1049,12 +1121,14 @@ function salvageTruncatedAgentEvent(raw, runId) {
1049
1121
  return oversizedPlaceholder(runId, type ?? "unknown", chunkType, void 0);
1050
1122
  }
1051
1123
  const reason = raw.match(/"stepResult"\s*:\s*\{[^{}]*"reason"\s*:\s*"([^"]+)"/)?.[1];
1124
+ const stopCause = type === "finish" ? extractDirectDataStringField(raw, "stopCause") : void 0;
1052
1125
  return {
1053
1126
  type,
1054
1127
  runId,
1055
1128
  data: type === "finish" ? {
1056
1129
  output: { steps: [] },
1057
- stepResult: reason ? { reason } : void 0
1130
+ stepResult: reason ? { reason } : void 0,
1131
+ ...stopCause ? { stopCause } : {}
1058
1132
  } : type === "error" ? { error: {
1059
1133
  name: "Error",
1060
1134
  message: OVERSIZED_ERROR_MESSAGE
@@ -2883,8 +2957,8 @@ function createAgenticLoopWorkflow(options) {
2883
2957
  const shouldContinue = state.lastStepResult?.isContinued === true;
2884
2958
  const effectiveMaxSteps = state.options?.maxSteps ?? maxSteps;
2885
2959
  const underMaxSteps = state.iterationCount < effectiveMaxSteps;
2886
- if (!shouldContinue || !underMaxSteps) {
2887
- recordStopCause(shouldContinue ? "max_steps" : "model_finished");
2960
+ if (!shouldContinue) {
2961
+ recordStopCause("model_finished");
2888
2962
  await emitStepFinish(false);
2889
2963
  return false;
2890
2964
  }
@@ -2892,7 +2966,8 @@ function createAgenticLoopWorkflow(options) {
2892
2966
  const stopWhen = getRunRegistryEntry(state.runId, mastra)?.stopWhen;
2893
2967
  if (!stopWhen || state.accumulatedSteps.length === 0) return false;
2894
2968
  const steps = durableStopConditionSteps(state.accumulatedSteps);
2895
- return (await Promise.all((Array.isArray(stopWhen) ? stopWhen : [stopWhen]).map(async (condition) => {
2969
+ const conditionList = Array.isArray(stopWhen) ? stopWhen : [stopWhen];
2970
+ if (underMaxSteps) return (await Promise.all(conditionList.map(async (condition) => {
2896
2971
  try {
2897
2972
  return await condition({ steps });
2898
2973
  } catch (error) {
@@ -2909,10 +2984,53 @@ function createAgenticLoopWorkflow(options) {
2909
2984
  }, originalError);
2910
2985
  }
2911
2986
  }))).some(Boolean);
2987
+ if (conditionList.length === 0) return false;
2988
+ const POST_BUDGET_STOP_WHEN_TIMEOUT_MS = 250;
2989
+ const safeWarn = (message, details) => {
2990
+ try {
2991
+ mastra?.getLogger?.()?.warn(message, details);
2992
+ } catch {}
2993
+ };
2994
+ let loggedRejection = false;
2995
+ const logPostBudgetFailure = (reason) => {
2996
+ if (loggedRejection) return;
2997
+ loggedRejection = true;
2998
+ safeWarn("A stopWhen condition failed after the step budget ran out; ignoring its result", {
2999
+ runId: state.runId,
3000
+ error: reason
3001
+ });
3002
+ };
3003
+ return await new Promise((resolve) => {
3004
+ let settled = false;
3005
+ let remaining = conditionList.length;
3006
+ const finish = (matched) => {
3007
+ if (settled) return;
3008
+ settled = true;
3009
+ clearTimeout(timeout);
3010
+ resolve(matched);
3011
+ };
3012
+ const timeout = setTimeout(() => {
3013
+ safeWarn("A stopWhen condition did not settle after the step budget ran out; attributing stop to maxSteps", { runId: state.runId });
3014
+ finish(false);
3015
+ }, POST_BUDGET_STOP_WHEN_TIMEOUT_MS);
3016
+ for (const condition of conditionList) (async () => Boolean(await condition({ steps })))().then((matched) => {
3017
+ remaining -= 1;
3018
+ if (matched) finish(true);
3019
+ else if (remaining === 0) finish(false);
3020
+ }, (reason) => {
3021
+ logPostBudgetFailure(reason);
3022
+ remaining -= 1;
3023
+ if (remaining === 0) finish(false);
3024
+ });
3025
+ });
2912
3026
  });
2913
- if (stopped) recordStopCause("stop_condition");
2914
- await emitStepFinish(!stopped);
2915
- return !stopped;
3027
+ if (stopped || !underMaxSteps) {
3028
+ recordStopCause(stopped ? "stop_condition" : "max_steps");
3029
+ await emitStepFinish(false);
3030
+ return false;
3031
+ }
3032
+ await emitStepFinish(true);
3033
+ return true;
2916
3034
  }).map(async (params) => {
2917
3035
  const { inputData, mastra, requestContext, tracingContext } = params;
2918
3036
  const state = inputData;
@@ -3058,7 +3176,8 @@ function createAgenticLoopWorkflow(options) {
3058
3176
  else if (pubsub) await emitFinishEvent(pubsub, state.runId, {
3059
3177
  output: finalOutput.output,
3060
3178
  stepResult: finalOutput.stepResult,
3061
- ...textRewritten && { textRewritten }
3179
+ ...textRewritten && { textRewritten },
3180
+ ...stopCause && { stopCause }
3062
3181
  });
3063
3182
  return finalOutput;
3064
3183
  }, { id: "map-final-output" }).map(async (params) => {
@@ -3312,6 +3431,22 @@ function createInngestAgent(options) {
3312
3431
  }
3313
3432
  }
3314
3433
  /**
3434
+ * The agent run span saved with a run that has no live span in this process (another process
3435
+ * started it, or it already finished here), so an observer still names the run's trace.
3436
+ * `undefined` when the run is untraced or its snapshot is gone. Never throws.
3437
+ */
3438
+ async function loadRunAgentSpan(runId) {
3439
+ try {
3440
+ const agentSpanData = ((await (await mastra?.getStorage()?.getStore("workflows"))?.loadWorkflowSnapshot({
3441
+ runId,
3442
+ workflowName: InngestDurableStepIds.AGENTIC_LOOP
3443
+ }))?.context?.input)?.agentSpanData;
3444
+ return agentSpanData ? mastra?.observability?.getSelectedInstance({})?.rebuildSpan(agentSpanData) : void 0;
3445
+ } catch {
3446
+ return;
3447
+ }
3448
+ }
3449
+ /**
3315
3450
  * A run parked on a suspension has no prepared run in this process, so a
3316
3451
  * fenced resume is the first point where it is known it can never continue.
3317
3452
  * Delete its still-suspended snapshot rows and publish the abort terminal so
@@ -3508,13 +3643,15 @@ function createInngestAgent(options) {
3508
3643
  })) return false;
3509
3644
  const threadId = workflowInput.state?.threadId;
3510
3645
  const resourceId = workflowInput.state?.resourceId;
3646
+ const { input: _input, attributes: _attributes, ...agentSpanData } = workflowInput.agentSpanData ?? {};
3511
3647
  const context = {};
3512
3648
  context.input = {
3513
3649
  agentId: workflowInput.agentId,
3514
3650
  state: {
3515
3651
  threadId,
3516
3652
  resourceId
3517
- }
3653
+ },
3654
+ ...workflowInput.agentSpanData ? { agentSpanData } : {}
3518
3655
  };
3519
3656
  await workflowsStore.persistWorkflowSnapshot({
3520
3657
  workflowName,
@@ -3823,6 +3960,7 @@ function createInngestAgent(options) {
3823
3960
  outputProcessors: registryEntry.outputProcessors,
3824
3961
  processorStates: registryEntry.processorStates,
3825
3962
  requestContext: registryEntry.requestContext,
3963
+ tracingContext: registryEntry.agentSpan ? { currentSpan: registryEntry.agentSpan } : void 0,
3826
3964
  onChunk: (chunk) => {
3827
3965
  if (chunk.type === "tool-call-approval" || chunk.type === "tool-call-suspended") stopForwardingAbort?.();
3828
3966
  return callbackOptions.onChunk?.(chunk);
@@ -3911,6 +4049,8 @@ function createInngestAgent(options) {
3911
4049
  runId,
3912
4050
  threadId,
3913
4051
  resourceId,
4052
+ traceId: output.traceId,
4053
+ spanId: output.spanId,
3914
4054
  cleanup,
3915
4055
  abort,
3916
4056
  get fullStream() {
@@ -4106,6 +4246,7 @@ function createInngestAgent(options) {
4106
4246
  deleteRunRegistryEntry(runId, mastra);
4107
4247
  };
4108
4248
  let resumedChunkSeen = false;
4249
+ const resumeSegmentSpan = existingEntry.resumeAgentSpan ?? existingEntry.agentSpan;
4109
4250
  const { output, cleanup: streamCleanup, detach: detachStream, ready } = createDurableAgentStream({
4110
4251
  pubsub: getPubsub(),
4111
4252
  runId,
@@ -4126,6 +4267,7 @@ function createInngestAgent(options) {
4126
4267
  outputProcessors: existingEntry.outputProcessors,
4127
4268
  processorStates: existingEntry.processorStates,
4128
4269
  requestContext: callbackOptions.requestContext,
4270
+ tracingContext: resumeSegmentSpan ? { currentSpan: resumeSegmentSpan } : void 0,
4129
4271
  onChunk: (chunk) => {
4130
4272
  resumedChunkSeen = true;
4131
4273
  if (chunk.type === "tool-call-approval" || chunk.type === "tool-call-suspended") {
@@ -4257,6 +4399,8 @@ function createInngestAgent(options) {
4257
4399
  runId,
4258
4400
  threadId: resumeOptions?.threadId,
4259
4401
  resourceId: resumeOptions?.resourceId,
4402
+ traceId: output.traceId,
4403
+ spanId: output.spanId,
4260
4404
  cleanup,
4261
4405
  abort,
4262
4406
  [STREAM_CLEANUP]: streamCleanup
@@ -4296,6 +4440,8 @@ function createInngestAgent(options) {
4296
4440
  };
4297
4441
  },
4298
4442
  async observe(runId, observeOptions) {
4443
+ const observedEntry = getRunRegistryEntry(runId, mastra);
4444
+ const observedAgentSpan = observedEntry?.resumeAgentSpan ?? observedEntry?.agentSpan ?? await loadRunAgentSpan(runId);
4299
4445
  const stream = createDurableAgentStream({
4300
4446
  pubsub: getPubsub(),
4301
4447
  runId,
@@ -4309,7 +4455,8 @@ function createInngestAgent(options) {
4309
4455
  replayResponseMessagesBeforeOffset: true,
4310
4456
  idleTimeoutMs: observeOptions?.idleTimeoutMs,
4311
4457
  isAlive: observeOptions?.isAlive,
4312
- structuredOutput: getRunRegistryEntry(runId, mastra)?.structuredOutput,
4458
+ structuredOutput: observedEntry?.structuredOutput,
4459
+ tracingContext: observedAgentSpan ? { currentSpan: observedAgentSpan } : void 0,
4313
4460
  onChunk: observeOptions?.onChunk,
4314
4461
  onStepFinish: observeOptions?.onStepFinish,
4315
4462
  onFinish: observeOptions?.onFinish,
@@ -4362,6 +4509,8 @@ function createInngestAgent(options) {
4362
4509
  return output.fullStream;
4363
4510
  },
4364
4511
  runId,
4512
+ traceId: output.traceId,
4513
+ spanId: output.spanId,
4365
4514
  cleanup: streamCleanup,
4366
4515
  detach,
4367
4516
  abort
@@ -5335,5 +5484,3 @@ function init(inngest) {
5335
5484
  };
5336
5485
  }
5337
5486
  export { createServe as a, isInngestAgent as c, InngestRun as d, InngestPubSub as f, connect as i, createInngestDurableAgenticWorkflow as l, InngestExecutionEngine as m, init as n, serve$1 as o, OVERSIZED_EVENT_CHUNK_TYPE as p, _compatibilityCheck as r, createInngestAgent as s, createStep as t, InngestWorkflow as u };
5338
-
5339
- //# sourceMappingURL=src-D5Qvqymw.js.map
@@ -1028,10 +1028,12 @@ function fitAgentEvent(event) {
1028
1028
  }
1029
1029
  const data = event.data ?? {};
1030
1030
  const output = data.output ?? {};
1031
+ const stopCause = typeof data.stopCause === "string" ? data.stopCause : void 0;
1031
1032
  const reduced = {
1032
1033
  ...event,
1033
1034
  data: {
1034
1035
  stepResult: data.stepResult,
1036
+ ...stopCause ? { stopCause } : {},
1035
1037
  output: {
1036
1038
  text: output.text,
1037
1039
  usage: output.usage,
@@ -1045,6 +1047,7 @@ function fitAgentEvent(event) {
1045
1047
  ...event,
1046
1048
  data: {
1047
1049
  stepResult: typeof reason === "string" ? { reason } : void 0,
1050
+ ...stopCause ? { stopCause } : {},
1048
1051
  output: { steps: [] }
1049
1052
  }
1050
1053
  };
@@ -1055,6 +1058,75 @@ function fitAgentEvent(event) {
1055
1058
  }
1056
1059
  return fallback;
1057
1060
  }
1061
+ /** Read a complete JSON string literal starting at `start` (pointing at `"`), returning `[value, nextIndex]` or `null` if truncated. */
1062
+ function readJsonString(raw, start) {
1063
+ if (raw[start] !== "\"") return null;
1064
+ let i = start + 1;
1065
+ while (i < raw.length) {
1066
+ const ch = raw[i];
1067
+ if (ch === "\\") {
1068
+ i += 2;
1069
+ continue;
1070
+ }
1071
+ if (ch === "\"") try {
1072
+ return [JSON.parse(raw.slice(start, i + 1)), i + 1];
1073
+ } catch {
1074
+ return null;
1075
+ }
1076
+ i++;
1077
+ }
1078
+ return null;
1079
+ }
1080
+ /**
1081
+ * Extract a direct string property of the top-level `data` object from a possibly
1082
+ * truncated JSON event string, ignoring keys nested inside `output`, tool results, etc.
1083
+ */
1084
+ function extractDirectDataStringField(raw, field) {
1085
+ let i = 0;
1086
+ const skipWs = () => {
1087
+ while (i < raw.length && /\s/.test(raw[i])) i++;
1088
+ };
1089
+ skipWs();
1090
+ if (raw[i] !== "{") return void 0;
1091
+ i++;
1092
+ let depth = 1;
1093
+ let inDataObject = false;
1094
+ let dataDepth = -1;
1095
+ while (i < raw.length && depth > 0) {
1096
+ skipWs();
1097
+ if (i >= raw.length) break;
1098
+ const ch = raw[i];
1099
+ if (ch === "\"") {
1100
+ const parsed = readJsonString(raw, i);
1101
+ if (!parsed) return void 0;
1102
+ const [str, next] = parsed;
1103
+ i = next;
1104
+ skipWs();
1105
+ if (raw[i] === ":") {
1106
+ i++;
1107
+ skipWs();
1108
+ if (depth === 1 && str === "data" && raw[i] === "{") {
1109
+ inDataObject = true;
1110
+ dataDepth = 2;
1111
+ depth = 2;
1112
+ i++;
1113
+ continue;
1114
+ }
1115
+ if (inDataObject && depth === dataDepth && str === field) {
1116
+ const val = readJsonString(raw, i);
1117
+ return val ? val[0] : void 0;
1118
+ }
1119
+ }
1120
+ continue;
1121
+ }
1122
+ if (ch === "{" || ch === "[") depth++;
1123
+ else if (ch === "}" || ch === "]") {
1124
+ if (inDataObject && depth === dataDepth) inDataObject = false;
1125
+ depth--;
1126
+ }
1127
+ i++;
1128
+ }
1129
+ }
1058
1130
  /**
1059
1131
  * Recover an agent event Realtime truncated into a raw string. Terminal events are
1060
1132
  * salvaged into a minimal envelope so attached streams close; anything else becomes
@@ -1071,12 +1143,14 @@ function salvageTruncatedAgentEvent(raw, runId) {
1071
1143
  return oversizedPlaceholder(runId, type ?? "unknown", chunkType, void 0);
1072
1144
  }
1073
1145
  const reason = raw.match(/"stepResult"\s*:\s*\{[^{}]*"reason"\s*:\s*"([^"]+)"/)?.[1];
1146
+ const stopCause = type === "finish" ? extractDirectDataStringField(raw, "stopCause") : void 0;
1074
1147
  return {
1075
1148
  type,
1076
1149
  runId,
1077
1150
  data: type === "finish" ? {
1078
1151
  output: { steps: [] },
1079
- stepResult: reason ? { reason } : void 0
1152
+ stepResult: reason ? { reason } : void 0,
1153
+ ...stopCause ? { stopCause } : {}
1080
1154
  } : type === "error" ? { error: {
1081
1155
  name: "Error",
1082
1156
  message: OVERSIZED_ERROR_MESSAGE
@@ -2905,8 +2979,8 @@ function createAgenticLoopWorkflow(options) {
2905
2979
  const shouldContinue = state.lastStepResult?.isContinued === true;
2906
2980
  const effectiveMaxSteps = state.options?.maxSteps ?? maxSteps;
2907
2981
  const underMaxSteps = state.iterationCount < effectiveMaxSteps;
2908
- if (!shouldContinue || !underMaxSteps) {
2909
- recordStopCause(shouldContinue ? "max_steps" : "model_finished");
2982
+ if (!shouldContinue) {
2983
+ recordStopCause("model_finished");
2910
2984
  await emitStepFinish(false);
2911
2985
  return false;
2912
2986
  }
@@ -2914,7 +2988,8 @@ function createAgenticLoopWorkflow(options) {
2914
2988
  const stopWhen = (0, _mastra_core_agent_durable.getRunRegistryEntry)(state.runId, mastra)?.stopWhen;
2915
2989
  if (!stopWhen || state.accumulatedSteps.length === 0) return false;
2916
2990
  const steps = durableStopConditionSteps(state.accumulatedSteps);
2917
- return (await Promise.all((Array.isArray(stopWhen) ? stopWhen : [stopWhen]).map(async (condition) => {
2991
+ const conditionList = Array.isArray(stopWhen) ? stopWhen : [stopWhen];
2992
+ if (underMaxSteps) return (await Promise.all(conditionList.map(async (condition) => {
2918
2993
  try {
2919
2994
  return await condition({ steps });
2920
2995
  } catch (error) {
@@ -2931,10 +3006,53 @@ function createAgenticLoopWorkflow(options) {
2931
3006
  }, originalError);
2932
3007
  }
2933
3008
  }))).some(Boolean);
3009
+ if (conditionList.length === 0) return false;
3010
+ const POST_BUDGET_STOP_WHEN_TIMEOUT_MS = 250;
3011
+ const safeWarn = (message, details) => {
3012
+ try {
3013
+ mastra?.getLogger?.()?.warn(message, details);
3014
+ } catch {}
3015
+ };
3016
+ let loggedRejection = false;
3017
+ const logPostBudgetFailure = (reason) => {
3018
+ if (loggedRejection) return;
3019
+ loggedRejection = true;
3020
+ safeWarn("A stopWhen condition failed after the step budget ran out; ignoring its result", {
3021
+ runId: state.runId,
3022
+ error: reason
3023
+ });
3024
+ };
3025
+ return await new Promise((resolve) => {
3026
+ let settled = false;
3027
+ let remaining = conditionList.length;
3028
+ const finish = (matched) => {
3029
+ if (settled) return;
3030
+ settled = true;
3031
+ clearTimeout(timeout);
3032
+ resolve(matched);
3033
+ };
3034
+ const timeout = setTimeout(() => {
3035
+ safeWarn("A stopWhen condition did not settle after the step budget ran out; attributing stop to maxSteps", { runId: state.runId });
3036
+ finish(false);
3037
+ }, POST_BUDGET_STOP_WHEN_TIMEOUT_MS);
3038
+ for (const condition of conditionList) (async () => Boolean(await condition({ steps })))().then((matched) => {
3039
+ remaining -= 1;
3040
+ if (matched) finish(true);
3041
+ else if (remaining === 0) finish(false);
3042
+ }, (reason) => {
3043
+ logPostBudgetFailure(reason);
3044
+ remaining -= 1;
3045
+ if (remaining === 0) finish(false);
3046
+ });
3047
+ });
2934
3048
  });
2935
- if (stopped) recordStopCause("stop_condition");
2936
- await emitStepFinish(!stopped);
2937
- return !stopped;
3049
+ if (stopped || !underMaxSteps) {
3050
+ recordStopCause(stopped ? "stop_condition" : "max_steps");
3051
+ await emitStepFinish(false);
3052
+ return false;
3053
+ }
3054
+ await emitStepFinish(true);
3055
+ return true;
2938
3056
  }).map(async (params) => {
2939
3057
  const { inputData, mastra, requestContext, tracingContext } = params;
2940
3058
  const state = inputData;
@@ -3080,7 +3198,8 @@ function createAgenticLoopWorkflow(options) {
3080
3198
  else if (pubsub) await (0, _mastra_core_agent_durable.emitFinishEvent)(pubsub, state.runId, {
3081
3199
  output: finalOutput.output,
3082
3200
  stepResult: finalOutput.stepResult,
3083
- ...textRewritten && { textRewritten }
3201
+ ...textRewritten && { textRewritten },
3202
+ ...stopCause && { stopCause }
3084
3203
  });
3085
3204
  return finalOutput;
3086
3205
  }, { id: "map-final-output" }).map(async (params) => {
@@ -3334,6 +3453,22 @@ function createInngestAgent(options) {
3334
3453
  }
3335
3454
  }
3336
3455
  /**
3456
+ * The agent run span saved with a run that has no live span in this process (another process
3457
+ * started it, or it already finished here), so an observer still names the run's trace.
3458
+ * `undefined` when the run is untraced or its snapshot is gone. Never throws.
3459
+ */
3460
+ async function loadRunAgentSpan(runId) {
3461
+ try {
3462
+ const agentSpanData = ((await (await mastra?.getStorage()?.getStore("workflows"))?.loadWorkflowSnapshot({
3463
+ runId,
3464
+ workflowName: InngestDurableStepIds.AGENTIC_LOOP
3465
+ }))?.context?.input)?.agentSpanData;
3466
+ return agentSpanData ? mastra?.observability?.getSelectedInstance({})?.rebuildSpan(agentSpanData) : void 0;
3467
+ } catch {
3468
+ return;
3469
+ }
3470
+ }
3471
+ /**
3337
3472
  * A run parked on a suspension has no prepared run in this process, so a
3338
3473
  * fenced resume is the first point where it is known it can never continue.
3339
3474
  * Delete its still-suspended snapshot rows and publish the abort terminal so
@@ -3530,13 +3665,15 @@ function createInngestAgent(options) {
3530
3665
  })) return false;
3531
3666
  const threadId = workflowInput.state?.threadId;
3532
3667
  const resourceId = workflowInput.state?.resourceId;
3668
+ const { input: _input, attributes: _attributes, ...agentSpanData } = workflowInput.agentSpanData ?? {};
3533
3669
  const context = {};
3534
3670
  context.input = {
3535
3671
  agentId: workflowInput.agentId,
3536
3672
  state: {
3537
3673
  threadId,
3538
3674
  resourceId
3539
- }
3675
+ },
3676
+ ...workflowInput.agentSpanData ? { agentSpanData } : {}
3540
3677
  };
3541
3678
  await workflowsStore.persistWorkflowSnapshot({
3542
3679
  workflowName,
@@ -3845,6 +3982,7 @@ function createInngestAgent(options) {
3845
3982
  outputProcessors: registryEntry.outputProcessors,
3846
3983
  processorStates: registryEntry.processorStates,
3847
3984
  requestContext: registryEntry.requestContext,
3985
+ tracingContext: registryEntry.agentSpan ? { currentSpan: registryEntry.agentSpan } : void 0,
3848
3986
  onChunk: (chunk) => {
3849
3987
  if (chunk.type === "tool-call-approval" || chunk.type === "tool-call-suspended") stopForwardingAbort?.();
3850
3988
  return callbackOptions.onChunk?.(chunk);
@@ -3933,6 +4071,8 @@ function createInngestAgent(options) {
3933
4071
  runId,
3934
4072
  threadId,
3935
4073
  resourceId,
4074
+ traceId: output.traceId,
4075
+ spanId: output.spanId,
3936
4076
  cleanup,
3937
4077
  abort,
3938
4078
  get fullStream() {
@@ -4128,6 +4268,7 @@ function createInngestAgent(options) {
4128
4268
  (0, _mastra_core_agent_durable.deleteRunRegistryEntry)(runId, mastra);
4129
4269
  };
4130
4270
  let resumedChunkSeen = false;
4271
+ const resumeSegmentSpan = existingEntry.resumeAgentSpan ?? existingEntry.agentSpan;
4131
4272
  const { output, cleanup: streamCleanup, detach: detachStream, ready } = (0, _mastra_core_agent_durable.createDurableAgentStream)({
4132
4273
  pubsub: getPubsub(),
4133
4274
  runId,
@@ -4148,6 +4289,7 @@ function createInngestAgent(options) {
4148
4289
  outputProcessors: existingEntry.outputProcessors,
4149
4290
  processorStates: existingEntry.processorStates,
4150
4291
  requestContext: callbackOptions.requestContext,
4292
+ tracingContext: resumeSegmentSpan ? { currentSpan: resumeSegmentSpan } : void 0,
4151
4293
  onChunk: (chunk) => {
4152
4294
  resumedChunkSeen = true;
4153
4295
  if (chunk.type === "tool-call-approval" || chunk.type === "tool-call-suspended") {
@@ -4279,6 +4421,8 @@ function createInngestAgent(options) {
4279
4421
  runId,
4280
4422
  threadId: resumeOptions?.threadId,
4281
4423
  resourceId: resumeOptions?.resourceId,
4424
+ traceId: output.traceId,
4425
+ spanId: output.spanId,
4282
4426
  cleanup,
4283
4427
  abort,
4284
4428
  [STREAM_CLEANUP]: streamCleanup
@@ -4318,6 +4462,8 @@ function createInngestAgent(options) {
4318
4462
  };
4319
4463
  },
4320
4464
  async observe(runId, observeOptions) {
4465
+ const observedEntry = (0, _mastra_core_agent_durable.getRunRegistryEntry)(runId, mastra);
4466
+ const observedAgentSpan = observedEntry?.resumeAgentSpan ?? observedEntry?.agentSpan ?? await loadRunAgentSpan(runId);
4321
4467
  const stream = (0, _mastra_core_agent_durable.createDurableAgentStream)({
4322
4468
  pubsub: getPubsub(),
4323
4469
  runId,
@@ -4331,7 +4477,8 @@ function createInngestAgent(options) {
4331
4477
  replayResponseMessagesBeforeOffset: true,
4332
4478
  idleTimeoutMs: observeOptions?.idleTimeoutMs,
4333
4479
  isAlive: observeOptions?.isAlive,
4334
- structuredOutput: (0, _mastra_core_agent_durable.getRunRegistryEntry)(runId, mastra)?.structuredOutput,
4480
+ structuredOutput: observedEntry?.structuredOutput,
4481
+ tracingContext: observedAgentSpan ? { currentSpan: observedAgentSpan } : void 0,
4335
4482
  onChunk: observeOptions?.onChunk,
4336
4483
  onStepFinish: observeOptions?.onStepFinish,
4337
4484
  onFinish: observeOptions?.onFinish,
@@ -4384,6 +4531,8 @@ function createInngestAgent(options) {
4384
4531
  return output.fullStream;
4385
4532
  },
4386
4533
  runId,
4534
+ traceId: output.traceId,
4535
+ spanId: output.spanId,
4387
4536
  cleanup: streamCleanup,
4388
4537
  detach,
4389
4538
  abort
@@ -5440,5 +5589,3 @@ Object.defineProperty(exports, "serve", {
5440
5589
  return serve;
5441
5590
  }
5442
5591
  });
5443
-
5444
- //# sourceMappingURL=src-Crbi-9ud.cjs.map