@mastra/deployer 0.15.3 → 0.16.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,8 +19,9 @@ import { timeout } from 'hono/timeout';
19
19
  import { HTTPException } from 'hono/http-exception';
20
20
  import { getAgentCardByIdHandler as getAgentCardByIdHandler$1, getAgentExecutionHandler as getAgentExecutionHandler$1 } from '@mastra/server/handlers/a2a';
21
21
  import { stream } from 'hono/streaming';
22
- import { getAgentsHandler as getAgentsHandler$1, getAgentByIdHandler as getAgentByIdHandler$1, getEvalsByAgentIdHandler as getEvalsByAgentIdHandler$1, getLiveEvalsByAgentIdHandler as getLiveEvalsByAgentIdHandler$1, generateLegacyHandler as generateLegacyHandler$1, generateHandler as generateHandler$1, generateVNextHandler as generateVNextHandler$1, streamVNextGenerateHandler as streamVNextGenerateHandler$1, streamGenerateLegacyHandler as streamGenerateLegacyHandler$1, streamGenerateHandler as streamGenerateHandler$1, streamVNextUIMessageHandler as streamVNextUIMessageHandler$1, updateAgentModelHandler as updateAgentModelHandler$1 } from '@mastra/server/handlers/agents';
23
22
  import { bodyLimit } from 'hono/body-limit';
23
+ import { getAgentBuilderActionsHandler as getAgentBuilderActionsHandler$1, getAgentBuilderActionByIdHandler as getAgentBuilderActionByIdHandler$1, getAgentBuilderActionRunsHandler as getAgentBuilderActionRunsHandler$1, getAgentBuilderActionRunExecutionResultHandler as getAgentBuilderActionRunExecutionResultHandler$1, getAgentBuilderActionRunByIdHandler as getAgentBuilderActionRunByIdHandler$1, resumeAgentBuilderActionHandler as resumeAgentBuilderActionHandler$1, resumeAsyncAgentBuilderActionHandler as resumeAsyncAgentBuilderActionHandler$1, streamAgentBuilderActionHandler as streamAgentBuilderActionHandler$1, streamVNextAgentBuilderActionHandler as streamVNextAgentBuilderActionHandler$1, createAgentBuilderActionRunHandler as createAgentBuilderActionRunHandler$1, startAsyncAgentBuilderActionHandler as startAsyncAgentBuilderActionHandler$1, startAgentBuilderActionRunHandler as startAgentBuilderActionRunHandler$1, watchAgentBuilderActionHandler as watchAgentBuilderActionHandler$1, cancelAgentBuilderActionRunHandler as cancelAgentBuilderActionRunHandler$1, sendAgentBuilderActionRunEventHandler as sendAgentBuilderActionRunEventHandler$1 } from '@mastra/server/handlers/agent-builder';
24
+ import { getAgentsHandler as getAgentsHandler$1, getAgentByIdHandler as getAgentByIdHandler$1, getEvalsByAgentIdHandler as getEvalsByAgentIdHandler$1, getLiveEvalsByAgentIdHandler as getLiveEvalsByAgentIdHandler$1, generateLegacyHandler as generateLegacyHandler$1, generateHandler as generateHandler$1, generateVNextHandler as generateVNextHandler$1, streamVNextGenerateHandler as streamVNextGenerateHandler$1, streamGenerateLegacyHandler as streamGenerateLegacyHandler$1, streamGenerateHandler as streamGenerateHandler$1, streamVNextUIMessageHandler as streamVNextUIMessageHandler$1, updateAgentModelHandler as updateAgentModelHandler$1 } from '@mastra/server/handlers/agents';
24
25
  import { Agent } from '@mastra/core/agent';
25
26
  import { z } from 'zod';
26
27
  import { getAgentToolHandler as getAgentToolHandler$1, executeAgentToolHandler as executeAgentToolHandler$1, getToolsHandler as getToolsHandler$1, getToolByIdHandler as getToolByIdHandler$1, executeToolHandler as executeToolHandler$1 } from '@mastra/server/handlers/tools';
@@ -280,13 +281,13 @@ var Response2 = class _Response {
280
281
  });
281
282
  Object.setPrototypeOf(Response2, GlobalResponse);
282
283
  Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
283
- function writeFromReadableStream(stream6, writable) {
284
- if (stream6.locked) {
284
+ function writeFromReadableStream(stream7, writable) {
285
+ if (stream7.locked) {
285
286
  throw new TypeError("ReadableStream is locked.");
286
287
  } else if (writable.destroyed) {
287
288
  return;
288
289
  }
289
- const reader = stream6.getReader();
290
+ const reader = stream7.getReader();
290
291
  const handleError2 = () => {
291
292
  };
292
293
  writable.on("error", handleError2);
@@ -553,18 +554,18 @@ var ENCODINGS = {
553
554
  gzip: ".gz"
554
555
  };
555
556
  var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
556
- var createStreamBody = (stream6) => {
557
+ var createStreamBody = (stream7) => {
557
558
  const body = new ReadableStream({
558
559
  start(controller) {
559
- stream6.on("data", (chunk) => {
560
+ stream7.on("data", (chunk) => {
560
561
  controller.enqueue(chunk);
561
562
  });
562
- stream6.on("end", () => {
563
+ stream7.on("end", () => {
563
564
  controller.close();
564
565
  });
565
566
  },
566
567
  cancel() {
567
- stream6.destroy();
568
+ stream7.destroy();
568
569
  }
569
570
  });
570
571
  return body;
@@ -653,10 +654,10 @@ var serveStatic = (options = { root: "" }) => {
653
654
  end = size - 1;
654
655
  }
655
656
  const chunksize = end - start + 1;
656
- const stream6 = createReadStream(path, { start, end });
657
+ const stream7 = createReadStream(path, { start, end });
657
658
  c2.header("Content-Length", chunksize.toString());
658
659
  c2.header("Content-Range", `bytes ${start}-${end}/${stats.size}`);
659
- return c2.body(createStreamBody(stream6), 206);
660
+ return c2.body(createStreamBody(stream7), 206);
660
661
  };
661
662
  };
662
663
  var RENDER_TYPE = {
@@ -795,21 +796,21 @@ function c(e2, t2, n2) {
795
796
  return e2 && t2 in e2 ? e2[t2] ?? n2 : n2;
796
797
  }
797
798
  function i(...e2) {
798
- return e2.reduce((e3, t2) => {
799
+ return e2.reduce(((e3, t2) => {
799
800
  if (!t2) return e3;
800
801
  let n2;
801
802
  return ("tags" in e3 && e3.tags || "tags" in t2 && t2.tags) && (n2 = Array.from(/* @__PURE__ */ new Set([...c(e3, "tags", []), ...c(t2, "tags", [])]))), { ...e3, ...t2, tags: n2, responses: { ...c(e3, "responses", {}), ...c(t2, "responses", {}) }, parameters: m(e3.parameters, t2.parameters) };
802
- }, {});
803
+ }), {});
803
804
  }
804
805
  function p({ path: e2, method: t2, data: n2, schema: s3 }) {
805
- e2 = ((e3) => e3.split("/").map((e4) => {
806
+ e2 = ((e3) => e3.split("/").map(((e4) => {
806
807
  let t3 = e4;
807
808
  if (t3.startsWith(":")) {
808
809
  const e5 = t3.match(/^:([^{?]+)(?:{(.+)})?(\?)?$/);
809
810
  e5 ? t3 = `{${e5[1]}}` : (t3 = t3.slice(1, t3.length), t3.endsWith("?") && (t3 = t3.slice(0, -1)), t3 = `{${t3}}`);
810
811
  }
811
812
  return t3;
812
- }).join("/"))(e2);
813
+ })).join("/"))(e2);
813
814
  const o2 = t2.toLowerCase();
814
815
  if ("all" === o2) {
815
816
  if (!n2) return;
@@ -818,30 +819,30 @@ function p({ path: e2, method: t2, data: n2, schema: s3 }) {
818
819
  r.set(e2, { ...t3, ...n2, parameters: m(t3.parameters, n2.parameters) });
819
820
  } else r.set(e2, n2);
820
821
  } else {
821
- const t3 = function(e3) {
822
+ const t3 = (function(e3) {
822
823
  const t4 = Array.from(r.keys());
823
824
  let n3 = {};
824
825
  for (const s4 of t4) e3.match(s4) && (n3 = i(n3, r.get(s4) ?? {}));
825
826
  return n3;
826
- }(e2);
827
+ })(e2);
827
828
  s3[e2] = { ...s3[e2] ? s3[e2] : {}, [o2]: { responses: {}, operationId: a(o2, e2), ...i(t3, s3[e2]?.[o2], n2) } };
828
829
  }
829
830
  }
830
831
  var f = (e2) => "$ref" in e2 ? e2.$ref : `${e2.in} ${e2.name}`;
831
832
  function m(...e2) {
832
- const t2 = e2.flatMap((e3) => e3 ?? []).reduce((e3, t3) => (e3.set(f(t3), t3), e3), /* @__PURE__ */ new Map());
833
+ const t2 = e2.flatMap(((e3) => e3 ?? [])).reduce(((e3, t3) => (e3.set(f(t3), t3), e3)), /* @__PURE__ */ new Map());
833
834
  return Array.from(t2.values());
834
835
  }
835
836
  function l(e2, { excludeStaticFile: t2 = true, exclude: n2 = [] }) {
836
837
  const s3 = {}, o2 = Array.isArray(n2) ? n2 : [n2];
837
- for (const [n3, a2] of Object.entries(e2)) if (!o2.some((e3) => "string" == typeof e3 ? n3 === e3 : e3.test(n3)) && (!n3.includes("*") || n3.includes("{")) && (!t2 || (!n3.includes(".") || n3.includes("{")))) {
838
+ for (const [n3, a2] of Object.entries(e2)) if (!o2.some(((e3) => "string" == typeof e3 ? n3 === e3 : e3.test(n3))) && (!n3.includes("*") || n3.includes("{")) && (!t2 || (!n3.includes(".") || n3.includes("{")))) {
838
839
  for (const e3 of Object.keys(a2)) {
839
840
  const t3 = a2[e3];
840
841
  if (n3.includes("{")) {
841
842
  t3.parameters || (t3.parameters = []);
842
- const e4 = n3.split("/").filter((e5) => e5.startsWith("{") && !t3.parameters.find((t4) => "path" === t4.in && t4.name === e5.slice(1, e5.length - 1)));
843
+ const e4 = n3.split("/").filter(((e5) => e5.startsWith("{") && !t3.parameters.find(((t4) => "path" === t4.in && t4.name === e5.slice(1, e5.length - 1)))));
843
844
  for (const n4 of e4) {
844
- const e5 = n4.slice(1, n4.length - 1), s4 = t3.parameters.findIndex((t4) => "param" === t4.in && t4.name === e5);
845
+ const e5 = n4.slice(1, n4.length - 1), s4 = t3.parameters.findIndex(((t4) => "param" === t4.in && t4.name === e5));
845
846
  -1 !== s4 ? t3.parameters[s4].in = "path" : t3.parameters.push({ schema: { type: "string" }, in: "path", name: e5, required: true });
846
847
  }
847
848
  }
@@ -859,7 +860,7 @@ function h(e2, t2) {
859
860
  return async (o2) => (s3 || (s3 = await y(e2, t2, n2, o2)), o2.json(s3));
860
861
  }
861
862
  async function y(t2, s3 = u, o2 = d, a2) {
862
- const r2 = { ...u, ...s3 }, c2 = { ...d, ...o2 }, i2 = r2.documentation ?? {}, f2 = await async function(t3, s4, o3) {
863
+ const r2 = { ...u, ...s3 }, c2 = { ...d, ...o2 }, i2 = r2.documentation ?? {}, f2 = await (async function(t3, s4, o3) {
863
864
  const a3 = {};
864
865
  for (const r3 of t3.routes) {
865
866
  if (!(e in r3.handler)) {
@@ -872,7 +873,7 @@ async function y(t2, s3 = u, o2 = d, a2) {
872
873
  o3.components = { ...o3.components, ...m2 ?? {} }, p({ method: r3.method, path: r3.path, data: f3, schema: a3 });
873
874
  }
874
875
  return a3;
875
- }(t2, r2, c2);
876
+ })(t2, r2, c2);
876
877
  for (const e2 in f2) for (const t3 in f2[e2]) {
877
878
  const n2 = f2[e2][t3]?.hide;
878
879
  if (n2) {
@@ -880,11 +881,11 @@ async function y(t2, s3 = u, o2 = d, a2) {
880
881
  "boolean" == typeof n2 ? s4 = n2 : "function" == typeof n2 && (a2 ? s4 = n2(a2) : console.warn(`'c' is not defined, cannot evaluate hide function for ${t3} ${e2}`)), s4 && delete f2[e2][t3];
881
882
  }
882
883
  }
883
- return { openapi: c2.version, ...{ ...i2, tags: i2.tags?.filter((e2) => !r2.excludeTags?.includes(e2?.name)), info: { title: "Hono Documentation", description: "Development documentation", version: "0.0.0", ...i2.info }, paths: { ...l(f2, r2), ...i2.paths }, components: { ...i2.components, schemas: { ...c2.components, ...i2.components?.schemas } } } };
884
+ return { openapi: c2.version, ...{ ...i2, tags: i2.tags?.filter(((e2) => !r2.excludeTags?.includes(e2?.name))), info: { title: "Hono Documentation", description: "Development documentation", version: "0.0.0", ...i2.info }, paths: { ...l(f2, r2), ...i2.paths }, components: { ...i2.components, schemas: { ...c2.components, ...i2.components?.schemas } } } };
884
885
  }
885
886
  function w(n2) {
886
887
  const { validateResponse: s3, ...o2 } = n2;
887
- return Object.assign(async (e2, o3) => {
888
+ return Object.assign((async (e2, o3) => {
888
889
  if (await o3(), s3 && n2.responses) {
889
890
  const o4 = e2.res.status, a2 = e2.res.headers.get("content-type");
890
891
  if (o4 && a2) {
@@ -903,7 +904,7 @@ function w(n2) {
903
904
  }
904
905
  }
905
906
  }
906
- }, { [e]: { resolver: (e2, t2) => x(e2, o2, t2) } });
907
+ }), { [e]: { resolver: (e2, t2) => x(e2, o2, t2) } });
907
908
  }
908
909
  async function x(e2, t2, n2 = {}) {
909
910
  let s3 = {};
@@ -954,15 +955,15 @@ async function getAgentExecutionHandler(c2) {
954
955
  if (body.method === "message/stream") {
955
956
  return stream(
956
957
  c2,
957
- async (stream6) => {
958
+ async (stream7) => {
958
959
  try {
959
- stream6.onAbort(() => {
960
+ stream7.onAbort(() => {
960
961
  if (!result.locked) {
961
962
  return result.cancel();
962
963
  }
963
964
  });
964
965
  for await (const chunk of result) {
965
- await stream6.write(JSON.stringify(chunk) + "");
966
+ await stream7.write(JSON.stringify(chunk) + "");
966
967
  }
967
968
  } catch (err) {
968
969
  logger2.error("Error in message/stream stream: " + err?.message);
@@ -992,250 +993,1128 @@ var defaultAuthConfig = {
992
993
  return user.role === "admin";
993
994
  }
994
995
  }
995
- return false;
996
+ return false;
997
+ },
998
+ allow: true
999
+ }
1000
+ ]
1001
+ };
1002
+
1003
+ // src/server/handlers/auth/helpers.ts
1004
+ var isDevPlaygroundRequest = (req) => {
1005
+ return req.header("x-mastra-dev-playground") === "true" && process.env.MASTRA_DEV === "true";
1006
+ };
1007
+ var isProtectedPath = (path, method, authConfig) => {
1008
+ const protectedAccess = [...defaultAuthConfig.protected || [], ...authConfig.protected || []];
1009
+ return isAnyMatch(path, method, protectedAccess);
1010
+ };
1011
+ var canAccessPublicly = (path, method, authConfig) => {
1012
+ const publicAccess = [...defaultAuthConfig.public || [], ...authConfig.public || []];
1013
+ return isAnyMatch(path, method, publicAccess);
1014
+ };
1015
+ var isAnyMatch = (path, method, patterns) => {
1016
+ if (!patterns) {
1017
+ return false;
1018
+ }
1019
+ for (const patternPathOrMethod of patterns) {
1020
+ if (patternPathOrMethod instanceof RegExp) {
1021
+ if (patternPathOrMethod.test(path)) {
1022
+ return true;
1023
+ }
1024
+ }
1025
+ if (typeof patternPathOrMethod === "string" && pathMatchesPattern(path, patternPathOrMethod)) {
1026
+ return true;
1027
+ }
1028
+ if (Array.isArray(patternPathOrMethod) && patternPathOrMethod.length === 2) {
1029
+ const [pattern, methodOrMethods] = patternPathOrMethod;
1030
+ if (pathMatchesPattern(path, pattern) && matchesOrIncludes(methodOrMethods, method)) {
1031
+ return true;
1032
+ }
1033
+ }
1034
+ }
1035
+ return false;
1036
+ };
1037
+ var pathMatchesPattern = (path, pattern) => {
1038
+ if (pattern.endsWith("*")) {
1039
+ const prefix = pattern.slice(0, -1);
1040
+ return path.startsWith(prefix);
1041
+ }
1042
+ return path === pattern;
1043
+ };
1044
+ var pathMatchesRule = (path, rulePath) => {
1045
+ if (!rulePath) return true;
1046
+ if (typeof rulePath === "string") {
1047
+ return pathMatchesPattern(path, rulePath);
1048
+ }
1049
+ if (rulePath instanceof RegExp) {
1050
+ console.log("rulePath", rulePath, path, rulePath.test(path));
1051
+ return rulePath.test(path);
1052
+ }
1053
+ if (Array.isArray(rulePath)) {
1054
+ return rulePath.some((p2) => pathMatchesPattern(path, p2));
1055
+ }
1056
+ return false;
1057
+ };
1058
+ var matchesOrIncludes = (values, value) => {
1059
+ if (typeof values === "string") {
1060
+ return values === value;
1061
+ }
1062
+ if (Array.isArray(values)) {
1063
+ return values.includes(value);
1064
+ }
1065
+ return false;
1066
+ };
1067
+ var checkRules = async (rules, path, method, user) => {
1068
+ for (const i2 in rules || []) {
1069
+ const rule = rules?.[i2];
1070
+ if (!pathMatchesRule(path, rule.path)) {
1071
+ continue;
1072
+ }
1073
+ if (rule.methods && !matchesOrIncludes(rule.methods, method)) {
1074
+ continue;
1075
+ }
1076
+ const condition = rule.condition;
1077
+ if (typeof condition === "function") {
1078
+ const allowed = await Promise.resolve().then(() => condition(user)).catch(() => false);
1079
+ if (allowed) {
1080
+ return true;
1081
+ }
1082
+ } else if (rule.allow) {
1083
+ return true;
1084
+ }
1085
+ }
1086
+ return false;
1087
+ };
1088
+
1089
+ // src/server/handlers/auth/index.ts
1090
+ var authenticationMiddleware = async (c2, next) => {
1091
+ const mastra = c2.get("mastra");
1092
+ const authConfig = mastra.getServer()?.experimental_auth;
1093
+ if (!authConfig) {
1094
+ return next();
1095
+ }
1096
+ if (isDevPlaygroundRequest(c2.req)) {
1097
+ return next();
1098
+ }
1099
+ if (!isProtectedPath(c2.req.path, c2.req.method, authConfig)) {
1100
+ return next();
1101
+ }
1102
+ if (canAccessPublicly(c2.req.path, c2.req.method, authConfig)) {
1103
+ return next();
1104
+ }
1105
+ const authHeader = c2.req.header("Authorization");
1106
+ let token = authHeader ? authHeader.replace("Bearer ", "") : null;
1107
+ if (!token && c2.req.query("apiKey")) {
1108
+ token = c2.req.query("apiKey") || null;
1109
+ }
1110
+ if (!token) {
1111
+ return c2.json({ error: "Authentication required" }, 401);
1112
+ }
1113
+ try {
1114
+ let user;
1115
+ if (typeof authConfig.authenticateToken === "function") {
1116
+ user = await authConfig.authenticateToken(token, c2.req);
1117
+ } else {
1118
+ throw new Error("No token verification method configured");
1119
+ }
1120
+ if (!user) {
1121
+ return c2.json({ error: "Invalid or expired token" }, 401);
1122
+ }
1123
+ c2.get("runtimeContext").set("user", user);
1124
+ return next();
1125
+ } catch (err) {
1126
+ console.error(err);
1127
+ return c2.json({ error: "Invalid or expired token" }, 401);
1128
+ }
1129
+ };
1130
+ var authorizationMiddleware = async (c2, next) => {
1131
+ const mastra = c2.get("mastra");
1132
+ const authConfig = mastra.getServer()?.experimental_auth;
1133
+ if (!authConfig) {
1134
+ return next();
1135
+ }
1136
+ const path = c2.req.path;
1137
+ const method = c2.req.method;
1138
+ if (isDevPlaygroundRequest(c2.req)) {
1139
+ return next();
1140
+ }
1141
+ if (!isProtectedPath(c2.req.path, c2.req.method, authConfig)) {
1142
+ return next();
1143
+ }
1144
+ if (canAccessPublicly(path, method, authConfig)) {
1145
+ return next();
1146
+ }
1147
+ const user = c2.get("runtimeContext").get("user");
1148
+ if ("authorizeUser" in authConfig && typeof authConfig.authorizeUser === "function") {
1149
+ try {
1150
+ const isAuthorized = await authConfig.authorizeUser(user, c2.req);
1151
+ if (isAuthorized) {
1152
+ return next();
1153
+ }
1154
+ return c2.json({ error: "Access denied" }, 403);
1155
+ } catch (err) {
1156
+ console.error(err);
1157
+ return c2.json({ error: "Authorization error" }, 500);
1158
+ }
1159
+ }
1160
+ if ("authorize" in authConfig && typeof authConfig.authorize === "function") {
1161
+ try {
1162
+ const isAuthorized = await authConfig.authorize(path, method, user, c2);
1163
+ if (isAuthorized) {
1164
+ return next();
1165
+ }
1166
+ return c2.json({ error: "Access denied" }, 403);
1167
+ } catch (err) {
1168
+ console.error(err);
1169
+ return c2.json({ error: "Authorization error" }, 500);
1170
+ }
1171
+ }
1172
+ if ("rules" in authConfig && authConfig.rules && authConfig.rules.length > 0) {
1173
+ const isAuthorized = await checkRules(authConfig.rules, path, method, user);
1174
+ if (isAuthorized) {
1175
+ return next();
1176
+ }
1177
+ return c2.json({ error: "Access denied" }, 403);
1178
+ }
1179
+ if (defaultAuthConfig.rules && defaultAuthConfig.rules.length > 0) {
1180
+ const isAuthorized = await checkRules(defaultAuthConfig.rules, path, method, user);
1181
+ if (isAuthorized) {
1182
+ return next();
1183
+ }
1184
+ }
1185
+ return c2.json({ error: "Access denied" }, 403);
1186
+ };
1187
+
1188
+ // src/server/handlers/client.ts
1189
+ var clients = /* @__PURE__ */ new Set();
1190
+ var hotReloadDisabled = false;
1191
+ function handleClientsRefresh(c2) {
1192
+ const stream7 = new ReadableStream({
1193
+ start(controller) {
1194
+ clients.add(controller);
1195
+ controller.enqueue("data: connected\n\n");
1196
+ c2.req.raw.signal.addEventListener("abort", () => {
1197
+ clients.delete(controller);
1198
+ });
1199
+ }
1200
+ });
1201
+ return new Response(stream7, {
1202
+ headers: {
1203
+ "Content-Type": "text/event-stream",
1204
+ "Cache-Control": "no-cache",
1205
+ Connection: "keep-alive",
1206
+ "Access-Control-Allow-Origin": "*"
1207
+ }
1208
+ });
1209
+ }
1210
+ function handleTriggerClientsRefresh(c2) {
1211
+ clients.forEach((controller) => {
1212
+ try {
1213
+ controller.enqueue("data: refresh\n\n");
1214
+ } catch {
1215
+ clients.delete(controller);
1216
+ }
1217
+ });
1218
+ return c2.json({ success: true, clients: clients.size });
1219
+ }
1220
+ function disableHotReload() {
1221
+ hotReloadDisabled = true;
1222
+ console.log("\u{1F512} Hot reload disabled for template installation");
1223
+ }
1224
+ function enableHotReload() {
1225
+ hotReloadDisabled = false;
1226
+ console.log("\u{1F513} Hot reload re-enabled after template installation");
1227
+ }
1228
+ function isHotReloadDisabled() {
1229
+ return hotReloadDisabled;
1230
+ }
1231
+ function handleError(error, defaultMessage) {
1232
+ const apiError = error;
1233
+ throw new HTTPException(apiError.status || 500, {
1234
+ message: apiError.message || defaultMessage,
1235
+ cause: apiError.cause
1236
+ });
1237
+ }
1238
+ function errorHandler(err, c2, isDev) {
1239
+ if (err instanceof HTTPException) {
1240
+ if (isDev) {
1241
+ return c2.json({ error: err.message, cause: err.cause, stack: err.stack }, err.status);
1242
+ }
1243
+ return c2.json({ error: err.message }, err.status);
1244
+ }
1245
+ console.error(err);
1246
+ return c2.json({ error: "Internal Server Error" }, 500);
1247
+ }
1248
+
1249
+ // src/server/handlers/root.ts
1250
+ async function rootHandler(c2) {
1251
+ return c2.text("Hello to the Mastra API!");
1252
+ }
1253
+ async function getAgentBuilderActionsHandler(c2) {
1254
+ try {
1255
+ const mastra = c2.get("mastra");
1256
+ const actions = await getAgentBuilderActionsHandler$1({
1257
+ mastra
1258
+ });
1259
+ return c2.json(actions);
1260
+ } catch (error) {
1261
+ return handleError(error, "Error getting agent builder actions");
1262
+ }
1263
+ }
1264
+ async function getAgentBuilderActionByIdHandler(c2) {
1265
+ try {
1266
+ const mastra = c2.get("mastra");
1267
+ const actionId = c2.req.param("actionId");
1268
+ const action = await getAgentBuilderActionByIdHandler$1({
1269
+ mastra,
1270
+ actionId
1271
+ });
1272
+ return c2.json(action);
1273
+ } catch (error) {
1274
+ return handleError(error, "Error getting agent builder action by ID");
1275
+ }
1276
+ }
1277
+ async function createAgentBuilderActionRunHandler(c2) {
1278
+ try {
1279
+ const mastra = c2.get("mastra");
1280
+ const actionId = c2.req.param("actionId");
1281
+ const runId = c2.req.query("runId");
1282
+ const result = await createAgentBuilderActionRunHandler$1({
1283
+ mastra,
1284
+ actionId,
1285
+ runId
1286
+ });
1287
+ return c2.json(result);
1288
+ } catch (error) {
1289
+ return handleError(error, "Error creating agent builder action run");
1290
+ }
1291
+ }
1292
+ async function startAsyncAgentBuilderActionHandler(c2) {
1293
+ try {
1294
+ const mastra = c2.get("mastra");
1295
+ const runtimeContext = c2.get("runtimeContext");
1296
+ const actionId = c2.req.param("actionId");
1297
+ const { inputData } = await c2.req.json();
1298
+ const runId = c2.req.query("runId");
1299
+ disableHotReload();
1300
+ const result = await startAsyncAgentBuilderActionHandler$1({
1301
+ mastra,
1302
+ runtimeContext,
1303
+ actionId,
1304
+ runId,
1305
+ inputData
1306
+ });
1307
+ enableHotReload();
1308
+ return c2.json(result);
1309
+ } catch (error) {
1310
+ enableHotReload();
1311
+ return handleError(error, "Error starting async agent builder action");
1312
+ }
1313
+ }
1314
+ async function startAgentBuilderActionRunHandler(c2) {
1315
+ try {
1316
+ const mastra = c2.get("mastra");
1317
+ const runtimeContext = c2.get("runtimeContext");
1318
+ const actionId = c2.req.param("actionId");
1319
+ const { inputData } = await c2.req.json();
1320
+ const runId = c2.req.query("runId");
1321
+ await startAgentBuilderActionRunHandler$1({
1322
+ mastra,
1323
+ runtimeContext,
1324
+ actionId,
1325
+ runId,
1326
+ inputData
1327
+ });
1328
+ return c2.json({ message: "Agent builder action run started" });
1329
+ } catch (error) {
1330
+ return handleError(error, "Error starting agent builder action run");
1331
+ }
1332
+ }
1333
+ async function watchAgentBuilderActionHandler(c2) {
1334
+ try {
1335
+ const mastra = c2.get("mastra");
1336
+ const logger2 = mastra.getLogger();
1337
+ const actionId = c2.req.param("actionId");
1338
+ const runId = c2.req.query("runId");
1339
+ const eventType = c2.req.query("eventType");
1340
+ if (!runId) {
1341
+ throw new HTTPException(400, { message: "runId required to watch action" });
1342
+ }
1343
+ c2.header("Transfer-Encoding", "chunked");
1344
+ return stream(c2, async (stream7) => {
1345
+ try {
1346
+ disableHotReload();
1347
+ const result = await watchAgentBuilderActionHandler$1({
1348
+ mastra,
1349
+ actionId,
1350
+ runId,
1351
+ eventType
1352
+ });
1353
+ const reader = result.getReader();
1354
+ stream7.onAbort(() => {
1355
+ void reader.cancel("request aborted");
1356
+ });
1357
+ let chunkResult;
1358
+ while ((chunkResult = await reader.read()) && !chunkResult.done) {
1359
+ await stream7.write(JSON.stringify(chunkResult.value) + "");
1360
+ }
1361
+ enableHotReload();
1362
+ } catch (err) {
1363
+ enableHotReload();
1364
+ logger2.error("Error in watch stream: " + (err?.message ?? "Unknown error"));
1365
+ }
1366
+ });
1367
+ } catch (error) {
1368
+ enableHotReload();
1369
+ return handleError(error, "Error watching agent builder action");
1370
+ }
1371
+ }
1372
+ async function streamAgentBuilderActionHandler(c2) {
1373
+ try {
1374
+ const mastra = c2.get("mastra");
1375
+ const runtimeContext = c2.get("runtimeContext");
1376
+ const logger2 = mastra.getLogger();
1377
+ const actionId = c2.req.param("actionId");
1378
+ const { inputData } = await c2.req.json();
1379
+ const runId = c2.req.query("runId");
1380
+ c2.header("Transfer-Encoding", "chunked");
1381
+ return stream(
1382
+ c2,
1383
+ async (stream7) => {
1384
+ try {
1385
+ disableHotReload();
1386
+ const result = await streamAgentBuilderActionHandler$1({
1387
+ mastra,
1388
+ actionId,
1389
+ runId,
1390
+ inputData,
1391
+ runtimeContext
1392
+ });
1393
+ const reader = result.stream.getReader();
1394
+ stream7.onAbort(() => {
1395
+ void reader.cancel("request aborted");
1396
+ });
1397
+ let chunkResult;
1398
+ while ((chunkResult = await reader.read()) && !chunkResult.done) {
1399
+ await stream7.write(JSON.stringify(chunkResult.value) + "");
1400
+ }
1401
+ } catch (err) {
1402
+ logger2.error("Error in action stream: " + (err?.message ?? "Unknown error"));
1403
+ }
1404
+ await stream7.close();
1405
+ enableHotReload();
1406
+ },
1407
+ async (err) => {
1408
+ logger2.error("Error in action stream: " + err?.message);
1409
+ }
1410
+ );
1411
+ } catch (error) {
1412
+ enableHotReload();
1413
+ return handleError(error, "Error streaming agent builder action");
1414
+ }
1415
+ }
1416
+ async function streamVNextAgentBuilderActionHandler(c2) {
1417
+ try {
1418
+ const mastra = c2.get("mastra");
1419
+ const runtimeContext = c2.get("runtimeContext");
1420
+ const logger2 = mastra.getLogger();
1421
+ const actionId = c2.req.param("actionId");
1422
+ const { inputData } = await c2.req.json();
1423
+ const runId = c2.req.query("runId");
1424
+ c2.header("Transfer-Encoding", "chunked");
1425
+ return stream(
1426
+ c2,
1427
+ async (stream7) => {
1428
+ try {
1429
+ disableHotReload();
1430
+ const result = await streamVNextAgentBuilderActionHandler$1({
1431
+ mastra,
1432
+ actionId,
1433
+ runId,
1434
+ inputData,
1435
+ runtimeContext
1436
+ });
1437
+ const reader = result.getReader();
1438
+ stream7.onAbort(() => {
1439
+ void reader.cancel("request aborted");
1440
+ });
1441
+ let chunkResult;
1442
+ while ((chunkResult = await reader.read()) && !chunkResult.done) {
1443
+ await stream7.write(JSON.stringify(chunkResult.value) + "");
1444
+ }
1445
+ } catch (err) {
1446
+ logger2.error("Error in action VNext stream: " + (err?.message ?? "Unknown error"));
1447
+ }
1448
+ enableHotReload();
1449
+ },
1450
+ async (err) => {
1451
+ logger2.error("Error in action VNext stream: " + err?.message);
1452
+ }
1453
+ );
1454
+ } catch (error) {
1455
+ enableHotReload();
1456
+ return handleError(error, "Error streaming VNext agent builder action");
1457
+ }
1458
+ }
1459
+ async function resumeAsyncAgentBuilderActionHandler(c2) {
1460
+ try {
1461
+ const mastra = c2.get("mastra");
1462
+ const runtimeContext = c2.get("runtimeContext");
1463
+ const actionId = c2.req.param("actionId");
1464
+ const runId = c2.req.query("runId");
1465
+ const { step, resumeData } = await c2.req.json();
1466
+ if (!runId) {
1467
+ throw new HTTPException(400, { message: "runId required to resume action" });
1468
+ }
1469
+ disableHotReload();
1470
+ const result = await resumeAsyncAgentBuilderActionHandler$1({
1471
+ mastra,
1472
+ runtimeContext,
1473
+ actionId,
1474
+ runId,
1475
+ body: { step, resumeData }
1476
+ });
1477
+ enableHotReload();
1478
+ return c2.json(result);
1479
+ } catch (error) {
1480
+ enableHotReload();
1481
+ return handleError(error, "Error resuming async agent builder action");
1482
+ }
1483
+ }
1484
+ async function resumeAgentBuilderActionHandler(c2) {
1485
+ try {
1486
+ const mastra = c2.get("mastra");
1487
+ const runtimeContext = c2.get("runtimeContext");
1488
+ const actionId = c2.req.param("actionId");
1489
+ const runId = c2.req.query("runId");
1490
+ const { step, resumeData } = await c2.req.json();
1491
+ if (!runId) {
1492
+ throw new HTTPException(400, { message: "runId required to resume action" });
1493
+ }
1494
+ disableHotReload();
1495
+ await resumeAgentBuilderActionHandler$1({
1496
+ mastra,
1497
+ runtimeContext,
1498
+ actionId,
1499
+ runId,
1500
+ body: { step, resumeData }
1501
+ });
1502
+ enableHotReload();
1503
+ return c2.json({ message: "Action run resumed" });
1504
+ } catch (error) {
1505
+ enableHotReload();
1506
+ return handleError(error, "Error resuming agent builder action");
1507
+ }
1508
+ }
1509
+ async function getAgentBuilderActionRunsHandler(c2) {
1510
+ try {
1511
+ const mastra = c2.get("mastra");
1512
+ const actionId = c2.req.param("actionId");
1513
+ const { fromDate, toDate, limit, offset, resourceId } = c2.req.query();
1514
+ const runs = await getAgentBuilderActionRunsHandler$1({
1515
+ mastra,
1516
+ actionId,
1517
+ fromDate: fromDate ? new Date(fromDate) : void 0,
1518
+ toDate: toDate ? new Date(toDate) : void 0,
1519
+ limit: limit ? Number(limit) : void 0,
1520
+ offset: offset ? Number(offset) : void 0,
1521
+ resourceId
1522
+ });
1523
+ return c2.json(runs);
1524
+ } catch (error) {
1525
+ return handleError(error, "Error getting agent builder action runs");
1526
+ }
1527
+ }
1528
+ async function getAgentBuilderActionRunByIdHandler(c2) {
1529
+ try {
1530
+ const mastra = c2.get("mastra");
1531
+ const actionId = c2.req.param("actionId");
1532
+ const runId = c2.req.param("runId");
1533
+ const run = await getAgentBuilderActionRunByIdHandler$1({
1534
+ mastra,
1535
+ actionId,
1536
+ runId
1537
+ });
1538
+ return c2.json(run);
1539
+ } catch (error) {
1540
+ return handleError(error, "Error getting agent builder action run by ID");
1541
+ }
1542
+ }
1543
+ async function getAgentBuilderActionRunExecutionResultHandler(c2) {
1544
+ try {
1545
+ const mastra = c2.get("mastra");
1546
+ const actionId = c2.req.param("actionId");
1547
+ const runId = c2.req.param("runId");
1548
+ const result = await getAgentBuilderActionRunExecutionResultHandler$1({
1549
+ mastra,
1550
+ actionId,
1551
+ runId
1552
+ });
1553
+ return c2.json(result);
1554
+ } catch (error) {
1555
+ return handleError(error, "Error getting agent builder action run execution result");
1556
+ }
1557
+ }
1558
+ async function cancelAgentBuilderActionRunHandler(c2) {
1559
+ try {
1560
+ const mastra = c2.get("mastra");
1561
+ const actionId = c2.req.param("actionId");
1562
+ const runId = c2.req.param("runId");
1563
+ const result = await cancelAgentBuilderActionRunHandler$1({
1564
+ mastra,
1565
+ actionId,
1566
+ runId
1567
+ });
1568
+ return c2.json(result);
1569
+ } catch (error) {
1570
+ return handleError(error, "Error cancelling agent builder action run");
1571
+ }
1572
+ }
1573
+ async function sendAgentBuilderActionRunEventHandler(c2) {
1574
+ try {
1575
+ const mastra = c2.get("mastra");
1576
+ const actionId = c2.req.param("actionId");
1577
+ const runId = c2.req.param("runId");
1578
+ const { event, data } = await c2.req.json();
1579
+ const result = await sendAgentBuilderActionRunEventHandler$1({
1580
+ mastra,
1581
+ actionId,
1582
+ runId,
1583
+ event,
1584
+ data
1585
+ });
1586
+ return c2.json(result);
1587
+ } catch (error) {
1588
+ return handleError(error, "Error sending agent builder action run event");
1589
+ }
1590
+ }
1591
+
1592
+ // src/server/handlers/routes/agent-builder/router.ts
1593
+ function agentBuilderRouter(bodyLimitOptions) {
1594
+ const router = new Hono();
1595
+ router.get(
1596
+ "/",
1597
+ w({
1598
+ description: "Get all agent builder actions",
1599
+ tags: ["agent-builder"],
1600
+ responses: {
1601
+ 200: {
1602
+ description: "List of all agent builder actions"
1603
+ }
1604
+ }
1605
+ }),
1606
+ getAgentBuilderActionsHandler
1607
+ );
1608
+ router.get(
1609
+ "/:actionId",
1610
+ w({
1611
+ description: "Get agent builder action by ID",
1612
+ tags: ["agent-builder"],
1613
+ parameters: [
1614
+ {
1615
+ name: "actionId",
1616
+ in: "path",
1617
+ required: true,
1618
+ schema: { type: "string" }
1619
+ }
1620
+ ],
1621
+ responses: {
1622
+ 200: {
1623
+ description: "Agent builder action details"
1624
+ },
1625
+ 404: {
1626
+ description: "Agent builder action not found"
1627
+ }
1628
+ }
1629
+ }),
1630
+ getAgentBuilderActionByIdHandler
1631
+ );
1632
+ router.get(
1633
+ "/:actionId/runs",
1634
+ w({
1635
+ description: "Get all runs for an agent builder action",
1636
+ tags: ["agent-builder"],
1637
+ parameters: [
1638
+ {
1639
+ name: "actionId",
1640
+ in: "path",
1641
+ required: true,
1642
+ schema: { type: "string" }
1643
+ },
1644
+ { name: "fromDate", in: "query", required: false, schema: { type: "string", format: "date-time" } },
1645
+ { name: "toDate", in: "query", required: false, schema: { type: "string", format: "date-time" } },
1646
+ { name: "limit", in: "query", required: false, schema: { type: "number" } },
1647
+ { name: "offset", in: "query", required: false, schema: { type: "number" } },
1648
+ { name: "resourceId", in: "query", required: false, schema: { type: "string" } }
1649
+ ],
1650
+ responses: {
1651
+ 200: {
1652
+ description: "List of agent builder action runs from storage"
1653
+ }
1654
+ }
1655
+ }),
1656
+ getAgentBuilderActionRunsHandler
1657
+ );
1658
+ router.get(
1659
+ "/:actionId/runs/:runId/execution-result",
1660
+ w({
1661
+ description: "Get execution result for an agent builder action run",
1662
+ tags: ["agent-builder"],
1663
+ parameters: [
1664
+ {
1665
+ name: "actionId",
1666
+ in: "path",
1667
+ required: true,
1668
+ schema: { type: "string" }
1669
+ },
1670
+ {
1671
+ name: "runId",
1672
+ in: "path",
1673
+ required: true,
1674
+ schema: { type: "string" }
1675
+ }
1676
+ ],
1677
+ responses: {
1678
+ 200: {
1679
+ description: "Agent builder action run execution result"
1680
+ },
1681
+ 404: {
1682
+ description: "Agent builder action run execution result not found"
1683
+ }
1684
+ }
1685
+ }),
1686
+ getAgentBuilderActionRunExecutionResultHandler
1687
+ );
1688
+ router.get(
1689
+ "/:actionId/runs/:runId",
1690
+ w({
1691
+ description: "Get agent builder action run by ID",
1692
+ tags: ["agent-builder"],
1693
+ parameters: [
1694
+ {
1695
+ name: "actionId",
1696
+ in: "path",
1697
+ required: true,
1698
+ schema: { type: "string" }
1699
+ },
1700
+ {
1701
+ name: "runId",
1702
+ in: "path",
1703
+ required: true,
1704
+ schema: { type: "string" }
1705
+ }
1706
+ ],
1707
+ responses: {
1708
+ 200: {
1709
+ description: "Agent builder action run by ID"
1710
+ },
1711
+ 404: {
1712
+ description: "Agent builder action run not found"
1713
+ }
1714
+ }
1715
+ }),
1716
+ getAgentBuilderActionRunByIdHandler
1717
+ );
1718
+ router.post(
1719
+ "/:actionId/resume",
1720
+ w({
1721
+ description: "Resume a suspended agent builder action step",
1722
+ tags: ["agent-builder"],
1723
+ parameters: [
1724
+ {
1725
+ name: "actionId",
1726
+ in: "path",
1727
+ required: true,
1728
+ schema: { type: "string" }
1729
+ },
1730
+ {
1731
+ name: "runId",
1732
+ in: "query",
1733
+ required: true,
1734
+ schema: { type: "string" }
1735
+ }
1736
+ ],
1737
+ requestBody: {
1738
+ required: true,
1739
+ content: {
1740
+ "application/json": {
1741
+ schema: {
1742
+ type: "object",
1743
+ properties: {
1744
+ step: {
1745
+ oneOf: [{ type: "string" }, { type: "array", items: { type: "string" } }]
1746
+ },
1747
+ resumeData: { type: "object" },
1748
+ runtimeContext: {
1749
+ type: "object",
1750
+ description: "Runtime context for the agent builder action execution"
1751
+ }
1752
+ },
1753
+ required: ["step"]
1754
+ }
1755
+ }
1756
+ }
1757
+ }
1758
+ }),
1759
+ resumeAgentBuilderActionHandler
1760
+ );
1761
+ router.post(
1762
+ "/:actionId/resume-async",
1763
+ bodyLimit(bodyLimitOptions),
1764
+ w({
1765
+ description: "Resume a suspended agent builder action step",
1766
+ tags: ["agent-builder"],
1767
+ parameters: [
1768
+ {
1769
+ name: "actionId",
1770
+ in: "path",
1771
+ required: true,
1772
+ schema: { type: "string" }
1773
+ },
1774
+ {
1775
+ name: "runId",
1776
+ in: "query",
1777
+ required: true,
1778
+ schema: { type: "string" }
1779
+ }
1780
+ ],
1781
+ requestBody: {
1782
+ required: true,
1783
+ content: {
1784
+ "application/json": {
1785
+ schema: {
1786
+ type: "object",
1787
+ properties: {
1788
+ step: {
1789
+ oneOf: [{ type: "string" }, { type: "array", items: { type: "string" } }]
1790
+ },
1791
+ resumeData: { type: "object" },
1792
+ runtimeContext: {
1793
+ type: "object",
1794
+ description: "Runtime context for the agent builder action execution"
1795
+ }
1796
+ },
1797
+ required: ["step"]
1798
+ }
1799
+ }
1800
+ }
1801
+ }
1802
+ }),
1803
+ resumeAsyncAgentBuilderActionHandler
1804
+ );
1805
+ router.post(
1806
+ "/:actionId/stream",
1807
+ w({
1808
+ description: "Stream agent builder action in real-time",
1809
+ parameters: [
1810
+ {
1811
+ name: "actionId",
1812
+ in: "path",
1813
+ required: true,
1814
+ schema: { type: "string" }
1815
+ },
1816
+ {
1817
+ name: "runId",
1818
+ in: "query",
1819
+ required: false,
1820
+ schema: { type: "string" }
1821
+ }
1822
+ ],
1823
+ requestBody: {
1824
+ required: true,
1825
+ content: {
1826
+ "application/json": {
1827
+ schema: {
1828
+ type: "object",
1829
+ properties: {
1830
+ inputData: { type: "object" },
1831
+ runtimeContext: {
1832
+ type: "object",
1833
+ description: "Runtime context for the agent builder action execution"
1834
+ }
1835
+ }
1836
+ }
1837
+ }
1838
+ }
1839
+ },
1840
+ responses: {
1841
+ 200: {
1842
+ description: "agent builder action run started"
1843
+ },
1844
+ 404: {
1845
+ description: "agent builder action not found"
1846
+ }
1847
+ },
1848
+ tags: ["agent-builder"]
1849
+ }),
1850
+ streamAgentBuilderActionHandler
1851
+ );
1852
+ router.post(
1853
+ "/:actionId/streamVNext",
1854
+ w({
1855
+ description: "Stream agent builder action in real-time using the VNext streaming API",
1856
+ parameters: [
1857
+ {
1858
+ name: "actionId",
1859
+ in: "path",
1860
+ required: true,
1861
+ schema: { type: "string" }
1862
+ },
1863
+ {
1864
+ name: "runId",
1865
+ in: "query",
1866
+ required: false,
1867
+ schema: { type: "string" }
1868
+ }
1869
+ ],
1870
+ requestBody: {
1871
+ required: true,
1872
+ content: {
1873
+ "application/json": {
1874
+ schema: {
1875
+ type: "object",
1876
+ properties: {
1877
+ inputData: { type: "object" },
1878
+ runtimeContext: {
1879
+ type: "object",
1880
+ description: "Runtime context for the agent builder action execution"
1881
+ }
1882
+ }
1883
+ }
1884
+ }
1885
+ }
1886
+ },
1887
+ responses: {
1888
+ 200: {
1889
+ description: "agent builder action run started"
1890
+ },
1891
+ 404: {
1892
+ description: "agent builder action not found"
1893
+ }
1894
+ },
1895
+ tags: ["agent-builder"]
1896
+ }),
1897
+ streamVNextAgentBuilderActionHandler
1898
+ );
1899
+ router.post(
1900
+ "/:actionId/create-run",
1901
+ bodyLimit(bodyLimitOptions),
1902
+ w({
1903
+ description: "Create a new agent builder action run",
1904
+ tags: ["agent-builder"],
1905
+ parameters: [
1906
+ {
1907
+ name: "actionId",
1908
+ in: "path",
1909
+ required: true,
1910
+ schema: { type: "string" }
1911
+ },
1912
+ {
1913
+ name: "runId",
1914
+ in: "query",
1915
+ required: false,
1916
+ schema: { type: "string" }
1917
+ }
1918
+ ],
1919
+ responses: {
1920
+ 200: {
1921
+ description: "New agent builder action run created"
1922
+ }
1923
+ }
1924
+ }),
1925
+ createAgentBuilderActionRunHandler
1926
+ );
1927
+ router.post(
1928
+ "/:actionId/start-async",
1929
+ bodyLimit(bodyLimitOptions),
1930
+ w({
1931
+ description: "Execute/Start an agent builder action",
1932
+ tags: ["agent-builder"],
1933
+ parameters: [
1934
+ {
1935
+ name: "actionId",
1936
+ in: "path",
1937
+ required: true,
1938
+ schema: { type: "string" }
1939
+ },
1940
+ {
1941
+ name: "runId",
1942
+ in: "query",
1943
+ required: false,
1944
+ schema: { type: "string" }
1945
+ }
1946
+ ],
1947
+ requestBody: {
1948
+ required: true,
1949
+ content: {
1950
+ "application/json": {
1951
+ schema: {
1952
+ type: "object",
1953
+ properties: {
1954
+ inputData: { type: "object" },
1955
+ runtimeContext: {
1956
+ type: "object",
1957
+ description: "Runtime context for the agent builder action execution"
1958
+ }
1959
+ }
1960
+ }
1961
+ }
1962
+ }
1963
+ },
1964
+ responses: {
1965
+ 200: {
1966
+ description: "agent builder action execution result"
1967
+ },
1968
+ 404: {
1969
+ description: "agent builder action not found"
1970
+ }
1971
+ }
1972
+ }),
1973
+ startAsyncAgentBuilderActionHandler
1974
+ );
1975
+ router.post(
1976
+ "/:actionId/start",
1977
+ w({
1978
+ description: "Create and start a new agent builder action run",
1979
+ tags: ["agent-builder"],
1980
+ parameters: [
1981
+ {
1982
+ name: "actionId",
1983
+ in: "path",
1984
+ required: true,
1985
+ schema: { type: "string" }
1986
+ },
1987
+ {
1988
+ name: "runId",
1989
+ in: "query",
1990
+ required: true,
1991
+ schema: { type: "string" }
1992
+ }
1993
+ ],
1994
+ requestBody: {
1995
+ required: true,
1996
+ content: {
1997
+ "application/json": {
1998
+ schema: {
1999
+ type: "object",
2000
+ properties: {
2001
+ inputData: { type: "object" },
2002
+ runtimeContext: {
2003
+ type: "object",
2004
+ description: "Runtime context for the agent builder action execution"
2005
+ }
2006
+ }
2007
+ }
2008
+ }
2009
+ }
2010
+ },
2011
+ responses: {
2012
+ 200: {
2013
+ description: "agent builder action run started"
2014
+ },
2015
+ 404: {
2016
+ description: "agent builder action not found"
2017
+ }
2018
+ }
2019
+ }),
2020
+ startAgentBuilderActionRunHandler
2021
+ );
2022
+ router.get(
2023
+ "/:actionId/watch",
2024
+ w({
2025
+ description: "Watch agent builder action transitions in real-time",
2026
+ parameters: [
2027
+ {
2028
+ name: "actionId",
2029
+ in: "path",
2030
+ required: true,
2031
+ schema: { type: "string" }
2032
+ },
2033
+ {
2034
+ name: "runId",
2035
+ in: "query",
2036
+ required: false,
2037
+ schema: { type: "string" }
2038
+ },
2039
+ {
2040
+ name: "eventType",
2041
+ in: "query",
2042
+ required: false,
2043
+ schema: { type: "string", enum: ["watch", "watch-v2"] }
2044
+ }
2045
+ ],
2046
+ tags: ["agent-builder"],
2047
+ responses: {
2048
+ 200: {
2049
+ description: "agent builder action transitions in real-time"
2050
+ }
2051
+ }
2052
+ }),
2053
+ watchAgentBuilderActionHandler
2054
+ );
2055
+ router.post(
2056
+ "/:actionId/runs/:runId/cancel",
2057
+ w({
2058
+ description: "Cancel an agent builder action run",
2059
+ parameters: [
2060
+ {
2061
+ name: "actionId",
2062
+ in: "path",
2063
+ required: true,
2064
+ schema: { type: "string" }
2065
+ },
2066
+ {
2067
+ name: "runId",
2068
+ in: "path",
2069
+ required: true,
2070
+ schema: { type: "string" }
2071
+ }
2072
+ ],
2073
+ tags: ["agent-builder"],
2074
+ responses: {
2075
+ 200: {
2076
+ description: "agent builder action run cancelled"
2077
+ }
2078
+ }
2079
+ }),
2080
+ cancelAgentBuilderActionRunHandler
2081
+ );
2082
+ router.post(
2083
+ "/:actionId/runs/:runId/send-event",
2084
+ w({
2085
+ description: "Send an event to an agent builder action run",
2086
+ parameters: [
2087
+ {
2088
+ name: "actionId",
2089
+ in: "path",
2090
+ required: true,
2091
+ schema: { type: "string" }
2092
+ },
2093
+ {
2094
+ name: "runId",
2095
+ in: "path",
2096
+ required: true,
2097
+ schema: { type: "string" }
2098
+ }
2099
+ ],
2100
+ requestBody: {
2101
+ required: true,
2102
+ content: {
2103
+ "application/json": {
2104
+ schema: { type: "object", properties: { event: { type: "string" }, data: { type: "object" } } }
2105
+ }
2106
+ }
996
2107
  },
997
- allow: true
998
- }
999
- ]
1000
- };
1001
-
1002
- // src/server/handlers/auth/helpers.ts
1003
- var isDevPlaygroundRequest = (req) => {
1004
- return req.header("x-mastra-dev-playground") === "true" && process.env.MASTRA_DEV === "true";
1005
- };
1006
- var isProtectedPath = (path, method, authConfig) => {
1007
- const protectedAccess = [...defaultAuthConfig.protected || [], ...authConfig.protected || []];
1008
- return isAnyMatch(path, method, protectedAccess);
1009
- };
1010
- var canAccessPublicly = (path, method, authConfig) => {
1011
- const publicAccess = [...defaultAuthConfig.public || [], ...authConfig.public || []];
1012
- return isAnyMatch(path, method, publicAccess);
1013
- };
1014
- var isAnyMatch = (path, method, patterns) => {
1015
- if (!patterns) {
1016
- return false;
1017
- }
1018
- for (const patternPathOrMethod of patterns) {
1019
- if (patternPathOrMethod instanceof RegExp) {
1020
- if (patternPathOrMethod.test(path)) {
1021
- return true;
1022
- }
1023
- }
1024
- if (typeof patternPathOrMethod === "string" && pathMatchesPattern(path, patternPathOrMethod)) {
1025
- return true;
1026
- }
1027
- if (Array.isArray(patternPathOrMethod) && patternPathOrMethod.length === 2) {
1028
- const [pattern, methodOrMethods] = patternPathOrMethod;
1029
- if (pathMatchesPattern(path, pattern) && matchesOrIncludes(methodOrMethods, method)) {
1030
- return true;
1031
- }
1032
- }
1033
- }
1034
- return false;
1035
- };
1036
- var pathMatchesPattern = (path, pattern) => {
1037
- if (pattern.endsWith("*")) {
1038
- const prefix = pattern.slice(0, -1);
1039
- return path.startsWith(prefix);
1040
- }
1041
- return path === pattern;
1042
- };
1043
- var pathMatchesRule = (path, rulePath) => {
1044
- if (!rulePath) return true;
1045
- if (typeof rulePath === "string") {
1046
- return pathMatchesPattern(path, rulePath);
1047
- }
1048
- if (rulePath instanceof RegExp) {
1049
- console.log("rulePath", rulePath, path, rulePath.test(path));
1050
- return rulePath.test(path);
1051
- }
1052
- if (Array.isArray(rulePath)) {
1053
- return rulePath.some((p2) => pathMatchesPattern(path, p2));
1054
- }
1055
- return false;
1056
- };
1057
- var matchesOrIncludes = (values, value) => {
1058
- if (typeof values === "string") {
1059
- return values === value;
1060
- }
1061
- if (Array.isArray(values)) {
1062
- return values.includes(value);
1063
- }
1064
- return false;
1065
- };
1066
- var checkRules = async (rules, path, method, user) => {
1067
- for (const i2 in rules || []) {
1068
- const rule = rules?.[i2];
1069
- if (!pathMatchesRule(path, rule.path)) {
1070
- continue;
1071
- }
1072
- if (rule.methods && !matchesOrIncludes(rule.methods, method)) {
1073
- continue;
1074
- }
1075
- const condition = rule.condition;
1076
- if (typeof condition === "function") {
1077
- const allowed = await Promise.resolve().then(() => condition(user)).catch(() => false);
1078
- if (allowed) {
1079
- return true;
1080
- }
1081
- } else if (rule.allow) {
1082
- return true;
1083
- }
1084
- }
1085
- return false;
1086
- };
1087
-
1088
- // src/server/handlers/auth/index.ts
1089
- var authenticationMiddleware = async (c2, next) => {
1090
- const mastra = c2.get("mastra");
1091
- const authConfig = mastra.getServer()?.experimental_auth;
1092
- if (!authConfig) {
1093
- return next();
1094
- }
1095
- if (isDevPlaygroundRequest(c2.req)) {
1096
- return next();
1097
- }
1098
- if (!isProtectedPath(c2.req.path, c2.req.method, authConfig)) {
1099
- return next();
1100
- }
1101
- if (canAccessPublicly(c2.req.path, c2.req.method, authConfig)) {
1102
- return next();
1103
- }
1104
- const authHeader = c2.req.header("Authorization");
1105
- let token = authHeader ? authHeader.replace("Bearer ", "") : null;
1106
- if (!token && c2.req.query("apiKey")) {
1107
- token = c2.req.query("apiKey") || null;
1108
- }
1109
- if (!token) {
1110
- return c2.json({ error: "Authentication required" }, 401);
1111
- }
1112
- try {
1113
- let user;
1114
- if (typeof authConfig.authenticateToken === "function") {
1115
- user = await authConfig.authenticateToken(token, c2.req);
1116
- } else {
1117
- throw new Error("No token verification method configured");
1118
- }
1119
- if (!user) {
1120
- return c2.json({ error: "Invalid or expired token" }, 401);
1121
- }
1122
- c2.get("runtimeContext").set("user", user);
1123
- return next();
1124
- } catch (err) {
1125
- console.error(err);
1126
- return c2.json({ error: "Invalid or expired token" }, 401);
1127
- }
1128
- };
1129
- var authorizationMiddleware = async (c2, next) => {
1130
- const mastra = c2.get("mastra");
1131
- const authConfig = mastra.getServer()?.experimental_auth;
1132
- if (!authConfig) {
1133
- return next();
1134
- }
1135
- const path = c2.req.path;
1136
- const method = c2.req.method;
1137
- if (isDevPlaygroundRequest(c2.req)) {
1138
- return next();
1139
- }
1140
- if (!isProtectedPath(c2.req.path, c2.req.method, authConfig)) {
1141
- return next();
1142
- }
1143
- if (canAccessPublicly(path, method, authConfig)) {
1144
- return next();
1145
- }
1146
- const user = c2.get("runtimeContext").get("user");
1147
- if ("authorizeUser" in authConfig && typeof authConfig.authorizeUser === "function") {
1148
- try {
1149
- const isAuthorized = await authConfig.authorizeUser(user, c2.req);
1150
- if (isAuthorized) {
1151
- return next();
1152
- }
1153
- return c2.json({ error: "Access denied" }, 403);
1154
- } catch (err) {
1155
- console.error(err);
1156
- return c2.json({ error: "Authorization error" }, 500);
1157
- }
1158
- }
1159
- if ("authorize" in authConfig && typeof authConfig.authorize === "function") {
1160
- try {
1161
- const isAuthorized = await authConfig.authorize(path, method, user, c2);
1162
- if (isAuthorized) {
1163
- return next();
2108
+ tags: ["agent-builder"],
2109
+ responses: {
2110
+ 200: {
2111
+ description: "agent builder action run event sent"
2112
+ }
1164
2113
  }
1165
- return c2.json({ error: "Access denied" }, 403);
1166
- } catch (err) {
1167
- console.error(err);
1168
- return c2.json({ error: "Authorization error" }, 500);
1169
- }
1170
- }
1171
- if ("rules" in authConfig && authConfig.rules && authConfig.rules.length > 0) {
1172
- const isAuthorized = await checkRules(authConfig.rules, path, method, user);
1173
- if (isAuthorized) {
1174
- return next();
1175
- }
1176
- return c2.json({ error: "Access denied" }, 403);
1177
- }
1178
- if (defaultAuthConfig.rules && defaultAuthConfig.rules.length > 0) {
1179
- const isAuthorized = await checkRules(defaultAuthConfig.rules, path, method, user);
1180
- if (isAuthorized) {
1181
- return next();
1182
- }
1183
- }
1184
- return c2.json({ error: "Access denied" }, 403);
1185
- };
1186
-
1187
- // src/server/handlers/client.ts
1188
- var clients = /* @__PURE__ */ new Set();
1189
- function handleClientsRefresh(c2) {
1190
- const stream6 = new ReadableStream({
1191
- start(controller) {
1192
- clients.add(controller);
1193
- controller.enqueue("data: connected\n\n");
1194
- c2.req.raw.signal.addEventListener("abort", () => {
1195
- clients.delete(controller);
1196
- });
1197
- }
1198
- });
1199
- return new Response(stream6, {
1200
- headers: {
1201
- "Content-Type": "text/event-stream",
1202
- "Cache-Control": "no-cache",
1203
- Connection: "keep-alive",
1204
- "Access-Control-Allow-Origin": "*"
1205
- }
1206
- });
1207
- }
1208
- function handleTriggerClientsRefresh(c2) {
1209
- clients.forEach((controller) => {
1210
- try {
1211
- controller.enqueue("data: refresh\n\n");
1212
- } catch {
1213
- clients.delete(controller);
1214
- }
1215
- });
1216
- return c2.json({ success: true, clients: clients.size });
1217
- }
1218
- function handleError(error, defaultMessage) {
1219
- const apiError = error;
1220
- throw new HTTPException(apiError.status || 500, {
1221
- message: apiError.message || defaultMessage,
1222
- cause: apiError.cause
1223
- });
1224
- }
1225
- function errorHandler(err, c2, isDev) {
1226
- if (err instanceof HTTPException) {
1227
- if (isDev) {
1228
- return c2.json({ error: err.message, cause: err.cause, stack: err.stack }, err.status);
1229
- }
1230
- return c2.json({ error: err.message }, err.status);
1231
- }
1232
- console.error(err);
1233
- return c2.json({ error: "Internal Server Error" }, 500);
1234
- }
1235
-
1236
- // src/server/handlers/root.ts
1237
- async function rootHandler(c2) {
1238
- return c2.text("Hello to the Mastra API!");
2114
+ }),
2115
+ sendAgentBuilderActionRunEventHandler
2116
+ );
2117
+ return router;
1239
2118
  }
1240
2119
  var AllowedProviderKeys = {
1241
2120
  openai: "OPENAI_API_KEY",
@@ -1438,7 +2317,7 @@ async function streamVNextGenerateHandler(c2) {
1438
2317
  c2.header("Transfer-Encoding", "chunked");
1439
2318
  return stream(
1440
2319
  c2,
1441
- async (stream6) => {
2320
+ async (stream7) => {
1442
2321
  try {
1443
2322
  const streamResponse = await streamVNextGenerateHandler$1({
1444
2323
  mastra,
@@ -1448,20 +2327,20 @@ async function streamVNextGenerateHandler(c2) {
1448
2327
  abortSignal: c2.req.raw.signal
1449
2328
  });
1450
2329
  const reader = streamResponse.fullStream.getReader();
1451
- stream6.onAbort(() => {
2330
+ stream7.onAbort(() => {
1452
2331
  void reader.cancel("request aborted");
1453
2332
  });
1454
2333
  let chunkResult;
1455
2334
  while ((chunkResult = await reader.read()) && !chunkResult.done) {
1456
- await stream6.write(`data: ${JSON.stringify(chunkResult.value)}
2335
+ await stream7.write(`data: ${JSON.stringify(chunkResult.value)}
1457
2336
 
1458
2337
  `);
1459
2338
  }
1460
- await stream6.write("data: [DONE]\n\n");
2339
+ await stream7.write("data: [DONE]\n\n");
1461
2340
  } catch (err) {
1462
2341
  logger2.error("Error in streamVNext generate: " + (err?.message ?? "Unknown error"));
1463
2342
  }
1464
- await stream6.close();
2343
+ await stream7.close();
1465
2344
  },
1466
2345
  async (err) => {
1467
2346
  logger2.error("Error in watch stream: " + err?.message);
@@ -7208,7 +8087,7 @@ async function streamGenerateVNextNetworkHandler(c2) {
7208
8087
  c2.header("Transfer-Encoding", "chunked");
7209
8088
  return stream(
7210
8089
  c2,
7211
- async (stream6) => {
8090
+ async (stream7) => {
7212
8091
  try {
7213
8092
  const result = await streamGenerateVNextNetworkHandler$1({
7214
8093
  mastra,
@@ -7217,12 +8096,12 @@ async function streamGenerateVNextNetworkHandler(c2) {
7217
8096
  body
7218
8097
  });
7219
8098
  const reader = result.stream.getReader();
7220
- stream6.onAbort(() => {
8099
+ stream7.onAbort(() => {
7221
8100
  void reader.cancel("request aborted");
7222
8101
  });
7223
8102
  let chunkResult;
7224
8103
  while ((chunkResult = await reader.read()) && !chunkResult.done) {
7225
- await stream6.write(JSON.stringify(chunkResult.value) + "");
8104
+ await stream7.write(JSON.stringify(chunkResult.value) + "");
7226
8105
  }
7227
8106
  } catch (err) {
7228
8107
  mastra.getLogger().error("Error in network stream: " + (err?.message ?? "Unknown error"));
@@ -7263,7 +8142,7 @@ async function loopStreamVNextNetworkHandler(c2) {
7263
8142
  c2.header("Transfer-Encoding", "chunked");
7264
8143
  return stream(
7265
8144
  c2,
7266
- async (stream6) => {
8145
+ async (stream7) => {
7267
8146
  try {
7268
8147
  const result = await loopStreamVNextNetworkHandler$1({
7269
8148
  mastra,
@@ -7272,12 +8151,12 @@ async function loopStreamVNextNetworkHandler(c2) {
7272
8151
  body
7273
8152
  });
7274
8153
  const reader = result.stream.getReader();
7275
- stream6.onAbort(() => {
8154
+ stream7.onAbort(() => {
7276
8155
  void reader.cancel("request aborted");
7277
8156
  });
7278
8157
  let chunkResult;
7279
8158
  while ((chunkResult = await reader.read()) && !chunkResult.done) {
7280
- await stream6.write(JSON.stringify(chunkResult.value) + "");
8159
+ await stream7.write(JSON.stringify(chunkResult.value) + "");
7281
8160
  }
7282
8161
  } catch (err) {
7283
8162
  mastra.getLogger().error("Error in network loop stream: " + (err?.message ?? "Unknown error"));
@@ -8663,7 +9542,7 @@ function watchWorkflowHandler(c2) {
8663
9542
  c2.header("Transfer-Encoding", "chunked");
8664
9543
  return stream(
8665
9544
  c2,
8666
- async (stream6) => {
9545
+ async (stream7) => {
8667
9546
  try {
8668
9547
  const result = await watchWorkflowHandler$1({
8669
9548
  mastra,
@@ -8671,12 +9550,12 @@ function watchWorkflowHandler(c2) {
8671
9550
  runId
8672
9551
  });
8673
9552
  const reader = result.getReader();
8674
- stream6.onAbort(() => {
9553
+ stream7.onAbort(() => {
8675
9554
  void reader.cancel("request aborted");
8676
9555
  });
8677
9556
  let chunkResult;
8678
9557
  while ((chunkResult = await reader.read()) && !chunkResult.done) {
8679
- await stream6.write(JSON.stringify(chunkResult.value) + "");
9558
+ await stream7.write(JSON.stringify(chunkResult.value) + "");
8680
9559
  }
8681
9560
  } catch (err) {
8682
9561
  logger2.error("Error in watch stream: " + (err?.message ?? "Unknown error"));
@@ -8701,7 +9580,7 @@ async function streamWorkflowHandler(c2) {
8701
9580
  c2.header("Transfer-Encoding", "chunked");
8702
9581
  return stream(
8703
9582
  c2,
8704
- async (stream6) => {
9583
+ async (stream7) => {
8705
9584
  try {
8706
9585
  const result = await streamWorkflowHandler$1({
8707
9586
  mastra,
@@ -8711,17 +9590,17 @@ async function streamWorkflowHandler(c2) {
8711
9590
  runtimeContext
8712
9591
  });
8713
9592
  const reader = result.stream.getReader();
8714
- stream6.onAbort(() => {
9593
+ stream7.onAbort(() => {
8715
9594
  void reader.cancel("request aborted");
8716
9595
  });
8717
9596
  let chunkResult;
8718
9597
  while ((chunkResult = await reader.read()) && !chunkResult.done) {
8719
- await stream6.write(JSON.stringify(chunkResult.value) + "");
9598
+ await stream7.write(JSON.stringify(chunkResult.value) + "");
8720
9599
  }
8721
9600
  } catch (err) {
8722
9601
  logger2.error("Error in workflow stream: " + (err?.message ?? "Unknown error"));
8723
9602
  }
8724
- await stream6.close();
9603
+ await stream7.close();
8725
9604
  },
8726
9605
  async (err) => {
8727
9606
  logger2.error("Error in workflow stream: " + err?.message);
@@ -8742,7 +9621,7 @@ async function streamVNextWorkflowHandler(c2) {
8742
9621
  c2.header("Transfer-Encoding", "chunked");
8743
9622
  return stream(
8744
9623
  c2,
8745
- async (stream6) => {
9624
+ async (stream7) => {
8746
9625
  try {
8747
9626
  const result = await streamVNextWorkflowHandler$1({
8748
9627
  mastra,
@@ -8752,12 +9631,12 @@ async function streamVNextWorkflowHandler(c2) {
8752
9631
  runtimeContext
8753
9632
  });
8754
9633
  const reader = result.getReader();
8755
- stream6.onAbort(() => {
9634
+ stream7.onAbort(() => {
8756
9635
  void reader.cancel("request aborted");
8757
9636
  });
8758
9637
  let chunkResult;
8759
9638
  while ((chunkResult = await reader.read()) && !chunkResult.done) {
8760
- await stream6.write(JSON.stringify(chunkResult.value) + "");
9639
+ await stream7.write(JSON.stringify(chunkResult.value) + "");
8761
9640
  }
8762
9641
  } catch (err) {
8763
9642
  logger2.error("Error in workflow VNext stream: " + (err?.message ?? "Unknown error"));
@@ -8985,20 +9864,20 @@ function watchLegacyWorkflowHandler(c2) {
8985
9864
  }
8986
9865
  return stream(
8987
9866
  c2,
8988
- async (stream6) => {
9867
+ async (stream7) => {
8989
9868
  try {
8990
9869
  const result = await watchLegacyWorkflowHandler$1({
8991
9870
  mastra,
8992
9871
  workflowId,
8993
9872
  runId
8994
9873
  });
8995
- stream6.onAbort(() => {
9874
+ stream7.onAbort(() => {
8996
9875
  if (!result.locked) {
8997
9876
  return result.cancel();
8998
9877
  }
8999
9878
  });
9000
9879
  for await (const chunk of result) {
9001
- await stream6.write(chunk.toString() + "");
9880
+ await stream7.write(chunk.toString() + "");
9002
9881
  }
9003
9882
  } catch (err) {
9004
9883
  console.log(err);
@@ -10298,6 +11177,7 @@ async function createHonoServer(mastra, options = {
10298
11177
  app.route("/api/workflows", workflowsRouter(bodyLimitOptions));
10299
11178
  app.route("/api/logs", logsRouter());
10300
11179
  app.route("/api/scores", scoresRouter(bodyLimitOptions));
11180
+ app.route("/api/agent-builder", agentBuilderRouter(bodyLimitOptions));
10301
11181
  app.route("/api/tools", toolsRouter(bodyLimitOptions, options.tools));
10302
11182
  app.route("/api/vector", vectorRouter(bodyLimitOptions));
10303
11183
  if (options?.isDev || server?.build?.openAPIDocs || server?.build?.swaggerUI) {
@@ -10335,6 +11215,18 @@ async function createHonoServer(mastra, options = {
10335
11215
  }),
10336
11216
  handleTriggerClientsRefresh
10337
11217
  );
11218
+ app.get(
11219
+ "/__hot-reload-status",
11220
+ w({
11221
+ hide: true
11222
+ }),
11223
+ (c2) => {
11224
+ return c2.json({
11225
+ disabled: isHotReloadDisabled(),
11226
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
11227
+ });
11228
+ }
11229
+ );
10338
11230
  app.use("/assets/*", async (c2, next) => {
10339
11231
  const path = c2.req.path;
10340
11232
  if (path.endsWith(".js")) {