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