@mastra/upstash 0.10.2-alpha.2 → 0.10.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/index.js CHANGED
@@ -11509,11 +11509,12 @@ var require_chunk_TICDQWVJ = __commonJS({
11509
11509
  }
11510
11510
  });
11511
11511
 
11512
- // ../../packages/core/dist/chunk-SWW4EBUZ.cjs
11513
- var require_chunk_SWW4EBUZ = __commonJS({
11514
- "../../packages/core/dist/chunk-SWW4EBUZ.cjs"(exports2) {
11512
+ // ../../packages/core/dist/chunk-RFAN7FAT.cjs
11513
+ var require_chunk_RFAN7FAT = __commonJS({
11514
+ "../../packages/core/dist/chunk-RFAN7FAT.cjs"(exports2) {
11515
11515
  var RegisteredLogger = {
11516
11516
  AGENT: "AGENT",
11517
+ AUTH: "AUTH",
11517
11518
  NETWORK: "NETWORK",
11518
11519
  WORKFLOW: "WORKFLOW",
11519
11520
  LLM: "LLM",
@@ -11603,19 +11604,19 @@ var require_chunk_SWW4EBUZ = __commonJS({
11603
11604
  }
11604
11605
  });
11605
11606
 
11606
- // ../../packages/core/dist/chunk-YEULQPUY.cjs
11607
- var require_chunk_YEULQPUY = __commonJS({
11608
- "../../packages/core/dist/chunk-YEULQPUY.cjs"(exports2) {
11609
- var chunkSWW4EBUZ_cjs = require_chunk_SWW4EBUZ();
11607
+ // ../../packages/core/dist/chunk-VHZPWE5L.cjs
11608
+ var require_chunk_VHZPWE5L = __commonJS({
11609
+ "../../packages/core/dist/chunk-VHZPWE5L.cjs"(exports2) {
11610
+ var chunkRFAN7FAT_cjs = require_chunk_RFAN7FAT();
11610
11611
  var MastraBase = class {
11611
- component = chunkSWW4EBUZ_cjs.RegisteredLogger.LLM;
11612
+ component = chunkRFAN7FAT_cjs.RegisteredLogger.LLM;
11612
11613
  logger;
11613
11614
  name;
11614
11615
  telemetry;
11615
11616
  constructor({ component, name }) {
11616
- this.component = component || chunkSWW4EBUZ_cjs.RegisteredLogger.LLM;
11617
+ this.component = component || chunkRFAN7FAT_cjs.RegisteredLogger.LLM;
11617
11618
  this.name = name;
11618
- this.logger = new chunkSWW4EBUZ_cjs.ConsoleLogger({ name: `${this.component} - ${this.name}` });
11619
+ this.logger = new chunkRFAN7FAT_cjs.ConsoleLogger({ name: `${this.component} - ${this.name}` });
11619
11620
  }
11620
11621
  /**
11621
11622
  * Set the logger for the agent
@@ -11623,7 +11624,7 @@ var require_chunk_YEULQPUY = __commonJS({
11623
11624
  */
11624
11625
  __setLogger(logger) {
11625
11626
  this.logger = logger;
11626
- if (this.component !== chunkSWW4EBUZ_cjs.RegisteredLogger.LLM) {
11627
+ if (this.component !== chunkRFAN7FAT_cjs.RegisteredLogger.LLM) {
11627
11628
  this.logger.debug(`Logger updated [component=${this.component}] [name=${this.name}]`);
11628
11629
  }
11629
11630
  }
@@ -11633,7 +11634,7 @@ var require_chunk_YEULQPUY = __commonJS({
11633
11634
  */
11634
11635
  __setTelemetry(telemetry) {
11635
11636
  this.telemetry = telemetry;
11636
- if (this.component !== chunkSWW4EBUZ_cjs.RegisteredLogger.LLM) {
11637
+ if (this.component !== chunkRFAN7FAT_cjs.RegisteredLogger.LLM) {
11637
11638
  this.logger.debug(`Telemetry updated [component=${this.component}] [name=${this.telemetry.name}]`);
11638
11639
  }
11639
11640
  }
@@ -11736,11 +11737,11 @@ var require_chunk_RWTSGWWL = __commonJS({
11736
11737
  }
11737
11738
  });
11738
11739
 
11739
- // ../../packages/core/dist/chunk-E4PVJAEL.cjs
11740
- var require_chunk_E4PVJAEL = __commonJS({
11741
- "../../packages/core/dist/chunk-E4PVJAEL.cjs"(exports2) {
11740
+ // ../../packages/core/dist/chunk-3JGO7S6X.cjs
11741
+ var require_chunk_3JGO7S6X = __commonJS({
11742
+ "../../packages/core/dist/chunk-3JGO7S6X.cjs"(exports2) {
11742
11743
  var chunkTICDQWVJ_cjs = require_chunk_TICDQWVJ();
11743
- var chunkYEULQPUY_cjs = require_chunk_YEULQPUY();
11744
+ var chunkVHZPWE5L_cjs = require_chunk_VHZPWE5L();
11744
11745
  var chunkRWTSGWWL_cjs = require_chunk_RWTSGWWL();
11745
11746
  var _MastraVoice_decorators;
11746
11747
  var _init;
@@ -11749,7 +11750,7 @@ var require_chunk_E4PVJAEL = __commonJS({
11749
11750
  prefix: "voice",
11750
11751
  excludeMethods: ["__setTools", "__setLogger", "__setTelemetry", "#log"]
11751
11752
  })];
11752
- exports2.MastraVoice = class MastraVoice extends (_a = chunkYEULQPUY_cjs.MastraBase) {
11753
+ exports2.MastraVoice = class MastraVoice extends (_a = chunkVHZPWE5L_cjs.MastraBase) {
11753
11754
  listeningModel;
11754
11755
  speechModel;
11755
11756
  speaker;
@@ -12027,90 +12028,34 @@ var require_chunk_E4PVJAEL = __commonJS({
12027
12028
  }
12028
12029
  });
12029
12030
 
12030
- // ../../packages/core/dist/chunk-ST5RMVLG.cjs
12031
- var require_chunk_ST5RMVLG = __commonJS({
12032
- "../../packages/core/dist/chunk-ST5RMVLG.cjs"(exports2) {
12033
- function mitt(all) {
12034
- all = all || /* @__PURE__ */ new Map();
12035
- return {
12036
- /**
12037
- * A Map of event names to registered handler functions.
12038
- */
12039
- all,
12040
- /**
12041
- * Register an event handler for the given type.
12042
- * @param {string|symbol} type Type of event to listen for, or `'*'` for all events
12043
- * @param {Function} handler Function to call in response to given event
12044
- * @memberOf mitt
12045
- */
12046
- on(type, handler) {
12047
- const handlers = all.get(type);
12048
- if (handlers) {
12049
- handlers.push(handler);
12050
- } else {
12051
- all.set(type, [handler]);
12052
- }
12053
- },
12054
- /**
12055
- * Remove an event handler for the given type.
12056
- * If `handler` is omitted, all handlers of the given type are removed.
12057
- * @param {string|symbol} type Type of event to unregister `handler` from (`'*'` to remove a wildcard handler)
12058
- * @param {Function} [handler] Handler function to remove
12059
- * @memberOf mitt
12060
- */
12061
- off(type, handler) {
12062
- const handlers = all.get(type);
12063
- if (handlers) {
12064
- if (handler) {
12065
- handlers.splice(handlers.indexOf(handler) >>> 0, 1);
12066
- } else {
12067
- all.set(type, []);
12068
- }
12069
- }
12070
- },
12071
- /**
12072
- * Invoke all handlers for the given type.
12073
- * If present, `'*'` handlers are invoked after type-matched handlers.
12074
- *
12075
- * Note: Manually firing '*' handlers is not supported.
12076
- *
12077
- * @param {string|symbol} type The event type to invoke
12078
- * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler
12079
- * @memberOf mitt
12080
- */
12081
- emit(type, evt) {
12082
- let handlers = all.get(type);
12083
- if (handlers) {
12084
- handlers.slice().map((handler) => {
12085
- handler(evt);
12086
- });
12087
- }
12088
- handlers = all.get("*");
12089
- if (handlers) {
12090
- handlers.slice().map((handler) => {
12091
- handler(type, evt);
12092
- });
12093
- }
12094
- }
12095
- };
12096
- }
12097
- var AvailableHooks = /* @__PURE__ */ ((AvailableHooks2) => {
12098
- AvailableHooks2["ON_EVALUATION"] = "onEvaluation";
12099
- AvailableHooks2["ON_GENERATION"] = "onGeneration";
12100
- return AvailableHooks2;
12101
- })(AvailableHooks || {});
12102
- var hooks = mitt();
12103
- function registerHook(hook, action) {
12104
- hooks.on(hook, action);
12031
+ // ../../packages/core/dist/chunk-4Z3OU5RY.cjs
12032
+ var require_chunk_4Z3OU5RY = __commonJS({
12033
+ "../../packages/core/dist/chunk-4Z3OU5RY.cjs"(exports2) {
12034
+ var Tool = class {
12035
+ id;
12036
+ description;
12037
+ inputSchema;
12038
+ outputSchema;
12039
+ execute;
12040
+ mastra;
12041
+ constructor(opts) {
12042
+ this.id = opts.id;
12043
+ this.description = opts.description;
12044
+ this.inputSchema = opts.inputSchema;
12045
+ this.outputSchema = opts.outputSchema;
12046
+ this.execute = opts.execute;
12047
+ this.mastra = opts.mastra;
12048
+ }
12049
+ };
12050
+ function createTool(opts) {
12051
+ return new Tool(opts);
12105
12052
  }
12106
- function executeHook(hook, data) {
12107
- setImmediate(() => {
12108
- hooks.emit(hook, data);
12109
- });
12053
+ function isVercelTool(tool) {
12054
+ return !!(tool && !(tool instanceof Tool) && "parameters" in tool);
12110
12055
  }
12111
- exports2.AvailableHooks = AvailableHooks;
12112
- exports2.executeHook = executeHook;
12113
- exports2.registerHook = registerHook;
12056
+ exports2.Tool = Tool;
12057
+ exports2.createTool = createTool;
12058
+ exports2.isVercelTool = isVercelTool;
12114
12059
  }
12115
12060
  });
12116
12061
 
@@ -21928,9 +21873,9 @@ var require_dist3 = __commonJS({
21928
21873
  }
21929
21874
  });
21930
21875
 
21931
- // ../../node_modules/.pnpm/ai@4.3.15_react@19.1.0_zod@3.24.4/node_modules/ai/dist/index.js
21876
+ // ../../node_modules/.pnpm/ai@4.3.16_react@19.1.0_zod@3.24.4/node_modules/ai/dist/index.js
21932
21877
  var require_dist4 = __commonJS({
21933
- "../../node_modules/.pnpm/ai@4.3.15_react@19.1.0_zod@3.24.4/node_modules/ai/dist/index.js"(exports2, module2) {
21878
+ "../../node_modules/.pnpm/ai@4.3.16_react@19.1.0_zod@3.24.4/node_modules/ai/dist/index.js"(exports2, module2) {
21934
21879
  var __defProp = Object.defineProperty;
21935
21880
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
21936
21881
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -24507,6 +24452,24 @@ var require_dist4 = __commonJS({
24507
24452
  }
24508
24453
  }
24509
24454
  }
24455
+ function stringifyForTelemetry(prompt) {
24456
+ const processedPrompt = prompt.map((message) => {
24457
+ return {
24458
+ ...message,
24459
+ content: typeof message.content === "string" ? message.content : message.content.map(processPart)
24460
+ };
24461
+ });
24462
+ return JSON.stringify(processedPrompt);
24463
+ }
24464
+ function processPart(part) {
24465
+ if (part.type === "image") {
24466
+ return {
24467
+ ...part,
24468
+ image: part.image instanceof Uint8Array ? convertDataContentToBase64String(part.image) : part.image
24469
+ };
24470
+ }
24471
+ return part;
24472
+ }
24510
24473
  var originalGenerateId = (0, import_provider_utils7.createIdGenerator)({ prefix: "aiobj", size: 24 });
24511
24474
  async function generateObject({
24512
24475
  model,
@@ -24733,7 +24696,7 @@ var require_dist4 = __commonJS({
24733
24696
  input: () => inputFormat
24734
24697
  },
24735
24698
  "ai.prompt.messages": {
24736
- input: () => JSON.stringify(promptMessages)
24699
+ input: () => stringifyForTelemetry(promptMessages)
24737
24700
  },
24738
24701
  "ai.settings.mode": mode,
24739
24702
  // standardized gen-ai llm span attributes:
@@ -25320,7 +25283,7 @@ var require_dist4 = __commonJS({
25320
25283
  input: () => callOptions.inputFormat
25321
25284
  },
25322
25285
  "ai.prompt.messages": {
25323
- input: () => JSON.stringify(callOptions.prompt)
25286
+ input: () => stringifyForTelemetry(callOptions.prompt)
25324
25287
  },
25325
25288
  "ai.settings.mode": mode,
25326
25289
  // standardized gen-ai llm span attributes:
@@ -26078,7 +26041,7 @@ var require_dist4 = __commonJS({
26078
26041
  // prompt:
26079
26042
  "ai.prompt.format": { input: () => promptFormat },
26080
26043
  "ai.prompt.messages": {
26081
- input: () => JSON.stringify(promptMessages)
26044
+ input: () => stringifyForTelemetry(promptMessages)
26082
26045
  },
26083
26046
  "ai.prompt.tools": {
26084
26047
  // convert the language model level tools:
@@ -27399,7 +27362,7 @@ var require_dist4 = __commonJS({
27399
27362
  input: () => promptFormat
27400
27363
  },
27401
27364
  "ai.prompt.messages": {
27402
- input: () => JSON.stringify(promptMessages)
27365
+ input: () => stringifyForTelemetry(promptMessages)
27403
27366
  },
27404
27367
  "ai.prompt.tools": {
27405
27368
  // convert the language model level tools:
@@ -30057,10 +30020,11 @@ var require_dist5 = __commonJS({
30057
30020
  }
30058
30021
  });
30059
30022
 
30060
- // ../../packages/core/dist/chunk-DXLVS7ML.cjs
30061
- var require_chunk_DXLVS7ML = __commonJS({
30062
- "../../packages/core/dist/chunk-DXLVS7ML.cjs"(exports2) {
30063
- var chunkYEULQPUY_cjs = require_chunk_YEULQPUY();
30023
+ // ../../packages/core/dist/chunk-WWLMZIHW.cjs
30024
+ var require_chunk_WWLMZIHW = __commonJS({
30025
+ "../../packages/core/dist/chunk-WWLMZIHW.cjs"(exports2) {
30026
+ var chunk4Z3OU5RY_cjs = require_chunk_4Z3OU5RY();
30027
+ var chunkVHZPWE5L_cjs = require_chunk_VHZPWE5L();
30064
30028
  var chunkLABUWBKX_cjs = require_chunk_LABUWBKX();
30065
30029
  var crypto2 = __require("crypto");
30066
30030
  var jsonSchemaToZod = require_cjs();
@@ -30072,25 +30036,6 @@ var require_chunk_DXLVS7ML = __commonJS({
30072
30036
  return e && e.__esModule ? e : { default: e };
30073
30037
  }
30074
30038
  var jsonSchemaToZod__default = /* @__PURE__ */ _interopDefault(jsonSchemaToZod);
30075
- var Tool = class {
30076
- id;
30077
- description;
30078
- inputSchema;
30079
- outputSchema;
30080
- execute;
30081
- mastra;
30082
- constructor(opts) {
30083
- this.id = opts.id;
30084
- this.description = opts.description;
30085
- this.inputSchema = opts.inputSchema;
30086
- this.outputSchema = opts.outputSchema;
30087
- this.execute = opts.execute;
30088
- this.mastra = opts.mastra;
30089
- }
30090
- };
30091
- function createTool(opts) {
30092
- return new Tool(opts);
30093
- }
30094
30039
  var ALL_STRING_CHECKS = ["regex", "emoji", "email", "url", "uuid", "cuid", "min", "max"];
30095
30040
  var ALL_NUMBER_CHECKS = [
30096
30041
  "min",
@@ -30111,7 +30056,7 @@ var require_chunk_DXLVS7ML = __commonJS({
30111
30056
  "ZodAny",
30112
30057
  "ZodDefault"
30113
30058
  ];
30114
- var ToolCompatibility = class extends chunkYEULQPUY_cjs.MastraBase {
30059
+ var ToolCompatibility = class extends chunkVHZPWE5L_cjs.MastraBase {
30115
30060
  model;
30116
30061
  constructor(model) {
30117
30062
  super({ name: "SchemaCompatibility" });
@@ -30352,7 +30297,7 @@ var require_chunk_DXLVS7ML = __commonJS({
30352
30297
  }
30353
30298
  }
30354
30299
  process(tool) {
30355
- if (isVercelTool(tool)) {
30300
+ if (chunk4Z3OU5RY_cjs.isVercelTool(tool)) {
30356
30301
  return {
30357
30302
  description: tool.description,
30358
30303
  // TODO: should we also process vercel tool params?
@@ -30675,7 +30620,7 @@ ${e.stack}` : "\nUnknown error object"));
30675
30620
  }
30676
30621
  }
30677
30622
  }
30678
- var CoreToolBuilder = class extends chunkYEULQPUY_cjs.MastraBase {
30623
+ var CoreToolBuilder = class extends chunkVHZPWE5L_cjs.MastraBase {
30679
30624
  originalTool;
30680
30625
  options;
30681
30626
  logType;
@@ -30687,7 +30632,7 @@ ${e.stack}` : "\nUnknown error object"));
30687
30632
  }
30688
30633
  // Helper to get parameters based on tool type
30689
30634
  getParameters = () => {
30690
- if (isVercelTool(this.originalTool)) {
30635
+ if (chunk4Z3OU5RY_cjs.isVercelTool(this.originalTool)) {
30691
30636
  return convertVercelToolParameters(this.originalTool);
30692
30637
  }
30693
30638
  return convertInputSchema(this.originalTool);
@@ -30732,7 +30677,7 @@ ${e.stack}` : "\nUnknown error object"));
30732
30677
  type: logType
30733
30678
  });
30734
30679
  const execFunction = async (args, execOptions) => {
30735
- if (isVercelTool(tool)) {
30680
+ if (chunk4Z3OU5RY_cjs.isVercelTool(tool)) {
30736
30681
  return tool?.execute?.(args, execOptions) ?? void 0;
30737
30682
  }
30738
30683
  return tool?.execute?.(
@@ -30774,7 +30719,7 @@ ${e.stack}` : "\nUnknown error object"));
30774
30719
  ) : void 0
30775
30720
  };
30776
30721
  const parametersObject = {};
30777
- if (isVercelTool(this.originalTool)) {
30722
+ if (chunk4Z3OU5RY_cjs.isVercelTool(this.originalTool)) {
30778
30723
  parametersObject.parameters = this.getParameters();
30779
30724
  } else {
30780
30725
  parametersObject.inputSchema = this.getParameters();
@@ -30894,9 +30839,6 @@ ${e.stack}` : "\nUnknown error object"));
30894
30839
  function resolveSerializedZodOutput(schema) {
30895
30840
  return Function("z", `"use strict";return (${schema});`)(zod.z);
30896
30841
  }
30897
- function isVercelTool(tool) {
30898
- return !!(tool && !(tool instanceof Tool) && "parameters" in tool);
30899
- }
30900
30842
  function isZodType(value) {
30901
30843
  return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
30902
30844
  }
@@ -30916,7 +30858,7 @@ ${e.stack}` : "\nUnknown error object"));
30916
30858
  const toolsWithProperties = Object.keys(tools).reduce((acc, key) => {
30917
30859
  const tool = tools?.[key];
30918
30860
  if (tool) {
30919
- if (isVercelTool(tool)) {
30861
+ if (chunk4Z3OU5RY_cjs.isVercelTool(tool)) {
30920
30862
  acc[key] = setVercelToolProperties(tool);
30921
30863
  } else {
30922
30864
  acc[key] = tool;
@@ -31045,16 +30987,13 @@ ${e.stack}` : "\nUnknown error object"));
31045
30987
  }
31046
30988
  return key;
31047
30989
  }
31048
- exports2.Tool = Tool;
31049
30990
  exports2.checkEvalStorageFields = checkEvalStorageFields;
31050
30991
  exports2.createMastraProxy = createMastraProxy;
31051
- exports2.createTool = createTool;
31052
30992
  exports2.deepMerge = deepMerge;
31053
30993
  exports2.delay = delay;
31054
30994
  exports2.ensureToolProperties = ensureToolProperties;
31055
30995
  exports2.isCoreMessage = isCoreMessage;
31056
30996
  exports2.isUiMessage = isUiMessage;
31057
- exports2.isVercelTool = isVercelTool;
31058
30997
  exports2.isZodType = isZodType;
31059
30998
  exports2.makeCoreTool = makeCoreTool;
31060
30999
  exports2.maskStreamTags = maskStreamTags;
@@ -31064,655 +31003,191 @@ ${e.stack}` : "\nUnknown error object"));
31064
31003
  }
31065
31004
  });
31066
31005
 
31067
- // ../../packages/core/dist/chunk-I5OLBJ26.cjs
31068
- var require_chunk_I5OLBJ26 = __commonJS({
31069
- "../../packages/core/dist/chunk-I5OLBJ26.cjs"(exports2) {
31070
- var chunkDXLVS7ML_cjs = require_chunk_DXLVS7ML();
31071
- var chunkYEULQPUY_cjs = require_chunk_YEULQPUY();
31072
- var chunkSWW4EBUZ_cjs = require_chunk_SWW4EBUZ();
31006
+ // ../../packages/core/dist/chunk-KUJQVCEL.cjs
31007
+ var require_chunk_KUJQVCEL = __commonJS({
31008
+ "../../packages/core/dist/chunk-KUJQVCEL.cjs"(exports2) {
31009
+ var chunkWWLMZIHW_cjs = require_chunk_WWLMZIHW();
31010
+ var crypto2 = __require("crypto");
31073
31011
  var ai = require_dist4();
31012
+ var providerUtils = require_dist2();
31074
31013
  var zod = require_lib();
31075
- var MastraLLMBase = class extends chunkYEULQPUY_cjs.MastraBase {
31076
- // @ts-ignore
31077
- #mastra;
31078
- #model;
31079
- constructor({ name, model }) {
31080
- super({
31081
- component: chunkSWW4EBUZ_cjs.RegisteredLogger.LLM,
31082
- name
31083
- });
31084
- this.#model = model;
31085
- }
31086
- getProvider() {
31087
- return this.#model.provider;
31014
+ zod.z.union([
31015
+ zod.z.string(),
31016
+ zod.z.instanceof(Uint8Array),
31017
+ zod.z.instanceof(ArrayBuffer),
31018
+ zod.z.custom(
31019
+ // Buffer might not be available in some environments such as CloudFlare:
31020
+ (value) => globalThis.Buffer?.isBuffer(value) ?? false,
31021
+ { message: "Must be a Buffer" }
31022
+ )
31023
+ ]);
31024
+ function convertDataContentToBase64String(content) {
31025
+ if (typeof content === "string") {
31026
+ return content;
31088
31027
  }
31089
- getModelId() {
31090
- return this.#model.modelId;
31028
+ if (content instanceof ArrayBuffer) {
31029
+ return providerUtils.convertUint8ArrayToBase64(new Uint8Array(content));
31091
31030
  }
31092
- getModel() {
31093
- return this.#model;
31031
+ return providerUtils.convertUint8ArrayToBase64(content);
31032
+ }
31033
+ function convertDataContentToUint8Array(content) {
31034
+ if (content instanceof Uint8Array) {
31035
+ return content;
31094
31036
  }
31095
- convertToMessages(messages) {
31096
- if (Array.isArray(messages)) {
31097
- return messages.map((m) => {
31098
- if (typeof m === "string") {
31099
- return {
31100
- role: "user",
31101
- content: m
31102
- };
31103
- }
31104
- return m;
31037
+ if (typeof content === "string") {
31038
+ try {
31039
+ return providerUtils.convertBase64ToUint8Array(content);
31040
+ } catch (error) {
31041
+ throw new Error("Invalid data content. Content string is not a base64-encoded media.", {
31042
+ cause: error
31105
31043
  });
31106
31044
  }
31107
- return [
31108
- {
31109
- role: "user",
31110
- content: messages
31111
- }
31112
- ];
31113
- }
31114
- __registerPrimitives(p) {
31115
- if (p.telemetry) {
31116
- this.__setTelemetry(p.telemetry);
31117
- }
31118
- if (p.logger) {
31119
- this.__setLogger(p.logger);
31120
- }
31121
- }
31122
- __registerMastra(p) {
31123
- this.#mastra = p;
31124
- }
31125
- async __text(input) {
31126
- this.logger.debug(`[LLMs:${this.name}] Generating text.`, { input });
31127
- throw new Error("Method not implemented.");
31128
- }
31129
- async __textObject(input) {
31130
- this.logger.debug(`[LLMs:${this.name}] Generating object.`, { input });
31131
- throw new Error("Method not implemented.");
31132
- }
31133
- async generate(messages, options) {
31134
- this.logger.debug(`[LLMs:${this.name}] Generating text.`, { messages, options });
31135
- throw new Error("Method not implemented.");
31136
- }
31137
- async __stream(input) {
31138
- this.logger.debug(`[LLMs:${this.name}] Streaming text.`, { input });
31139
- throw new Error("Method not implemented.");
31140
- }
31141
- async __streamObject(input) {
31142
- this.logger.debug(`[LLMs:${this.name}] Streaming object.`, { input });
31143
- throw new Error("Method not implemented.");
31144
31045
  }
31145
- async stream(messages, options) {
31146
- this.logger.debug(`[LLMs:${this.name}] Streaming text.`, { messages, options });
31147
- throw new Error("Method not implemented.");
31046
+ if (content instanceof ArrayBuffer) {
31047
+ return new Uint8Array(content);
31148
31048
  }
31149
- };
31150
- var MastraLLM = class extends MastraLLMBase {
31151
- #model;
31152
- #mastra;
31153
- constructor({ model, mastra }) {
31154
- super({ name: "aisdk", model });
31155
- this.#model = model;
31156
- if (mastra) {
31157
- this.#mastra = mastra;
31158
- if (mastra.getLogger()) {
31159
- this.__setLogger(this.#mastra.getLogger());
31160
- }
31161
- }
31049
+ throw new Error(content);
31050
+ }
31051
+ function convertUint8ArrayToText(uint8Array) {
31052
+ try {
31053
+ return new TextDecoder().decode(uint8Array);
31054
+ } catch {
31055
+ throw new Error("Error decoding Uint8Array to text");
31162
31056
  }
31163
- __registerPrimitives(p) {
31164
- if (p.telemetry) {
31165
- this.__setTelemetry(p.telemetry);
31057
+ }
31058
+ function attachmentsToParts(attachments) {
31059
+ const parts = [];
31060
+ for (const attachment of attachments) {
31061
+ let url;
31062
+ try {
31063
+ url = new URL(attachment.url);
31064
+ } catch {
31065
+ throw new Error(`Invalid URL: ${attachment.url}`);
31166
31066
  }
31167
- if (p.logger) {
31168
- this.__setLogger(p.logger);
31067
+ switch (url.protocol) {
31068
+ case "http:":
31069
+ case "https:": {
31070
+ if (attachment.contentType?.startsWith("image/")) {
31071
+ parts.push({ type: "image", image: url.toString(), mimeType: attachment.contentType });
31072
+ } else {
31073
+ if (!attachment.contentType) {
31074
+ throw new Error("If the attachment is not an image, it must specify a content type");
31075
+ }
31076
+ parts.push({
31077
+ type: "file",
31078
+ data: url.toString(),
31079
+ mimeType: attachment.contentType
31080
+ });
31081
+ }
31082
+ break;
31083
+ }
31084
+ case "data:": {
31085
+ let header;
31086
+ let base64Content;
31087
+ let mimeType;
31088
+ try {
31089
+ [header, base64Content] = attachment.url.split(",");
31090
+ mimeType = header?.split?.(";")?.[0]?.split(":")[1];
31091
+ } catch {
31092
+ throw new Error(`Error processing data URL: ${attachment.url}`);
31093
+ }
31094
+ if (mimeType == null || base64Content == null) {
31095
+ throw new Error(`Invalid data URL format: ${attachment.url}`);
31096
+ }
31097
+ if (attachment.contentType?.startsWith("image/")) {
31098
+ parts.push({
31099
+ type: "image",
31100
+ image: attachment.url,
31101
+ mimeType: attachment.contentType
31102
+ });
31103
+ } else if (attachment.contentType?.startsWith("text/")) {
31104
+ parts.push({
31105
+ type: "text",
31106
+ text: convertUint8ArrayToText(convertDataContentToUint8Array(base64Content))
31107
+ });
31108
+ } else {
31109
+ if (!attachment.contentType) {
31110
+ throw new Error("If the attachment is not an image or text, it must specify a content type");
31111
+ }
31112
+ parts.push({
31113
+ type: "file",
31114
+ data: base64Content,
31115
+ mimeType: attachment.contentType
31116
+ });
31117
+ }
31118
+ break;
31119
+ }
31120
+ default: {
31121
+ throw new Error(`Unsupported URL protocol: ${url.protocol}`);
31122
+ }
31169
31123
  }
31170
31124
  }
31171
- __registerMastra(p) {
31172
- this.#mastra = p;
31173
- }
31174
- getProvider() {
31175
- return this.#model.provider;
31176
- }
31177
- getModelId() {
31178
- return this.#model.modelId;
31179
- }
31180
- getModel() {
31181
- return this.#model;
31125
+ return parts;
31126
+ }
31127
+ var makePushOrCombine = (v1Messages) => (msg) => {
31128
+ const previousMessage = v1Messages.at(-1);
31129
+ if (msg.role === previousMessage?.role && Array.isArray(previousMessage.content) && Array.isArray(msg.content) && // we were creating new messages for tool calls before and not appending to the assistant message
31130
+ // so don't append here so everything works as before
31131
+ (msg.role !== `assistant` || msg.role === `assistant` && msg.content.at(-1)?.type !== `tool-call`)) {
31132
+ for (const part of msg.content) {
31133
+ previousMessage.content.push(part);
31134
+ }
31135
+ } else {
31136
+ v1Messages.push(msg);
31182
31137
  }
31183
- async __text({
31184
- runId,
31185
- messages,
31186
- maxSteps = 5,
31187
- tools = {},
31188
- temperature,
31189
- toolChoice = "auto",
31190
- onStepFinish,
31191
- experimental_output,
31192
- telemetry,
31193
- threadId,
31194
- resourceId,
31195
- memory,
31196
- runtimeContext,
31197
- ...rest
31198
- }) {
31199
- const model = this.#model;
31200
- this.logger.debug(`[LLM] - Generating text`, {
31201
- runId,
31202
- messages,
31203
- maxSteps,
31204
- threadId,
31205
- resourceId,
31206
- tools: Object.keys(tools)
31207
- });
31208
- const argsForExecute = {
31209
- model,
31210
- temperature,
31211
- tools: {
31212
- ...tools
31213
- },
31214
- toolChoice,
31215
- maxSteps,
31216
- onStepFinish: async (props) => {
31217
- await onStepFinish?.(props);
31218
- this.logger.debug("[LLM] - Step Change:", {
31219
- text: props?.text,
31220
- toolCalls: props?.toolCalls,
31221
- toolResults: props?.toolResults,
31222
- finishReason: props?.finishReason,
31223
- usage: props?.usage,
31224
- runId
31225
- });
31226
- if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
31227
- this.logger.warn("Rate limit approaching, waiting 10 seconds", { runId });
31228
- await chunkDXLVS7ML_cjs.delay(10 * 1e3);
31229
- }
31230
- },
31231
- ...rest
31138
+ };
31139
+ function convertToV1Messages(messages) {
31140
+ const v1Messages = [];
31141
+ const pushOrCombine = makePushOrCombine(v1Messages);
31142
+ for (let i = 0; i < messages.length; i++) {
31143
+ const message = messages[i];
31144
+ const isLastMessage = i === messages.length - 1;
31145
+ if (!message?.content) continue;
31146
+ const { content, experimental_attachments: inputAttachments = [], parts: inputParts } = message.content;
31147
+ const { role } = message;
31148
+ const fields = {
31149
+ id: message.id,
31150
+ createdAt: message.createdAt,
31151
+ resourceId: message.resourceId,
31152
+ threadId: message.threadId
31232
31153
  };
31233
- let schema;
31234
- if (experimental_output) {
31235
- this.logger.debug("[LLM] - Using experimental output", {
31236
- runId
31237
- });
31238
- if (typeof experimental_output.parse === "function") {
31239
- schema = experimental_output;
31240
- if (schema instanceof zod.z.ZodArray) {
31241
- schema = schema._def.type;
31242
- }
31154
+ const experimental_attachments = [...inputAttachments];
31155
+ const parts = [];
31156
+ for (const part of inputParts) {
31157
+ if (part.type === "file") {
31158
+ experimental_attachments.push({
31159
+ url: part.data,
31160
+ contentType: part.mimeType
31161
+ });
31243
31162
  } else {
31244
- schema = ai.jsonSchema(experimental_output);
31163
+ parts.push(part);
31245
31164
  }
31246
31165
  }
31247
- return await ai.generateText({
31248
- messages,
31249
- ...argsForExecute,
31250
- experimental_telemetry: {
31251
- ...this.experimental_telemetry,
31252
- ...telemetry
31253
- },
31254
- experimental_output: schema ? ai.Output.object({
31255
- schema
31256
- }) : void 0
31257
- });
31258
- }
31259
- async __textObject({
31260
- messages,
31261
- onStepFinish,
31262
- maxSteps = 5,
31263
- tools = {},
31264
- structuredOutput,
31265
- runId,
31266
- temperature,
31267
- toolChoice = "auto",
31268
- telemetry,
31269
- threadId,
31270
- resourceId,
31271
- memory,
31272
- runtimeContext,
31273
- ...rest
31274
- }) {
31275
- const model = this.#model;
31276
- this.logger.debug(`[LLM] - Generating a text object`, { runId });
31277
- const argsForExecute = {
31278
- model,
31279
- temperature,
31280
- tools: {
31281
- ...tools
31282
- },
31283
- maxSteps,
31284
- toolChoice,
31285
- onStepFinish: async (props) => {
31286
- await onStepFinish?.(props);
31287
- this.logger.debug("[LLM] - Step Change:", {
31288
- text: props?.text,
31289
- toolCalls: props?.toolCalls,
31290
- toolResults: props?.toolResults,
31291
- finishReason: props?.finishReason,
31292
- usage: props?.usage,
31293
- runId
31294
- });
31295
- if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
31296
- this.logger.warn("Rate limit approaching, waiting 10 seconds", { runId });
31297
- await chunkDXLVS7ML_cjs.delay(10 * 1e3);
31166
+ switch (role) {
31167
+ case "user": {
31168
+ if (parts == null) {
31169
+ const userContent = experimental_attachments ? [{ type: "text", text: content || "" }, ...attachmentsToParts(experimental_attachments)] : { type: "text", text: content || "" };
31170
+ pushOrCombine({
31171
+ role: "user",
31172
+ ...fields,
31173
+ type: "text",
31174
+ // @ts-ignore
31175
+ content: userContent
31176
+ });
31177
+ } else {
31178
+ const textParts = message.content.parts.filter((part) => part.type === "text").map((part) => ({
31179
+ type: "text",
31180
+ text: part.text
31181
+ }));
31182
+ const userContent = experimental_attachments ? [...textParts, ...attachmentsToParts(experimental_attachments)] : textParts;
31183
+ pushOrCombine({
31184
+ role: "user",
31185
+ ...fields,
31186
+ type: "text",
31187
+ content: Array.isArray(userContent) && userContent.length === 1 && userContent[0]?.type === `text` && typeof content !== `undefined` ? content : userContent
31188
+ });
31298
31189
  }
31299
- },
31300
- ...rest
31301
- };
31302
- let schema;
31303
- let output = "object";
31304
- if (typeof structuredOutput.parse === "function") {
31305
- schema = structuredOutput;
31306
- if (schema instanceof zod.z.ZodArray) {
31307
- output = "array";
31308
- schema = schema._def.type;
31309
- }
31310
- } else {
31311
- schema = ai.jsonSchema(structuredOutput);
31312
- }
31313
- return await ai.generateObject({
31314
- messages,
31315
- ...argsForExecute,
31316
- output,
31317
- schema,
31318
- experimental_telemetry: {
31319
- ...this.experimental_telemetry,
31320
- ...telemetry
31321
- }
31322
- });
31323
- }
31324
- async __stream({
31325
- messages,
31326
- onStepFinish,
31327
- onFinish,
31328
- maxSteps = 5,
31329
- tools = {},
31330
- runId,
31331
- temperature,
31332
- toolChoice = "auto",
31333
- experimental_output,
31334
- telemetry,
31335
- threadId,
31336
- resourceId,
31337
- memory,
31338
- runtimeContext,
31339
- ...rest
31340
- }) {
31341
- const model = this.#model;
31342
- this.logger.debug(`[LLM] - Streaming text`, {
31343
- runId,
31344
- threadId,
31345
- resourceId,
31346
- messages,
31347
- maxSteps,
31348
- tools: Object.keys(tools || {})
31349
- });
31350
- const argsForExecute = {
31351
- model,
31352
- temperature,
31353
- tools: {
31354
- ...tools
31355
- },
31356
- maxSteps,
31357
- toolChoice,
31358
- onStepFinish: async (props) => {
31359
- await onStepFinish?.(props);
31360
- this.logger.debug("[LLM] - Stream Step Change:", {
31361
- text: props?.text,
31362
- toolCalls: props?.toolCalls,
31363
- toolResults: props?.toolResults,
31364
- finishReason: props?.finishReason,
31365
- usage: props?.usage,
31366
- runId
31367
- });
31368
- if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
31369
- this.logger.warn("Rate limit approaching, waiting 10 seconds", { runId });
31370
- await chunkDXLVS7ML_cjs.delay(10 * 1e3);
31371
- }
31372
- },
31373
- onFinish: async (props) => {
31374
- await onFinish?.(props);
31375
- this.logger.debug("[LLM] - Stream Finished:", {
31376
- text: props?.text,
31377
- toolCalls: props?.toolCalls,
31378
- toolResults: props?.toolResults,
31379
- finishReason: props?.finishReason,
31380
- usage: props?.usage,
31381
- runId,
31382
- threadId,
31383
- resourceId
31384
- });
31385
- },
31386
- ...rest
31387
- };
31388
- let schema;
31389
- if (experimental_output) {
31390
- this.logger.debug("[LLM] - Using experimental output", {
31391
- runId
31392
- });
31393
- if (typeof experimental_output.parse === "function") {
31394
- schema = experimental_output;
31395
- if (schema instanceof zod.z.ZodArray) {
31396
- schema = schema._def.type;
31397
- }
31398
- } else {
31399
- schema = ai.jsonSchema(experimental_output);
31400
- }
31401
- }
31402
- return await ai.streamText({
31403
- messages,
31404
- ...argsForExecute,
31405
- experimental_telemetry: {
31406
- ...this.experimental_telemetry,
31407
- ...telemetry
31408
- },
31409
- experimental_output: schema ? ai.Output.object({
31410
- schema
31411
- }) : void 0
31412
- });
31413
- }
31414
- async __streamObject({
31415
- messages,
31416
- runId,
31417
- tools = {},
31418
- maxSteps = 5,
31419
- toolChoice = "auto",
31420
- runtimeContext,
31421
- threadId,
31422
- resourceId,
31423
- memory,
31424
- temperature,
31425
- onStepFinish,
31426
- onFinish,
31427
- structuredOutput,
31428
- telemetry,
31429
- ...rest
31430
- }) {
31431
- const model = this.#model;
31432
- this.logger.debug(`[LLM] - Streaming structured output`, {
31433
- runId,
31434
- messages,
31435
- maxSteps,
31436
- tools: Object.keys(tools || {})
31437
- });
31438
- const finalTools = tools;
31439
- const argsForExecute = {
31440
- model,
31441
- temperature,
31442
- tools: {
31443
- ...finalTools
31444
- },
31445
- maxSteps,
31446
- toolChoice,
31447
- onStepFinish: async (props) => {
31448
- await onStepFinish?.(props);
31449
- this.logger.debug("[LLM] - Stream Step Change:", {
31450
- text: props?.text,
31451
- toolCalls: props?.toolCalls,
31452
- toolResults: props?.toolResults,
31453
- finishReason: props?.finishReason,
31454
- usage: props?.usage,
31455
- runId,
31456
- threadId,
31457
- resourceId
31458
- });
31459
- if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
31460
- this.logger.warn("Rate limit approaching, waiting 10 seconds", { runId });
31461
- await chunkDXLVS7ML_cjs.delay(10 * 1e3);
31462
- }
31463
- },
31464
- onFinish: async (props) => {
31465
- await onFinish?.(props);
31466
- this.logger.debug("[LLM] - Stream Finished:", {
31467
- text: props?.text,
31468
- toolCalls: props?.toolCalls,
31469
- toolResults: props?.toolResults,
31470
- finishReason: props?.finishReason,
31471
- usage: props?.usage,
31472
- runId,
31473
- threadId,
31474
- resourceId
31475
- });
31476
- },
31477
- ...rest
31478
- };
31479
- let schema;
31480
- let output = "object";
31481
- if (typeof structuredOutput.parse === "function") {
31482
- schema = structuredOutput;
31483
- if (schema instanceof zod.z.ZodArray) {
31484
- output = "array";
31485
- schema = schema._def.type;
31486
- }
31487
- } else {
31488
- schema = ai.jsonSchema(structuredOutput);
31489
- }
31490
- return ai.streamObject({
31491
- messages,
31492
- ...argsForExecute,
31493
- output,
31494
- schema,
31495
- experimental_telemetry: {
31496
- ...this.experimental_telemetry,
31497
- ...telemetry
31498
- }
31499
- });
31500
- }
31501
- async generate(messages, { maxSteps = 5, output, ...rest }) {
31502
- const msgs = this.convertToMessages(messages);
31503
- if (!output) {
31504
- return await this.__text({
31505
- messages: msgs,
31506
- maxSteps,
31507
- ...rest
31508
- });
31509
- }
31510
- return await this.__textObject({
31511
- messages: msgs,
31512
- structuredOutput: output,
31513
- maxSteps,
31514
- ...rest
31515
- });
31516
- }
31517
- async stream(messages, { maxSteps = 5, output, ...rest }) {
31518
- const msgs = this.convertToMessages(messages);
31519
- if (!output) {
31520
- return await this.__stream({
31521
- messages: msgs,
31522
- maxSteps,
31523
- ...rest
31524
- });
31525
- }
31526
- return await this.__streamObject({
31527
- messages: msgs,
31528
- structuredOutput: output,
31529
- maxSteps,
31530
- ...rest
31531
- });
31532
- }
31533
- };
31534
- exports2.MastraLLM = MastraLLM;
31535
- }
31536
- });
31537
-
31538
- // ../../packages/core/dist/chunk-OB2PB6SX.cjs
31539
- var require_chunk_OB2PB6SX = __commonJS({
31540
- "../../packages/core/dist/chunk-OB2PB6SX.cjs"(exports2) {
31541
- var chunkDXLVS7ML_cjs = require_chunk_DXLVS7ML();
31542
- var crypto2 = __require("crypto");
31543
- var ai = require_dist4();
31544
- var providerUtils = require_dist2();
31545
- var zod = require_lib();
31546
- zod.z.union([
31547
- zod.z.string(),
31548
- zod.z.instanceof(Uint8Array),
31549
- zod.z.instanceof(ArrayBuffer),
31550
- zod.z.custom(
31551
- // Buffer might not be available in some environments such as CloudFlare:
31552
- (value) => globalThis.Buffer?.isBuffer(value) ?? false,
31553
- { message: "Must be a Buffer" }
31554
- )
31555
- ]);
31556
- function convertDataContentToBase64String(content) {
31557
- if (typeof content === "string") {
31558
- return content;
31559
- }
31560
- if (content instanceof ArrayBuffer) {
31561
- return providerUtils.convertUint8ArrayToBase64(new Uint8Array(content));
31562
- }
31563
- return providerUtils.convertUint8ArrayToBase64(content);
31564
- }
31565
- function convertDataContentToUint8Array(content) {
31566
- if (content instanceof Uint8Array) {
31567
- return content;
31568
- }
31569
- if (typeof content === "string") {
31570
- try {
31571
- return providerUtils.convertBase64ToUint8Array(content);
31572
- } catch (error) {
31573
- throw new Error("Invalid data content. Content string is not a base64-encoded media.", {
31574
- cause: error
31575
- });
31576
- }
31577
- }
31578
- if (content instanceof ArrayBuffer) {
31579
- return new Uint8Array(content);
31580
- }
31581
- throw new Error(content);
31582
- }
31583
- function convertUint8ArrayToText(uint8Array) {
31584
- try {
31585
- return new TextDecoder().decode(uint8Array);
31586
- } catch {
31587
- throw new Error("Error decoding Uint8Array to text");
31588
- }
31589
- }
31590
- function attachmentsToParts(attachments) {
31591
- const parts = [];
31592
- for (const attachment of attachments) {
31593
- let url;
31594
- try {
31595
- url = new URL(attachment.url);
31596
- } catch {
31597
- throw new Error(`Invalid URL: ${attachment.url}`);
31598
- }
31599
- switch (url.protocol) {
31600
- case "http:":
31601
- case "https:": {
31602
- if (attachment.contentType?.startsWith("image/")) {
31603
- parts.push({ type: "image", image: url });
31604
- } else {
31605
- if (!attachment.contentType) {
31606
- throw new Error("If the attachment is not an image, it must specify a content type");
31607
- }
31608
- parts.push({
31609
- type: "file",
31610
- data: url,
31611
- mimeType: attachment.contentType
31612
- });
31613
- }
31614
- break;
31615
- }
31616
- case "data:": {
31617
- let header;
31618
- let base64Content;
31619
- let mimeType;
31620
- try {
31621
- [header, base64Content] = attachment.url.split(",");
31622
- mimeType = header?.split?.(";")?.[0]?.split(":")[1];
31623
- } catch {
31624
- throw new Error(`Error processing data URL: ${attachment.url}`);
31625
- }
31626
- if (mimeType == null || base64Content == null) {
31627
- throw new Error(`Invalid data URL format: ${attachment.url}`);
31628
- }
31629
- if (attachment.contentType?.startsWith("image/")) {
31630
- parts.push({
31631
- type: "image",
31632
- image: convertDataContentToUint8Array(base64Content)
31633
- });
31634
- } else if (attachment.contentType?.startsWith("text/")) {
31635
- parts.push({
31636
- type: "text",
31637
- text: convertUint8ArrayToText(convertDataContentToUint8Array(base64Content))
31638
- });
31639
- } else {
31640
- if (!attachment.contentType) {
31641
- throw new Error("If the attachment is not an image or text, it must specify a content type");
31642
- }
31643
- parts.push({
31644
- type: "file",
31645
- data: base64Content,
31646
- mimeType: attachment.contentType
31647
- });
31648
- }
31649
- break;
31650
- }
31651
- default: {
31652
- throw new Error(`Unsupported URL protocol: ${url.protocol}`);
31653
- }
31654
- }
31655
- }
31656
- return parts;
31657
- }
31658
- var makePushOrCombine = (v1Messages) => (msg) => {
31659
- const previousMessage = v1Messages.at(-1);
31660
- if (msg.role === previousMessage?.role && Array.isArray(previousMessage.content) && Array.isArray(msg.content) && // we were creating new messages for tool calls before and not appending to the assistant message
31661
- // so don't append here so everything works as before
31662
- (msg.role !== `assistant` || msg.role === `assistant` && msg.content.at(-1)?.type !== `tool-call`)) {
31663
- for (const part of msg.content) {
31664
- previousMessage.content.push(part);
31665
- }
31666
- } else {
31667
- v1Messages.push(msg);
31668
- }
31669
- };
31670
- function convertToV1Messages(messages) {
31671
- const v1Messages = [];
31672
- const pushOrCombine = makePushOrCombine(v1Messages);
31673
- for (let i = 0; i < messages.length; i++) {
31674
- const message = messages[i];
31675
- const isLastMessage = i === messages.length - 1;
31676
- if (!message?.content) continue;
31677
- const { content, experimental_attachments, parts } = message.content;
31678
- const { role } = message;
31679
- const fields = {
31680
- id: message.id,
31681
- createdAt: message.createdAt,
31682
- resourceId: message.resourceId,
31683
- threadId: message.threadId
31684
- };
31685
- switch (role) {
31686
- case "user": {
31687
- if (parts == null) {
31688
- const userContent = experimental_attachments ? [{ type: "text", text: content || "" }, ...attachmentsToParts(experimental_attachments)] : { type: "text", text: content || "" };
31689
- pushOrCombine({
31690
- role: "user",
31691
- ...fields,
31692
- type: "text",
31693
- // @ts-ignore
31694
- content: userContent
31695
- // Array.isArray(userContent) && userContent.length === 1 && userContent[0]?.type === `text`
31696
- // ? userContent[0].text
31697
- // : userContent,
31698
- });
31699
- throw new Error(`will we ever hit this code?`);
31700
- } else {
31701
- const textParts = message.content.parts.filter((part) => part.type === "text").map((part) => ({
31702
- type: "text",
31703
- text: part.text
31704
- }));
31705
- const userContent = experimental_attachments ? [...textParts, ...attachmentsToParts(experimental_attachments)] : textParts;
31706
- pushOrCombine({
31707
- role: "user",
31708
- ...fields,
31709
- type: "text",
31710
- // content: userContent,
31711
- // @ts-ignore
31712
- content: Array.isArray(userContent) && userContent.length === 1 && userContent[0]?.type === `text` && typeof content !== `undefined` ? content : userContent
31713
- });
31714
- }
31715
- break;
31190
+ break;
31716
31191
  }
31717
31192
  case "assistant": {
31718
31193
  if (message.content.parts != null) {
@@ -31815,683 +31290,1249 @@ var require_chunk_OB2PB6SX = __commonJS({
31815
31290
  processBlock2();
31816
31291
  break;
31817
31292
  }
31818
- const toolInvocations = message.content.toolInvocations;
31819
- if (toolInvocations == null || toolInvocations.length === 0) {
31820
- pushOrCombine({ role: "assistant", ...fields, content: content || "", type: "text" });
31821
- break;
31293
+ const toolInvocations = message.content.toolInvocations;
31294
+ if (toolInvocations == null || toolInvocations.length === 0) {
31295
+ pushOrCombine({ role: "assistant", ...fields, content: content || "", type: "text" });
31296
+ break;
31297
+ }
31298
+ const maxStep = toolInvocations.reduce((max, toolInvocation) => {
31299
+ return Math.max(max, toolInvocation.step ?? 0);
31300
+ }, 0);
31301
+ for (let i2 = 0; i2 <= maxStep; i2++) {
31302
+ const stepInvocations = toolInvocations.filter((toolInvocation) => (toolInvocation.step ?? 0) === i2);
31303
+ if (stepInvocations.length === 0) {
31304
+ continue;
31305
+ }
31306
+ pushOrCombine({
31307
+ role: "assistant",
31308
+ ...fields,
31309
+ type: "tool-call",
31310
+ content: [
31311
+ ...isLastMessage && content && i2 === 0 ? [{ type: "text", text: content }] : [],
31312
+ ...stepInvocations.map(({ toolCallId, toolName, args }) => ({
31313
+ type: "tool-call",
31314
+ toolCallId,
31315
+ toolName,
31316
+ args
31317
+ }))
31318
+ ]
31319
+ });
31320
+ pushOrCombine({
31321
+ role: "tool",
31322
+ ...fields,
31323
+ type: "tool-result",
31324
+ content: stepInvocations.map((toolInvocation) => {
31325
+ if (!("result" in toolInvocation)) {
31326
+ return toolInvocation;
31327
+ }
31328
+ const { toolCallId, toolName, result } = toolInvocation;
31329
+ return {
31330
+ type: "tool-result",
31331
+ toolCallId,
31332
+ toolName,
31333
+ result
31334
+ };
31335
+ })
31336
+ });
31337
+ }
31338
+ if (content && !isLastMessage) {
31339
+ pushOrCombine({ role: "assistant", ...fields, type: "text", content: content || "" });
31340
+ }
31341
+ break;
31342
+ }
31343
+ }
31344
+ }
31345
+ return v1Messages;
31346
+ }
31347
+ var MessageList2 = class _MessageList {
31348
+ messages = [];
31349
+ // passed in by dev in input or context
31350
+ systemMessages = [];
31351
+ // passed in by us for a specific purpose, eg memory system message
31352
+ taggedSystemMessages = {};
31353
+ memoryInfo = null;
31354
+ // used to filter this.messages by how it was added: input/response/memory
31355
+ memoryMessages = /* @__PURE__ */ new Set();
31356
+ newUserMessages = /* @__PURE__ */ new Set();
31357
+ newResponseMessages = /* @__PURE__ */ new Set();
31358
+ generateMessageId;
31359
+ constructor({
31360
+ threadId,
31361
+ resourceId,
31362
+ generateMessageId
31363
+ } = {}) {
31364
+ if (threadId) {
31365
+ this.memoryInfo = { threadId, resourceId };
31366
+ this.generateMessageId = generateMessageId;
31367
+ }
31368
+ }
31369
+ add(messages, messageSource) {
31370
+ for (const message of Array.isArray(messages) ? messages : [messages]) {
31371
+ this.addOne(
31372
+ typeof message === `string` ? {
31373
+ role: "user",
31374
+ content: message
31375
+ } : message,
31376
+ messageSource
31377
+ );
31378
+ }
31379
+ return this;
31380
+ }
31381
+ getLatestUserContent() {
31382
+ const currentUserMessages = this.all.core().filter((m) => m.role === "user");
31383
+ const content = currentUserMessages.at(-1)?.content;
31384
+ if (!content) return null;
31385
+ return _MessageList.coreContentToString(content);
31386
+ }
31387
+ get get() {
31388
+ return {
31389
+ all: this.all,
31390
+ remembered: this.remembered,
31391
+ input: this.input,
31392
+ response: this.response
31393
+ };
31394
+ }
31395
+ all = {
31396
+ v2: () => this.messages,
31397
+ v1: () => convertToV1Messages(this.messages),
31398
+ ui: () => this.messages.map(_MessageList.toUIMessage),
31399
+ core: () => this.convertToCoreMessages(this.all.ui()),
31400
+ prompt: () => {
31401
+ return [...this.systemMessages, ...Object.values(this.taggedSystemMessages).flat(), ...this.all.core()];
31402
+ }
31403
+ };
31404
+ remembered = {
31405
+ v2: () => this.messages.filter((m) => this.memoryMessages.has(m)),
31406
+ v1: () => convertToV1Messages(this.remembered.v2()),
31407
+ ui: () => this.remembered.v2().map(_MessageList.toUIMessage),
31408
+ core: () => this.convertToCoreMessages(this.remembered.ui())
31409
+ };
31410
+ input = {
31411
+ v2: () => this.messages.filter((m) => this.newUserMessages.has(m)),
31412
+ v1: () => convertToV1Messages(this.input.v2()),
31413
+ ui: () => this.input.v2().map(_MessageList.toUIMessage),
31414
+ core: () => this.convertToCoreMessages(this.input.ui())
31415
+ };
31416
+ response = {
31417
+ v2: () => this.messages.filter((m) => this.newResponseMessages.has(m))
31418
+ };
31419
+ drainUnsavedMessages() {
31420
+ const messages = this.messages.filter((m) => this.newUserMessages.has(m) || this.newResponseMessages.has(m));
31421
+ this.newUserMessages.clear();
31422
+ this.newResponseMessages.clear();
31423
+ return messages;
31424
+ }
31425
+ getSystemMessages(tag) {
31426
+ if (tag) {
31427
+ return this.taggedSystemMessages[tag] || [];
31428
+ }
31429
+ return this.systemMessages;
31430
+ }
31431
+ addSystem(messages, tag) {
31432
+ if (!messages) return this;
31433
+ for (const message of Array.isArray(messages) ? messages : [messages]) {
31434
+ this.addOneSystem(message, tag);
31435
+ }
31436
+ return this;
31437
+ }
31438
+ convertToCoreMessages(messages) {
31439
+ return ai.convertToCoreMessages(this.sanitizeUIMessages(messages));
31440
+ }
31441
+ sanitizeUIMessages(messages) {
31442
+ const msgs = messages.map((m) => {
31443
+ if (m.parts.length === 0) return false;
31444
+ const safeParts = m.parts.filter(
31445
+ (p) => p.type !== `tool-invocation` || // calls and partial-calls should be updated to be results at this point
31446
+ // if they haven't we can't send them back to the llm and need to remove them.
31447
+ p.toolInvocation.state !== `call` && p.toolInvocation.state !== `partial-call`
31448
+ );
31449
+ if (!safeParts.length) return false;
31450
+ const sanitized = {
31451
+ ...m,
31452
+ parts: safeParts
31453
+ };
31454
+ if (`toolInvocations` in m && m.toolInvocations) {
31455
+ sanitized.toolInvocations = m.toolInvocations.filter((t) => t.state === `result`);
31456
+ }
31457
+ return sanitized;
31458
+ }).filter((m) => Boolean(m));
31459
+ return msgs;
31460
+ }
31461
+ addOneSystem(message, tag) {
31462
+ if (typeof message === `string`) message = { role: "system", content: message };
31463
+ if (tag && !this.isDuplicateSystem(message, tag)) {
31464
+ this.taggedSystemMessages[tag] ||= [];
31465
+ this.taggedSystemMessages[tag].push(message);
31466
+ } else if (!this.isDuplicateSystem(message)) {
31467
+ this.systemMessages.push(message);
31468
+ }
31469
+ }
31470
+ isDuplicateSystem(message, tag) {
31471
+ if (tag) {
31472
+ if (!this.taggedSystemMessages[tag]) return false;
31473
+ return this.taggedSystemMessages[tag].some(
31474
+ (m) => _MessageList.cacheKeyFromContent(m.content) === _MessageList.cacheKeyFromContent(message.content)
31475
+ );
31476
+ }
31477
+ return this.systemMessages.some(
31478
+ (m) => _MessageList.cacheKeyFromContent(m.content) === _MessageList.cacheKeyFromContent(message.content)
31479
+ );
31480
+ }
31481
+ static toUIMessage(m) {
31482
+ const experimentalAttachments = m.content.experimental_attachments ? [...m.content.experimental_attachments] : [];
31483
+ const contentString = typeof m.content.content === `string` && m.content.content !== "" ? m.content.content : m.content.parts.reduce((prev, part) => {
31484
+ if (part.type === `text`) {
31485
+ return part.text;
31486
+ }
31487
+ return prev;
31488
+ }, "");
31489
+ const parts = [];
31490
+ if (m.content.parts.length) {
31491
+ for (const part of m.content.parts) {
31492
+ if (part.type === `file`) {
31493
+ experimentalAttachments.push({
31494
+ contentType: part.mimeType,
31495
+ url: part.data
31496
+ });
31497
+ } else {
31498
+ parts.push(part);
31499
+ }
31500
+ }
31501
+ }
31502
+ if (parts.length === 0 && experimentalAttachments.length > 0) {
31503
+ parts.push({ type: "text", text: "" });
31504
+ }
31505
+ if (m.role === `user`) {
31506
+ return {
31507
+ id: m.id,
31508
+ role: m.role,
31509
+ content: m.content.content || contentString,
31510
+ createdAt: m.createdAt,
31511
+ parts,
31512
+ experimental_attachments: experimentalAttachments
31513
+ };
31514
+ } else if (m.role === `assistant`) {
31515
+ return {
31516
+ id: m.id,
31517
+ role: m.role,
31518
+ content: m.content.content || contentString,
31519
+ createdAt: m.createdAt,
31520
+ parts,
31521
+ reasoning: void 0,
31522
+ toolInvocations: `toolInvocations` in m.content ? m.content.toolInvocations : void 0
31523
+ };
31524
+ }
31525
+ return {
31526
+ id: m.id,
31527
+ role: m.role,
31528
+ content: m.content.content || contentString,
31529
+ createdAt: m.createdAt,
31530
+ parts,
31531
+ experimental_attachments: experimentalAttachments
31532
+ };
31533
+ }
31534
+ getMessageById(id) {
31535
+ return this.messages.find((m) => m.id === id);
31536
+ }
31537
+ shouldReplaceMessage(message) {
31538
+ if (!this.messages.length) return { exists: false };
31539
+ if (!(`id` in message) || !message?.id) {
31540
+ return { exists: false };
31541
+ }
31542
+ const existingMessage = this.getMessageById(message.id);
31543
+ if (!existingMessage) return { exists: false };
31544
+ return {
31545
+ exists: true,
31546
+ shouldReplace: !_MessageList.messagesAreEqual(existingMessage, message),
31547
+ id: existingMessage.id
31548
+ };
31549
+ }
31550
+ addOne(message, messageSource) {
31551
+ if (message.role === `system` && _MessageList.isVercelCoreMessage(message)) return this.addSystem(message);
31552
+ if (message.role === `system`) {
31553
+ throw new Error(
31554
+ `A non-CoreMessage system message was added - this is not supported as we didn't expect this could happen. Please open a Github issue and let us know what you did to get here. This is the non-CoreMessage system message we received:
31555
+
31556
+ messageSource: ${messageSource}
31557
+
31558
+ ${JSON.stringify(message, null, 2)}`
31559
+ );
31560
+ }
31561
+ const messageV2 = this.inputToMastraMessageV2(message, messageSource);
31562
+ const { exists, shouldReplace, id } = this.shouldReplaceMessage(messageV2);
31563
+ const latestMessage = this.messages.at(-1);
31564
+ const singleToolResult = messageV2.role === `assistant` && messageV2.content.parts.length === 1 && messageV2.content.parts[0]?.type === `tool-invocation` && messageV2.content.parts[0].toolInvocation.state === `result` && messageV2.content.parts[0];
31565
+ if (singleToolResult && (latestMessage?.role !== `assistant` || !latestMessage.content.parts.some(
31566
+ (p) => p.type === `tool-invocation` && p.toolInvocation.toolCallId === singleToolResult.toolInvocation.toolCallId
31567
+ ))) {
31568
+ return;
31569
+ }
31570
+ if (messageSource === `memory`) {
31571
+ for (const existingMessage of this.messages) {
31572
+ if (_MessageList.messagesAreEqual(existingMessage, messageV2)) {
31573
+ return;
31822
31574
  }
31823
- const maxStep = toolInvocations.reduce((max, toolInvocation) => {
31824
- return Math.max(max, toolInvocation.step ?? 0);
31825
- }, 0);
31826
- for (let i2 = 0; i2 <= maxStep; i2++) {
31827
- const stepInvocations = toolInvocations.filter((toolInvocation) => (toolInvocation.step ?? 0) === i2);
31828
- if (stepInvocations.length === 0) {
31829
- continue;
31575
+ }
31576
+ }
31577
+ const latestMessagePartType = latestMessage?.content?.parts?.filter((p) => p.type !== `step-start`)?.at?.(-1)?.type;
31578
+ const newMessageFirstPartType = messageV2.content.parts.filter((p) => p.type !== `step-start`).at(0)?.type;
31579
+ const shouldAppendToLastAssistantMessage = latestMessage?.role === "assistant" && messageV2.role === "assistant";
31580
+ const shouldAppendToLastAssistantMessageParts = shouldAppendToLastAssistantMessage && newMessageFirstPartType && (newMessageFirstPartType === `tool-invocation` && latestMessagePartType !== `text` || newMessageFirstPartType === latestMessagePartType);
31581
+ if (
31582
+ // backwards compat check!
31583
+ // this condition can technically be removed and it will make it so all new assistant parts will be added to the last assistant message parts instead of creating new db entries.
31584
+ // however, for any downstream code that isn't based around using message parts yet, this may cause tool invocations to show up in the wrong order in their UI, because they use the message.toolInvocations and message.content properties which do not indicate how each is ordered in relation to each other.
31585
+ // this code check then causes any tool invocation to be created as a new message and not update the previous assistant message parts.
31586
+ // without this condition we will see something like
31587
+ // parts: [{type:"step-start"}, {type: "text", text: "let me check the weather"}, {type: "tool-invocation", toolInvocation: x}, {type: "text", text: "the weather in x is y"}]
31588
+ // with this condition we will see
31589
+ // message1.parts: [{type:"step-start"}, {type: "text", text: "let me check the weather"}]
31590
+ // message2.parts: [{type: "tool-invocation", toolInvocation: x}]
31591
+ // message3.parts: [{type: "text", text: "the weather in x is y"}]
31592
+ shouldAppendToLastAssistantMessageParts
31593
+ ) {
31594
+ latestMessage.createdAt = messageV2.createdAt || latestMessage.createdAt;
31595
+ for (const [index, part] of messageV2.content.parts.entries()) {
31596
+ if (part.type === "tool-invocation" && part.toolInvocation.state === "result") {
31597
+ const existingCallPart = [...latestMessage.content.parts].reverse().find((p) => p.type === "tool-invocation" && p.toolInvocation.toolCallId === part.toolInvocation.toolCallId);
31598
+ if (existingCallPart && existingCallPart.type === "tool-invocation") {
31599
+ existingCallPart.toolInvocation = {
31600
+ ...existingCallPart.toolInvocation,
31601
+ state: "result",
31602
+ result: part.toolInvocation.result
31603
+ };
31604
+ if (!latestMessage.content.toolInvocations) {
31605
+ latestMessage.content.toolInvocations = [];
31606
+ }
31607
+ if (!latestMessage.content.toolInvocations.some(
31608
+ (t) => t.toolCallId === existingCallPart.toolInvocation.toolCallId
31609
+ )) {
31610
+ latestMessage.content.toolInvocations.push(existingCallPart.toolInvocation);
31611
+ }
31830
31612
  }
31831
- pushOrCombine({
31832
- role: "assistant",
31833
- ...fields,
31834
- type: "tool-call",
31835
- content: [
31836
- ...isLastMessage && content && i2 === 0 ? [{ type: "text", text: content }] : [],
31837
- ...stepInvocations.map(({ toolCallId, toolName, args }) => ({
31838
- type: "tool-call",
31839
- toolCallId,
31840
- toolName,
31841
- args
31842
- }))
31843
- ]
31844
- });
31845
- pushOrCombine({
31846
- role: "tool",
31847
- ...fields,
31848
- type: "tool-result",
31849
- content: stepInvocations.map((toolInvocation) => {
31850
- if (!("result" in toolInvocation)) {
31851
- return toolInvocation;
31852
- }
31853
- const { toolCallId, toolName, result } = toolInvocation;
31854
- return {
31855
- type: "tool-result",
31856
- toolCallId,
31857
- toolName,
31858
- result
31859
- };
31860
- })
31861
- });
31862
- }
31863
- if (content && !isLastMessage) {
31864
- pushOrCombine({ role: "assistant", ...fields, type: "text", content: content || "" });
31613
+ } else if (
31614
+ // if there's no part at this index yet in the existing message we're merging into
31615
+ !latestMessage.content.parts[index] || // or there is and the parts are not identical
31616
+ _MessageList.cacheKeyFromParts([latestMessage.content.parts[index]]) !== _MessageList.cacheKeyFromParts([part])
31617
+ ) {
31618
+ latestMessage.content.parts.push(part);
31865
31619
  }
31866
- break;
31620
+ }
31621
+ if (latestMessage.createdAt.getTime() < messageV2.createdAt.getTime()) {
31622
+ latestMessage.createdAt = messageV2.createdAt;
31623
+ }
31624
+ if (!latestMessage.content.content && messageV2.content.content) {
31625
+ latestMessage.content.content = messageV2.content.content;
31626
+ }
31627
+ if (latestMessage.content.content && messageV2.content.content && latestMessage.content.content !== messageV2.content.content) {
31628
+ latestMessage.content.content = messageV2.content.content;
31629
+ }
31630
+ } else {
31631
+ if (messageV2.role === "assistant" && messageV2.content.parts[0]?.type !== `step-start`) {
31632
+ messageV2.content.parts.unshift({ type: "step-start" });
31633
+ }
31634
+ const existingIndex = shouldReplace && this.messages.findIndex((m) => m.id === id) || -1;
31635
+ const existingMessage = existingIndex !== -1 && this.messages[existingIndex];
31636
+ if (shouldReplace && existingMessage) {
31637
+ this.messages[existingIndex] = messageV2;
31638
+ } else if (!exists) {
31639
+ this.messages.push(messageV2);
31640
+ }
31641
+ if (messageSource === `memory`) {
31642
+ this.memoryMessages.add(messageV2);
31643
+ } else if (messageSource === `response`) {
31644
+ this.newResponseMessages.add(messageV2);
31645
+ } else if (messageSource === `user`) {
31646
+ this.newUserMessages.add(messageV2);
31647
+ } else {
31648
+ throw new Error(`Missing message source for message ${messageV2}`);
31867
31649
  }
31868
31650
  }
31651
+ this.messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
31652
+ return this;
31869
31653
  }
31870
- return v1Messages;
31871
- }
31872
- var MessageList2 = class _MessageList {
31873
- messages = [];
31874
- // passed in by dev in input or context
31875
- systemMessages = [];
31876
- // passed in by us for a specific purpose, eg memory system message
31877
- taggedSystemMessages = {};
31878
- memoryInfo = null;
31879
- // used to filter this.messages by how it was added: input/response/memory
31880
- memoryMessages = /* @__PURE__ */ new Set();
31881
- newUserMessages = /* @__PURE__ */ new Set();
31882
- newResponseMessages = /* @__PURE__ */ new Set();
31883
- generateMessageId;
31884
- constructor({
31885
- threadId,
31886
- resourceId,
31887
- generateMessageId
31888
- } = {}) {
31889
- if (threadId) {
31890
- this.memoryInfo = { threadId, resourceId };
31891
- this.generateMessageId = generateMessageId;
31654
+ inputToMastraMessageV2(message, messageSource) {
31655
+ if (`threadId` in message && message.threadId && this.memoryInfo && message.threadId !== this.memoryInfo.threadId) {
31656
+ throw new Error(
31657
+ `Received input message with wrong threadId. Input ${message.threadId}, expected ${this.memoryInfo.threadId}`
31658
+ );
31659
+ }
31660
+ if (`resourceId` in message && message.resourceId && this.memoryInfo?.resourceId && message.resourceId !== this.memoryInfo.resourceId) {
31661
+ throw new Error(
31662
+ `Received input message with wrong resourceId. Input ${message.resourceId}, expected ${this.memoryInfo.resourceId}`
31663
+ );
31664
+ }
31665
+ if (_MessageList.isMastraMessageV1(message)) {
31666
+ return this.mastraMessageV1ToMastraMessageV2(message, messageSource);
31667
+ }
31668
+ if (_MessageList.isMastraMessageV2(message)) {
31669
+ return this.hydrateMastraMessageV2Fields(message);
31670
+ }
31671
+ if (_MessageList.isVercelCoreMessage(message)) {
31672
+ return this.vercelCoreMessageToMastraMessageV2(message, messageSource);
31673
+ }
31674
+ if (_MessageList.isVercelUIMessage(message)) {
31675
+ return this.vercelUIMessageToMastraMessageV2(message, messageSource);
31676
+ }
31677
+ throw new Error(`Found unhandled message ${JSON.stringify(message)}`);
31678
+ }
31679
+ lastCreatedAt;
31680
+ // this makes sure messages added in order will always have a date atleast 1ms apart.
31681
+ generateCreatedAt(messageSource, start) {
31682
+ start = start instanceof Date ? start : start ? new Date(start) : void 0;
31683
+ if (start && !this.lastCreatedAt) {
31684
+ this.lastCreatedAt = start.getTime();
31685
+ return start;
31686
+ }
31687
+ if (start && messageSource === `memory`) {
31688
+ return start;
31689
+ }
31690
+ const now = /* @__PURE__ */ new Date();
31691
+ const nowTime = start?.getTime() || now.getTime();
31692
+ const lastTime = this.messages.reduce((p, m) => {
31693
+ if (m.createdAt.getTime() > p) return m.createdAt.getTime();
31694
+ return p;
31695
+ }, this.lastCreatedAt || 0);
31696
+ if (nowTime <= lastTime) {
31697
+ const newDate = new Date(lastTime + 1);
31698
+ this.lastCreatedAt = newDate.getTime();
31699
+ return newDate;
31892
31700
  }
31701
+ this.lastCreatedAt = nowTime;
31702
+ return now;
31893
31703
  }
31894
- add(messages, messageSource) {
31895
- for (const message of Array.isArray(messages) ? messages : [messages]) {
31896
- this.addOne(
31897
- typeof message === `string` ? {
31898
- role: "user",
31899
- content: message
31900
- } : message,
31901
- messageSource
31902
- );
31704
+ newMessageId() {
31705
+ if (this.generateMessageId) {
31706
+ return this.generateMessageId();
31903
31707
  }
31904
- return this;
31905
- }
31906
- getLatestUserContent() {
31907
- const currentUserMessages = this.all.core().filter((m) => m.role === "user");
31908
- const content = currentUserMessages.at(-1)?.content;
31909
- if (!content) return null;
31910
- return _MessageList.coreContentToString(content);
31708
+ return crypto2.randomUUID();
31911
31709
  }
31912
- get get() {
31710
+ mastraMessageV1ToMastraMessageV2(message, messageSource) {
31711
+ const coreV2 = this.vercelCoreMessageToMastraMessageV2(
31712
+ {
31713
+ content: message.content,
31714
+ role: message.role
31715
+ },
31716
+ messageSource
31717
+ );
31913
31718
  return {
31914
- all: this.all,
31915
- remembered: this.remembered,
31916
- input: this.input,
31917
- response: this.response
31719
+ id: message.id,
31720
+ role: coreV2.role,
31721
+ createdAt: this.generateCreatedAt(messageSource, message.createdAt),
31722
+ threadId: message.threadId,
31723
+ resourceId: message.resourceId,
31724
+ content: coreV2.content
31918
31725
  };
31919
31726
  }
31920
- all = {
31921
- v2: () => this.messages,
31922
- v1: () => convertToV1Messages(this.messages),
31923
- ui: () => this.messages.map(_MessageList.toUIMessage),
31924
- core: () => this.convertToCoreMessages(this.all.ui()),
31925
- prompt: () => {
31926
- return [...this.systemMessages, ...Object.values(this.taggedSystemMessages).flat(), ...this.all.core()];
31927
- }
31928
- };
31929
- remembered = {
31930
- v2: () => this.messages.filter((m) => this.memoryMessages.has(m)),
31931
- v1: () => convertToV1Messages(this.remembered.v2()),
31932
- ui: () => this.remembered.v2().map(_MessageList.toUIMessage),
31933
- core: () => this.convertToCoreMessages(this.remembered.ui())
31934
- };
31935
- input = {
31936
- v2: () => this.messages.filter((m) => this.newUserMessages.has(m)),
31937
- v1: () => convertToV1Messages(this.input.v2()),
31938
- ui: () => this.input.v2().map(_MessageList.toUIMessage),
31939
- core: () => this.convertToCoreMessages(this.input.ui())
31940
- };
31941
- response = {
31942
- v2: () => this.messages.filter((m) => this.newResponseMessages.has(m))
31943
- };
31944
- drainUnsavedMessages() {
31945
- const messages = this.messages.filter((m) => this.newUserMessages.has(m) || this.newResponseMessages.has(m));
31946
- this.newUserMessages.clear();
31947
- this.newResponseMessages.clear();
31948
- return messages;
31727
+ hydrateMastraMessageV2Fields(message) {
31728
+ if (!(message.createdAt instanceof Date)) message.createdAt = new Date(message.createdAt);
31729
+ return message;
31949
31730
  }
31950
- getSystemMessages(tag) {
31951
- if (tag) {
31952
- return this.taggedSystemMessages[tag] || [];
31731
+ vercelUIMessageToMastraMessageV2(message, messageSource) {
31732
+ const content = {
31733
+ format: 2,
31734
+ parts: message.parts
31735
+ };
31736
+ if (message.toolInvocations) content.toolInvocations = message.toolInvocations;
31737
+ if (message.reasoning) content.reasoning = message.reasoning;
31738
+ if (message.annotations) content.annotations = message.annotations;
31739
+ if (message.experimental_attachments) {
31740
+ content.experimental_attachments = message.experimental_attachments;
31953
31741
  }
31954
- return this.systemMessages;
31742
+ return {
31743
+ id: message.id || this.newMessageId(),
31744
+ role: _MessageList.getRole(message),
31745
+ createdAt: this.generateCreatedAt(messageSource, message.createdAt),
31746
+ threadId: this.memoryInfo?.threadId,
31747
+ resourceId: this.memoryInfo?.resourceId,
31748
+ content
31749
+ };
31955
31750
  }
31956
- addSystem(messages, tag) {
31957
- if (!messages) return this;
31958
- for (const message of Array.isArray(messages) ? messages : [messages]) {
31959
- this.addOneSystem(message, tag);
31751
+ vercelCoreMessageToMastraMessageV2(coreMessage, messageSource) {
31752
+ const id = `id` in coreMessage ? coreMessage.id : this.newMessageId();
31753
+ const parts = [];
31754
+ const experimentalAttachments = [];
31755
+ const toolInvocations = [];
31756
+ if (typeof coreMessage.content === "string") {
31757
+ parts.push({ type: "step-start" });
31758
+ parts.push({
31759
+ type: "text",
31760
+ text: coreMessage.content
31761
+ });
31762
+ } else if (Array.isArray(coreMessage.content)) {
31763
+ for (const part of coreMessage.content) {
31764
+ switch (part.type) {
31765
+ case "text":
31766
+ parts.push({
31767
+ type: "text",
31768
+ text: part.text
31769
+ });
31770
+ break;
31771
+ case "tool-call":
31772
+ parts.push({
31773
+ type: "tool-invocation",
31774
+ toolInvocation: {
31775
+ state: "call",
31776
+ toolCallId: part.toolCallId,
31777
+ toolName: part.toolName,
31778
+ args: part.args
31779
+ }
31780
+ });
31781
+ break;
31782
+ case "tool-result":
31783
+ const invocation = {
31784
+ state: "result",
31785
+ toolCallId: part.toolCallId,
31786
+ toolName: part.toolName,
31787
+ result: part.result ?? "",
31788
+ // undefined will cause AI SDK to throw an error, but for client side tool calls this really could be undefined
31789
+ args: {}
31790
+ // when we combine this invocation onto the existing tool-call part it will have args already
31791
+ };
31792
+ parts.push({
31793
+ type: "tool-invocation",
31794
+ toolInvocation: invocation
31795
+ });
31796
+ toolInvocations.push(invocation);
31797
+ break;
31798
+ case "reasoning":
31799
+ parts.push({
31800
+ type: "reasoning",
31801
+ reasoning: "",
31802
+ // leave this blank so we aren't double storing it in the db along with details
31803
+ details: [{ type: "text", text: part.text, signature: part.signature }]
31804
+ });
31805
+ break;
31806
+ case "redacted-reasoning":
31807
+ parts.push({
31808
+ type: "reasoning",
31809
+ reasoning: "",
31810
+ // No text reasoning for redacted parts
31811
+ details: [{ type: "redacted", data: part.data }]
31812
+ });
31813
+ break;
31814
+ case "image":
31815
+ parts.push({ type: "file", data: part.image.toString(), mimeType: part.mimeType });
31816
+ break;
31817
+ case "file":
31818
+ if (part.data instanceof URL) {
31819
+ parts.push({
31820
+ type: "file",
31821
+ data: part.data.toString(),
31822
+ mimeType: part.mimeType
31823
+ });
31824
+ } else {
31825
+ try {
31826
+ parts.push({
31827
+ type: "file",
31828
+ mimeType: part.mimeType,
31829
+ data: convertDataContentToBase64String(part.data)
31830
+ });
31831
+ } catch (error) {
31832
+ console.error(`Failed to convert binary data to base64 in CoreMessage file part: ${error}`, error);
31833
+ }
31834
+ }
31835
+ break;
31836
+ }
31837
+ }
31960
31838
  }
31961
- return this;
31839
+ const content = {
31840
+ format: 2,
31841
+ parts
31842
+ };
31843
+ if (toolInvocations.length) content.toolInvocations = toolInvocations;
31844
+ if (typeof coreMessage.content === `string`) content.content = coreMessage.content;
31845
+ if (experimentalAttachments.length) content.experimental_attachments = experimentalAttachments;
31846
+ return {
31847
+ id,
31848
+ role: _MessageList.getRole(coreMessage),
31849
+ createdAt: this.generateCreatedAt(messageSource),
31850
+ threadId: this.memoryInfo?.threadId,
31851
+ resourceId: this.memoryInfo?.resourceId,
31852
+ content
31853
+ };
31962
31854
  }
31963
- convertToCoreMessages(messages) {
31964
- return ai.convertToCoreMessages(this.sanitizeUIMessages(messages));
31855
+ static isVercelUIMessage(msg) {
31856
+ return !_MessageList.isMastraMessage(msg) && chunkWWLMZIHW_cjs.isUiMessage(msg);
31965
31857
  }
31966
- sanitizeUIMessages(messages) {
31967
- const msgs = messages.map((m) => {
31968
- if (m.parts.length === 0) return false;
31969
- const safeParts = m.parts.filter(
31970
- (p) => p.type !== `tool-invocation` || // calls and partial-calls should be updated to be results at this point
31971
- // if they haven't we can't send them back to the llm and need to remove them.
31972
- p.toolInvocation.state !== `call` && p.toolInvocation.state !== `partial-call`
31973
- );
31974
- if (!safeParts.length) return false;
31975
- const sanitized = {
31976
- ...m,
31977
- parts: safeParts
31978
- };
31979
- if (`toolInvocations` in m && m.toolInvocations) {
31980
- sanitized.toolInvocations = m.toolInvocations.filter((t) => t.state === `result`);
31981
- }
31982
- return sanitized;
31983
- }).filter((m) => Boolean(m));
31984
- return msgs;
31858
+ static isVercelCoreMessage(msg) {
31859
+ return !_MessageList.isMastraMessage(msg) && chunkWWLMZIHW_cjs.isCoreMessage(msg);
31985
31860
  }
31986
- addOneSystem(message, tag) {
31987
- if (typeof message === `string`) message = { role: "system", content: message };
31988
- if (tag && !this.isDuplicateSystem(message, tag)) {
31989
- this.taggedSystemMessages[tag] ||= [];
31990
- this.taggedSystemMessages[tag].push(message);
31991
- } else if (!this.isDuplicateSystem(message)) {
31992
- this.systemMessages.push(message);
31993
- }
31861
+ static isMastraMessage(msg) {
31862
+ return _MessageList.isMastraMessageV2(msg) || _MessageList.isMastraMessageV1(msg);
31994
31863
  }
31995
- isDuplicateSystem(message, tag) {
31996
- if (tag) {
31997
- if (!this.taggedSystemMessages[tag]) return false;
31998
- return this.taggedSystemMessages[tag].some(
31999
- (m) => _MessageList.cacheKeyFromContent(m.content) === _MessageList.cacheKeyFromContent(message.content)
32000
- );
32001
- }
32002
- return this.systemMessages.some(
32003
- (m) => _MessageList.cacheKeyFromContent(m.content) === _MessageList.cacheKeyFromContent(message.content)
31864
+ static isMastraMessageV1(msg) {
31865
+ return !_MessageList.isMastraMessageV2(msg) && (`threadId` in msg || `resourceId` in msg);
31866
+ }
31867
+ static isMastraMessageV2(msg) {
31868
+ return Boolean(
31869
+ msg.content && !Array.isArray(msg.content) && typeof msg.content !== `string` && // any newly saved Mastra message v2 shape will have content: { format: 2 }
31870
+ `format` in msg.content && msg.content.format === 2
31871
+ );
31872
+ }
31873
+ static getRole(message) {
31874
+ if (message.role === `assistant` || message.role === `tool`) return `assistant`;
31875
+ if (message.role === `user`) return `user`;
31876
+ throw new Error(
31877
+ `BUG: add handling for message role ${message.role} in message ${JSON.stringify(message, null, 2)}`
32004
31878
  );
32005
31879
  }
32006
- static toUIMessage(m) {
32007
- const contentString = typeof m.content.content === `string` && m.content.content !== "" ? m.content.content : m.content.parts.reduce((prev, part) => {
31880
+ static cacheKeyFromParts(parts) {
31881
+ let key = ``;
31882
+ for (const part of parts) {
31883
+ key += part.type;
32008
31884
  if (part.type === `text`) {
32009
- return part.text;
31885
+ key += part.text.length;
31886
+ }
31887
+ if (part.type === `tool-invocation`) {
31888
+ key += part.toolInvocation.toolCallId;
31889
+ key += part.toolInvocation.state;
31890
+ }
31891
+ if (part.type === `reasoning`) {
31892
+ key += part.reasoning.length;
31893
+ key += part.details.reduce((prev, current) => {
31894
+ if (current.type === `text`) {
31895
+ return prev + current.text.length + (current.signature?.length || 0);
31896
+ }
31897
+ return prev;
31898
+ }, 0);
31899
+ }
31900
+ if (part.type === `file`) {
31901
+ key += part.data.length;
31902
+ key += part.mimeType;
32010
31903
  }
32011
- return prev;
32012
- }, "");
32013
- if (m.role === `user`) {
32014
- return {
32015
- id: m.id,
32016
- role: m.role,
32017
- content: m.content.content || contentString,
32018
- createdAt: m.createdAt,
32019
- parts: m.content.parts,
32020
- experimental_attachments: m.content.experimental_attachments || []
32021
- };
32022
- } else if (m.role === `assistant`) {
32023
- return {
32024
- id: m.id,
32025
- role: m.role,
32026
- content: m.content.content || contentString,
32027
- createdAt: m.createdAt,
32028
- parts: m.content.parts,
32029
- reasoning: void 0,
32030
- toolInvocations: `toolInvocations` in m.content ? m.content.toolInvocations : void 0
32031
- };
32032
31904
  }
32033
- return {
32034
- id: m.id,
32035
- role: m.role,
32036
- content: m.content.content || contentString,
32037
- createdAt: m.createdAt,
32038
- parts: m.content.parts
32039
- };
31905
+ return key;
32040
31906
  }
32041
- getMessageById(id) {
32042
- return this.messages.find((m) => m.id === id);
31907
+ static coreContentToString(content) {
31908
+ if (typeof content === `string`) return content;
31909
+ return content.reduce((p, c) => {
31910
+ if (c.type === `text`) {
31911
+ p += c.text;
31912
+ }
31913
+ return p;
31914
+ }, "");
32043
31915
  }
32044
- shouldReplaceMessage(message) {
32045
- if (!this.messages.length) return { exists: false };
32046
- if (!(`id` in message) || !message?.id) {
32047
- return { exists: false };
31916
+ static cacheKeyFromContent(content) {
31917
+ if (typeof content === `string`) return content;
31918
+ let key = ``;
31919
+ for (const part of content) {
31920
+ key += part.type;
31921
+ if (part.type === `text`) {
31922
+ key += part.text.length;
31923
+ }
31924
+ if (part.type === `reasoning`) {
31925
+ key += part.text.length;
31926
+ }
31927
+ if (part.type === `tool-call`) {
31928
+ key += part.toolCallId;
31929
+ key += part.toolName;
31930
+ }
31931
+ if (part.type === `tool-result`) {
31932
+ key += part.toolCallId;
31933
+ key += part.toolName;
31934
+ }
31935
+ if (part.type === `file`) {
31936
+ key += part.filename;
31937
+ key += part.mimeType;
31938
+ }
31939
+ if (part.type === `image`) {
31940
+ key += part.image instanceof URL ? part.image.toString() : part.image.toString().length;
31941
+ key += part.mimeType;
31942
+ }
31943
+ if (part.type === `redacted-reasoning`) {
31944
+ key += part.data.length;
31945
+ }
32048
31946
  }
32049
- const existingMessage = this.getMessageById(message.id);
32050
- if (!existingMessage) return { exists: false };
32051
- return {
32052
- exists: true,
32053
- shouldReplace: !_MessageList.messagesAreEqual(existingMessage, message),
32054
- id: existingMessage.id
32055
- };
31947
+ return key;
32056
31948
  }
32057
- addOne(message, messageSource) {
32058
- if (message.role === `system` && _MessageList.isVercelCoreMessage(message)) return this.addSystem(message);
32059
- if (message.role === `system`) {
32060
- throw new Error(
32061
- `A non-CoreMessage system message was added - this is not supported as we didn't expect this could happen. Please open a Github issue and let us know what you did to get here. This is the non-CoreMessage system message we received:
32062
-
32063
- messageSource: ${messageSource}
32064
-
32065
- ${JSON.stringify(message, null, 2)}`
32066
- );
31949
+ static messagesAreEqual(one, two) {
31950
+ const oneUI = _MessageList.isVercelUIMessage(one) && one;
31951
+ const twoUI = _MessageList.isVercelUIMessage(two) && two;
31952
+ if (oneUI && !twoUI) return false;
31953
+ if (oneUI && twoUI) {
31954
+ return _MessageList.cacheKeyFromParts(one.parts) === _MessageList.cacheKeyFromParts(two.parts);
32067
31955
  }
32068
- const messageV2 = this.inputToMastraMessageV2(message, messageSource);
32069
- const { exists, shouldReplace, id } = this.shouldReplaceMessage(messageV2);
32070
- const latestMessage = this.messages.at(-1);
32071
- const singleToolResult = messageV2.role === `assistant` && messageV2.content.parts.length === 1 && messageV2.content.parts[0]?.type === `tool-invocation` && messageV2.content.parts[0].toolInvocation.state === `result` && messageV2.content.parts[0];
32072
- if (singleToolResult && (latestMessage?.role !== `assistant` || !latestMessage.content.parts.some(
32073
- (p) => p.type === `tool-invocation` && p.toolInvocation.toolCallId === singleToolResult.toolInvocation.toolCallId
32074
- ))) {
32075
- return;
31956
+ const oneCM = _MessageList.isVercelCoreMessage(one) && one;
31957
+ const twoCM = _MessageList.isVercelCoreMessage(two) && two;
31958
+ if (oneCM && !twoCM) return false;
31959
+ if (oneCM && twoCM) {
31960
+ return _MessageList.cacheKeyFromContent(oneCM.content) === _MessageList.cacheKeyFromContent(twoCM.content);
32076
31961
  }
32077
- if (messageSource === `memory`) {
32078
- for (const existingMessage of this.messages) {
32079
- if (_MessageList.messagesAreEqual(existingMessage, messageV2)) {
32080
- return;
32081
- }
32082
- }
31962
+ const oneMM1 = _MessageList.isMastraMessageV1(one) && one;
31963
+ const twoMM1 = _MessageList.isMastraMessageV1(two) && two;
31964
+ if (oneMM1 && !twoMM1) return false;
31965
+ if (oneMM1 && twoMM1) {
31966
+ return oneMM1.id === twoMM1.id && _MessageList.cacheKeyFromContent(oneMM1.content) === _MessageList.cacheKeyFromContent(twoMM1.content);
32083
31967
  }
32084
- const latestMessagePartType = latestMessage?.content?.parts?.filter((p) => p.type !== `step-start`)?.at?.(-1)?.type;
32085
- const newMessageFirstPartType = messageV2.content.parts.filter((p) => p.type !== `step-start`).at(0)?.type;
32086
- const shouldAppendToLastAssistantMessage = latestMessage?.role === "assistant" && messageV2.role === "assistant";
32087
- const shouldAppendToLastAssistantMessageParts = shouldAppendToLastAssistantMessage && newMessageFirstPartType && (newMessageFirstPartType === `tool-invocation` && latestMessagePartType !== `text` || newMessageFirstPartType === latestMessagePartType);
32088
- if (
32089
- // backwards compat check!
32090
- // this condition can technically be removed and it will make it so all new assistant parts will be added to the last assistant message parts instead of creating new db entries.
32091
- // however, for any downstream code that isn't based around using message parts yet, this may cause tool invocations to show up in the wrong order in their UI, because they use the message.toolInvocations and message.content properties which do not indicate how each is ordered in relation to each other.
32092
- // this code check then causes any tool invocation to be created as a new message and not update the previous assistant message parts.
32093
- // without this condition we will see something like
32094
- // parts: [{type:"step-start"}, {type: "text", text: "let me check the weather"}, {type: "tool-invocation", toolInvocation: x}, {type: "text", text: "the weather in x is y"}]
32095
- // with this condition we will see
32096
- // message1.parts: [{type:"step-start"}, {type: "text", text: "let me check the weather"}]
32097
- // message2.parts: [{type: "tool-invocation", toolInvocation: x}]
32098
- // message3.parts: [{type: "text", text: "the weather in x is y"}]
32099
- shouldAppendToLastAssistantMessageParts
32100
- ) {
32101
- latestMessage.createdAt = messageV2.createdAt || latestMessage.createdAt;
32102
- for (const [index, part] of messageV2.content.parts.entries()) {
32103
- if (part.type === "tool-invocation" && part.toolInvocation.state === "result") {
32104
- const existingCallPart = [...latestMessage.content.parts].reverse().find((p) => p.type === "tool-invocation" && p.toolInvocation.toolCallId === part.toolInvocation.toolCallId);
32105
- if (existingCallPart && existingCallPart.type === "tool-invocation") {
32106
- existingCallPart.toolInvocation = {
32107
- ...existingCallPart.toolInvocation,
32108
- state: "result",
32109
- result: part.toolInvocation.result
32110
- };
32111
- if (!latestMessage.content.toolInvocations) {
32112
- latestMessage.content.toolInvocations = [];
32113
- }
32114
- if (!latestMessage.content.toolInvocations.some(
32115
- (t) => t.toolCallId === existingCallPart.toolInvocation.toolCallId
32116
- )) {
32117
- latestMessage.content.toolInvocations.push(existingCallPart.toolInvocation);
32118
- }
32119
- }
32120
- } else if (
32121
- // if there's no part at this index yet in the existing message we're merging into
32122
- !latestMessage.content.parts[index] || // or there is and the parts are not identical
32123
- _MessageList.cacheKeyFromParts([latestMessage.content.parts[index]]) !== _MessageList.cacheKeyFromParts([part])
32124
- ) {
32125
- latestMessage.content.parts.push(part);
32126
- }
32127
- }
32128
- if (latestMessage.createdAt.getTime() < messageV2.createdAt.getTime()) {
32129
- latestMessage.createdAt = messageV2.createdAt;
32130
- }
32131
- if (!latestMessage.content.content && messageV2.content.content) {
32132
- latestMessage.content.content = messageV2.content.content;
32133
- }
32134
- if (latestMessage.content.content && messageV2.content.content && latestMessage.content.content !== messageV2.content.content) {
32135
- latestMessage.content.content = messageV2.content.content;
31968
+ const oneMM2 = _MessageList.isMastraMessageV2(one) && one;
31969
+ const twoMM2 = _MessageList.isMastraMessageV2(two) && two;
31970
+ if (oneMM2 && !twoMM2) return false;
31971
+ if (oneMM2 && twoMM2) {
31972
+ return oneMM2.id === twoMM2.id && _MessageList.cacheKeyFromParts(oneMM2.content.parts) === _MessageList.cacheKeyFromParts(twoMM2.content.parts);
31973
+ }
31974
+ return true;
31975
+ }
31976
+ };
31977
+ exports2.MessageList = MessageList2;
31978
+ }
31979
+ });
31980
+
31981
+ // ../../packages/core/dist/chunk-ST5RMVLG.cjs
31982
+ var require_chunk_ST5RMVLG = __commonJS({
31983
+ "../../packages/core/dist/chunk-ST5RMVLG.cjs"(exports2) {
31984
+ function mitt(all) {
31985
+ all = all || /* @__PURE__ */ new Map();
31986
+ return {
31987
+ /**
31988
+ * A Map of event names to registered handler functions.
31989
+ */
31990
+ all,
31991
+ /**
31992
+ * Register an event handler for the given type.
31993
+ * @param {string|symbol} type Type of event to listen for, or `'*'` for all events
31994
+ * @param {Function} handler Function to call in response to given event
31995
+ * @memberOf mitt
31996
+ */
31997
+ on(type, handler) {
31998
+ const handlers = all.get(type);
31999
+ if (handlers) {
32000
+ handlers.push(handler);
32001
+ } else {
32002
+ all.set(type, [handler]);
32136
32003
  }
32137
- } else {
32138
- if (messageV2.role === "assistant" && messageV2.content.parts[0]?.type !== `step-start`) {
32139
- messageV2.content.parts.unshift({ type: "step-start" });
32004
+ },
32005
+ /**
32006
+ * Remove an event handler for the given type.
32007
+ * If `handler` is omitted, all handlers of the given type are removed.
32008
+ * @param {string|symbol} type Type of event to unregister `handler` from (`'*'` to remove a wildcard handler)
32009
+ * @param {Function} [handler] Handler function to remove
32010
+ * @memberOf mitt
32011
+ */
32012
+ off(type, handler) {
32013
+ const handlers = all.get(type);
32014
+ if (handlers) {
32015
+ if (handler) {
32016
+ handlers.splice(handlers.indexOf(handler) >>> 0, 1);
32017
+ } else {
32018
+ all.set(type, []);
32019
+ }
32140
32020
  }
32141
- const existingIndex = shouldReplace && this.messages.findIndex((m) => m.id === id) || -1;
32142
- const existingMessage = existingIndex !== -1 && this.messages[existingIndex];
32143
- if (shouldReplace && existingMessage) {
32144
- this.messages[existingIndex] = messageV2;
32145
- } else if (!exists) {
32146
- this.messages.push(messageV2);
32021
+ },
32022
+ /**
32023
+ * Invoke all handlers for the given type.
32024
+ * If present, `'*'` handlers are invoked after type-matched handlers.
32025
+ *
32026
+ * Note: Manually firing '*' handlers is not supported.
32027
+ *
32028
+ * @param {string|symbol} type The event type to invoke
32029
+ * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler
32030
+ * @memberOf mitt
32031
+ */
32032
+ emit(type, evt) {
32033
+ let handlers = all.get(type);
32034
+ if (handlers) {
32035
+ handlers.slice().map((handler) => {
32036
+ handler(evt);
32037
+ });
32147
32038
  }
32148
- if (messageSource === `memory`) {
32149
- this.memoryMessages.add(messageV2);
32150
- } else if (messageSource === `response`) {
32151
- this.newResponseMessages.add(messageV2);
32152
- } else if (messageSource === `user`) {
32153
- this.newUserMessages.add(messageV2);
32154
- } else {
32155
- throw new Error(`Missing message source for message ${messageV2}`);
32039
+ handlers = all.get("*");
32040
+ if (handlers) {
32041
+ handlers.slice().map((handler) => {
32042
+ handler(type, evt);
32043
+ });
32156
32044
  }
32157
32045
  }
32158
- this.messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
32159
- return this;
32046
+ };
32047
+ }
32048
+ var AvailableHooks = /* @__PURE__ */ ((AvailableHooks2) => {
32049
+ AvailableHooks2["ON_EVALUATION"] = "onEvaluation";
32050
+ AvailableHooks2["ON_GENERATION"] = "onGeneration";
32051
+ return AvailableHooks2;
32052
+ })(AvailableHooks || {});
32053
+ var hooks = mitt();
32054
+ function registerHook(hook, action) {
32055
+ hooks.on(hook, action);
32056
+ }
32057
+ function executeHook(hook, data) {
32058
+ setImmediate(() => {
32059
+ hooks.emit(hook, data);
32060
+ });
32061
+ }
32062
+ exports2.AvailableHooks = AvailableHooks;
32063
+ exports2.executeHook = executeHook;
32064
+ exports2.registerHook = registerHook;
32065
+ }
32066
+ });
32067
+
32068
+ // ../../packages/core/dist/chunk-VBSKHNCY.cjs
32069
+ var require_chunk_VBSKHNCY = __commonJS({
32070
+ "../../packages/core/dist/chunk-VBSKHNCY.cjs"(exports2) {
32071
+ var chunkWWLMZIHW_cjs = require_chunk_WWLMZIHW();
32072
+ var chunkVHZPWE5L_cjs = require_chunk_VHZPWE5L();
32073
+ var chunkRFAN7FAT_cjs = require_chunk_RFAN7FAT();
32074
+ var ai = require_dist4();
32075
+ var zod = require_lib();
32076
+ var MastraLLMBase = class extends chunkVHZPWE5L_cjs.MastraBase {
32077
+ // @ts-ignore
32078
+ #mastra;
32079
+ #model;
32080
+ constructor({ name, model }) {
32081
+ super({
32082
+ component: chunkRFAN7FAT_cjs.RegisteredLogger.LLM,
32083
+ name
32084
+ });
32085
+ this.#model = model;
32160
32086
  }
32161
- inputToMastraMessageV2(message, messageSource) {
32162
- if (`threadId` in message && message.threadId && this.memoryInfo && message.threadId !== this.memoryInfo.threadId) {
32163
- throw new Error(
32164
- `Received input message with wrong threadId. Input ${message.threadId}, expected ${this.memoryInfo.threadId}`
32165
- );
32166
- }
32167
- if (`resourceId` in message && message.resourceId && this.memoryInfo?.resourceId && message.resourceId !== this.memoryInfo.resourceId) {
32168
- throw new Error(
32169
- `Received input message with wrong resourceId. Input ${message.resourceId}, expected ${this.memoryInfo.resourceId}`
32170
- );
32171
- }
32172
- if (_MessageList.isMastraMessageV1(message)) {
32173
- return this.mastraMessageV1ToMastraMessageV2(message, messageSource);
32174
- }
32175
- if (_MessageList.isMastraMessageV2(message)) {
32176
- return this.hydrateMastraMessageV2Fields(message);
32087
+ getProvider() {
32088
+ return this.#model.provider;
32089
+ }
32090
+ getModelId() {
32091
+ return this.#model.modelId;
32092
+ }
32093
+ getModel() {
32094
+ return this.#model;
32095
+ }
32096
+ convertToMessages(messages) {
32097
+ if (Array.isArray(messages)) {
32098
+ return messages.map((m) => {
32099
+ if (typeof m === "string") {
32100
+ return {
32101
+ role: "user",
32102
+ content: m
32103
+ };
32104
+ }
32105
+ return m;
32106
+ });
32177
32107
  }
32178
- if (_MessageList.isVercelCoreMessage(message)) {
32179
- return this.vercelCoreMessageToMastraMessageV2(message, messageSource);
32108
+ return [
32109
+ {
32110
+ role: "user",
32111
+ content: messages
32112
+ }
32113
+ ];
32114
+ }
32115
+ __registerPrimitives(p) {
32116
+ if (p.telemetry) {
32117
+ this.__setTelemetry(p.telemetry);
32180
32118
  }
32181
- if (_MessageList.isVercelUIMessage(message)) {
32182
- return this.vercelUIMessageToMastraMessageV2(message, messageSource);
32119
+ if (p.logger) {
32120
+ this.__setLogger(p.logger);
32183
32121
  }
32184
- throw new Error(`Found unhandled message ${JSON.stringify(message)}`);
32185
32122
  }
32186
- lastCreatedAt;
32187
- // this makes sure messages added in order will always have a date atleast 1ms apart.
32188
- generateCreatedAt(messageSource, start) {
32189
- start = start instanceof Date ? start : start ? new Date(start) : void 0;
32190
- if (start && !this.lastCreatedAt) {
32191
- this.lastCreatedAt = start.getTime();
32192
- return start;
32123
+ __registerMastra(p) {
32124
+ this.#mastra = p;
32125
+ }
32126
+ async __text(input) {
32127
+ this.logger.debug(`[LLMs:${this.name}] Generating text.`, { input });
32128
+ throw new Error("Method not implemented.");
32129
+ }
32130
+ async __textObject(input) {
32131
+ this.logger.debug(`[LLMs:${this.name}] Generating object.`, { input });
32132
+ throw new Error("Method not implemented.");
32133
+ }
32134
+ async generate(messages, options) {
32135
+ this.logger.debug(`[LLMs:${this.name}] Generating text.`, { messages, options });
32136
+ throw new Error("Method not implemented.");
32137
+ }
32138
+ async __stream(input) {
32139
+ this.logger.debug(`[LLMs:${this.name}] Streaming text.`, { input });
32140
+ throw new Error("Method not implemented.");
32141
+ }
32142
+ async __streamObject(input) {
32143
+ this.logger.debug(`[LLMs:${this.name}] Streaming object.`, { input });
32144
+ throw new Error("Method not implemented.");
32145
+ }
32146
+ async stream(messages, options) {
32147
+ this.logger.debug(`[LLMs:${this.name}] Streaming text.`, { messages, options });
32148
+ throw new Error("Method not implemented.");
32149
+ }
32150
+ };
32151
+ var MastraLLM = class extends MastraLLMBase {
32152
+ #model;
32153
+ #mastra;
32154
+ constructor({ model, mastra }) {
32155
+ super({ name: "aisdk", model });
32156
+ this.#model = model;
32157
+ if (mastra) {
32158
+ this.#mastra = mastra;
32159
+ if (mastra.getLogger()) {
32160
+ this.__setLogger(this.#mastra.getLogger());
32161
+ }
32193
32162
  }
32194
- if (start && messageSource === `memory`) {
32195
- return start;
32163
+ }
32164
+ __registerPrimitives(p) {
32165
+ if (p.telemetry) {
32166
+ this.__setTelemetry(p.telemetry);
32196
32167
  }
32197
- const now = /* @__PURE__ */ new Date();
32198
- const nowTime = start?.getTime() || now.getTime();
32199
- const lastTime = this.messages.reduce((p, m) => {
32200
- if (m.createdAt.getTime() > p) return m.createdAt.getTime();
32201
- return p;
32202
- }, this.lastCreatedAt || 0);
32203
- if (nowTime <= lastTime) {
32204
- const newDate = new Date(lastTime + 1);
32205
- this.lastCreatedAt = newDate.getTime();
32206
- return newDate;
32168
+ if (p.logger) {
32169
+ this.__setLogger(p.logger);
32207
32170
  }
32208
- this.lastCreatedAt = nowTime;
32209
- return now;
32210
32171
  }
32211
- newMessageId() {
32212
- if (this.generateMessageId) {
32213
- return this.generateMessageId();
32172
+ __registerMastra(p) {
32173
+ this.#mastra = p;
32174
+ }
32175
+ getProvider() {
32176
+ return this.#model.provider;
32177
+ }
32178
+ getModelId() {
32179
+ return this.#model.modelId;
32180
+ }
32181
+ getModel() {
32182
+ return this.#model;
32183
+ }
32184
+ async __text({
32185
+ runId,
32186
+ messages,
32187
+ maxSteps = 5,
32188
+ tools = {},
32189
+ temperature,
32190
+ toolChoice = "auto",
32191
+ onStepFinish,
32192
+ experimental_output,
32193
+ telemetry,
32194
+ threadId,
32195
+ resourceId,
32196
+ memory,
32197
+ runtimeContext,
32198
+ ...rest
32199
+ }) {
32200
+ const model = this.#model;
32201
+ this.logger.debug(`[LLM] - Generating text`, {
32202
+ runId,
32203
+ messages,
32204
+ maxSteps,
32205
+ threadId,
32206
+ resourceId,
32207
+ tools: Object.keys(tools)
32208
+ });
32209
+ const argsForExecute = {
32210
+ model,
32211
+ temperature,
32212
+ tools: {
32213
+ ...tools
32214
+ },
32215
+ toolChoice,
32216
+ maxSteps,
32217
+ onStepFinish: async (props) => {
32218
+ await onStepFinish?.(props);
32219
+ this.logger.debug("[LLM] - Step Change:", {
32220
+ text: props?.text,
32221
+ toolCalls: props?.toolCalls,
32222
+ toolResults: props?.toolResults,
32223
+ finishReason: props?.finishReason,
32224
+ usage: props?.usage,
32225
+ runId
32226
+ });
32227
+ if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
32228
+ this.logger.warn("Rate limit approaching, waiting 10 seconds", { runId });
32229
+ await chunkWWLMZIHW_cjs.delay(10 * 1e3);
32230
+ }
32231
+ },
32232
+ ...rest
32233
+ };
32234
+ let schema;
32235
+ if (experimental_output) {
32236
+ this.logger.debug("[LLM] - Using experimental output", {
32237
+ runId
32238
+ });
32239
+ if (typeof experimental_output.parse === "function") {
32240
+ schema = experimental_output;
32241
+ if (schema instanceof zod.z.ZodArray) {
32242
+ schema = schema._def.type;
32243
+ }
32244
+ } else {
32245
+ schema = ai.jsonSchema(experimental_output);
32246
+ }
32214
32247
  }
32215
- return crypto2.randomUUID();
32216
- }
32217
- mastraMessageV1ToMastraMessageV2(message, messageSource) {
32218
- const coreV2 = this.vercelCoreMessageToMastraMessageV2(
32219
- {
32220
- content: message.content,
32221
- role: message.role
32248
+ return await ai.generateText({
32249
+ messages,
32250
+ ...argsForExecute,
32251
+ experimental_telemetry: {
32252
+ ...this.experimental_telemetry,
32253
+ ...telemetry
32222
32254
  },
32223
- messageSource
32224
- );
32225
- return {
32226
- id: message.id,
32227
- role: coreV2.role,
32228
- createdAt: this.generateCreatedAt(messageSource, message.createdAt),
32229
- threadId: message.threadId,
32230
- resourceId: message.resourceId,
32231
- content: coreV2.content
32232
- };
32233
- }
32234
- hydrateMastraMessageV2Fields(message) {
32235
- if (!(message.createdAt instanceof Date)) message.createdAt = new Date(message.createdAt);
32236
- return message;
32255
+ experimental_output: schema ? ai.Output.object({
32256
+ schema
32257
+ }) : void 0
32258
+ });
32237
32259
  }
32238
- vercelUIMessageToMastraMessageV2(message, messageSource) {
32239
- const content = {
32240
- format: 2,
32241
- parts: message.parts
32260
+ async __textObject({
32261
+ messages,
32262
+ onStepFinish,
32263
+ maxSteps = 5,
32264
+ tools = {},
32265
+ structuredOutput,
32266
+ runId,
32267
+ temperature,
32268
+ toolChoice = "auto",
32269
+ telemetry,
32270
+ threadId,
32271
+ resourceId,
32272
+ memory,
32273
+ runtimeContext,
32274
+ ...rest
32275
+ }) {
32276
+ const model = this.#model;
32277
+ this.logger.debug(`[LLM] - Generating a text object`, { runId });
32278
+ const argsForExecute = {
32279
+ model,
32280
+ temperature,
32281
+ tools: {
32282
+ ...tools
32283
+ },
32284
+ maxSteps,
32285
+ toolChoice,
32286
+ onStepFinish: async (props) => {
32287
+ await onStepFinish?.(props);
32288
+ this.logger.debug("[LLM] - Step Change:", {
32289
+ text: props?.text,
32290
+ toolCalls: props?.toolCalls,
32291
+ toolResults: props?.toolResults,
32292
+ finishReason: props?.finishReason,
32293
+ usage: props?.usage,
32294
+ runId
32295
+ });
32296
+ if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
32297
+ this.logger.warn("Rate limit approaching, waiting 10 seconds", { runId });
32298
+ await chunkWWLMZIHW_cjs.delay(10 * 1e3);
32299
+ }
32300
+ },
32301
+ ...rest
32242
32302
  };
32243
- if (message.toolInvocations) content.toolInvocations = message.toolInvocations;
32244
- if (message.reasoning) content.reasoning = message.reasoning;
32245
- if (message.annotations) content.annotations = message.annotations;
32246
- if (message.experimental_attachments) {
32247
- content.experimental_attachments = message.experimental_attachments;
32303
+ let schema;
32304
+ let output = "object";
32305
+ if (typeof structuredOutput.parse === "function") {
32306
+ schema = structuredOutput;
32307
+ if (schema instanceof zod.z.ZodArray) {
32308
+ output = "array";
32309
+ schema = schema._def.type;
32310
+ }
32311
+ } else {
32312
+ schema = ai.jsonSchema(structuredOutput);
32248
32313
  }
32249
- return {
32250
- id: message.id || this.newMessageId(),
32251
- role: _MessageList.getRole(message),
32252
- createdAt: this.generateCreatedAt(messageSource, message.createdAt),
32253
- threadId: this.memoryInfo?.threadId,
32254
- resourceId: this.memoryInfo?.resourceId,
32255
- content
32256
- };
32314
+ return await ai.generateObject({
32315
+ messages,
32316
+ ...argsForExecute,
32317
+ output,
32318
+ schema,
32319
+ experimental_telemetry: {
32320
+ ...this.experimental_telemetry,
32321
+ ...telemetry
32322
+ }
32323
+ });
32257
32324
  }
32258
- vercelCoreMessageToMastraMessageV2(coreMessage, messageSource) {
32259
- const id = `id` in coreMessage ? coreMessage.id : this.newMessageId();
32260
- const parts = [];
32261
- const experimentalAttachments = [];
32262
- const toolInvocations = [];
32263
- if (typeof coreMessage.content === "string") {
32264
- parts.push({ type: "step-start" });
32265
- parts.push({
32266
- type: "text",
32267
- text: coreMessage.content
32268
- });
32269
- } else if (Array.isArray(coreMessage.content)) {
32270
- for (const part of coreMessage.content) {
32271
- switch (part.type) {
32272
- case "text":
32273
- parts.push({
32274
- type: "text",
32275
- text: part.text
32276
- });
32277
- break;
32278
- case "tool-call":
32279
- parts.push({
32280
- type: "tool-invocation",
32281
- toolInvocation: {
32282
- state: "call",
32283
- toolCallId: part.toolCallId,
32284
- toolName: part.toolName,
32285
- args: part.args
32286
- }
32287
- });
32288
- break;
32289
- case "tool-result":
32290
- const invocation = {
32291
- state: "result",
32292
- toolCallId: part.toolCallId,
32293
- toolName: part.toolName,
32294
- result: part.result ?? "",
32295
- // undefined will cause AI SDK to throw an error, but for client side tool calls this really could be undefined
32296
- args: {}
32297
- // when we combine this invocation onto the existing tool-call part it will have args already
32298
- };
32299
- parts.push({
32300
- type: "tool-invocation",
32301
- toolInvocation: invocation
32302
- });
32303
- toolInvocations.push(invocation);
32304
- break;
32305
- case "reasoning":
32306
- parts.push({
32307
- type: "reasoning",
32308
- reasoning: part.text,
32309
- // Assuming text is the main reasoning content
32310
- details: [{ type: "text", text: part.text, signature: part.signature }]
32311
- });
32312
- break;
32313
- case "redacted-reasoning":
32314
- parts.push({
32315
- type: "reasoning",
32316
- reasoning: "",
32317
- // No text reasoning for redacted parts
32318
- details: [{ type: "redacted", data: part.data }]
32319
- });
32320
- break;
32321
- case "file":
32322
- if (part.data instanceof URL) {
32323
- if (part.data.protocol !== "data:") {
32324
- experimentalAttachments.push({
32325
- name: part.filename,
32326
- url: part.data.toString(),
32327
- contentType: part.mimeType
32328
- });
32329
- } else {
32330
- try {
32331
- const base64Match = part.data.toString().match(/^data:[^;]+;base64,(.+)$/);
32332
- if (base64Match && base64Match[1]) {
32333
- parts.push({
32334
- type: "file",
32335
- mimeType: part.mimeType,
32336
- data: base64Match[1]
32337
- });
32338
- } else {
32339
- console.error(`Invalid data URL format: ${part.data}`);
32340
- }
32341
- } catch (error) {
32342
- console.error(`Failed to process data URL in CoreMessage file part: ${error}`, error);
32343
- }
32344
- }
32345
- } else {
32346
- try {
32347
- parts.push({
32348
- type: "file",
32349
- mimeType: part.mimeType,
32350
- data: convertDataContentToBase64String(part.data)
32351
- });
32352
- } catch (error) {
32353
- console.error(`Failed to convert binary data to base64 in CoreMessage file part: ${error}`, error);
32354
- }
32355
- }
32356
- break;
32357
- default:
32358
- throw new Error(`Found unknown CoreMessage content part type: ${part.type}`);
32325
+ async __stream({
32326
+ messages,
32327
+ onStepFinish,
32328
+ onFinish,
32329
+ maxSteps = 5,
32330
+ tools = {},
32331
+ runId,
32332
+ temperature,
32333
+ toolChoice = "auto",
32334
+ experimental_output,
32335
+ telemetry,
32336
+ threadId,
32337
+ resourceId,
32338
+ memory,
32339
+ runtimeContext,
32340
+ ...rest
32341
+ }) {
32342
+ const model = this.#model;
32343
+ this.logger.debug(`[LLM] - Streaming text`, {
32344
+ runId,
32345
+ threadId,
32346
+ resourceId,
32347
+ messages,
32348
+ maxSteps,
32349
+ tools: Object.keys(tools || {})
32350
+ });
32351
+ const argsForExecute = {
32352
+ model,
32353
+ temperature,
32354
+ tools: {
32355
+ ...tools
32356
+ },
32357
+ maxSteps,
32358
+ toolChoice,
32359
+ onStepFinish: async (props) => {
32360
+ await onStepFinish?.(props);
32361
+ this.logger.debug("[LLM] - Stream Step Change:", {
32362
+ text: props?.text,
32363
+ toolCalls: props?.toolCalls,
32364
+ toolResults: props?.toolResults,
32365
+ finishReason: props?.finishReason,
32366
+ usage: props?.usage,
32367
+ runId
32368
+ });
32369
+ if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
32370
+ this.logger.warn("Rate limit approaching, waiting 10 seconds", { runId });
32371
+ await chunkWWLMZIHW_cjs.delay(10 * 1e3);
32372
+ }
32373
+ },
32374
+ onFinish: async (props) => {
32375
+ await onFinish?.(props);
32376
+ this.logger.debug("[LLM] - Stream Finished:", {
32377
+ text: props?.text,
32378
+ toolCalls: props?.toolCalls,
32379
+ toolResults: props?.toolResults,
32380
+ finishReason: props?.finishReason,
32381
+ usage: props?.usage,
32382
+ runId,
32383
+ threadId,
32384
+ resourceId
32385
+ });
32386
+ },
32387
+ ...rest
32388
+ };
32389
+ let schema;
32390
+ if (experimental_output) {
32391
+ this.logger.debug("[LLM] - Using experimental output", {
32392
+ runId
32393
+ });
32394
+ if (typeof experimental_output.parse === "function") {
32395
+ schema = experimental_output;
32396
+ if (schema instanceof zod.z.ZodArray) {
32397
+ schema = schema._def.type;
32359
32398
  }
32399
+ } else {
32400
+ schema = ai.jsonSchema(experimental_output);
32360
32401
  }
32361
32402
  }
32362
- const content = {
32363
- format: 2,
32364
- parts
32365
- };
32366
- if (toolInvocations.length) content.toolInvocations = toolInvocations;
32367
- if (typeof coreMessage.content === `string`) content.content = coreMessage.content;
32368
- if (experimentalAttachments.length) content.experimental_attachments = experimentalAttachments;
32369
- return {
32370
- id,
32371
- role: _MessageList.getRole(coreMessage),
32372
- createdAt: this.generateCreatedAt(messageSource),
32373
- threadId: this.memoryInfo?.threadId,
32374
- resourceId: this.memoryInfo?.resourceId,
32375
- content
32376
- };
32377
- }
32378
- static isVercelUIMessage(msg) {
32379
- return !_MessageList.isMastraMessage(msg) && chunkDXLVS7ML_cjs.isUiMessage(msg);
32380
- }
32381
- static isVercelCoreMessage(msg) {
32382
- return !_MessageList.isMastraMessage(msg) && chunkDXLVS7ML_cjs.isCoreMessage(msg);
32383
- }
32384
- static isMastraMessage(msg) {
32385
- return _MessageList.isMastraMessageV2(msg) || _MessageList.isMastraMessageV1(msg);
32386
- }
32387
- static isMastraMessageV1(msg) {
32388
- return !_MessageList.isMastraMessageV2(msg) && (`threadId` in msg || `resourceId` in msg);
32389
- }
32390
- static isMastraMessageV2(msg) {
32391
- return Boolean(
32392
- msg.content && !Array.isArray(msg.content) && typeof msg.content !== `string` && // any newly saved Mastra message v2 shape will have content: { format: 2 }
32393
- `format` in msg.content && msg.content.format === 2
32394
- );
32395
- }
32396
- static getRole(message) {
32397
- if (message.role === `assistant` || message.role === `tool`) return `assistant`;
32398
- if (message.role === `user`) return `user`;
32399
- throw new Error(
32400
- `BUG: add handling for message role ${message.role} in message ${JSON.stringify(message, null, 2)}`
32401
- );
32403
+ return await ai.streamText({
32404
+ messages,
32405
+ ...argsForExecute,
32406
+ experimental_telemetry: {
32407
+ ...this.experimental_telemetry,
32408
+ ...telemetry
32409
+ },
32410
+ experimental_output: schema ? ai.Output.object({
32411
+ schema
32412
+ }) : void 0
32413
+ });
32402
32414
  }
32403
- static cacheKeyFromParts(parts) {
32404
- let key = ``;
32405
- for (const part of parts) {
32406
- key += part.type;
32407
- if (part.type === `text`) {
32408
- key += part.text.length;
32409
- }
32410
- if (part.type === `tool-invocation`) {
32411
- key += part.toolInvocation.toolCallId;
32412
- key += part.toolInvocation.state;
32413
- }
32414
- if (part.type === `reasoning`) {
32415
- key += part.reasoning.length;
32416
- }
32417
- if (part.type === `file`) {
32418
- key += part.data.length;
32419
- key += part.mimeType;
32415
+ async __streamObject({
32416
+ messages,
32417
+ runId,
32418
+ tools = {},
32419
+ maxSteps = 5,
32420
+ toolChoice = "auto",
32421
+ runtimeContext,
32422
+ threadId,
32423
+ resourceId,
32424
+ memory,
32425
+ temperature,
32426
+ onStepFinish,
32427
+ onFinish,
32428
+ structuredOutput,
32429
+ telemetry,
32430
+ ...rest
32431
+ }) {
32432
+ const model = this.#model;
32433
+ this.logger.debug(`[LLM] - Streaming structured output`, {
32434
+ runId,
32435
+ messages,
32436
+ maxSteps,
32437
+ tools: Object.keys(tools || {})
32438
+ });
32439
+ const finalTools = tools;
32440
+ const argsForExecute = {
32441
+ model,
32442
+ temperature,
32443
+ tools: {
32444
+ ...finalTools
32445
+ },
32446
+ maxSteps,
32447
+ toolChoice,
32448
+ onStepFinish: async (props) => {
32449
+ await onStepFinish?.(props);
32450
+ this.logger.debug("[LLM] - Stream Step Change:", {
32451
+ text: props?.text,
32452
+ toolCalls: props?.toolCalls,
32453
+ toolResults: props?.toolResults,
32454
+ finishReason: props?.finishReason,
32455
+ usage: props?.usage,
32456
+ runId,
32457
+ threadId,
32458
+ resourceId
32459
+ });
32460
+ if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
32461
+ this.logger.warn("Rate limit approaching, waiting 10 seconds", { runId });
32462
+ await chunkWWLMZIHW_cjs.delay(10 * 1e3);
32463
+ }
32464
+ },
32465
+ onFinish: async (props) => {
32466
+ await onFinish?.(props);
32467
+ this.logger.debug("[LLM] - Stream Finished:", {
32468
+ text: props?.text,
32469
+ toolCalls: props?.toolCalls,
32470
+ toolResults: props?.toolResults,
32471
+ finishReason: props?.finishReason,
32472
+ usage: props?.usage,
32473
+ runId,
32474
+ threadId,
32475
+ resourceId
32476
+ });
32477
+ },
32478
+ ...rest
32479
+ };
32480
+ let schema;
32481
+ let output = "object";
32482
+ if (typeof structuredOutput.parse === "function") {
32483
+ schema = structuredOutput;
32484
+ if (schema instanceof zod.z.ZodArray) {
32485
+ output = "array";
32486
+ schema = schema._def.type;
32420
32487
  }
32488
+ } else {
32489
+ schema = ai.jsonSchema(structuredOutput);
32421
32490
  }
32422
- return key;
32423
- }
32424
- static coreContentToString(content) {
32425
- if (typeof content === `string`) return content;
32426
- return content.reduce((p, c) => {
32427
- if (c.type === `text`) {
32428
- p += c.text;
32491
+ return ai.streamObject({
32492
+ messages,
32493
+ ...argsForExecute,
32494
+ output,
32495
+ schema,
32496
+ experimental_telemetry: {
32497
+ ...this.experimental_telemetry,
32498
+ ...telemetry
32429
32499
  }
32430
- return p;
32431
- }, "");
32500
+ });
32432
32501
  }
32433
- static cacheKeyFromContent(content) {
32434
- if (typeof content === `string`) return content;
32435
- let key = ``;
32436
- for (const part of content) {
32437
- key += part.type;
32438
- if (part.type === `text`) {
32439
- key += part.text.length;
32440
- }
32441
- if (part.type === `reasoning`) {
32442
- key += part.text.length;
32443
- }
32444
- if (part.type === `tool-call`) {
32445
- key += part.toolCallId;
32446
- key += part.toolName;
32447
- }
32448
- if (part.type === `tool-result`) {
32449
- key += part.toolCallId;
32450
- key += part.toolName;
32451
- }
32452
- if (part.type === `file`) {
32453
- key += part.filename;
32454
- key += part.mimeType;
32455
- }
32456
- if (part.type === `image`) {
32457
- key += part.image instanceof URL ? part.image.toString() : part.image.toString().length;
32458
- key += part.mimeType;
32459
- }
32460
- if (part.type === `redacted-reasoning`) {
32461
- key += part.data.length;
32462
- }
32502
+ async generate(messages, { maxSteps = 5, output, ...rest }) {
32503
+ const msgs = this.convertToMessages(messages);
32504
+ if (!output) {
32505
+ return await this.__text({
32506
+ messages: msgs,
32507
+ maxSteps,
32508
+ ...rest
32509
+ });
32463
32510
  }
32464
- return key;
32511
+ return await this.__textObject({
32512
+ messages: msgs,
32513
+ structuredOutput: output,
32514
+ maxSteps,
32515
+ ...rest
32516
+ });
32465
32517
  }
32466
- static messagesAreEqual(one, two) {
32467
- const oneUI = _MessageList.isVercelUIMessage(one) && one;
32468
- const twoUI = _MessageList.isVercelUIMessage(two) && two;
32469
- if (oneUI && !twoUI) return false;
32470
- if (oneUI && twoUI) {
32471
- return _MessageList.cacheKeyFromParts(one.parts) === _MessageList.cacheKeyFromParts(two.parts);
32472
- }
32473
- const oneCM = _MessageList.isVercelCoreMessage(one) && one;
32474
- const twoCM = _MessageList.isVercelCoreMessage(two) && two;
32475
- if (oneCM && !twoCM) return false;
32476
- if (oneCM && twoCM) {
32477
- return _MessageList.cacheKeyFromContent(oneCM.content) === _MessageList.cacheKeyFromContent(twoCM.content);
32478
- }
32479
- const oneMM1 = _MessageList.isMastraMessageV1(one) && one;
32480
- const twoMM1 = _MessageList.isMastraMessageV1(two) && two;
32481
- if (oneMM1 && !twoMM1) return false;
32482
- if (oneMM1 && twoMM1) {
32483
- return oneMM1.id === twoMM1.id && _MessageList.cacheKeyFromContent(oneMM1.content) === _MessageList.cacheKeyFromContent(twoMM1.content);
32484
- }
32485
- const oneMM2 = _MessageList.isMastraMessageV2(one) && one;
32486
- const twoMM2 = _MessageList.isMastraMessageV2(two) && two;
32487
- if (oneMM2 && !twoMM2) return false;
32488
- if (oneMM2 && twoMM2) {
32489
- return oneMM2.id === twoMM2.id && _MessageList.cacheKeyFromParts(oneMM2.content.parts) === _MessageList.cacheKeyFromParts(twoMM2.content.parts);
32518
+ async stream(messages, { maxSteps = 5, output, ...rest }) {
32519
+ const msgs = this.convertToMessages(messages);
32520
+ if (!output) {
32521
+ return await this.__stream({
32522
+ messages: msgs,
32523
+ maxSteps,
32524
+ ...rest
32525
+ });
32490
32526
  }
32491
- return true;
32527
+ return await this.__streamObject({
32528
+ messages: msgs,
32529
+ structuredOutput: output,
32530
+ maxSteps,
32531
+ ...rest
32532
+ });
32492
32533
  }
32493
32534
  };
32494
- exports2.MessageList = MessageList2;
32535
+ exports2.MastraLLM = MastraLLM;
32495
32536
  }
32496
32537
  });
32497
32538
 
@@ -38170,17 +38211,17 @@ ${err.message}`);
38170
38211
  }
38171
38212
  });
38172
38213
 
38173
- // ../../packages/core/dist/chunk-EZDS6FFZ.cjs
38174
- var require_chunk_EZDS6FFZ = __commonJS({
38175
- "../../packages/core/dist/chunk-EZDS6FFZ.cjs"(exports2) {
38176
- var chunkE4PVJAEL_cjs = require_chunk_E4PVJAEL();
38214
+ // ../../packages/core/dist/chunk-TO5645ZP.cjs
38215
+ var require_chunk_TO5645ZP = __commonJS({
38216
+ "../../packages/core/dist/chunk-TO5645ZP.cjs"(exports2) {
38217
+ var chunk3JGO7S6X_cjs = require_chunk_3JGO7S6X();
38218
+ var chunkKUJQVCEL_cjs = require_chunk_KUJQVCEL();
38177
38219
  var chunkST5RMVLG_cjs = require_chunk_ST5RMVLG();
38178
- var chunkI5OLBJ26_cjs = require_chunk_I5OLBJ26();
38220
+ var chunkVBSKHNCY_cjs = require_chunk_VBSKHNCY();
38179
38221
  var chunkTICDQWVJ_cjs = require_chunk_TICDQWVJ();
38180
- var chunkOB2PB6SX_cjs = require_chunk_OB2PB6SX();
38181
- var chunkDXLVS7ML_cjs = require_chunk_DXLVS7ML();
38182
- var chunkYEULQPUY_cjs = require_chunk_YEULQPUY();
38183
- var chunkSWW4EBUZ_cjs = require_chunk_SWW4EBUZ();
38222
+ var chunkWWLMZIHW_cjs = require_chunk_WWLMZIHW();
38223
+ var chunkVHZPWE5L_cjs = require_chunk_VHZPWE5L();
38224
+ var chunkRFAN7FAT_cjs = require_chunk_RFAN7FAT();
38184
38225
  var chunkLABUWBKX_cjs = require_chunk_LABUWBKX();
38185
38226
  var chunkRWTSGWWL_cjs = require_chunk_RWTSGWWL();
38186
38227
  var api = (init_esm(), __toCommonJS(esm_exports));
@@ -38242,7 +38283,7 @@ var require_chunk_EZDS6FFZ = __commonJS({
38242
38283
  prefix: "agent",
38243
38284
  excludeMethods: ["hasOwnMemory", "getMemory", "__primitive", "__registerMastra", "__registerPrimitives", "__setTools", "__setLogger", "__setTelemetry", "log", "getModel", "getInstructions", "getTools", "getLLM", "getWorkflows", "getDefaultGenerateOptions", "getDefaultStreamOptions", "getDescription"]
38244
38285
  })];
38245
- exports2.Agent = class Agent extends (_a = chunkYEULQPUY_cjs.MastraBase) {
38286
+ exports2.Agent = class Agent extends (_a = chunkVHZPWE5L_cjs.MastraBase) {
38246
38287
  id;
38247
38288
  name;
38248
38289
  #instructions;
@@ -38260,7 +38301,7 @@ var require_chunk_EZDS6FFZ = __commonJS({
38260
38301
  #voice;
38261
38302
  constructor(config) {
38262
38303
  super({
38263
- component: chunkSWW4EBUZ_cjs.RegisteredLogger.AGENT
38304
+ component: chunkRFAN7FAT_cjs.RegisteredLogger.AGENT
38264
38305
  });
38265
38306
  this.name = config.name;
38266
38307
  this.id = config.name;
@@ -38305,7 +38346,7 @@ var require_chunk_EZDS6FFZ = __commonJS({
38305
38346
  this.#voice?.addInstructions(config.instructions);
38306
38347
  }
38307
38348
  } else {
38308
- this.#voice = new chunkE4PVJAEL_cjs.DefaultVoice();
38349
+ this.#voice = new chunk3JGO7S6X_cjs.DefaultVoice();
38309
38350
  }
38310
38351
  }
38311
38352
  hasOwnMemory() {
@@ -38358,7 +38399,7 @@ var require_chunk_EZDS6FFZ = __commonJS({
38358
38399
  }));
38359
38400
  return voice;
38360
38401
  } else {
38361
- return new chunkE4PVJAEL_cjs.DefaultVoice();
38402
+ return new chunk3JGO7S6X_cjs.DefaultVoice();
38362
38403
  }
38363
38404
  }
38364
38405
  get instructions() {
@@ -38399,13 +38440,13 @@ var require_chunk_EZDS6FFZ = __commonJS({
38399
38440
  if (typeof this.#tools === "function") {
38400
38441
  throw new Error("Tools are not compatible when tools are a function. Please use getTools() instead.");
38401
38442
  }
38402
- return chunkDXLVS7ML_cjs.ensureToolProperties(this.#tools);
38443
+ return chunkWWLMZIHW_cjs.ensureToolProperties(this.#tools);
38403
38444
  }
38404
38445
  getTools({
38405
38446
  runtimeContext = new chunkLABUWBKX_cjs.RuntimeContext()
38406
38447
  } = {}) {
38407
38448
  if (typeof this.#tools !== "function") {
38408
- return chunkDXLVS7ML_cjs.ensureToolProperties(this.#tools);
38449
+ return chunkWWLMZIHW_cjs.ensureToolProperties(this.#tools);
38409
38450
  }
38410
38451
  const result = this.#tools({
38411
38452
  runtimeContext
@@ -38415,7 +38456,7 @@ var require_chunk_EZDS6FFZ = __commonJS({
38415
38456
  this.logger.error(`[Agent:${this.name}] - Function-based tools returned empty value`);
38416
38457
  throw new Error("Tools are required when using a function to provide them. The function returned an empty value.");
38417
38458
  }
38418
- return chunkDXLVS7ML_cjs.ensureToolProperties(tools);
38459
+ return chunkWWLMZIHW_cjs.ensureToolProperties(tools);
38419
38460
  });
38420
38461
  }
38421
38462
  get llm() {
@@ -38437,7 +38478,7 @@ var require_chunk_EZDS6FFZ = __commonJS({
38437
38478
  runtimeContext
38438
38479
  });
38439
38480
  return resolveMaybePromise(model, (model2) => {
38440
- const llm = new chunkI5OLBJ26_cjs.MastraLLM({
38481
+ const llm = new chunkVBSKHNCY_cjs.MastraLLM({
38441
38482
  model: model2,
38442
38483
  mastra: this.#mastra
38443
38484
  });
@@ -38564,7 +38605,7 @@ var require_chunk_EZDS6FFZ = __commonJS({
38564
38605
  memoryConfig,
38565
38606
  resourceId,
38566
38607
  runId,
38567
- messageList = new chunkOB2PB6SX_cjs.MessageList({
38608
+ messageList = new chunkKUJQVCEL_cjs.MessageList({
38568
38609
  threadId,
38569
38610
  resourceId
38570
38611
  })
@@ -38696,7 +38737,7 @@ var require_chunk_EZDS6FFZ = __commonJS({
38696
38737
  runtimeContext
38697
38738
  }) : this.model
38698
38739
  };
38699
- return [k, chunkDXLVS7ML_cjs.makeCoreTool(tool, options)];
38740
+ return [k, chunkWWLMZIHW_cjs.makeCoreTool(tool, options)];
38700
38741
  }));
38701
38742
  const assignedToolEntriesConverted = Object.fromEntries(assignedCoreToolEntries.filter((entry) => Boolean(entry)));
38702
38743
  toolsForRequest = {
@@ -38736,7 +38777,7 @@ var require_chunk_EZDS6FFZ = __commonJS({
38736
38777
  runtimeContext
38737
38778
  }) : this.model
38738
38779
  };
38739
- const convertedToCoreTool = chunkDXLVS7ML_cjs.makeCoreTool(toolObj, options, "toolset");
38780
+ const convertedToCoreTool = chunkWWLMZIHW_cjs.makeCoreTool(toolObj, options, "toolset");
38740
38781
  toolsForRequest[toolName] = convertedToCoreTool;
38741
38782
  }
38742
38783
  }
@@ -38777,7 +38818,7 @@ var require_chunk_EZDS6FFZ = __commonJS({
38777
38818
  runtimeContext
38778
38819
  }) : this.model
38779
38820
  };
38780
- const convertedToCoreTool = chunkDXLVS7ML_cjs.makeCoreTool(rest, options, "client-tool");
38821
+ const convertedToCoreTool = chunkWWLMZIHW_cjs.makeCoreTool(rest, options, "client-tool");
38781
38822
  toolsForRequest[toolName] = convertedToCoreTool;
38782
38823
  }
38783
38824
  }
@@ -38844,7 +38885,7 @@ var require_chunk_EZDS6FFZ = __commonJS({
38844
38885
  let mastraProxy = void 0;
38845
38886
  const logger = this.logger;
38846
38887
  if (this.#mastra) {
38847
- mastraProxy = chunkDXLVS7ML_cjs.createMastraProxy({
38888
+ mastraProxy = chunkWWLMZIHW_cjs.createMastraProxy({
38848
38889
  mastra: this.#mastra,
38849
38890
  logger
38850
38891
  });
@@ -38935,7 +38976,7 @@ var require_chunk_EZDS6FFZ = __commonJS({
38935
38976
  runId,
38936
38977
  runtimeContext
38937
38978
  });
38938
- const messageList = new chunkOB2PB6SX_cjs.MessageList({
38979
+ const messageList = new chunkKUJQVCEL_cjs.MessageList({
38939
38980
  threadId,
38940
38981
  resourceId,
38941
38982
  generateMessageId
@@ -38997,7 +39038,7 @@ var require_chunk_EZDS6FFZ = __commonJS({
38997
39038
  systemMessage,
38998
39039
  memorySystemMessage: memorySystemMessage || void 0
38999
39040
  });
39000
- const processedList = new chunkOB2PB6SX_cjs.MessageList({
39041
+ const processedList = new chunkKUJQVCEL_cjs.MessageList({
39001
39042
  threadId,
39002
39043
  resourceId
39003
39044
  }).addSystem(instructions || `${this.instructions}.`).addSystem(memorySystemMessage).add(context2 || [], "user").add(processedMemoryMessages, "memory").add(messageList.get.input.v2(), "user").get.all.prompt();
@@ -39334,6 +39375,7 @@ var require_chunk_EZDS6FFZ = __commonJS({
39334
39375
  runId,
39335
39376
  toolChoice,
39336
39377
  experimental_output,
39378
+ telemetry,
39337
39379
  memory: this.getMemory(),
39338
39380
  runtimeContext,
39339
39381
  ...args
@@ -40080,7 +40122,7 @@ var require_chunk_EZDS6FFZ = __commonJS({
40080
40122
  const logger = this.logger;
40081
40123
  let mastraProxy = void 0;
40082
40124
  if (this.#mastra) {
40083
- mastraProxy = chunkDXLVS7ML_cjs.createMastraProxy({
40125
+ mastraProxy = chunkWWLMZIHW_cjs.createMastraProxy({
40084
40126
  mastra: this.#mastra,
40085
40127
  logger
40086
40128
  });
@@ -41461,7 +41503,7 @@ var require_chunk_EZDS6FFZ = __commonJS({
41461
41503
  return key.includes("&&");
41462
41504
  }
41463
41505
  };
41464
- var LegacyWorkflow = class extends chunkYEULQPUY_cjs.MastraBase {
41506
+ var LegacyWorkflow = class extends chunkVHZPWE5L_cjs.MastraBase {
41465
41507
  name;
41466
41508
  triggerSchema;
41467
41509
  resultSchema;
@@ -42471,18 +42513,18 @@ var require_chunk_EZDS6FFZ = __commonJS({
42471
42513
  // ../../packages/core/dist/agent/index.cjs
42472
42514
  var require_agent = __commonJS({
42473
42515
  "../../packages/core/dist/agent/index.cjs"(exports2) {
42474
- var chunkEZDS6FFZ_cjs = require_chunk_EZDS6FFZ();
42475
- var chunkOB2PB6SX_cjs = require_chunk_OB2PB6SX();
42516
+ var chunkTO5645ZP_cjs = require_chunk_TO5645ZP();
42517
+ var chunkKUJQVCEL_cjs = require_chunk_KUJQVCEL();
42476
42518
  Object.defineProperty(exports2, "Agent", {
42477
42519
  enumerable: true,
42478
42520
  get: function() {
42479
- return chunkEZDS6FFZ_cjs.Agent;
42521
+ return chunkTO5645ZP_cjs.Agent;
42480
42522
  }
42481
42523
  });
42482
42524
  Object.defineProperty(exports2, "MessageList", {
42483
42525
  enumerable: true,
42484
42526
  get: function() {
42485
- return chunkOB2PB6SX_cjs.MessageList;
42527
+ return chunkKUJQVCEL_cjs.MessageList;
42486
42528
  }
42487
42529
  });
42488
42530
  }