@mastra/deployer 0.15.3 → 0.16.0-alpha.1

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