@mastra/deployer 0.0.0-a2a-20250421213654

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.
Files changed (58) hide show
  1. package/LICENSE.md +46 -0
  2. package/README.md +159 -0
  3. package/dist/_tsup-dts-rollup.d.cts +548 -0
  4. package/dist/_tsup-dts-rollup.d.ts +548 -0
  5. package/dist/build/analyze.cjs +10 -0
  6. package/dist/build/analyze.d.cts +1 -0
  7. package/dist/build/analyze.d.ts +1 -0
  8. package/dist/build/analyze.js +1 -0
  9. package/dist/build/bundler.cjs +14 -0
  10. package/dist/build/bundler.d.cts +2 -0
  11. package/dist/build/bundler.d.ts +2 -0
  12. package/dist/build/bundler.js +1 -0
  13. package/dist/build/index.cjs +46 -0
  14. package/dist/build/index.d.cts +9 -0
  15. package/dist/build/index.d.ts +9 -0
  16. package/dist/build/index.js +5 -0
  17. package/dist/bundler/index.cjs +10 -0
  18. package/dist/bundler/index.d.cts +1 -0
  19. package/dist/bundler/index.d.ts +1 -0
  20. package/dist/bundler/index.js +1 -0
  21. package/dist/chunk-2ZPQX6BX.cjs +254 -0
  22. package/dist/chunk-4AYFLP6G.js +227 -0
  23. package/dist/chunk-4VC5Z4YR.cjs +391 -0
  24. package/dist/chunk-54KOF3NB.cjs +137 -0
  25. package/dist/chunk-5QD7CDGY.js +306 -0
  26. package/dist/chunk-6QMONK4A.cjs +2 -0
  27. package/dist/chunk-AOSWYZKN.js +138 -0
  28. package/dist/chunk-C4JT7CIH.js +1 -0
  29. package/dist/chunk-IMGVLBV7.cjs +149 -0
  30. package/dist/chunk-KTYDROLB.js +136 -0
  31. package/dist/chunk-LA6Y6GAB.cjs +312 -0
  32. package/dist/chunk-Q6OKTZNC.cjs +316 -0
  33. package/dist/chunk-USZDOFES.js +301 -0
  34. package/dist/chunk-UV4RQQ3R.js +359 -0
  35. package/dist/chunk-WVBUOQT6.js +111 -0
  36. package/dist/chunk-Z7KAM3CZ.cjs +164 -0
  37. package/dist/index.cjs +190 -0
  38. package/dist/index.d.cts +6 -0
  39. package/dist/index.d.ts +6 -0
  40. package/dist/index.js +149 -0
  41. package/dist/server/index.cjs +3952 -0
  42. package/dist/server/index.d.cts +2 -0
  43. package/dist/server/index.d.ts +2 -0
  44. package/dist/server/index.js +3944 -0
  45. package/dist/services/index.cjs +18 -0
  46. package/dist/services/index.d.cts +3 -0
  47. package/dist/services/index.d.ts +3 -0
  48. package/dist/services/index.js +1 -0
  49. package/dist/templates/instrumentation-template.js +89 -0
  50. package/dist/validator/custom-resolver.cjs +52 -0
  51. package/dist/validator/custom-resolver.d.cts +1 -0
  52. package/dist/validator/custom-resolver.d.ts +1 -0
  53. package/dist/validator/custom-resolver.js +50 -0
  54. package/dist/validator/loader.cjs +7 -0
  55. package/dist/validator/loader.d.cts +1 -0
  56. package/dist/validator/loader.d.ts +1 -0
  57. package/dist/validator/loader.js +4 -0
  58. package/package.json +140 -0
@@ -0,0 +1,3944 @@
1
+ import crypto, { randomUUID } from 'crypto';
2
+ import { readFile } from 'fs/promises';
3
+ import { dirname } from 'path';
4
+ import { join } from 'path/posix';
5
+ import { fileURLToPath, pathToFileURL } from 'url';
6
+ import { createServer } from 'http';
7
+ import { Http2ServerRequest } from 'http2';
8
+ import { Readable } from 'stream';
9
+ import { getFilePathWithoutDefaultDocument, getFilePath } from 'hono/utils/filepath';
10
+ import { getMimeType } from 'hono/utils/mime';
11
+ import { createReadStream, lstatSync } from 'fs';
12
+ import { html } from 'hono/html';
13
+ import { Telemetry } from '@mastra/core';
14
+ import { Container } from '@mastra/core/di';
15
+ import { Hono } from 'hono';
16
+ import { bodyLimit } from 'hono/body-limit';
17
+ import { cors } from 'hono/cors';
18
+ import { logger } from 'hono/logger';
19
+ import { timeout } from 'hono/timeout';
20
+ import { HTTPException } from 'hono/http-exception';
21
+ import { handleA2ARequest, handleAgentCardRequest } from '@mastra/server/handlers/a2a';
22
+ import { getAgentsHandler as getAgentsHandler$1, getAgentByIdHandler as getAgentByIdHandler$1, getEvalsByAgentIdHandler as getEvalsByAgentIdHandler$1, getLiveEvalsByAgentIdHandler as getLiveEvalsByAgentIdHandler$1, generateHandler as generateHandler$2, streamGenerateHandler as streamGenerateHandler$2 } from '@mastra/server/handlers/agents';
23
+ import { getLogsHandler as getLogsHandler$1, getLogTransports as getLogTransports$1, getLogsByRunIdHandler as getLogsByRunIdHandler$1 } from '@mastra/server/handlers/logs';
24
+ import { getMemoryStatusHandler as getMemoryStatusHandler$1, getThreadsHandler as getThreadsHandler$1, getThreadByIdHandler as getThreadByIdHandler$1, getMessagesHandler as getMessagesHandler$1, createThreadHandler as createThreadHandler$1, updateThreadHandler as updateThreadHandler$1, deleteThreadHandler as deleteThreadHandler$1, saveMessagesHandler as saveMessagesHandler$1 } from '@mastra/server/handlers/memory';
25
+ import { getNetworksHandler as getNetworksHandler$1, getNetworkByIdHandler as getNetworkByIdHandler$1, generateHandler as generateHandler$1, streamGenerateHandler as streamGenerateHandler$1 } from '@mastra/server/handlers/network';
26
+ import { Agent } from '@mastra/core/agent';
27
+ import { z } from 'zod';
28
+ import { getTelemetryHandler as getTelemetryHandler$1, storeTelemetryHandler as storeTelemetryHandler$1 } from '@mastra/server/handlers/telemetry';
29
+ import { executeAgentToolHandler as executeAgentToolHandler$1, getToolsHandler as getToolsHandler$1, getToolByIdHandler as getToolByIdHandler$1, executeToolHandler as executeToolHandler$1 } from '@mastra/server/handlers/tools';
30
+ import { upsertVectors as upsertVectors$1, createIndex as createIndex$1, queryVectors as queryVectors$1, listIndexes as listIndexes$1, describeIndex as describeIndex$1, deleteIndex as deleteIndex$1 } from '@mastra/server/handlers/vector';
31
+ import { getSpeakersHandler as getSpeakersHandler$1, generateSpeechHandler, transcribeSpeechHandler } from '@mastra/server/handlers/voice';
32
+ import { getWorkflowsHandler as getWorkflowsHandler$1, getWorkflowByIdHandler as getWorkflowByIdHandler$1, getWorkflowRunsHandler as getWorkflowRunsHandler$1, resumeWorkflowHandler as resumeWorkflowHandler$1, resumeAsyncWorkflowHandler as resumeAsyncWorkflowHandler$1, createRunHandler as createRunHandler$1, startAsyncWorkflowHandler as startAsyncWorkflowHandler$1, startWorkflowRunHandler as startWorkflowRunHandler$1, watchWorkflowHandler as watchWorkflowHandler$1 } from '@mastra/server/handlers/workflows';
33
+ import { stream } from 'hono/streaming';
34
+
35
+ // src/server/index.ts
36
+ var RequestError = class extends Error {
37
+ static name = "RequestError";
38
+ constructor(message, options) {
39
+ super(message, options);
40
+ }
41
+ };
42
+ var toRequestError = (e2) => {
43
+ if (e2 instanceof RequestError) {
44
+ return e2;
45
+ }
46
+ return new RequestError(e2.message, { cause: e2 });
47
+ };
48
+ var GlobalRequest = global.Request;
49
+ var Request = class extends GlobalRequest {
50
+ constructor(input, options) {
51
+ if (typeof input === "object" && getRequestCache in input) {
52
+ input = input[getRequestCache]();
53
+ }
54
+ if (typeof options?.body?.getReader !== "undefined") {
55
+ options.duplex ??= "half";
56
+ }
57
+ super(input, options);
58
+ }
59
+ };
60
+ var newRequestFromIncoming = (method, url, incoming, abortController) => {
61
+ const headerRecord = [];
62
+ const rawHeaders = incoming.rawHeaders;
63
+ for (let i2 = 0; i2 < rawHeaders.length; i2 += 2) {
64
+ const { [i2]: key, [i2 + 1]: value } = rawHeaders;
65
+ if (key.charCodeAt(0) !== /*:*/
66
+ 58) {
67
+ headerRecord.push([key, value]);
68
+ }
69
+ }
70
+ const init = {
71
+ method,
72
+ headers: headerRecord,
73
+ signal: abortController.signal
74
+ };
75
+ if (method === "TRACE") {
76
+ init.method = "GET";
77
+ const req = new Request(url, init);
78
+ Object.defineProperty(req, "method", {
79
+ get() {
80
+ return "TRACE";
81
+ }
82
+ });
83
+ return req;
84
+ }
85
+ if (!(method === "GET" || method === "HEAD")) {
86
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
87
+ init.body = new ReadableStream({
88
+ start(controller) {
89
+ controller.enqueue(incoming.rawBody);
90
+ controller.close();
91
+ }
92
+ });
93
+ } else {
94
+ init.body = Readable.toWeb(incoming);
95
+ }
96
+ }
97
+ return new Request(url, init);
98
+ };
99
+ var getRequestCache = Symbol("getRequestCache");
100
+ var requestCache = Symbol("requestCache");
101
+ var incomingKey = Symbol("incomingKey");
102
+ var urlKey = Symbol("urlKey");
103
+ var abortControllerKey = Symbol("abortControllerKey");
104
+ var getAbortController = Symbol("getAbortController");
105
+ var requestPrototype = {
106
+ get method() {
107
+ return this[incomingKey].method || "GET";
108
+ },
109
+ get url() {
110
+ return this[urlKey];
111
+ },
112
+ [getAbortController]() {
113
+ this[getRequestCache]();
114
+ return this[abortControllerKey];
115
+ },
116
+ [getRequestCache]() {
117
+ this[abortControllerKey] ||= new AbortController();
118
+ return this[requestCache] ||= newRequestFromIncoming(
119
+ this.method,
120
+ this[urlKey],
121
+ this[incomingKey],
122
+ this[abortControllerKey]
123
+ );
124
+ }
125
+ };
126
+ [
127
+ "body",
128
+ "bodyUsed",
129
+ "cache",
130
+ "credentials",
131
+ "destination",
132
+ "headers",
133
+ "integrity",
134
+ "mode",
135
+ "redirect",
136
+ "referrer",
137
+ "referrerPolicy",
138
+ "signal",
139
+ "keepalive"
140
+ ].forEach((k) => {
141
+ Object.defineProperty(requestPrototype, k, {
142
+ get() {
143
+ return this[getRequestCache]()[k];
144
+ }
145
+ });
146
+ });
147
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
148
+ Object.defineProperty(requestPrototype, k, {
149
+ value: function() {
150
+ return this[getRequestCache]()[k]();
151
+ }
152
+ });
153
+ });
154
+ Object.setPrototypeOf(requestPrototype, Request.prototype);
155
+ var newRequest = (incoming, defaultHostname) => {
156
+ const req = Object.create(requestPrototype);
157
+ req[incomingKey] = incoming;
158
+ const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
159
+ if (!host) {
160
+ throw new RequestError("Missing host header");
161
+ }
162
+ const url = new URL(
163
+ `${incoming instanceof Http2ServerRequest || incoming.socket && incoming.socket.encrypted ? "https" : "http"}://${host}${incoming.url}`
164
+ );
165
+ if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
166
+ throw new RequestError("Invalid host header");
167
+ }
168
+ req[urlKey] = url.href;
169
+ return req;
170
+ };
171
+ function writeFromReadableStream(stream2, writable) {
172
+ if (stream2.locked) {
173
+ throw new TypeError("ReadableStream is locked.");
174
+ } else if (writable.destroyed) {
175
+ stream2.cancel();
176
+ return;
177
+ }
178
+ const reader = stream2.getReader();
179
+ writable.on("close", cancel);
180
+ writable.on("error", cancel);
181
+ reader.read().then(flow, cancel);
182
+ return reader.closed.finally(() => {
183
+ writable.off("close", cancel);
184
+ writable.off("error", cancel);
185
+ });
186
+ function cancel(error) {
187
+ reader.cancel(error).catch(() => {
188
+ });
189
+ if (error) {
190
+ writable.destroy(error);
191
+ }
192
+ }
193
+ function onDrain() {
194
+ reader.read().then(flow, cancel);
195
+ }
196
+ function flow({ done, value }) {
197
+ try {
198
+ if (done) {
199
+ writable.end();
200
+ } else if (!writable.write(value)) {
201
+ writable.once("drain", onDrain);
202
+ } else {
203
+ return reader.read().then(flow, cancel);
204
+ }
205
+ } catch (e2) {
206
+ cancel(e2);
207
+ }
208
+ }
209
+ }
210
+ var buildOutgoingHttpHeaders = (headers) => {
211
+ const res = {};
212
+ if (!(headers instanceof Headers)) {
213
+ headers = new Headers(headers ?? void 0);
214
+ }
215
+ const cookies = [];
216
+ for (const [k, v] of headers) {
217
+ if (k === "set-cookie") {
218
+ cookies.push(v);
219
+ } else {
220
+ res[k] = v;
221
+ }
222
+ }
223
+ if (cookies.length > 0) {
224
+ res["set-cookie"] = cookies;
225
+ }
226
+ res["content-type"] ??= "text/plain; charset=UTF-8";
227
+ return res;
228
+ };
229
+ var responseCache = Symbol("responseCache");
230
+ var getResponseCache = Symbol("getResponseCache");
231
+ var cacheKey = Symbol("cache");
232
+ var GlobalResponse = global.Response;
233
+ var Response2 = class _Response {
234
+ #body;
235
+ #init;
236
+ [getResponseCache]() {
237
+ delete this[cacheKey];
238
+ return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
239
+ }
240
+ constructor(body, init) {
241
+ this.#body = body;
242
+ if (init instanceof _Response) {
243
+ const cachedGlobalResponse = init[responseCache];
244
+ if (cachedGlobalResponse) {
245
+ this.#init = cachedGlobalResponse;
246
+ this[getResponseCache]();
247
+ return;
248
+ } else {
249
+ this.#init = init.#init;
250
+ }
251
+ } else {
252
+ this.#init = init;
253
+ }
254
+ if (typeof body === "string" || typeof body?.getReader !== "undefined") {
255
+ let headers = init?.headers || { "content-type": "text/plain; charset=UTF-8" };
256
+ if (headers instanceof Headers) {
257
+ headers = buildOutgoingHttpHeaders(headers);
258
+ }
259
+ this[cacheKey] = [init?.status || 200, body, headers];
260
+ }
261
+ }
262
+ };
263
+ [
264
+ "body",
265
+ "bodyUsed",
266
+ "headers",
267
+ "ok",
268
+ "redirected",
269
+ "status",
270
+ "statusText",
271
+ "trailers",
272
+ "type",
273
+ "url"
274
+ ].forEach((k) => {
275
+ Object.defineProperty(Response2.prototype, k, {
276
+ get() {
277
+ return this[getResponseCache]()[k];
278
+ }
279
+ });
280
+ });
281
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
282
+ Object.defineProperty(Response2.prototype, k, {
283
+ value: function() {
284
+ return this[getResponseCache]()[k]();
285
+ }
286
+ });
287
+ });
288
+ Object.setPrototypeOf(Response2, GlobalResponse);
289
+ Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
290
+ var stateKey = Reflect.ownKeys(new GlobalResponse()).find(
291
+ (k) => typeof k === "symbol" && k.toString() === "Symbol(state)"
292
+ );
293
+ if (!stateKey) {
294
+ console.warn("Failed to find Response internal state key");
295
+ }
296
+ function getInternalBody(response) {
297
+ if (!stateKey) {
298
+ return;
299
+ }
300
+ if (response instanceof Response2) {
301
+ response = response[getResponseCache]();
302
+ }
303
+ const state = response[stateKey];
304
+ return state && state.body || void 0;
305
+ }
306
+ var X_ALREADY_SENT = "x-hono-already-sent";
307
+ var webFetch = global.fetch;
308
+ if (typeof global.crypto === "undefined") {
309
+ global.crypto = crypto;
310
+ }
311
+ global.fetch = (info, init) => {
312
+ init = {
313
+ // Disable compression handling so people can return the result of a fetch
314
+ // directly in the loader without messing with the Content-Encoding header.
315
+ compress: false,
316
+ ...init
317
+ };
318
+ return webFetch(info, init);
319
+ };
320
+ var regBuffer = /^no$/i;
321
+ var regContentType = /^(application\/json\b|text\/(?!event-stream\b))/i;
322
+ var handleRequestError = () => new Response(null, {
323
+ status: 400
324
+ });
325
+ var handleFetchError = (e2) => new Response(null, {
326
+ status: e2 instanceof Error && (e2.name === "TimeoutError" || e2.constructor.name === "TimeoutError") ? 504 : 500
327
+ });
328
+ var handleResponseError = (e2, outgoing) => {
329
+ const err = e2 instanceof Error ? e2 : new Error("unknown error", { cause: e2 });
330
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
331
+ console.info("The user aborted a request.");
332
+ } else {
333
+ console.error(e2);
334
+ if (!outgoing.headersSent) {
335
+ outgoing.writeHead(500, { "Content-Type": "text/plain" });
336
+ }
337
+ outgoing.end(`Error: ${err.message}`);
338
+ outgoing.destroy(err);
339
+ }
340
+ };
341
+ var responseViaCache = (res, outgoing) => {
342
+ const [status, body, header] = res[cacheKey];
343
+ if (typeof body === "string") {
344
+ header["Content-Length"] = Buffer.byteLength(body);
345
+ outgoing.writeHead(status, header);
346
+ outgoing.end(body);
347
+ } else {
348
+ outgoing.writeHead(status, header);
349
+ return writeFromReadableStream(body, outgoing)?.catch(
350
+ (e2) => handleResponseError(e2, outgoing)
351
+ );
352
+ }
353
+ };
354
+ var responseViaResponseObject = async (res, outgoing, options = {}) => {
355
+ if (res instanceof Promise) {
356
+ if (options.errorHandler) {
357
+ try {
358
+ res = await res;
359
+ } catch (err) {
360
+ const errRes = await options.errorHandler(err);
361
+ if (!errRes) {
362
+ return;
363
+ }
364
+ res = errRes;
365
+ }
366
+ } else {
367
+ res = await res.catch(handleFetchError);
368
+ }
369
+ }
370
+ if (cacheKey in res) {
371
+ return responseViaCache(res, outgoing);
372
+ }
373
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
374
+ const internalBody = getInternalBody(res);
375
+ if (internalBody) {
376
+ const { length, source, stream: stream2 } = internalBody;
377
+ if (source instanceof Uint8Array && source.byteLength !== length) ; else {
378
+ if (length) {
379
+ resHeaderRecord["content-length"] = length;
380
+ }
381
+ outgoing.writeHead(res.status, resHeaderRecord);
382
+ if (typeof source === "string" || source instanceof Uint8Array) {
383
+ outgoing.end(source);
384
+ } else if (source instanceof Blob) {
385
+ outgoing.end(new Uint8Array(await source.arrayBuffer()));
386
+ } else {
387
+ await writeFromReadableStream(stream2, outgoing);
388
+ }
389
+ return;
390
+ }
391
+ }
392
+ if (res.body) {
393
+ const {
394
+ "transfer-encoding": transferEncoding,
395
+ "content-encoding": contentEncoding,
396
+ "content-length": contentLength,
397
+ "x-accel-buffering": accelBuffering,
398
+ "content-type": contentType
399
+ } = resHeaderRecord;
400
+ if (transferEncoding || contentEncoding || contentLength || // nginx buffering variant
401
+ accelBuffering && regBuffer.test(accelBuffering) || !regContentType.test(contentType)) {
402
+ outgoing.writeHead(res.status, resHeaderRecord);
403
+ await writeFromReadableStream(res.body, outgoing);
404
+ } else {
405
+ const buffer = await res.arrayBuffer();
406
+ resHeaderRecord["content-length"] = buffer.byteLength;
407
+ outgoing.writeHead(res.status, resHeaderRecord);
408
+ outgoing.end(new Uint8Array(buffer));
409
+ }
410
+ } else if (resHeaderRecord[X_ALREADY_SENT]) ; else {
411
+ outgoing.writeHead(res.status, resHeaderRecord);
412
+ outgoing.end();
413
+ }
414
+ };
415
+ var getRequestListener = (fetchCallback, options = {}) => {
416
+ if (options.overrideGlobalObjects !== false && global.Request !== Request) {
417
+ Object.defineProperty(global, "Request", {
418
+ value: Request
419
+ });
420
+ Object.defineProperty(global, "Response", {
421
+ value: Response2
422
+ });
423
+ }
424
+ return async (incoming, outgoing) => {
425
+ let res, req;
426
+ try {
427
+ req = newRequest(incoming, options.hostname);
428
+ outgoing.on("close", () => {
429
+ const abortController = req[abortControllerKey];
430
+ if (!abortController) {
431
+ return;
432
+ }
433
+ if (incoming.errored) {
434
+ req[abortControllerKey].abort(incoming.errored.toString());
435
+ } else if (!outgoing.writableFinished) {
436
+ req[abortControllerKey].abort("Client connection prematurely closed.");
437
+ }
438
+ });
439
+ res = fetchCallback(req, { incoming, outgoing });
440
+ if (cacheKey in res) {
441
+ return responseViaCache(res, outgoing);
442
+ }
443
+ } catch (e2) {
444
+ if (!res) {
445
+ if (options.errorHandler) {
446
+ res = await options.errorHandler(req ? e2 : toRequestError(e2));
447
+ if (!res) {
448
+ return;
449
+ }
450
+ } else if (!req) {
451
+ res = handleRequestError();
452
+ } else {
453
+ res = handleFetchError(e2);
454
+ }
455
+ } else {
456
+ return handleResponseError(e2, outgoing);
457
+ }
458
+ }
459
+ try {
460
+ return responseViaResponseObject(res, outgoing, options);
461
+ } catch (e2) {
462
+ return handleResponseError(e2, outgoing);
463
+ }
464
+ };
465
+ };
466
+ var createAdaptorServer = (options) => {
467
+ const fetchCallback = options.fetch;
468
+ const requestListener = getRequestListener(fetchCallback, {
469
+ hostname: options.hostname,
470
+ overrideGlobalObjects: options.overrideGlobalObjects
471
+ });
472
+ const createServer$1 = options.createServer || createServer;
473
+ const server = createServer$1(options.serverOptions || {}, requestListener);
474
+ return server;
475
+ };
476
+ var serve = (options, listeningListener) => {
477
+ const server = createAdaptorServer(options);
478
+ server.listen(options?.port ?? 3e3, options.hostname, () => {
479
+ const serverInfo = server.address();
480
+ listeningListener && listeningListener(serverInfo);
481
+ });
482
+ return server;
483
+ };
484
+ var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
485
+ var ENCODINGS = {
486
+ br: ".br",
487
+ zstd: ".zst",
488
+ gzip: ".gz"
489
+ };
490
+ var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
491
+ var createStreamBody = (stream2) => {
492
+ const body = new ReadableStream({
493
+ start(controller) {
494
+ stream2.on("data", (chunk) => {
495
+ controller.enqueue(chunk);
496
+ });
497
+ stream2.on("end", () => {
498
+ controller.close();
499
+ });
500
+ },
501
+ cancel() {
502
+ stream2.destroy();
503
+ }
504
+ });
505
+ return body;
506
+ };
507
+ var addCurrentDirPrefix = (path) => {
508
+ return `./${path}`;
509
+ };
510
+ var getStats = (path) => {
511
+ let stats;
512
+ try {
513
+ stats = lstatSync(path);
514
+ } catch {
515
+ }
516
+ return stats;
517
+ };
518
+ var serveStatic = (options = { root: "" }) => {
519
+ return async (c2, next) => {
520
+ if (c2.finalized) {
521
+ return next();
522
+ }
523
+ let filename;
524
+ try {
525
+ filename = options.path ?? decodeURIComponent(c2.req.path);
526
+ } catch {
527
+ await options.onNotFound?.(c2.req.path, c2);
528
+ return next();
529
+ }
530
+ let path = getFilePathWithoutDefaultDocument({
531
+ filename: options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename,
532
+ root: options.root
533
+ });
534
+ if (path) {
535
+ path = addCurrentDirPrefix(path);
536
+ } else {
537
+ return next();
538
+ }
539
+ let stats = getStats(path);
540
+ if (stats && stats.isDirectory()) {
541
+ path = getFilePath({
542
+ filename: options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename,
543
+ root: options.root,
544
+ defaultDocument: options.index ?? "index.html"
545
+ });
546
+ if (path) {
547
+ path = addCurrentDirPrefix(path);
548
+ } else {
549
+ return next();
550
+ }
551
+ stats = getStats(path);
552
+ }
553
+ if (!stats) {
554
+ await options.onNotFound?.(path, c2);
555
+ return next();
556
+ }
557
+ await options.onFound?.(path, c2);
558
+ const mimeType = getMimeType(path);
559
+ c2.header("Content-Type", mimeType || "application/octet-stream");
560
+ if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
561
+ const acceptEncodingSet = new Set(
562
+ c2.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim())
563
+ );
564
+ for (const encoding of ENCODINGS_ORDERED_KEYS) {
565
+ if (!acceptEncodingSet.has(encoding)) {
566
+ continue;
567
+ }
568
+ const precompressedStats = getStats(path + ENCODINGS[encoding]);
569
+ if (precompressedStats) {
570
+ c2.header("Content-Encoding", encoding);
571
+ c2.header("Vary", "Accept-Encoding", { append: true });
572
+ stats = precompressedStats;
573
+ path = path + ENCODINGS[encoding];
574
+ break;
575
+ }
576
+ }
577
+ }
578
+ const size = stats.size;
579
+ if (c2.req.method == "HEAD" || c2.req.method == "OPTIONS") {
580
+ c2.header("Content-Length", size.toString());
581
+ c2.status(200);
582
+ return c2.body(null);
583
+ }
584
+ const range = c2.req.header("range") || "";
585
+ if (!range) {
586
+ c2.header("Content-Length", size.toString());
587
+ return c2.body(createStreamBody(createReadStream(path)), 200);
588
+ }
589
+ c2.header("Accept-Ranges", "bytes");
590
+ c2.header("Date", stats.birthtime.toUTCString());
591
+ const parts = range.replace(/bytes=/, "").split("-", 2);
592
+ const start = parts[0] ? parseInt(parts[0], 10) : 0;
593
+ let end = parts[1] ? parseInt(parts[1], 10) : stats.size - 1;
594
+ if (size < end - start + 1) {
595
+ end = size - 1;
596
+ }
597
+ const chunksize = end - start + 1;
598
+ const stream2 = createReadStream(path, { start, end });
599
+ c2.header("Content-Length", chunksize.toString());
600
+ c2.header("Content-Range", `bytes ${start}-${end}/${stats.size}`);
601
+ return c2.body(createStreamBody(stream2), 206);
602
+ };
603
+ };
604
+ var RENDER_TYPE = {
605
+ STRING_ARRAY: "string_array",
606
+ STRING: "string",
607
+ JSON_STRING: "json_string",
608
+ RAW: "raw"
609
+ };
610
+ var RENDER_TYPE_MAP = {
611
+ configUrl: RENDER_TYPE.STRING,
612
+ deepLinking: RENDER_TYPE.RAW,
613
+ presets: RENDER_TYPE.STRING_ARRAY,
614
+ plugins: RENDER_TYPE.STRING_ARRAY,
615
+ spec: RENDER_TYPE.JSON_STRING,
616
+ url: RENDER_TYPE.STRING,
617
+ urls: RENDER_TYPE.JSON_STRING,
618
+ layout: RENDER_TYPE.STRING,
619
+ docExpansion: RENDER_TYPE.STRING,
620
+ maxDisplayedTags: RENDER_TYPE.RAW,
621
+ operationsSorter: RENDER_TYPE.RAW,
622
+ requestInterceptor: RENDER_TYPE.RAW,
623
+ responseInterceptor: RENDER_TYPE.RAW,
624
+ persistAuthorization: RENDER_TYPE.RAW,
625
+ defaultModelsExpandDepth: RENDER_TYPE.RAW,
626
+ defaultModelExpandDepth: RENDER_TYPE.RAW,
627
+ defaultModelRendering: RENDER_TYPE.STRING,
628
+ displayRequestDuration: RENDER_TYPE.RAW,
629
+ filter: RENDER_TYPE.RAW,
630
+ showExtensions: RENDER_TYPE.RAW,
631
+ showCommonExtensions: RENDER_TYPE.RAW,
632
+ queryConfigEnabled: RENDER_TYPE.RAW,
633
+ displayOperationId: RENDER_TYPE.RAW,
634
+ tagsSorter: RENDER_TYPE.RAW,
635
+ onComplete: RENDER_TYPE.RAW,
636
+ syntaxHighlight: RENDER_TYPE.JSON_STRING,
637
+ tryItOutEnabled: RENDER_TYPE.RAW,
638
+ requestSnippetsEnabled: RENDER_TYPE.RAW,
639
+ requestSnippets: RENDER_TYPE.JSON_STRING,
640
+ oauth2RedirectUrl: RENDER_TYPE.STRING,
641
+ showMutabledRequest: RENDER_TYPE.RAW,
642
+ request: RENDER_TYPE.JSON_STRING,
643
+ supportedSubmitMethods: RENDER_TYPE.JSON_STRING,
644
+ validatorUrl: RENDER_TYPE.STRING,
645
+ withCredentials: RENDER_TYPE.RAW,
646
+ modelPropertyMacro: RENDER_TYPE.RAW,
647
+ parameterMacro: RENDER_TYPE.RAW
648
+ };
649
+ var renderSwaggerUIOptions = (options) => {
650
+ const optionsStrings = Object.entries(options).map(([k, v]) => {
651
+ const key = k;
652
+ if (!RENDER_TYPE_MAP[key] || v === void 0) {
653
+ return "";
654
+ }
655
+ switch (RENDER_TYPE_MAP[key]) {
656
+ case RENDER_TYPE.STRING:
657
+ return `${key}: '${v}'`;
658
+ case RENDER_TYPE.STRING_ARRAY:
659
+ if (!Array.isArray(v)) {
660
+ return "";
661
+ }
662
+ return `${key}: [${v.map((ve) => `${ve}`).join(",")}]`;
663
+ case RENDER_TYPE.JSON_STRING:
664
+ return `${key}: ${JSON.stringify(v)}`;
665
+ case RENDER_TYPE.RAW:
666
+ return `${key}: ${v}`;
667
+ default:
668
+ return "";
669
+ }
670
+ }).filter((item) => item !== "").join(",");
671
+ return optionsStrings;
672
+ };
673
+ var remoteAssets = ({ version }) => {
674
+ const url = `https://cdn.jsdelivr.net/npm/swagger-ui-dist${version !== void 0 ? `@${version}` : ""}`;
675
+ return {
676
+ css: [`${url}/swagger-ui.css`],
677
+ js: [`${url}/swagger-ui-bundle.js`]
678
+ };
679
+ };
680
+ var SwaggerUI = (options) => {
681
+ const asset = remoteAssets({ version: options?.version });
682
+ delete options.version;
683
+ if (options.manuallySwaggerUIHtml) {
684
+ return options.manuallySwaggerUIHtml(asset);
685
+ }
686
+ const optionsStrings = renderSwaggerUIOptions(options);
687
+ return `
688
+ <div>
689
+ <div id="swagger-ui"></div>
690
+ ${asset.css.map((url) => html`<link rel="stylesheet" href="${url}" />`)}
691
+ ${asset.js.map((url) => html`<script src="${url}" crossorigin="anonymous"></script>`)}
692
+ <script>
693
+ window.onload = () => {
694
+ window.ui = SwaggerUIBundle({
695
+ dom_id: '#swagger-ui',${optionsStrings},
696
+ })
697
+ }
698
+ </script>
699
+ </div>
700
+ `;
701
+ };
702
+ var middleware = (options) => async (c2) => {
703
+ const title = options?.title ?? "SwaggerUI";
704
+ return c2.html(
705
+ /* html */
706
+ `
707
+ <html lang="en">
708
+ <head>
709
+ <meta charset="utf-8" />
710
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
711
+ <meta name="description" content="SwaggerUI" />
712
+ <title>${title}</title>
713
+ </head>
714
+ <body>
715
+ ${SwaggerUI(options)}
716
+ </body>
717
+ </html>
718
+ `
719
+ );
720
+ };
721
+
722
+ // ../../node_modules/.pnpm/hono-openapi@0.4.6_hono@4.7.4_openapi-types@12.1.3_zod@3.24.3/node_modules/hono-openapi/utils.js
723
+ var e = Symbol("openapi");
724
+ var s2 = ["GET", "PUT", "POST", "DELETE", "OPTIONS", "HEAD", "PATCH", "TRACE"];
725
+ var n = (e2) => e2.charAt(0).toUpperCase() + e2.slice(1);
726
+ var o = /* @__PURE__ */ new Map();
727
+ var a = (e2, t2) => {
728
+ const s3 = `${e2}:${t2}`;
729
+ if (o.has(s3)) return o.get(s3);
730
+ let a2 = e2;
731
+ if ("/" === t2) return `${a2}Index`;
732
+ for (const e3 of t2.split("/")) 123 === e3.charCodeAt(0) ? a2 += `By${n(e3.slice(1, -1))}` : a2 += n(e3);
733
+ return o.set(s3, a2), a2;
734
+ };
735
+ var r = /* @__PURE__ */ new Map();
736
+ function c(e2, t2, s3) {
737
+ return e2 && t2 in e2 ? e2[t2] ?? s3 : s3;
738
+ }
739
+ function i(...e2) {
740
+ return e2.reduce((e3, t2) => {
741
+ if (!t2) return e3;
742
+ let s3;
743
+ return ("tags" in e3 && e3.tags || "tags" in t2 && t2.tags) && (s3 = [...c(e3, "tags", []), ...c(t2, "tags", [])]), { ...e3, ...t2, tags: s3, responses: { ...c(e3, "responses", {}), ...c(t2, "responses", {}) }, parameters: m(e3.parameters, t2.parameters) };
744
+ }, {});
745
+ }
746
+ function p({ path: e2, method: t2, data: s3, schema: n2 }) {
747
+ e2 = ((e3) => e3.split("/").map((e4) => {
748
+ let t3 = e4;
749
+ return t3.startsWith(":") && (t3 = t3.slice(1, t3.length), t3.endsWith("?") && (t3 = t3.slice(0, -1)), t3 = `{${t3}}`), t3;
750
+ }).join("/"))(e2);
751
+ const o2 = t2.toLowerCase();
752
+ if ("all" === o2) if (r.has(e2)) {
753
+ const t3 = r.get(e2) ?? {};
754
+ r.set(e2, { ...t3, ...s3, parameters: m(t3.parameters, s3.parameters) });
755
+ } else r.set(e2, s3);
756
+ else {
757
+ const t3 = function(e3) {
758
+ const t4 = Array.from(r.keys());
759
+ let s4 = {};
760
+ for (const n3 of t4) e3.match(n3) && (s4 = i(s4, r.get(n3) ?? {}));
761
+ return s4;
762
+ }(e2);
763
+ n2[e2] = { ...n2[e2] ? n2[e2] : {}, [o2]: { responses: {}, operationId: a(o2, e2), ...i(t3, n2[e2]?.[o2], s3) } };
764
+ }
765
+ }
766
+ var l = (e2) => "$ref" in e2 ? e2.$ref : `${e2.in} ${e2.name}`;
767
+ function m(...e2) {
768
+ const t2 = e2.flatMap((e3) => e3 ?? []).reduce((e3, t3) => (e3.set(l(t3), t3), e3), /* @__PURE__ */ new Map());
769
+ return Array.from(t2.values());
770
+ }
771
+ function u(e2, { excludeStaticFile: t2 = true, exclude: s3 = [] }) {
772
+ const n2 = {}, o2 = Array.isArray(s3) ? s3 : [s3];
773
+ for (const [s4, a2] of Object.entries(e2)) if (!(o2.some((e3) => "string" == typeof e3 ? s4 === e3 : e3.test(s4)) || s4.includes("*") || t2 && s4.includes("."))) {
774
+ for (const e3 of Object.keys(a2)) {
775
+ const t3 = a2[e3];
776
+ if (s4.includes("{")) {
777
+ t3.parameters || (t3.parameters = []);
778
+ const e4 = s4.split("/").filter((e5) => e5.startsWith("{") && !t3.parameters.find((t4) => "path" === t4.in && t4.name === e5.slice(1, e5.length - 1)));
779
+ for (const s5 of e4) {
780
+ const e5 = s5.slice(1, s5.length - 1), n3 = t3.parameters.findIndex((t4) => "param" === t4.in && t4.name === e5);
781
+ -1 !== n3 ? t3.parameters[n3].in = "path" : t3.parameters.push({ schema: { type: "string" }, in: "path", name: e5, required: true });
782
+ }
783
+ }
784
+ t3.responses || (t3.responses = { 200: {} });
785
+ }
786
+ n2[s4] = a2;
787
+ }
788
+ return n2;
789
+ }
790
+ function f(e2, t2) {
791
+ const s3 = { version: "3.1.0", components: {} };
792
+ let n2 = null;
793
+ return async (o2) => (n2 || (n2 = await d(e2, t2, s3, o2)), o2.json(n2));
794
+ }
795
+ async function d(t2, { documentation: n2 = {}, excludeStaticFile: o2 = true, exclude: a2 = [], excludeMethods: r2 = ["OPTIONS"], excludeTags: c2 = [], defaultOptions: i2 } = { documentation: {}, excludeStaticFile: true, exclude: [], excludeMethods: ["OPTIONS"], excludeTags: [] }, { version: l2 = "3.1.0", components: m2 = {} } = { version: "3.1.0", components: {} }, f2) {
796
+ const d2 = { version: l2, components: m2 }, h2 = {};
797
+ for (const n3 of t2.routes) {
798
+ if (!(e in n3.handler)) continue;
799
+ if (r2.includes(n3.method)) continue;
800
+ if (false === s2.includes(n3.method) && "ALL" !== n3.method) continue;
801
+ const { resolver: t3, metadata: o3 = {} } = n3.handler[e], a3 = i2?.[n3.method], { docs: c3, components: l3 } = await t3({ ...d2, ...o3 }, a3);
802
+ d2.components = { ...d2.components, ...l3 ?? {} }, p({ method: n3.method, path: n3.path, data: c3, schema: h2 });
803
+ }
804
+ for (const e2 in h2) for (const t3 in h2[e2]) {
805
+ const s3 = h2[e2][t3]?.hide;
806
+ s3 && ("boolean" == typeof s3 ? s3 : f2 && s3(f2)) && delete h2[e2][t3];
807
+ }
808
+ return { openapi: d2.version, ...{ ...n2, tags: n2.tags?.filter((e2) => !c2?.includes(e2?.name)), info: { title: "Hono Documentation", description: "Development documentation", version: "0.0.0", ...n2.info }, paths: { ...u(h2, { excludeStaticFile: o2, exclude: a2 }), ...n2.paths }, components: { ...n2.components, schemas: { ...d2.components, ...n2.components?.schemas } } } };
809
+ }
810
+ function h(s3) {
811
+ const { validateResponse: n2, ...o2 } = s3;
812
+ return Object.assign(async (e2, o3) => {
813
+ if (await o3(), n2 && s3.responses) {
814
+ const o4 = e2.res.status, a2 = e2.res.headers.get("content-type");
815
+ if (o4 && a2) {
816
+ const r2 = s3.responses[o4];
817
+ if (r2 && "content" in r2 && r2.content) {
818
+ const s4 = a2.split(";")[0], o5 = r2.content[s4];
819
+ if (o5?.schema && "validator" in o5.schema) try {
820
+ let t2;
821
+ const n3 = e2.res.clone();
822
+ if ("application/json" === s4 ? t2 = await n3.json() : "text/plain" === s4 && (t2 = await n3.text()), !t2) throw new Error("No data to validate!");
823
+ await o5.schema.validator(t2);
824
+ } catch (e3) {
825
+ let s5 = { status: 500, message: "Response validation failed!" };
826
+ throw "object" == typeof n2 && (s5 = { ...s5, ...n2 }), new HTTPException(s5.status, { message: s5.message, cause: e3 });
827
+ }
828
+ }
829
+ }
830
+ }
831
+ }, { [e]: { resolver: (e2, t2) => x(e2, o2, t2) } });
832
+ }
833
+ async function x(e2, t2, s3 = {}) {
834
+ let n2 = {};
835
+ const o2 = { ...s3, ...t2, responses: { ...s3?.responses, ...t2.responses } };
836
+ if (o2.responses) for (const t3 of Object.keys(o2.responses)) {
837
+ const s4 = o2.responses[t3];
838
+ if (s4 && "content" in s4) for (const t4 of Object.keys(s4.content ?? {})) {
839
+ const o3 = s4.content?.[t4];
840
+ if (o3 && (o3.schema && "builder" in o3.schema)) {
841
+ const t5 = await o3.schema.builder(e2);
842
+ o3.schema = t5.schema, t5.components && (n2 = { ...n2, ...t5.components });
843
+ }
844
+ }
845
+ }
846
+ return { docs: o2, components: n2 };
847
+ }
848
+ function handleError(error, defaultMessage) {
849
+ const apiError = error;
850
+ throw new HTTPException(apiError.status || 500, {
851
+ message: apiError.message || defaultMessage
852
+ });
853
+ }
854
+ function errorHandler(err, c2) {
855
+ if (err instanceof HTTPException) {
856
+ return c2.json({ error: err.message }, err.status);
857
+ }
858
+ console.error(err);
859
+ return c2.json({ error: "Internal Server Error" }, 500);
860
+ }
861
+
862
+ // src/server/handlers/a2a.ts
863
+ async function handleA2ARequestEndpoint(c2) {
864
+ try {
865
+ const mastra = c2.get("mastra");
866
+ const agents = mastra.getAgents();
867
+ const agent = Object.values(agents)[0];
868
+ if (!agent) {
869
+ return c2.json(
870
+ {
871
+ jsonrpc: "2.0",
872
+ id: null,
873
+ error: {
874
+ code: -32603,
875
+ message: "No agent available"
876
+ }
877
+ },
878
+ 500
879
+ );
880
+ }
881
+ const body = await c2.req.json();
882
+ const response = await handleA2ARequest({ request: body, agent });
883
+ return c2.json(response);
884
+ } catch (error) {
885
+ return handleError(error, "Error handling A2A request");
886
+ }
887
+ }
888
+ async function handleAgentCardEndpoint(c2) {
889
+ try {
890
+ const mastra = c2.get("mastra");
891
+ const agents = mastra.getAgents();
892
+ const agent = Object.values(agents)[0];
893
+ if (!agent) {
894
+ return c2.json({ error: "No agent available" }, 500);
895
+ }
896
+ const baseUrl = `${c2.req.url.split("/api/")[0]}`;
897
+ const agentCard = handleAgentCardRequest({ agent, baseUrl });
898
+ return c2.json(agentCard);
899
+ } catch (error) {
900
+ return handleError(error, "Error handling agent card request");
901
+ }
902
+ }
903
+ async function getAgentsHandler(c2) {
904
+ const serializedAgents = await getAgentsHandler$1({ mastra: c2.get("mastra") });
905
+ return c2.json(serializedAgents);
906
+ }
907
+ async function getAgentByIdHandler(c2) {
908
+ const mastra = c2.get("mastra");
909
+ const agentId = c2.req.param("agentId");
910
+ const result = await getAgentByIdHandler$1({
911
+ mastra,
912
+ agentId
913
+ });
914
+ return c2.json(result);
915
+ }
916
+ async function getEvalsByAgentIdHandler(c2) {
917
+ const mastra = c2.get("mastra");
918
+ const agentId = c2.req.param("agentId");
919
+ const result = await getEvalsByAgentIdHandler$1({
920
+ mastra,
921
+ agentId
922
+ });
923
+ return c2.json(result);
924
+ }
925
+ async function getLiveEvalsByAgentIdHandler(c2) {
926
+ const mastra = c2.get("mastra");
927
+ const agentId = c2.req.param("agentId");
928
+ const result = await getLiveEvalsByAgentIdHandler$1({
929
+ mastra,
930
+ agentId
931
+ });
932
+ return c2.json(result);
933
+ }
934
+ async function generateHandler(c2) {
935
+ try {
936
+ const mastra = c2.get("mastra");
937
+ const agentId = c2.req.param("agentId");
938
+ const container = c2.get("container");
939
+ const body = await c2.req.json();
940
+ const result = await generateHandler$2({
941
+ mastra,
942
+ agentId,
943
+ container,
944
+ body
945
+ });
946
+ return c2.json(result);
947
+ } catch (error) {
948
+ return handleError(error, "Error generating from agent");
949
+ }
950
+ }
951
+ async function streamGenerateHandler(c2) {
952
+ try {
953
+ const mastra = c2.get("mastra");
954
+ const agentId = c2.req.param("agentId");
955
+ const container = c2.get("container");
956
+ const body = await c2.req.json();
957
+ const streamResponse = await streamGenerateHandler$2({
958
+ mastra,
959
+ agentId,
960
+ container,
961
+ body
962
+ });
963
+ return streamResponse;
964
+ } catch (error) {
965
+ return handleError(error, "Error streaming from agent");
966
+ }
967
+ }
968
+ async function setAgentInstructionsHandler(c2) {
969
+ try {
970
+ const isPlayground = c2.get("playground") === true;
971
+ if (!isPlayground) {
972
+ return c2.json({ error: "This API is only available in the playground environment" }, 403);
973
+ }
974
+ const agentId = c2.req.param("agentId");
975
+ const { instructions } = await c2.req.json();
976
+ if (!agentId || !instructions) {
977
+ return c2.json({ error: "Missing required fields" }, 400);
978
+ }
979
+ const mastra = c2.get("mastra");
980
+ const agent = mastra.getAgent(agentId);
981
+ if (!agent) {
982
+ return c2.json({ error: "Agent not found" }, 404);
983
+ }
984
+ agent.__updateInstructions(instructions);
985
+ return c2.json(
986
+ {
987
+ instructions
988
+ },
989
+ 200
990
+ );
991
+ } catch (error) {
992
+ return handleError(error, "Error setting agent instructions");
993
+ }
994
+ }
995
+
996
+ // src/server/handlers/client.ts
997
+ var clients = /* @__PURE__ */ new Set();
998
+ function handleClientsRefresh(c2) {
999
+ const stream2 = new ReadableStream({
1000
+ start(controller) {
1001
+ clients.add(controller);
1002
+ controller.enqueue("data: connected\n\n");
1003
+ c2.req.raw.signal.addEventListener("abort", () => {
1004
+ clients.delete(controller);
1005
+ });
1006
+ }
1007
+ });
1008
+ return new Response(stream2, {
1009
+ headers: {
1010
+ "Content-Type": "text/event-stream",
1011
+ "Cache-Control": "no-cache",
1012
+ Connection: "keep-alive",
1013
+ "Access-Control-Allow-Origin": "*"
1014
+ }
1015
+ });
1016
+ }
1017
+ function handleTriggerClientsRefresh(c2) {
1018
+ clients.forEach((controller) => {
1019
+ try {
1020
+ controller.enqueue("data: refresh\n\n");
1021
+ } catch {
1022
+ clients.delete(controller);
1023
+ }
1024
+ });
1025
+ return c2.json({ success: true, clients: clients.size });
1026
+ }
1027
+ async function getLogsHandler(c2) {
1028
+ try {
1029
+ const mastra = c2.get("mastra");
1030
+ const transportId = c2.req.query("transportId");
1031
+ const logs = await getLogsHandler$1({
1032
+ mastra,
1033
+ transportId
1034
+ });
1035
+ return c2.json(logs);
1036
+ } catch (error) {
1037
+ return handleError(error, "Error getting logs");
1038
+ }
1039
+ }
1040
+ async function getLogsByRunIdHandler(c2) {
1041
+ try {
1042
+ const mastra = c2.get("mastra");
1043
+ const runId = c2.req.param("runId");
1044
+ const transportId = c2.req.query("transportId");
1045
+ const logs = await getLogsByRunIdHandler$1({
1046
+ mastra,
1047
+ runId,
1048
+ transportId
1049
+ });
1050
+ return c2.json(logs);
1051
+ } catch (error) {
1052
+ return handleError(error, "Error getting logs by run ID");
1053
+ }
1054
+ }
1055
+ async function getLogTransports(c2) {
1056
+ try {
1057
+ const mastra = c2.get("mastra");
1058
+ const result = await getLogTransports$1({
1059
+ mastra
1060
+ });
1061
+ return c2.json(result);
1062
+ } catch (error) {
1063
+ return handleError(error, "Error getting log Transports");
1064
+ }
1065
+ }
1066
+ async function getMemoryStatusHandler(c2) {
1067
+ try {
1068
+ const mastra = c2.get("mastra");
1069
+ const agentId = c2.req.query("agentId");
1070
+ const result = await getMemoryStatusHandler$1({
1071
+ mastra,
1072
+ agentId
1073
+ });
1074
+ return c2.json(result);
1075
+ } catch (error) {
1076
+ return handleError(error, "Error getting memory status");
1077
+ }
1078
+ }
1079
+ async function getThreadsHandler(c2) {
1080
+ try {
1081
+ const mastra = c2.get("mastra");
1082
+ const agentId = c2.req.query("agentId");
1083
+ const resourceId = c2.req.query("resourceid");
1084
+ const result = await getThreadsHandler$1({
1085
+ mastra,
1086
+ agentId,
1087
+ resourceId
1088
+ });
1089
+ return c2.json(result);
1090
+ } catch (error) {
1091
+ return handleError(error, "Error getting threads");
1092
+ }
1093
+ }
1094
+ async function getThreadByIdHandler(c2) {
1095
+ try {
1096
+ const mastra = c2.get("mastra");
1097
+ const agentId = c2.req.query("agentId");
1098
+ const threadId = c2.req.param("threadId");
1099
+ const result = await getThreadByIdHandler$1({
1100
+ mastra,
1101
+ agentId,
1102
+ threadId
1103
+ });
1104
+ return c2.json(result);
1105
+ } catch (error) {
1106
+ return handleError(error, "Error getting thread");
1107
+ }
1108
+ }
1109
+ async function saveMessagesHandler(c2) {
1110
+ try {
1111
+ const mastra = c2.get("mastra");
1112
+ const agentId = c2.req.query("agentId");
1113
+ const body = await c2.req.json();
1114
+ const result = await saveMessagesHandler$1({
1115
+ mastra,
1116
+ agentId,
1117
+ body
1118
+ });
1119
+ return c2.json(result);
1120
+ } catch (error) {
1121
+ return handleError(error, "Error saving messages");
1122
+ }
1123
+ }
1124
+ async function createThreadHandler(c2) {
1125
+ try {
1126
+ const mastra = c2.get("mastra");
1127
+ const agentId = c2.req.query("agentId");
1128
+ const body = await c2.req.json();
1129
+ const result = await createThreadHandler$1({
1130
+ mastra,
1131
+ agentId,
1132
+ body
1133
+ });
1134
+ return c2.json(result);
1135
+ } catch (error) {
1136
+ return handleError(error, "Error saving thread to memory");
1137
+ }
1138
+ }
1139
+ async function updateThreadHandler(c2) {
1140
+ try {
1141
+ const mastra = c2.get("mastra");
1142
+ const agentId = c2.req.query("agentId");
1143
+ const threadId = c2.req.param("threadId");
1144
+ const body = await c2.req.json();
1145
+ const result = await updateThreadHandler$1({
1146
+ mastra,
1147
+ agentId,
1148
+ threadId,
1149
+ body
1150
+ });
1151
+ return c2.json(result);
1152
+ } catch (error) {
1153
+ return handleError(error, "Error updating thread");
1154
+ }
1155
+ }
1156
+ async function deleteThreadHandler(c2) {
1157
+ try {
1158
+ const mastra = c2.get("mastra");
1159
+ const agentId = c2.req.query("agentId");
1160
+ const threadId = c2.req.param("threadId");
1161
+ const result = await deleteThreadHandler$1({
1162
+ mastra,
1163
+ agentId,
1164
+ threadId
1165
+ });
1166
+ return c2.json(result);
1167
+ } catch (error) {
1168
+ return handleError(error, "Error deleting thread");
1169
+ }
1170
+ }
1171
+ async function getMessagesHandler(c2) {
1172
+ try {
1173
+ const mastra = c2.get("mastra");
1174
+ const agentId = c2.req.query("agentId");
1175
+ const threadId = c2.req.param("threadId");
1176
+ const result = await getMessagesHandler$1({
1177
+ mastra,
1178
+ agentId,
1179
+ threadId
1180
+ });
1181
+ return c2.json(result);
1182
+ } catch (error) {
1183
+ return handleError(error, "Error getting messages");
1184
+ }
1185
+ }
1186
+ async function getNetworksHandler(c2) {
1187
+ try {
1188
+ const mastra = c2.get("mastra");
1189
+ const networks = await getNetworksHandler$1({
1190
+ mastra
1191
+ });
1192
+ return c2.json(networks);
1193
+ } catch (error) {
1194
+ return handleError(error, "Error getting networks");
1195
+ }
1196
+ }
1197
+ async function getNetworkByIdHandler(c2) {
1198
+ try {
1199
+ const mastra = c2.get("mastra");
1200
+ const networkId = c2.req.param("networkId");
1201
+ const network = await getNetworkByIdHandler$1({
1202
+ mastra,
1203
+ networkId
1204
+ });
1205
+ return c2.json(network);
1206
+ } catch (error) {
1207
+ return handleError(error, "Error getting network by ID");
1208
+ }
1209
+ }
1210
+ async function generateHandler2(c2) {
1211
+ try {
1212
+ const mastra = c2.get("mastra");
1213
+ const container = c2.get("container");
1214
+ const networkId = c2.req.param("networkId");
1215
+ const body = await c2.req.json();
1216
+ const result = await generateHandler$1({
1217
+ mastra,
1218
+ container,
1219
+ networkId,
1220
+ body
1221
+ });
1222
+ return c2.json(result);
1223
+ } catch (error) {
1224
+ return handleError(error, "Error generating from network");
1225
+ }
1226
+ }
1227
+ async function streamGenerateHandler2(c2) {
1228
+ try {
1229
+ const mastra = c2.get("mastra");
1230
+ const container = c2.get("container");
1231
+ const networkId = c2.req.param("networkId");
1232
+ const body = await c2.req.json();
1233
+ const streamResponse = await streamGenerateHandler$1({
1234
+ mastra,
1235
+ container,
1236
+ networkId,
1237
+ body
1238
+ });
1239
+ return streamResponse;
1240
+ } catch (error) {
1241
+ return handleError(error, "Error streaming from network");
1242
+ }
1243
+ }
1244
+ async function generateSystemPromptHandler(c2) {
1245
+ try {
1246
+ const agentId = c2.req.param("agentId");
1247
+ const isPlayground = c2.get("playground") === true;
1248
+ if (!isPlayground) {
1249
+ return c2.json({ error: "This API is only available in the playground environment" }, 403);
1250
+ }
1251
+ const { instructions, comment } = await c2.req.json();
1252
+ if (!instructions) {
1253
+ return c2.json({ error: "Missing instructions in request body" }, 400);
1254
+ }
1255
+ const mastra = c2.get("mastra");
1256
+ const agent = mastra.getAgent(agentId);
1257
+ if (!agent) {
1258
+ return c2.json({ error: "Agent not found" }, 404);
1259
+ }
1260
+ let evalSummary = "";
1261
+ try {
1262
+ const testEvals = await mastra.getStorage()?.getEvalsByAgentName?.(agent.name, "test") || [];
1263
+ const liveEvals = await mastra.getStorage()?.getEvalsByAgentName?.(agent.name, "live") || [];
1264
+ const evalsMapped = [...testEvals, ...liveEvals].filter(
1265
+ ({ instructions: evalInstructions }) => evalInstructions === instructions
1266
+ );
1267
+ evalSummary = evalsMapped.map(
1268
+ ({ input, output, result: result2 }) => `
1269
+ Input: ${input}
1270
+
1271
+ Output: ${output}
1272
+
1273
+ Result: ${JSON.stringify(result2)}
1274
+
1275
+ `
1276
+ ).join("");
1277
+ } catch (error) {
1278
+ mastra.getLogger().error(`Error fetching evals`, { error });
1279
+ }
1280
+ const ENHANCE_SYSTEM_PROMPT_INSTRUCTIONS = `
1281
+ You are an expert system prompt engineer, specialized in analyzing and enhancing instructions to create clear, effective, and comprehensive system prompts. Your goal is to help users transform their basic instructions into well-structured system prompts that will guide AI behavior effectively.
1282
+ Follow these steps to analyze and enhance the instructions:
1283
+ 1. ANALYSIS PHASE
1284
+ - Identify the core purpose and goals
1285
+ - Extract key constraints and requirements
1286
+ - Recognize domain-specific terminology and concepts
1287
+ - Note any implicit assumptions that should be made explicit
1288
+ 2. PROMPT STRUCTURE
1289
+ Create a system prompt with these components:
1290
+ a) ROLE DEFINITION
1291
+ - Clear statement of the AI's role and purpose
1292
+ - Key responsibilities and scope
1293
+ - Primary stakeholders and users
1294
+ b) CORE CAPABILITIES
1295
+ - Main functions and abilities
1296
+ - Specific domain knowledge required
1297
+ - Tools and resources available
1298
+ c) BEHAVIORAL GUIDELINES
1299
+ - Communication style and tone
1300
+ - Decision-making framework
1301
+ - Error handling approach
1302
+ - Ethical considerations
1303
+ d) CONSTRAINTS & BOUNDARIES
1304
+ - Explicit limitations
1305
+ - Out-of-scope activities
1306
+ - Security and privacy considerations
1307
+ e) SUCCESS CRITERIA
1308
+ - Quality standards
1309
+ - Expected outcomes
1310
+ - Performance metrics
1311
+ 3. QUALITY CHECKS
1312
+ Ensure the prompt is:
1313
+ - Clear and unambiguous
1314
+ - Comprehensive yet concise
1315
+ - Properly scoped
1316
+ - Technically accurate
1317
+ - Ethically sound
1318
+ 4. OUTPUT FORMAT
1319
+ Return a structured response with:
1320
+ - Enhanced system prompt
1321
+ - Analysis of key components
1322
+ - Identified goals and constraints
1323
+ - Core domain concepts
1324
+ Remember: A good system prompt should be specific enough to guide behavior but flexible enough to handle edge cases.
1325
+ Focus on creating prompts that are clear, actionable, and aligned with the intended use case.
1326
+ `;
1327
+ const systemPromptAgent = new Agent({
1328
+ name: "system-prompt-enhancer",
1329
+ instructions: ENHANCE_SYSTEM_PROMPT_INSTRUCTIONS,
1330
+ model: agent.llm?.getModel()
1331
+ });
1332
+ const result = await systemPromptAgent.generate(
1333
+ `
1334
+ We need to improve the system prompt.
1335
+ Current: ${instructions}
1336
+ ${comment ? `User feedback: ${comment}` : ""}
1337
+ ${evalSummary ? `
1338
+ Evaluation Results:
1339
+ ${evalSummary}` : ""}
1340
+ `,
1341
+ {
1342
+ output: z.object({
1343
+ new_prompt: z.string(),
1344
+ explanation: z.string()
1345
+ })
1346
+ }
1347
+ );
1348
+ return c2.json(result?.object || {});
1349
+ } catch (error) {
1350
+ return handleError(error, "Error generating system prompt");
1351
+ }
1352
+ }
1353
+
1354
+ // src/server/handlers/root.ts
1355
+ async function rootHandler(c2) {
1356
+ return c2.text("Hello to the Mastra API!");
1357
+ }
1358
+ async function getTelemetryHandler(c2) {
1359
+ try {
1360
+ const mastra = c2.get("mastra");
1361
+ const { name, scope, page, perPage } = c2.req.query();
1362
+ const attribute = c2.req.queries("attribute");
1363
+ const traces = await getTelemetryHandler$1({
1364
+ mastra,
1365
+ body: { name, scope, page: Number(page ?? 0), perPage: Number(perPage ?? 100), attribute }
1366
+ });
1367
+ return c2.json({ traces });
1368
+ } catch (error) {
1369
+ return handleError(error, "Error getting telemetry traces");
1370
+ }
1371
+ }
1372
+ async function storeTelemetryHandler(c2) {
1373
+ try {
1374
+ const body = await c2.req.json();
1375
+ const mastra = c2.get("mastra");
1376
+ const result = await storeTelemetryHandler$1({ mastra, body });
1377
+ if (result.status === "error") {
1378
+ return c2.json(result, 500);
1379
+ }
1380
+ return c2.json(result, 200);
1381
+ } catch (error) {
1382
+ return handleError(error, "Error storing telemetry traces");
1383
+ }
1384
+ }
1385
+ async function getToolsHandler(c2) {
1386
+ try {
1387
+ const tools = c2.get("tools");
1388
+ const result = await getToolsHandler$1({
1389
+ tools
1390
+ });
1391
+ return c2.json(result);
1392
+ } catch (error) {
1393
+ return handleError(error, "Error getting tools");
1394
+ }
1395
+ }
1396
+ async function getToolByIdHandler(c2) {
1397
+ try {
1398
+ const tools = c2.get("tools");
1399
+ const toolId = c2.req.param("toolId");
1400
+ const result = await getToolByIdHandler$1({
1401
+ tools,
1402
+ toolId
1403
+ });
1404
+ return c2.json(result);
1405
+ } catch (error) {
1406
+ return handleError(error, "Error getting tool");
1407
+ }
1408
+ }
1409
+ function executeToolHandler(tools) {
1410
+ return async (c2) => {
1411
+ try {
1412
+ const mastra = c2.get("mastra");
1413
+ const container = c2.get("container");
1414
+ const toolId = decodeURIComponent(c2.req.param("toolId"));
1415
+ const { data } = await c2.req.json();
1416
+ const result = await executeToolHandler$1(tools)({
1417
+ mastra,
1418
+ toolId,
1419
+ data,
1420
+ container
1421
+ });
1422
+ return c2.json(result);
1423
+ } catch (error) {
1424
+ return handleError(error, "Error executing tool");
1425
+ }
1426
+ };
1427
+ }
1428
+ async function executeAgentToolHandler(c2) {
1429
+ try {
1430
+ const mastra = c2.get("mastra");
1431
+ const container = c2.get("container");
1432
+ const agentId = c2.req.param("agentId");
1433
+ const toolId = c2.req.param("toolId");
1434
+ const { data } = await c2.req.json();
1435
+ const result = await executeAgentToolHandler$1({
1436
+ mastra,
1437
+ agentId,
1438
+ toolId,
1439
+ data,
1440
+ container
1441
+ });
1442
+ return c2.json(result);
1443
+ } catch (error) {
1444
+ return handleError(error, "Error executing tool");
1445
+ }
1446
+ }
1447
+ async function upsertVectors(c2) {
1448
+ try {
1449
+ const mastra = c2.get("mastra");
1450
+ const vectorName = c2.req.param("vectorName");
1451
+ const body = await c2.req.json();
1452
+ const result = await upsertVectors$1({
1453
+ mastra,
1454
+ vectorName,
1455
+ index: body
1456
+ });
1457
+ return c2.json({ ids: result });
1458
+ } catch (error) {
1459
+ return handleError(error, "Error upserting vectors");
1460
+ }
1461
+ }
1462
+ async function createIndex(c2) {
1463
+ try {
1464
+ const mastra = c2.get("mastra");
1465
+ const vectorName = c2.req.param("vectorName");
1466
+ const body = await c2.req.json();
1467
+ await createIndex$1({
1468
+ mastra,
1469
+ vectorName,
1470
+ index: body
1471
+ });
1472
+ return c2.json({ success: true });
1473
+ } catch (error) {
1474
+ return handleError(error, "Error creating index");
1475
+ }
1476
+ }
1477
+ async function queryVectors(c2) {
1478
+ try {
1479
+ const mastra = c2.get("mastra");
1480
+ const vectorName = c2.req.param("vectorName");
1481
+ const { indexName, queryVector, topK = 10, filter, includeVector = false } = await c2.req.json();
1482
+ const results = await queryVectors$1({
1483
+ mastra,
1484
+ vectorName,
1485
+ query: { indexName, queryVector, topK, filter, includeVector }
1486
+ });
1487
+ return c2.json({ results });
1488
+ } catch (error) {
1489
+ return handleError(error, "Error querying vectors");
1490
+ }
1491
+ }
1492
+ async function listIndexes(c2) {
1493
+ try {
1494
+ const mastra = c2.get("mastra");
1495
+ const vectorName = c2.req.param("vectorName");
1496
+ const indexes = await listIndexes$1({
1497
+ mastra,
1498
+ vectorName
1499
+ });
1500
+ return c2.json({ indexes });
1501
+ } catch (error) {
1502
+ return handleError(error, "Error listing indexes");
1503
+ }
1504
+ }
1505
+ async function describeIndex(c2) {
1506
+ try {
1507
+ const mastra = c2.get("mastra");
1508
+ const vectorName = c2.req.param("vectorName");
1509
+ const indexName = c2.req.param("indexName");
1510
+ if (!indexName) {
1511
+ throw new HTTPException(400, { message: "Index name is required" });
1512
+ }
1513
+ const stats = await describeIndex$1({
1514
+ mastra,
1515
+ vectorName,
1516
+ indexName
1517
+ });
1518
+ return c2.json({
1519
+ dimension: stats.dimension,
1520
+ count: stats.count,
1521
+ metric: stats.metric?.toLowerCase()
1522
+ });
1523
+ } catch (error) {
1524
+ return handleError(error, "Error describing index");
1525
+ }
1526
+ }
1527
+ async function deleteIndex(c2) {
1528
+ try {
1529
+ const mastra = c2.get("mastra");
1530
+ const vectorName = c2.req.param("vectorName");
1531
+ const indexName = c2.req.param("indexName");
1532
+ if (!indexName) {
1533
+ throw new HTTPException(400, { message: "Index name is required" });
1534
+ }
1535
+ await deleteIndex$1({
1536
+ mastra,
1537
+ vectorName,
1538
+ indexName
1539
+ });
1540
+ return c2.json({ success: true });
1541
+ } catch (error) {
1542
+ return handleError(error, "Error deleting index");
1543
+ }
1544
+ }
1545
+ async function getSpeakersHandler(c2) {
1546
+ try {
1547
+ const mastra = c2.get("mastra");
1548
+ const agentId = c2.req.param("agentId");
1549
+ const speakers = await getSpeakersHandler$1({
1550
+ mastra,
1551
+ agentId
1552
+ });
1553
+ return c2.json(speakers);
1554
+ } catch (error) {
1555
+ return handleError(error, "Error getting speakers");
1556
+ }
1557
+ }
1558
+ async function speakHandler(c2) {
1559
+ try {
1560
+ const mastra = c2.get("mastra");
1561
+ const agentId = c2.req.param("agentId");
1562
+ const { input, options } = await c2.req.json();
1563
+ const audioStream = await generateSpeechHandler({
1564
+ mastra,
1565
+ agentId,
1566
+ body: { text: input, speakerId: options?.speakerId }
1567
+ });
1568
+ c2.header("Content-Type", `audio/${options?.filetype ?? "mp3"}`);
1569
+ c2.header("Transfer-Encoding", "chunked");
1570
+ return c2.body(audioStream);
1571
+ } catch (error) {
1572
+ return handleError(error, "Error generating speech");
1573
+ }
1574
+ }
1575
+ async function listenHandler(c2) {
1576
+ try {
1577
+ const mastra = c2.get("mastra");
1578
+ const agentId = c2.req.param("agentId");
1579
+ const formData = await c2.req.formData();
1580
+ const audioFile = formData.get("audio");
1581
+ const options = formData.get("options");
1582
+ if (!audioFile || !(audioFile instanceof File)) {
1583
+ throw new HTTPException(400, { message: "Audio file is required" });
1584
+ }
1585
+ const audioData = await audioFile.arrayBuffer();
1586
+ let parsedOptions = {};
1587
+ try {
1588
+ parsedOptions = options ? JSON.parse(options) : {};
1589
+ } catch {
1590
+ }
1591
+ const transcription = await transcribeSpeechHandler({
1592
+ mastra,
1593
+ agentId,
1594
+ body: {
1595
+ audioData: Buffer.from(audioData),
1596
+ options: parsedOptions
1597
+ }
1598
+ });
1599
+ return c2.json({ text: transcription });
1600
+ } catch (error) {
1601
+ return handleError(error, "Error transcribing speech");
1602
+ }
1603
+ }
1604
+ async function getWorkflowsHandler(c2) {
1605
+ try {
1606
+ const mastra = c2.get("mastra");
1607
+ const workflows = await getWorkflowsHandler$1({
1608
+ mastra
1609
+ });
1610
+ return c2.json(workflows);
1611
+ } catch (error) {
1612
+ return handleError(error, "Error getting workflows");
1613
+ }
1614
+ }
1615
+ async function getWorkflowByIdHandler(c2) {
1616
+ try {
1617
+ const mastra = c2.get("mastra");
1618
+ const workflowId = c2.req.param("workflowId");
1619
+ const workflow = await getWorkflowByIdHandler$1({
1620
+ mastra,
1621
+ workflowId
1622
+ });
1623
+ return c2.json(workflow);
1624
+ } catch (error) {
1625
+ return handleError(error, "Error getting workflow");
1626
+ }
1627
+ }
1628
+ async function startAsyncWorkflowHandler(c2) {
1629
+ try {
1630
+ const mastra = c2.get("mastra");
1631
+ const container = c2.get("container");
1632
+ const workflowId = c2.req.param("workflowId");
1633
+ const triggerData = await c2.req.json();
1634
+ const runId = c2.req.query("runId");
1635
+ const result = await startAsyncWorkflowHandler$1({
1636
+ mastra,
1637
+ container,
1638
+ workflowId,
1639
+ runId,
1640
+ triggerData
1641
+ });
1642
+ return c2.json(result);
1643
+ } catch (error) {
1644
+ return handleError(error, "Error executing workflow");
1645
+ }
1646
+ }
1647
+ async function createRunHandler(c2) {
1648
+ try {
1649
+ const mastra = c2.get("mastra");
1650
+ const workflowId = c2.req.param("workflowId");
1651
+ const prevRunId = c2.req.query("runId");
1652
+ const result = await createRunHandler$1({
1653
+ mastra,
1654
+ workflowId,
1655
+ runId: prevRunId
1656
+ });
1657
+ return c2.json(result);
1658
+ } catch (e2) {
1659
+ return handleError(e2, "Error creating run");
1660
+ }
1661
+ }
1662
+ async function startWorkflowRunHandler(c2) {
1663
+ try {
1664
+ const mastra = c2.get("mastra");
1665
+ const container = c2.get("container");
1666
+ const workflowId = c2.req.param("workflowId");
1667
+ const triggerData = await c2.req.json();
1668
+ const runId = c2.req.query("runId");
1669
+ await startWorkflowRunHandler$1({
1670
+ mastra,
1671
+ container,
1672
+ workflowId,
1673
+ runId,
1674
+ triggerData
1675
+ });
1676
+ return c2.json({ message: "Workflow run started" });
1677
+ } catch (e2) {
1678
+ return handleError(e2, "Error starting workflow run");
1679
+ }
1680
+ }
1681
+ function watchWorkflowHandler(c2) {
1682
+ try {
1683
+ const mastra = c2.get("mastra");
1684
+ const logger2 = mastra.getLogger();
1685
+ const workflowId = c2.req.param("workflowId");
1686
+ const runId = c2.req.query("runId");
1687
+ if (!runId) {
1688
+ throw new HTTPException(400, { message: "runId required to watch workflow" });
1689
+ }
1690
+ return stream(
1691
+ c2,
1692
+ async (stream2) => {
1693
+ try {
1694
+ const result = await watchWorkflowHandler$1({
1695
+ mastra,
1696
+ workflowId,
1697
+ runId
1698
+ });
1699
+ stream2.onAbort(() => {
1700
+ if (!result.locked) {
1701
+ return result.cancel();
1702
+ }
1703
+ });
1704
+ for await (const chunk of result) {
1705
+ await stream2.write(chunk.toString() + "");
1706
+ }
1707
+ } catch (err) {
1708
+ console.log(err);
1709
+ }
1710
+ },
1711
+ async (err) => {
1712
+ logger2.error("Error in watch stream: " + err?.message);
1713
+ }
1714
+ );
1715
+ } catch (error) {
1716
+ return handleError(error, "Error watching workflow");
1717
+ }
1718
+ }
1719
+ async function resumeAsyncWorkflowHandler(c2) {
1720
+ try {
1721
+ const mastra = c2.get("mastra");
1722
+ const container = c2.get("container");
1723
+ const workflowId = c2.req.param("workflowId");
1724
+ const runId = c2.req.query("runId");
1725
+ const { stepId, context } = await c2.req.json();
1726
+ if (!runId) {
1727
+ throw new HTTPException(400, { message: "runId required to resume workflow" });
1728
+ }
1729
+ const result = await resumeAsyncWorkflowHandler$1({
1730
+ mastra,
1731
+ container,
1732
+ workflowId,
1733
+ runId,
1734
+ body: { stepId, context }
1735
+ });
1736
+ return c2.json(result);
1737
+ } catch (error) {
1738
+ return handleError(error, "Error resuming workflow step");
1739
+ }
1740
+ }
1741
+ async function resumeWorkflowHandler(c2) {
1742
+ try {
1743
+ const mastra = c2.get("mastra");
1744
+ const container = c2.get("container");
1745
+ const workflowId = c2.req.param("workflowId");
1746
+ const runId = c2.req.query("runId");
1747
+ const { stepId, context } = await c2.req.json();
1748
+ if (!runId) {
1749
+ throw new HTTPException(400, { message: "runId required to resume workflow" });
1750
+ }
1751
+ await resumeWorkflowHandler$1({
1752
+ mastra,
1753
+ container,
1754
+ workflowId,
1755
+ runId,
1756
+ body: { stepId, context }
1757
+ });
1758
+ return c2.json({ message: "Workflow run resumed" });
1759
+ } catch (error) {
1760
+ return handleError(error, "Error resuming workflow");
1761
+ }
1762
+ }
1763
+ async function getWorkflowRunsHandler(c2) {
1764
+ try {
1765
+ const mastra = c2.get("mastra");
1766
+ const workflowId = c2.req.param("workflowId");
1767
+ const workflowRuns = await getWorkflowRunsHandler$1({
1768
+ mastra,
1769
+ workflowId
1770
+ });
1771
+ return c2.json(workflowRuns);
1772
+ } catch (error) {
1773
+ return handleError(error, "Error getting workflow runs");
1774
+ }
1775
+ }
1776
+
1777
+ // src/server/welcome.ts
1778
+ var html2 = `
1779
+ <!doctype html>
1780
+ <html lang="en">
1781
+ <head>
1782
+ <meta charset="UTF-8" />
1783
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
1784
+ <title>Welcome to Mastra</title>
1785
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/inter-ui/3.19.3/inter.min.css" />
1786
+ <style>
1787
+ body {
1788
+ margin: 0;
1789
+ padding: 0;
1790
+ background-color: #0d0d0d;
1791
+ color: #ffffff;
1792
+ font-family:
1793
+ 'Inter',
1794
+ -apple-system,
1795
+ BlinkMacSystemFont,
1796
+ system-ui,
1797
+ sans-serif;
1798
+ min-height: 100vh;
1799
+ display: flex;
1800
+ flex-direction: column;
1801
+ }
1802
+
1803
+ main {
1804
+ flex: 1;
1805
+ display: flex;
1806
+ flex-direction: column;
1807
+ align-items: center;
1808
+ justify-content: center;
1809
+ padding: 2rem;
1810
+ text-align: center;
1811
+ }
1812
+
1813
+ h1 {
1814
+ font-size: 4rem;
1815
+ font-weight: 600;
1816
+ margin: 0 0 1rem 0;
1817
+ background: linear-gradient(to right, #fff, #ccc);
1818
+ -webkit-background-clip: text;
1819
+ -webkit-text-fill-color: transparent;
1820
+ line-height: 1.2;
1821
+ }
1822
+
1823
+ .subtitle {
1824
+ color: #9ca3af;
1825
+ font-size: 1.25rem;
1826
+ max-width: 600px;
1827
+ margin: 0 auto 3rem auto;
1828
+ line-height: 1.6;
1829
+ }
1830
+
1831
+ .docs-link {
1832
+ background-color: #1a1a1a;
1833
+ padding: 1rem 2rem;
1834
+ border-radius: 0.5rem;
1835
+ display: flex;
1836
+ align-items: center;
1837
+ gap: 1rem;
1838
+ font-family: monospace;
1839
+ font-size: 1rem;
1840
+ color: #ffffff;
1841
+ text-decoration: none;
1842
+ transition: background-color 0.2s;
1843
+ }
1844
+
1845
+ .docs-link:hover {
1846
+ background-color: #252525;
1847
+ }
1848
+
1849
+ .arrow-icon {
1850
+ transition: transform 0.2s;
1851
+ }
1852
+
1853
+ .docs-link:hover .arrow-icon {
1854
+ transform: translateX(4px);
1855
+ }
1856
+ </style>
1857
+ </head>
1858
+ <body>
1859
+ <main>
1860
+ <h1>Welcome to Mastra</h1>
1861
+ <p class="subtitle">
1862
+ From the team that brought you Gatsby: prototype and productionize AI features with a modern JS/TS stack.
1863
+ </p>
1864
+
1865
+ <a href="https://mastra.ai/docs" class="docs-link">
1866
+ Browse the docs
1867
+ <svg
1868
+ class="arrow-icon"
1869
+ width="20"
1870
+ height="20"
1871
+ viewBox="0 0 24 24"
1872
+ fill="none"
1873
+ stroke="currentColor"
1874
+ strokeWidth="2"
1875
+ >
1876
+ <path d="M5 12h14M12 5l7 7-7 7" />
1877
+ </svg>
1878
+ </a>
1879
+ </main>
1880
+ </body>
1881
+ </html>
1882
+ `;
1883
+
1884
+ // src/server/index.ts
1885
+ async function createHonoServer(mastra, options = {}) {
1886
+ const app = new Hono();
1887
+ const server = mastra.getServer();
1888
+ const __dirname = dirname(fileURLToPath(import.meta.url));
1889
+ const mastraToolsPaths = (await import(pathToFileURL(join(__dirname, "tools.mjs")).href)).tools;
1890
+ const toolImports = mastraToolsPaths ? await Promise.all(
1891
+ // @ts-ignore
1892
+ mastraToolsPaths.map(async (toolPath) => {
1893
+ return import(pathToFileURL(join(__dirname, toolPath)).href);
1894
+ })
1895
+ ) : [];
1896
+ const tools = toolImports.reduce((acc, toolModule) => {
1897
+ Object.entries(toolModule).forEach(([key, tool]) => {
1898
+ acc[key] = tool;
1899
+ });
1900
+ return acc;
1901
+ }, {});
1902
+ app.use("*", async function setTelemetryInfo(c2, next) {
1903
+ const requestId = c2.req.header("x-request-id") ?? randomUUID();
1904
+ const span = Telemetry.getActiveSpan();
1905
+ if (span) {
1906
+ span.setAttribute("http.request_id", requestId);
1907
+ span.updateName(`${c2.req.method} ${c2.req.path}`);
1908
+ const newCtx = Telemetry.setBaggage({
1909
+ "http.request_id": requestId
1910
+ });
1911
+ await new Promise((resolve) => {
1912
+ Telemetry.withContext(newCtx, async () => {
1913
+ await next();
1914
+ resolve(true);
1915
+ });
1916
+ });
1917
+ } else {
1918
+ await next();
1919
+ }
1920
+ });
1921
+ if (options.apiReqLogs) {
1922
+ app.use(logger());
1923
+ }
1924
+ app.onError(errorHandler);
1925
+ app.use("*", function setContext(c2, next) {
1926
+ const container = new Container();
1927
+ c2.set("container", container);
1928
+ c2.set("mastra", mastra);
1929
+ c2.set("tools", tools);
1930
+ c2.set("playground", options.playground === true);
1931
+ return next();
1932
+ });
1933
+ const serverMiddleware = mastra.getServerMiddleware?.();
1934
+ if (serverMiddleware && serverMiddleware.length > 0) {
1935
+ for (const m2 of serverMiddleware) {
1936
+ app.use(m2.path, m2.handler);
1937
+ }
1938
+ }
1939
+ if (server?.cors === false) {
1940
+ app.use("*", timeout(server?.timeout ?? 3 * 60 * 1e3));
1941
+ } else {
1942
+ const corsConfig = {
1943
+ origin: "*",
1944
+ allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
1945
+ credentials: false,
1946
+ maxAge: 3600,
1947
+ ...server?.cors,
1948
+ allowHeaders: ["Content-Type", "Authorization", "x-mastra-client-type", ...server?.cors?.allowHeaders ?? []],
1949
+ exposeHeaders: ["Content-Length", "X-Requested-With", ...server?.cors?.exposeHeaders ?? []]
1950
+ };
1951
+ app.use("*", timeout(server?.timeout ?? 3 * 60 * 1e3), cors(corsConfig));
1952
+ }
1953
+ const bodyLimitOptions = {
1954
+ maxSize: 4.5 * 1024 * 1024,
1955
+ // 4.5 MB,
1956
+ onError: (c2) => c2.json({ error: "Request body too large" }, 413)
1957
+ };
1958
+ const routes = server?.apiRoutes;
1959
+ if (server?.middleware) {
1960
+ const normalizedMiddlewares = Array.isArray(server.middleware) ? server.middleware : [server.middleware];
1961
+ const middlewares = normalizedMiddlewares.map((middleware2) => {
1962
+ if (typeof middleware2 === "function") {
1963
+ return {
1964
+ path: "*",
1965
+ handler: middleware2
1966
+ };
1967
+ }
1968
+ return middleware2;
1969
+ });
1970
+ for (const middleware2 of middlewares) {
1971
+ app.use(middleware2.path, middleware2.handler);
1972
+ }
1973
+ }
1974
+ if (routes) {
1975
+ for (const route of routes) {
1976
+ const middlewares = [];
1977
+ if (route.middleware) {
1978
+ middlewares.push(...Array.isArray(route.middleware) ? route.middleware : [route.middleware]);
1979
+ }
1980
+ if (route.openapi) {
1981
+ middlewares.push(h(route.openapi));
1982
+ }
1983
+ if (route.method === "GET") {
1984
+ app.get(route.path, ...middlewares, route.handler);
1985
+ } else if (route.method === "POST") {
1986
+ app.post(route.path, ...middlewares, route.handler);
1987
+ } else if (route.method === "PUT") {
1988
+ app.put(route.path, ...middlewares, route.handler);
1989
+ } else if (route.method === "DELETE") {
1990
+ app.delete(route.path, ...middlewares, route.handler);
1991
+ }
1992
+ }
1993
+ }
1994
+ app.get(
1995
+ "/api",
1996
+ h({
1997
+ description: "Get API status",
1998
+ tags: ["system"],
1999
+ responses: {
2000
+ 200: {
2001
+ description: "Success"
2002
+ }
2003
+ }
2004
+ }),
2005
+ rootHandler
2006
+ );
2007
+ app.get(
2008
+ "/api/agents",
2009
+ h({
2010
+ description: "Get all available agents",
2011
+ tags: ["agents"],
2012
+ responses: {
2013
+ 200: {
2014
+ description: "List of all agents"
2015
+ }
2016
+ }
2017
+ }),
2018
+ getAgentsHandler
2019
+ );
2020
+ app.get(
2021
+ "/api/networks",
2022
+ h({
2023
+ description: "Get all available networks",
2024
+ tags: ["networks"],
2025
+ responses: {
2026
+ 200: {
2027
+ description: "List of all networks"
2028
+ }
2029
+ }
2030
+ }),
2031
+ getNetworksHandler
2032
+ );
2033
+ app.get(
2034
+ "/api/networks/:networkId",
2035
+ h({
2036
+ description: "Get network by ID",
2037
+ tags: ["networks"],
2038
+ parameters: [
2039
+ {
2040
+ name: "networkId",
2041
+ in: "path",
2042
+ required: true,
2043
+ schema: { type: "string" }
2044
+ }
2045
+ ],
2046
+ responses: {
2047
+ 200: {
2048
+ description: "Network details"
2049
+ },
2050
+ 404: {
2051
+ description: "Network not found"
2052
+ }
2053
+ }
2054
+ }),
2055
+ getNetworkByIdHandler
2056
+ );
2057
+ app.post(
2058
+ "/api/networks/:networkId/generate",
2059
+ bodyLimit(bodyLimitOptions),
2060
+ h({
2061
+ description: "Generate a response from a network",
2062
+ tags: ["networks"],
2063
+ parameters: [
2064
+ {
2065
+ name: "networkId",
2066
+ in: "path",
2067
+ required: true,
2068
+ schema: { type: "string" }
2069
+ }
2070
+ ],
2071
+ requestBody: {
2072
+ required: true,
2073
+ content: {
2074
+ "application/json": {
2075
+ schema: {
2076
+ type: "object",
2077
+ properties: {
2078
+ input: {
2079
+ oneOf: [
2080
+ { type: "string" },
2081
+ {
2082
+ type: "array",
2083
+ items: { type: "object" }
2084
+ }
2085
+ ],
2086
+ description: "Input for the network, can be a string or an array of CoreMessage objects"
2087
+ }
2088
+ },
2089
+ required: ["input"]
2090
+ }
2091
+ }
2092
+ }
2093
+ },
2094
+ responses: {
2095
+ 200: {
2096
+ description: "Generated response"
2097
+ },
2098
+ 404: {
2099
+ description: "Network not found"
2100
+ }
2101
+ }
2102
+ }),
2103
+ generateHandler2
2104
+ );
2105
+ app.post(
2106
+ "/api/networks/:networkId/stream",
2107
+ bodyLimit(bodyLimitOptions),
2108
+ h({
2109
+ description: "Generate a response from a network",
2110
+ tags: ["networks"],
2111
+ parameters: [
2112
+ {
2113
+ name: "networkId",
2114
+ in: "path",
2115
+ required: true,
2116
+ schema: { type: "string" }
2117
+ }
2118
+ ],
2119
+ requestBody: {
2120
+ required: true,
2121
+ content: {
2122
+ "application/json": {
2123
+ schema: {
2124
+ type: "object",
2125
+ properties: {
2126
+ input: {
2127
+ oneOf: [
2128
+ { type: "string" },
2129
+ {
2130
+ type: "array",
2131
+ items: { type: "object" }
2132
+ }
2133
+ ],
2134
+ description: "Input for the network, can be a string or an array of CoreMessage objects"
2135
+ }
2136
+ },
2137
+ required: ["input"]
2138
+ }
2139
+ }
2140
+ }
2141
+ },
2142
+ responses: {
2143
+ 200: {
2144
+ description: "Generated response"
2145
+ },
2146
+ 404: {
2147
+ description: "Network not found"
2148
+ }
2149
+ }
2150
+ }),
2151
+ streamGenerateHandler2
2152
+ );
2153
+ app.get(
2154
+ "/api/agents/:agentId",
2155
+ h({
2156
+ description: "Get agent by ID",
2157
+ tags: ["agents"],
2158
+ parameters: [
2159
+ {
2160
+ name: "agentId",
2161
+ in: "path",
2162
+ required: true,
2163
+ schema: { type: "string" }
2164
+ }
2165
+ ],
2166
+ responses: {
2167
+ 200: {
2168
+ description: "Agent details"
2169
+ },
2170
+ 404: {
2171
+ description: "Agent not found"
2172
+ }
2173
+ }
2174
+ }),
2175
+ getAgentByIdHandler
2176
+ );
2177
+ app.get(
2178
+ "/api/agents/:agentId/evals/ci",
2179
+ h({
2180
+ description: "Get CI evals by agent ID",
2181
+ tags: ["agents"],
2182
+ parameters: [
2183
+ {
2184
+ name: "agentId",
2185
+ in: "path",
2186
+ required: true,
2187
+ schema: { type: "string" }
2188
+ }
2189
+ ],
2190
+ responses: {
2191
+ 200: {
2192
+ description: "List of evals"
2193
+ }
2194
+ }
2195
+ }),
2196
+ getEvalsByAgentIdHandler
2197
+ );
2198
+ app.get(
2199
+ "/api/agents/:agentId/evals/live",
2200
+ h({
2201
+ description: "Get live evals by agent ID",
2202
+ tags: ["agents"],
2203
+ parameters: [
2204
+ {
2205
+ name: "agentId",
2206
+ in: "path",
2207
+ required: true,
2208
+ schema: { type: "string" }
2209
+ }
2210
+ ],
2211
+ responses: {
2212
+ 200: {
2213
+ description: "List of evals"
2214
+ }
2215
+ }
2216
+ }),
2217
+ getLiveEvalsByAgentIdHandler
2218
+ );
2219
+ app.post(
2220
+ "/api/agents/:agentId/generate",
2221
+ bodyLimit(bodyLimitOptions),
2222
+ h({
2223
+ description: "Generate a response from an agent",
2224
+ tags: ["agents"],
2225
+ parameters: [
2226
+ {
2227
+ name: "agentId",
2228
+ in: "path",
2229
+ required: true,
2230
+ schema: { type: "string" }
2231
+ }
2232
+ ],
2233
+ requestBody: {
2234
+ required: true,
2235
+ content: {
2236
+ "application/json": {
2237
+ schema: {
2238
+ type: "object",
2239
+ properties: {
2240
+ messages: {
2241
+ type: "array",
2242
+ items: { type: "object" }
2243
+ },
2244
+ threadId: { type: "string" },
2245
+ resourceId: { type: "string", description: "The resource ID for the conversation" },
2246
+ resourceid: {
2247
+ type: "string",
2248
+ description: "The resource ID for the conversation (deprecated, use resourceId instead)",
2249
+ deprecated: true
2250
+ },
2251
+ runId: { type: "string" },
2252
+ output: { type: "object" }
2253
+ },
2254
+ required: ["messages"]
2255
+ }
2256
+ }
2257
+ }
2258
+ },
2259
+ responses: {
2260
+ 200: {
2261
+ description: "Generated response"
2262
+ },
2263
+ 404: {
2264
+ description: "Agent not found"
2265
+ }
2266
+ }
2267
+ }),
2268
+ generateHandler
2269
+ );
2270
+ app.post(
2271
+ "/api/agents/:agentId/stream",
2272
+ bodyLimit(bodyLimitOptions),
2273
+ h({
2274
+ description: "Stream a response from an agent",
2275
+ tags: ["agents"],
2276
+ parameters: [
2277
+ {
2278
+ name: "agentId",
2279
+ in: "path",
2280
+ required: true,
2281
+ schema: { type: "string" }
2282
+ }
2283
+ ],
2284
+ requestBody: {
2285
+ required: true,
2286
+ content: {
2287
+ "application/json": {
2288
+ schema: {
2289
+ type: "object",
2290
+ properties: {
2291
+ messages: {
2292
+ type: "array",
2293
+ items: { type: "object" }
2294
+ },
2295
+ threadId: { type: "string" },
2296
+ resourceId: { type: "string", description: "The resource ID for the conversation" },
2297
+ resourceid: {
2298
+ type: "string",
2299
+ description: "The resource ID for the conversation (deprecated, use resourceId instead)",
2300
+ deprecated: true
2301
+ },
2302
+ runId: { type: "string" },
2303
+ output: { type: "object" }
2304
+ },
2305
+ required: ["messages"]
2306
+ }
2307
+ }
2308
+ }
2309
+ },
2310
+ responses: {
2311
+ 200: {
2312
+ description: "Streamed response"
2313
+ },
2314
+ 404: {
2315
+ description: "Agent not found"
2316
+ }
2317
+ }
2318
+ }),
2319
+ streamGenerateHandler
2320
+ );
2321
+ app.post(
2322
+ "/api/agents/:agentId/instructions",
2323
+ bodyLimit(bodyLimitOptions),
2324
+ h({
2325
+ description: "Update an agent's instructions",
2326
+ tags: ["agents"],
2327
+ parameters: [
2328
+ {
2329
+ name: "agentId",
2330
+ in: "path",
2331
+ required: true,
2332
+ schema: { type: "string" }
2333
+ }
2334
+ ],
2335
+ requestBody: {
2336
+ required: true,
2337
+ content: {
2338
+ "application/json": {
2339
+ schema: {
2340
+ type: "object",
2341
+ properties: {
2342
+ instructions: {
2343
+ type: "string",
2344
+ description: "New instructions for the agent"
2345
+ }
2346
+ },
2347
+ required: ["instructions"]
2348
+ }
2349
+ }
2350
+ }
2351
+ },
2352
+ responses: {
2353
+ 200: {
2354
+ description: "Instructions updated successfully"
2355
+ },
2356
+ 403: {
2357
+ description: "Not allowed in non-playground environment"
2358
+ },
2359
+ 404: {
2360
+ description: "Agent not found"
2361
+ }
2362
+ }
2363
+ }),
2364
+ setAgentInstructionsHandler
2365
+ );
2366
+ app.post(
2367
+ "/api/agents/:agentId/instructions/enhance",
2368
+ bodyLimit(bodyLimitOptions),
2369
+ h({
2370
+ description: "Generate an improved system prompt from instructions",
2371
+ tags: ["agents"],
2372
+ parameters: [
2373
+ {
2374
+ name: "agentId",
2375
+ in: "path",
2376
+ required: true,
2377
+ schema: { type: "string" },
2378
+ description: "ID of the agent whose model will be used for prompt generation"
2379
+ }
2380
+ ],
2381
+ requestBody: {
2382
+ required: true,
2383
+ content: {
2384
+ "application/json": {
2385
+ schema: {
2386
+ type: "object",
2387
+ properties: {
2388
+ instructions: {
2389
+ type: "string",
2390
+ description: "Instructions to generate a system prompt from"
2391
+ },
2392
+ comment: {
2393
+ type: "string",
2394
+ description: "Optional comment for the enhanced prompt"
2395
+ }
2396
+ },
2397
+ required: ["instructions"]
2398
+ }
2399
+ }
2400
+ }
2401
+ },
2402
+ responses: {
2403
+ 200: {
2404
+ description: "Generated system prompt and analysis",
2405
+ content: {
2406
+ "application/json": {
2407
+ schema: {
2408
+ type: "object",
2409
+ properties: {
2410
+ explanation: {
2411
+ type: "string",
2412
+ description: "Detailed analysis of the instructions"
2413
+ },
2414
+ new_prompt: {
2415
+ type: "string",
2416
+ description: "The enhanced system prompt"
2417
+ }
2418
+ }
2419
+ }
2420
+ }
2421
+ }
2422
+ },
2423
+ 400: {
2424
+ description: "Missing or invalid request parameters"
2425
+ },
2426
+ 404: {
2427
+ description: "Agent not found"
2428
+ },
2429
+ 500: {
2430
+ description: "Internal server error or model response parsing error"
2431
+ }
2432
+ }
2433
+ }),
2434
+ generateSystemPromptHandler
2435
+ );
2436
+ app.get(
2437
+ "/api/agents/:agentId/speakers",
2438
+ async (c2, next) => {
2439
+ c2.header("Deprecation", "true");
2440
+ c2.header("Warning", '299 - "This endpoint is deprecated, use /api/agents/:agentId/voice/speakers instead"');
2441
+ c2.header("Link", '</api/agents/:agentId/voice/speakers>; rel="successor-version"');
2442
+ return next();
2443
+ },
2444
+ h({
2445
+ description: "[DEPRECATED] Use /api/agents/:agentId/voice/speakers instead. Get available speakers for an agent",
2446
+ tags: ["agents"],
2447
+ parameters: [
2448
+ {
2449
+ name: "agentId",
2450
+ in: "path",
2451
+ required: true,
2452
+ schema: { type: "string" }
2453
+ }
2454
+ ],
2455
+ responses: {
2456
+ 200: {
2457
+ description: "List of available speakers",
2458
+ content: {
2459
+ "application/json": {
2460
+ schema: {
2461
+ type: "array",
2462
+ items: {
2463
+ type: "object",
2464
+ description: "Speaker information depending on the voice provider",
2465
+ properties: {
2466
+ voiceId: { type: "string" }
2467
+ },
2468
+ additionalProperties: true
2469
+ }
2470
+ }
2471
+ }
2472
+ }
2473
+ },
2474
+ 400: {
2475
+ description: "Agent does not have voice capabilities"
2476
+ },
2477
+ 404: {
2478
+ description: "Agent not found"
2479
+ }
2480
+ }
2481
+ }),
2482
+ getSpeakersHandler
2483
+ );
2484
+ app.get(
2485
+ "/api/agents/:agentId/voice/speakers",
2486
+ h({
2487
+ description: "Get available speakers for an agent",
2488
+ tags: ["agents"],
2489
+ parameters: [
2490
+ {
2491
+ name: "agentId",
2492
+ in: "path",
2493
+ required: true,
2494
+ schema: { type: "string" }
2495
+ }
2496
+ ],
2497
+ responses: {
2498
+ 200: {
2499
+ description: "List of available speakers",
2500
+ content: {
2501
+ "application/json": {
2502
+ schema: {
2503
+ type: "array",
2504
+ items: {
2505
+ type: "object",
2506
+ description: "Speaker information depending on the voice provider",
2507
+ properties: {
2508
+ voiceId: { type: "string" }
2509
+ },
2510
+ additionalProperties: true
2511
+ }
2512
+ }
2513
+ }
2514
+ }
2515
+ },
2516
+ 400: {
2517
+ description: "Agent does not have voice capabilities"
2518
+ },
2519
+ 404: {
2520
+ description: "Agent not found"
2521
+ }
2522
+ }
2523
+ }),
2524
+ getSpeakersHandler
2525
+ );
2526
+ app.post(
2527
+ "/api/agents/:agentId/speak",
2528
+ bodyLimit(bodyLimitOptions),
2529
+ async (c2, next) => {
2530
+ c2.header("Deprecation", "true");
2531
+ c2.header("Warning", '299 - "This endpoint is deprecated, use /api/agents/:agentId/voice/speak instead"');
2532
+ c2.header("Link", '</api/agents/:agentId/voice/speak>; rel="successor-version"');
2533
+ return next();
2534
+ },
2535
+ h({
2536
+ description: "[DEPRECATED] Use /api/agents/:agentId/voice/speak instead. Convert text to speech using the agent's voice provider",
2537
+ tags: ["agents"],
2538
+ parameters: [
2539
+ {
2540
+ name: "agentId",
2541
+ in: "path",
2542
+ required: true,
2543
+ schema: { type: "string" }
2544
+ }
2545
+ ],
2546
+ requestBody: {
2547
+ required: true,
2548
+ content: {
2549
+ "application/json": {
2550
+ schema: {
2551
+ type: "object",
2552
+ properties: {
2553
+ text: {
2554
+ type: "string",
2555
+ description: "Text to convert to speech"
2556
+ },
2557
+ options: {
2558
+ type: "object",
2559
+ description: "Provider-specific options for speech generation",
2560
+ properties: {
2561
+ speaker: {
2562
+ type: "string",
2563
+ description: "Speaker ID to use for speech generation"
2564
+ }
2565
+ },
2566
+ additionalProperties: true
2567
+ }
2568
+ },
2569
+ required: ["text"]
2570
+ }
2571
+ }
2572
+ }
2573
+ },
2574
+ responses: {
2575
+ 200: {
2576
+ description: "Audio stream",
2577
+ content: {
2578
+ "audio/mpeg": {
2579
+ schema: {
2580
+ format: "binary",
2581
+ description: "Audio stream containing the generated speech"
2582
+ }
2583
+ },
2584
+ "audio/*": {
2585
+ schema: {
2586
+ format: "binary",
2587
+ description: "Audio stream depending on the provider"
2588
+ }
2589
+ }
2590
+ }
2591
+ },
2592
+ 400: {
2593
+ description: "Agent does not have voice capabilities or invalid request"
2594
+ },
2595
+ 404: {
2596
+ description: "Agent not found"
2597
+ }
2598
+ }
2599
+ }),
2600
+ speakHandler
2601
+ );
2602
+ app.post(
2603
+ "/api/agents/:agentId/voice/speak",
2604
+ bodyLimit(bodyLimitOptions),
2605
+ h({
2606
+ description: "Convert text to speech using the agent's voice provider",
2607
+ tags: ["agents"],
2608
+ parameters: [
2609
+ {
2610
+ name: "agentId",
2611
+ in: "path",
2612
+ required: true,
2613
+ schema: { type: "string" }
2614
+ }
2615
+ ],
2616
+ requestBody: {
2617
+ required: true,
2618
+ content: {
2619
+ "application/json": {
2620
+ schema: {
2621
+ type: "object",
2622
+ properties: {
2623
+ input: {
2624
+ type: "string",
2625
+ description: "Text to convert to speech"
2626
+ },
2627
+ options: {
2628
+ type: "object",
2629
+ description: "Provider-specific options for speech generation",
2630
+ properties: {
2631
+ speaker: {
2632
+ type: "string",
2633
+ description: "Speaker ID to use for speech generation"
2634
+ },
2635
+ options: {
2636
+ type: "object",
2637
+ description: "Provider-specific options for speech generation",
2638
+ additionalProperties: true
2639
+ }
2640
+ },
2641
+ additionalProperties: true
2642
+ }
2643
+ },
2644
+ required: ["text"]
2645
+ }
2646
+ }
2647
+ }
2648
+ },
2649
+ responses: {
2650
+ 200: {
2651
+ description: "Audio stream",
2652
+ content: {
2653
+ "audio/mpeg": {
2654
+ schema: {
2655
+ format: "binary",
2656
+ description: "Audio stream containing the generated speech"
2657
+ }
2658
+ },
2659
+ "audio/*": {
2660
+ schema: {
2661
+ format: "binary",
2662
+ description: "Audio stream depending on the provider"
2663
+ }
2664
+ }
2665
+ }
2666
+ },
2667
+ 400: {
2668
+ description: "Agent does not have voice capabilities or invalid request"
2669
+ },
2670
+ 404: {
2671
+ description: "Agent not found"
2672
+ }
2673
+ }
2674
+ }),
2675
+ speakHandler
2676
+ );
2677
+ app.post(
2678
+ "/api/agents/:agentId/listen",
2679
+ bodyLimit({
2680
+ ...bodyLimitOptions,
2681
+ maxSize: 10 * 1024 * 1024
2682
+ // 10 MB for audio files
2683
+ }),
2684
+ async (c2, next) => {
2685
+ c2.header("Deprecation", "true");
2686
+ c2.header("Warning", '299 - "This endpoint is deprecated, use /api/agents/:agentId/voice/listen instead"');
2687
+ c2.header("Link", '</api/agents/:agentId/voice/listen>; rel="successor-version"');
2688
+ return next();
2689
+ },
2690
+ h({
2691
+ description: "[DEPRECATED] Use /api/agents/:agentId/voice/listen instead. Convert speech to text using the agent's voice provider. Additional provider-specific options can be passed as query parameters.",
2692
+ tags: ["agents"],
2693
+ parameters: [
2694
+ {
2695
+ name: "agentId",
2696
+ in: "path",
2697
+ required: true,
2698
+ schema: { type: "string" }
2699
+ }
2700
+ ],
2701
+ requestBody: {
2702
+ required: true,
2703
+ content: {
2704
+ "audio/mpeg": {
2705
+ schema: {
2706
+ format: "binary",
2707
+ description: "Audio data stream to transcribe (supports various formats depending on provider like mp3, wav, webm, flac)"
2708
+ }
2709
+ }
2710
+ }
2711
+ },
2712
+ responses: {
2713
+ 200: {
2714
+ description: "Transcription result",
2715
+ content: {
2716
+ "application/json": {
2717
+ schema: {
2718
+ type: "object",
2719
+ properties: {
2720
+ text: {
2721
+ type: "string",
2722
+ description: "Transcribed text"
2723
+ }
2724
+ }
2725
+ }
2726
+ }
2727
+ }
2728
+ },
2729
+ 400: {
2730
+ description: "Agent does not have voice capabilities or invalid request"
2731
+ },
2732
+ 404: {
2733
+ description: "Agent not found"
2734
+ }
2735
+ }
2736
+ }),
2737
+ listenHandler
2738
+ );
2739
+ app.post(
2740
+ "/api/agents/:agentId/voice/listen",
2741
+ bodyLimit({
2742
+ ...bodyLimitOptions,
2743
+ maxSize: 10 * 1024 * 1024
2744
+ // 10 MB for audio files
2745
+ }),
2746
+ h({
2747
+ description: "Convert speech to text using the agent's voice provider. Additional provider-specific options can be passed as query parameters.",
2748
+ tags: ["agents"],
2749
+ parameters: [
2750
+ {
2751
+ name: "agentId",
2752
+ in: "path",
2753
+ required: true,
2754
+ schema: { type: "string" }
2755
+ }
2756
+ ],
2757
+ requestBody: {
2758
+ required: true,
2759
+ content: {
2760
+ "multipart/form-data": {
2761
+ schema: {
2762
+ type: "object",
2763
+ required: ["audio"],
2764
+ properties: {
2765
+ audio: {
2766
+ type: "string",
2767
+ format: "binary",
2768
+ description: "Audio data stream to transcribe (supports various formats depending on provider like mp3, wav, webm, flac)"
2769
+ },
2770
+ options: {
2771
+ type: "object",
2772
+ description: "Provider-specific options for speech-to-text",
2773
+ additionalProperties: true
2774
+ }
2775
+ }
2776
+ }
2777
+ }
2778
+ }
2779
+ },
2780
+ responses: {
2781
+ 200: {
2782
+ description: "Transcription result",
2783
+ content: {
2784
+ "application/json": {
2785
+ schema: {
2786
+ type: "object",
2787
+ properties: {
2788
+ text: {
2789
+ type: "string",
2790
+ description: "Transcribed text"
2791
+ }
2792
+ }
2793
+ }
2794
+ }
2795
+ }
2796
+ },
2797
+ 400: {
2798
+ description: "Agent does not have voice capabilities or invalid request"
2799
+ },
2800
+ 404: {
2801
+ description: "Agent not found"
2802
+ }
2803
+ }
2804
+ }),
2805
+ listenHandler
2806
+ );
2807
+ app.post(
2808
+ "/api/agents/:agentId/tools/:toolId/execute",
2809
+ bodyLimit(bodyLimitOptions),
2810
+ h({
2811
+ description: "Execute a tool through an agent",
2812
+ tags: ["agents"],
2813
+ parameters: [
2814
+ {
2815
+ name: "agentId",
2816
+ in: "path",
2817
+ required: true,
2818
+ schema: { type: "string" }
2819
+ },
2820
+ {
2821
+ name: "toolId",
2822
+ in: "path",
2823
+ required: true,
2824
+ schema: { type: "string" }
2825
+ }
2826
+ ],
2827
+ requestBody: {
2828
+ required: true,
2829
+ content: {
2830
+ "application/json": {
2831
+ schema: {
2832
+ type: "object",
2833
+ properties: {
2834
+ data: { type: "object" }
2835
+ },
2836
+ required: ["data"]
2837
+ }
2838
+ }
2839
+ }
2840
+ },
2841
+ responses: {
2842
+ 200: {
2843
+ description: "Tool execution result"
2844
+ },
2845
+ 404: {
2846
+ description: "Tool or agent not found"
2847
+ }
2848
+ }
2849
+ }),
2850
+ executeAgentToolHandler
2851
+ );
2852
+ app.get(
2853
+ "/api/memory/status",
2854
+ h({
2855
+ description: "Get memory status",
2856
+ tags: ["memory"],
2857
+ parameters: [
2858
+ {
2859
+ name: "agentId",
2860
+ in: "query",
2861
+ required: true,
2862
+ schema: { type: "string" }
2863
+ }
2864
+ ],
2865
+ responses: {
2866
+ 200: {
2867
+ description: "Memory status"
2868
+ }
2869
+ }
2870
+ }),
2871
+ getMemoryStatusHandler
2872
+ );
2873
+ app.get(
2874
+ "/api/memory/threads",
2875
+ h({
2876
+ description: "Get all threads",
2877
+ tags: ["memory"],
2878
+ parameters: [
2879
+ {
2880
+ name: "resourceid",
2881
+ in: "query",
2882
+ required: true,
2883
+ schema: { type: "string" }
2884
+ },
2885
+ {
2886
+ name: "agentId",
2887
+ in: "query",
2888
+ required: true,
2889
+ schema: { type: "string" }
2890
+ }
2891
+ ],
2892
+ responses: {
2893
+ 200: {
2894
+ description: "List of all threads"
2895
+ }
2896
+ }
2897
+ }),
2898
+ getThreadsHandler
2899
+ );
2900
+ app.get(
2901
+ "/api/memory/threads/:threadId",
2902
+ h({
2903
+ description: "Get thread by ID",
2904
+ tags: ["memory"],
2905
+ parameters: [
2906
+ {
2907
+ name: "threadId",
2908
+ in: "path",
2909
+ required: true,
2910
+ schema: { type: "string" }
2911
+ },
2912
+ {
2913
+ name: "agentId",
2914
+ in: "query",
2915
+ required: true,
2916
+ schema: { type: "string" }
2917
+ }
2918
+ ],
2919
+ responses: {
2920
+ 200: {
2921
+ description: "Thread details"
2922
+ },
2923
+ 404: {
2924
+ description: "Thread not found"
2925
+ }
2926
+ }
2927
+ }),
2928
+ getThreadByIdHandler
2929
+ );
2930
+ app.get(
2931
+ "/api/memory/threads/:threadId/messages",
2932
+ h({
2933
+ description: "Get messages for a thread",
2934
+ tags: ["memory"],
2935
+ parameters: [
2936
+ {
2937
+ name: "threadId",
2938
+ in: "path",
2939
+ required: true,
2940
+ schema: { type: "string" }
2941
+ },
2942
+ {
2943
+ name: "agentId",
2944
+ in: "query",
2945
+ required: true,
2946
+ schema: { type: "string" }
2947
+ }
2948
+ ],
2949
+ responses: {
2950
+ 200: {
2951
+ description: "List of messages"
2952
+ }
2953
+ }
2954
+ }),
2955
+ getMessagesHandler
2956
+ );
2957
+ app.post(
2958
+ "/api/memory/threads",
2959
+ bodyLimit(bodyLimitOptions),
2960
+ h({
2961
+ description: "Create a new thread",
2962
+ tags: ["memory"],
2963
+ parameters: [
2964
+ {
2965
+ name: "agentId",
2966
+ in: "query",
2967
+ required: true,
2968
+ schema: { type: "string" }
2969
+ }
2970
+ ],
2971
+ requestBody: {
2972
+ required: true,
2973
+ content: {
2974
+ "application/json": {
2975
+ schema: {
2976
+ type: "object",
2977
+ properties: {
2978
+ title: { type: "string" },
2979
+ metadata: { type: "object" },
2980
+ resourceid: { type: "string" },
2981
+ threadId: { type: "string" }
2982
+ }
2983
+ }
2984
+ }
2985
+ }
2986
+ },
2987
+ responses: {
2988
+ 200: {
2989
+ description: "Created thread"
2990
+ }
2991
+ }
2992
+ }),
2993
+ createThreadHandler
2994
+ );
2995
+ app.patch(
2996
+ "/api/memory/threads/:threadId",
2997
+ h({
2998
+ description: "Update a thread",
2999
+ tags: ["memory"],
3000
+ parameters: [
3001
+ {
3002
+ name: "threadId",
3003
+ in: "path",
3004
+ required: true,
3005
+ schema: { type: "string" }
3006
+ },
3007
+ {
3008
+ name: "agentId",
3009
+ in: "query",
3010
+ required: true,
3011
+ schema: { type: "string" }
3012
+ }
3013
+ ],
3014
+ requestBody: {
3015
+ required: true,
3016
+ content: {
3017
+ "application/json": {
3018
+ schema: { type: "object" }
3019
+ }
3020
+ }
3021
+ },
3022
+ responses: {
3023
+ 200: {
3024
+ description: "Updated thread"
3025
+ },
3026
+ 404: {
3027
+ description: "Thread not found"
3028
+ }
3029
+ }
3030
+ }),
3031
+ updateThreadHandler
3032
+ );
3033
+ app.delete(
3034
+ "/api/memory/threads/:threadId",
3035
+ h({
3036
+ description: "Delete a thread",
3037
+ tags: ["memory"],
3038
+ parameters: [
3039
+ {
3040
+ name: "threadId",
3041
+ in: "path",
3042
+ required: true,
3043
+ schema: { type: "string" }
3044
+ },
3045
+ {
3046
+ name: "agentId",
3047
+ in: "query",
3048
+ required: true,
3049
+ schema: { type: "string" }
3050
+ }
3051
+ ],
3052
+ responses: {
3053
+ 200: {
3054
+ description: "Thread deleted"
3055
+ },
3056
+ 404: {
3057
+ description: "Thread not found"
3058
+ }
3059
+ }
3060
+ }),
3061
+ deleteThreadHandler
3062
+ );
3063
+ app.post(
3064
+ "/api/memory/save-messages",
3065
+ bodyLimit(bodyLimitOptions),
3066
+ h({
3067
+ description: "Save messages",
3068
+ tags: ["memory"],
3069
+ parameters: [
3070
+ {
3071
+ name: "agentId",
3072
+ in: "query",
3073
+ required: true,
3074
+ schema: { type: "string" }
3075
+ }
3076
+ ],
3077
+ requestBody: {
3078
+ required: true,
3079
+ content: {
3080
+ "application/json": {
3081
+ schema: {
3082
+ type: "object",
3083
+ properties: {
3084
+ messages: {
3085
+ type: "array",
3086
+ items: { type: "object" }
3087
+ }
3088
+ },
3089
+ required: ["messages"]
3090
+ }
3091
+ }
3092
+ }
3093
+ },
3094
+ responses: {
3095
+ 200: {
3096
+ description: "Messages saved"
3097
+ }
3098
+ }
3099
+ }),
3100
+ saveMessagesHandler
3101
+ );
3102
+ app.get(
3103
+ "/api/telemetry",
3104
+ h({
3105
+ description: "Get all traces",
3106
+ tags: ["telemetry"],
3107
+ responses: {
3108
+ 200: {
3109
+ description: "List of all traces (paged)"
3110
+ }
3111
+ }
3112
+ }),
3113
+ getTelemetryHandler
3114
+ );
3115
+ app.post(
3116
+ "/api/telemetry",
3117
+ h({
3118
+ description: "Store telemetry",
3119
+ tags: ["telemetry"],
3120
+ responses: {
3121
+ 200: {
3122
+ description: "Traces stored"
3123
+ }
3124
+ }
3125
+ }),
3126
+ storeTelemetryHandler
3127
+ );
3128
+ app.get(
3129
+ "/api/workflows",
3130
+ h({
3131
+ description: "Get all workflows",
3132
+ tags: ["workflows"],
3133
+ responses: {
3134
+ 200: {
3135
+ description: "List of all workflows"
3136
+ }
3137
+ }
3138
+ }),
3139
+ getWorkflowsHandler
3140
+ );
3141
+ app.get(
3142
+ "/api/workflows/:workflowId",
3143
+ h({
3144
+ description: "Get workflow by ID",
3145
+ tags: ["workflows"],
3146
+ parameters: [
3147
+ {
3148
+ name: "workflowId",
3149
+ in: "path",
3150
+ required: true,
3151
+ schema: { type: "string" }
3152
+ }
3153
+ ],
3154
+ responses: {
3155
+ 200: {
3156
+ description: "Workflow details"
3157
+ },
3158
+ 404: {
3159
+ description: "Workflow not found"
3160
+ }
3161
+ }
3162
+ }),
3163
+ getWorkflowByIdHandler
3164
+ );
3165
+ app.get(
3166
+ "/api/workflows/:workflowId/runs",
3167
+ h({
3168
+ description: "Get all runs for a workflow",
3169
+ tags: ["workflows"],
3170
+ parameters: [
3171
+ {
3172
+ name: "workflowId",
3173
+ in: "path",
3174
+ required: true,
3175
+ schema: { type: "string" }
3176
+ }
3177
+ ],
3178
+ responses: {
3179
+ 200: {
3180
+ description: "List of workflow runs from storage"
3181
+ }
3182
+ }
3183
+ }),
3184
+ getWorkflowRunsHandler
3185
+ );
3186
+ app.post(
3187
+ "/api/workflows/:workflowId/resume",
3188
+ h({
3189
+ description: "Resume a suspended workflow step",
3190
+ tags: ["workflows"],
3191
+ parameters: [
3192
+ {
3193
+ name: "workflowId",
3194
+ in: "path",
3195
+ required: true,
3196
+ schema: { type: "string" }
3197
+ },
3198
+ {
3199
+ name: "runId",
3200
+ in: "query",
3201
+ required: true,
3202
+ schema: { type: "string" }
3203
+ }
3204
+ ],
3205
+ requestBody: {
3206
+ required: true,
3207
+ content: {
3208
+ "application/json": {
3209
+ schema: {
3210
+ type: "object",
3211
+ properties: {
3212
+ stepId: { type: "string" },
3213
+ context: { type: "object" }
3214
+ }
3215
+ }
3216
+ }
3217
+ }
3218
+ }
3219
+ }),
3220
+ resumeWorkflowHandler
3221
+ );
3222
+ app.post(
3223
+ "/api/workflows/:workflowId/resumeAsync",
3224
+ bodyLimit(bodyLimitOptions),
3225
+ h({
3226
+ description: "@deprecated Use /api/workflows/:workflowId/resume-async instead",
3227
+ tags: ["workflows"],
3228
+ parameters: [
3229
+ {
3230
+ name: "workflowId",
3231
+ in: "path",
3232
+ required: true,
3233
+ schema: { type: "string" }
3234
+ },
3235
+ {
3236
+ name: "runId",
3237
+ in: "query",
3238
+ required: true,
3239
+ schema: { type: "string" }
3240
+ }
3241
+ ],
3242
+ requestBody: {
3243
+ required: true,
3244
+ content: {
3245
+ "application/json": {
3246
+ schema: {
3247
+ type: "object",
3248
+ properties: {
3249
+ stepId: { type: "string" },
3250
+ context: { type: "object" }
3251
+ }
3252
+ }
3253
+ }
3254
+ }
3255
+ }
3256
+ }),
3257
+ resumeAsyncWorkflowHandler
3258
+ );
3259
+ app.post(
3260
+ "/api/workflows/:workflowId/resume-async",
3261
+ bodyLimit(bodyLimitOptions),
3262
+ h({
3263
+ description: "Resume a suspended workflow step",
3264
+ tags: ["workflows"],
3265
+ parameters: [
3266
+ {
3267
+ name: "workflowId",
3268
+ in: "path",
3269
+ required: true,
3270
+ schema: { type: "string" }
3271
+ },
3272
+ {
3273
+ name: "runId",
3274
+ in: "query",
3275
+ required: true,
3276
+ schema: { type: "string" }
3277
+ }
3278
+ ],
3279
+ requestBody: {
3280
+ required: true,
3281
+ content: {
3282
+ "application/json": {
3283
+ schema: {
3284
+ type: "object",
3285
+ properties: {
3286
+ stepId: { type: "string" },
3287
+ context: { type: "object" }
3288
+ }
3289
+ }
3290
+ }
3291
+ }
3292
+ }
3293
+ }),
3294
+ resumeAsyncWorkflowHandler
3295
+ );
3296
+ app.post(
3297
+ "/api/workflows/:workflowId/createRun",
3298
+ h({
3299
+ description: "Create a new workflow run",
3300
+ tags: ["workflows"],
3301
+ parameters: [
3302
+ {
3303
+ name: "workflowId",
3304
+ in: "path",
3305
+ required: true,
3306
+ schema: { type: "string" }
3307
+ },
3308
+ {
3309
+ name: "runId",
3310
+ in: "query",
3311
+ required: false,
3312
+ schema: { type: "string" }
3313
+ }
3314
+ ],
3315
+ responses: {
3316
+ 200: {
3317
+ description: "New workflow run created"
3318
+ }
3319
+ }
3320
+ }),
3321
+ createRunHandler
3322
+ );
3323
+ app.post(
3324
+ "/api/workflows/:workflowId/startAsync",
3325
+ bodyLimit(bodyLimitOptions),
3326
+ h({
3327
+ description: "Execute/Start a workflow",
3328
+ tags: ["workflows"],
3329
+ parameters: [
3330
+ {
3331
+ name: "workflowId",
3332
+ in: "path",
3333
+ required: true,
3334
+ schema: { type: "string" }
3335
+ },
3336
+ {
3337
+ name: "runId",
3338
+ in: "query",
3339
+ required: false,
3340
+ schema: { type: "string" }
3341
+ }
3342
+ ],
3343
+ requestBody: {
3344
+ required: true,
3345
+ content: {
3346
+ "application/json": {
3347
+ schema: {
3348
+ type: "object",
3349
+ properties: {
3350
+ input: { type: "object" }
3351
+ }
3352
+ }
3353
+ }
3354
+ }
3355
+ },
3356
+ responses: {
3357
+ 200: {
3358
+ description: "Workflow execution result"
3359
+ },
3360
+ 404: {
3361
+ description: "Workflow not found"
3362
+ }
3363
+ }
3364
+ }),
3365
+ startAsyncWorkflowHandler
3366
+ );
3367
+ app.post(
3368
+ "/api/workflows/:workflowId/start-async",
3369
+ bodyLimit(bodyLimitOptions),
3370
+ h({
3371
+ description: "@deprecated Use /api/workflows/:workflowId/start-async instead",
3372
+ tags: ["workflows"],
3373
+ parameters: [
3374
+ {
3375
+ name: "workflowId",
3376
+ in: "path",
3377
+ required: true,
3378
+ schema: { type: "string" }
3379
+ },
3380
+ {
3381
+ name: "runId",
3382
+ in: "query",
3383
+ required: false,
3384
+ schema: { type: "string" }
3385
+ }
3386
+ ],
3387
+ requestBody: {
3388
+ required: true,
3389
+ content: {
3390
+ "application/json": {
3391
+ schema: {
3392
+ type: "object",
3393
+ properties: {
3394
+ input: { type: "object" }
3395
+ }
3396
+ }
3397
+ }
3398
+ }
3399
+ },
3400
+ responses: {
3401
+ 200: {
3402
+ description: "Workflow execution result"
3403
+ },
3404
+ 404: {
3405
+ description: "Workflow not found"
3406
+ }
3407
+ }
3408
+ }),
3409
+ startAsyncWorkflowHandler
3410
+ );
3411
+ app.post(
3412
+ "/api/workflows/:workflowId/start",
3413
+ h({
3414
+ description: "Create and start a new workflow run",
3415
+ tags: ["workflows"],
3416
+ parameters: [
3417
+ {
3418
+ name: "workflowId",
3419
+ in: "path",
3420
+ required: true,
3421
+ schema: { type: "string" }
3422
+ },
3423
+ {
3424
+ name: "runId",
3425
+ in: "query",
3426
+ required: true,
3427
+ schema: { type: "string" }
3428
+ }
3429
+ ],
3430
+ requestBody: {
3431
+ required: true,
3432
+ content: {
3433
+ "application/json": {
3434
+ schema: {
3435
+ type: "object",
3436
+ properties: {
3437
+ input: { type: "object" }
3438
+ }
3439
+ }
3440
+ }
3441
+ }
3442
+ },
3443
+ responses: {
3444
+ 200: {
3445
+ description: "Workflow run started"
3446
+ },
3447
+ 404: {
3448
+ description: "Workflow not found"
3449
+ }
3450
+ }
3451
+ }),
3452
+ startWorkflowRunHandler
3453
+ );
3454
+ app.get(
3455
+ "/api/workflows/:workflowId/watch",
3456
+ h({
3457
+ description: "Watch workflow transitions in real-time",
3458
+ parameters: [
3459
+ {
3460
+ name: "workflowId",
3461
+ in: "path",
3462
+ required: true,
3463
+ schema: { type: "string" }
3464
+ },
3465
+ {
3466
+ name: "runId",
3467
+ in: "query",
3468
+ required: false,
3469
+ schema: { type: "string" }
3470
+ }
3471
+ ],
3472
+ tags: ["workflows"],
3473
+ responses: {
3474
+ 200: {
3475
+ description: "Workflow transitions in real-time"
3476
+ }
3477
+ }
3478
+ }),
3479
+ watchWorkflowHandler
3480
+ );
3481
+ app.get(
3482
+ "/api/logs",
3483
+ h({
3484
+ description: "Get all logs",
3485
+ tags: ["logs"],
3486
+ parameters: [
3487
+ {
3488
+ name: "transportId",
3489
+ in: "query",
3490
+ required: true,
3491
+ schema: { type: "string" }
3492
+ }
3493
+ ],
3494
+ responses: {
3495
+ 200: {
3496
+ description: "List of all logs"
3497
+ }
3498
+ }
3499
+ }),
3500
+ getLogsHandler
3501
+ );
3502
+ app.get(
3503
+ "/api/logs/transports",
3504
+ h({
3505
+ description: "List of all log transports",
3506
+ tags: ["logs"],
3507
+ responses: {
3508
+ 200: {
3509
+ description: "List of all log transports"
3510
+ }
3511
+ }
3512
+ }),
3513
+ getLogTransports
3514
+ );
3515
+ app.get(
3516
+ "/api/logs/:runId",
3517
+ h({
3518
+ description: "Get logs by run ID",
3519
+ tags: ["logs"],
3520
+ parameters: [
3521
+ {
3522
+ name: "runId",
3523
+ in: "path",
3524
+ required: true,
3525
+ schema: { type: "string" }
3526
+ },
3527
+ {
3528
+ name: "transportId",
3529
+ in: "query",
3530
+ required: true,
3531
+ schema: { type: "string" }
3532
+ }
3533
+ ],
3534
+ responses: {
3535
+ 200: {
3536
+ description: "List of logs for run ID"
3537
+ }
3538
+ }
3539
+ }),
3540
+ getLogsByRunIdHandler
3541
+ );
3542
+ app.get(
3543
+ "/api/tools",
3544
+ h({
3545
+ description: "Get all tools",
3546
+ tags: ["tools"],
3547
+ responses: {
3548
+ 200: {
3549
+ description: "List of all tools"
3550
+ }
3551
+ }
3552
+ }),
3553
+ getToolsHandler
3554
+ );
3555
+ app.get(
3556
+ "/api/tools/:toolId",
3557
+ h({
3558
+ description: "Get tool by ID",
3559
+ tags: ["tools"],
3560
+ parameters: [
3561
+ {
3562
+ name: "toolId",
3563
+ in: "path",
3564
+ required: true,
3565
+ schema: { type: "string" }
3566
+ }
3567
+ ],
3568
+ responses: {
3569
+ 200: {
3570
+ description: "Tool details"
3571
+ },
3572
+ 404: {
3573
+ description: "Tool not found"
3574
+ }
3575
+ }
3576
+ }),
3577
+ getToolByIdHandler
3578
+ );
3579
+ app.post(
3580
+ "/api/tools/:toolId/execute",
3581
+ bodyLimit(bodyLimitOptions),
3582
+ h({
3583
+ description: "Execute a tool",
3584
+ tags: ["tools"],
3585
+ parameters: [
3586
+ {
3587
+ name: "toolId",
3588
+ in: "path",
3589
+ required: true,
3590
+ schema: { type: "string" }
3591
+ }
3592
+ ],
3593
+ requestBody: {
3594
+ required: true,
3595
+ content: {
3596
+ "application/json": {
3597
+ schema: {
3598
+ type: "object",
3599
+ properties: {
3600
+ data: { type: "object" }
3601
+ },
3602
+ required: ["data"]
3603
+ }
3604
+ }
3605
+ }
3606
+ },
3607
+ responses: {
3608
+ 200: {
3609
+ description: "Tool execution result"
3610
+ },
3611
+ 404: {
3612
+ description: "Tool not found"
3613
+ }
3614
+ }
3615
+ }),
3616
+ executeToolHandler(tools)
3617
+ );
3618
+ app.post(
3619
+ "/api/vector/:vectorName/upsert",
3620
+ bodyLimit(bodyLimitOptions),
3621
+ h({
3622
+ description: "Upsert vectors into an index",
3623
+ tags: ["vector"],
3624
+ parameters: [
3625
+ {
3626
+ name: "vectorName",
3627
+ in: "path",
3628
+ required: true,
3629
+ schema: { type: "string" }
3630
+ }
3631
+ ],
3632
+ requestBody: {
3633
+ required: true,
3634
+ content: {
3635
+ "application/json": {
3636
+ schema: {
3637
+ type: "object",
3638
+ properties: {
3639
+ indexName: { type: "string" },
3640
+ vectors: {
3641
+ type: "array",
3642
+ items: {
3643
+ type: "array",
3644
+ items: { type: "number" }
3645
+ }
3646
+ },
3647
+ metadata: {
3648
+ type: "array",
3649
+ items: { type: "object" }
3650
+ },
3651
+ ids: {
3652
+ type: "array",
3653
+ items: { type: "string" }
3654
+ }
3655
+ },
3656
+ required: ["indexName", "vectors"]
3657
+ }
3658
+ }
3659
+ }
3660
+ },
3661
+ responses: {
3662
+ 200: {
3663
+ description: "Vectors upserted successfully"
3664
+ }
3665
+ }
3666
+ }),
3667
+ upsertVectors
3668
+ );
3669
+ app.post(
3670
+ "/api/vector/:vectorName/create-index",
3671
+ bodyLimit(bodyLimitOptions),
3672
+ h({
3673
+ description: "Create a new vector index",
3674
+ tags: ["vector"],
3675
+ parameters: [
3676
+ {
3677
+ name: "vectorName",
3678
+ in: "path",
3679
+ required: true,
3680
+ schema: { type: "string" }
3681
+ }
3682
+ ],
3683
+ requestBody: {
3684
+ required: true,
3685
+ content: {
3686
+ "application/json": {
3687
+ schema: {
3688
+ type: "object",
3689
+ properties: {
3690
+ indexName: { type: "string" },
3691
+ dimension: { type: "number" },
3692
+ metric: {
3693
+ type: "string",
3694
+ enum: ["cosine", "euclidean", "dotproduct"]
3695
+ }
3696
+ },
3697
+ required: ["indexName", "dimension"]
3698
+ }
3699
+ }
3700
+ }
3701
+ },
3702
+ responses: {
3703
+ 200: {
3704
+ description: "Index created successfully"
3705
+ }
3706
+ }
3707
+ }),
3708
+ createIndex
3709
+ );
3710
+ app.post(
3711
+ "/api/vector/:vectorName/query",
3712
+ bodyLimit(bodyLimitOptions),
3713
+ h({
3714
+ description: "Query vectors from an index",
3715
+ tags: ["vector"],
3716
+ parameters: [
3717
+ {
3718
+ name: "vectorName",
3719
+ in: "path",
3720
+ required: true,
3721
+ schema: { type: "string" }
3722
+ }
3723
+ ],
3724
+ requestBody: {
3725
+ required: true,
3726
+ content: {
3727
+ "application/json": {
3728
+ schema: {
3729
+ type: "object",
3730
+ properties: {
3731
+ indexName: { type: "string" },
3732
+ queryVector: {
3733
+ type: "array",
3734
+ items: { type: "number" }
3735
+ },
3736
+ topK: { type: "number" },
3737
+ filter: { type: "object" },
3738
+ includeVector: { type: "boolean" }
3739
+ },
3740
+ required: ["indexName", "queryVector"]
3741
+ }
3742
+ }
3743
+ }
3744
+ },
3745
+ responses: {
3746
+ 200: {
3747
+ description: "Query results"
3748
+ }
3749
+ }
3750
+ }),
3751
+ queryVectors
3752
+ );
3753
+ app.get(
3754
+ "/api/vector/:vectorName/indexes",
3755
+ h({
3756
+ description: "List all indexes for a vector store",
3757
+ tags: ["vector"],
3758
+ parameters: [
3759
+ {
3760
+ name: "vectorName",
3761
+ in: "path",
3762
+ required: true,
3763
+ schema: { type: "string" }
3764
+ }
3765
+ ],
3766
+ responses: {
3767
+ 200: {
3768
+ description: "List of indexes"
3769
+ }
3770
+ }
3771
+ }),
3772
+ listIndexes
3773
+ );
3774
+ app.get(
3775
+ "/api/vector/:vectorName/indexes/:indexName",
3776
+ h({
3777
+ description: "Get details about a specific index",
3778
+ tags: ["vector"],
3779
+ parameters: [
3780
+ {
3781
+ name: "vectorName",
3782
+ in: "path",
3783
+ required: true,
3784
+ schema: { type: "string" }
3785
+ },
3786
+ {
3787
+ name: "indexName",
3788
+ in: "path",
3789
+ required: true,
3790
+ schema: { type: "string" }
3791
+ }
3792
+ ],
3793
+ responses: {
3794
+ 200: {
3795
+ description: "Index details"
3796
+ }
3797
+ }
3798
+ }),
3799
+ describeIndex
3800
+ );
3801
+ app.delete(
3802
+ "/api/vector/:vectorName/indexes/:indexName",
3803
+ h({
3804
+ description: "Delete a specific index",
3805
+ tags: ["vector"],
3806
+ parameters: [
3807
+ {
3808
+ name: "vectorName",
3809
+ in: "path",
3810
+ required: true,
3811
+ schema: { type: "string" }
3812
+ },
3813
+ {
3814
+ name: "indexName",
3815
+ in: "path",
3816
+ required: true,
3817
+ schema: { type: "string" }
3818
+ }
3819
+ ],
3820
+ responses: {
3821
+ 200: {
3822
+ description: "Index deleted successfully"
3823
+ }
3824
+ }
3825
+ }),
3826
+ deleteIndex
3827
+ );
3828
+ app.get(
3829
+ "/openapi.json",
3830
+ f(app, {
3831
+ documentation: {
3832
+ info: { title: "Mastra API", version: "1.0.0", description: "Mastra API" }
3833
+ }
3834
+ })
3835
+ );
3836
+ app.get("/swagger-ui", middleware({ url: "/openapi.json" }));
3837
+ if (options?.swaggerUI) {
3838
+ app.get("/swagger-ui", middleware({ url: "/openapi.json" }));
3839
+ }
3840
+ app.post(
3841
+ "/api/a2a",
3842
+ h({
3843
+ description: "A2A Protocol endpoint for agent-to-agent communication",
3844
+ tags: ["a2a"],
3845
+ requestBody: {
3846
+ content: {
3847
+ "application/json": {
3848
+ schema: { type: "object" }
3849
+ }
3850
+ }
3851
+ },
3852
+ responses: {
3853
+ 200: {
3854
+ description: "A2A response",
3855
+ content: {
3856
+ "application/json": {
3857
+ schema: { type: "object" }
3858
+ }
3859
+ }
3860
+ }
3861
+ }
3862
+ }),
3863
+ handleA2ARequestEndpoint
3864
+ );
3865
+ app.get(
3866
+ "/api/a2a/agent-card",
3867
+ h({
3868
+ description: "Get the A2A agent card for this agent",
3869
+ tags: ["a2a"],
3870
+ responses: {
3871
+ 200: {
3872
+ description: "Agent card",
3873
+ content: {
3874
+ "application/json": {
3875
+ schema: { type: "object" }
3876
+ }
3877
+ }
3878
+ }
3879
+ }
3880
+ }),
3881
+ handleAgentCardEndpoint
3882
+ );
3883
+ if (options?.playground) {
3884
+ app.get("/refresh-events", handleClientsRefresh);
3885
+ app.post("/__refresh", handleTriggerClientsRefresh);
3886
+ app.use("/assets/*", async (c2, next) => {
3887
+ const path = c2.req.path;
3888
+ if (path.endsWith(".js")) {
3889
+ c2.header("Content-Type", "application/javascript");
3890
+ } else if (path.endsWith(".css")) {
3891
+ c2.header("Content-Type", "text/css");
3892
+ }
3893
+ await next();
3894
+ });
3895
+ app.use(
3896
+ "/assets/*",
3897
+ serveStatic({
3898
+ root: "./playground/assets"
3899
+ })
3900
+ );
3901
+ app.use(
3902
+ "*",
3903
+ serveStatic({
3904
+ root: "./playground"
3905
+ })
3906
+ );
3907
+ }
3908
+ app.get("*", async (c2, next) => {
3909
+ if (c2.req.path.startsWith("/api/") || c2.req.path.startsWith("/swagger-ui") || c2.req.path.startsWith("/openapi.json")) {
3910
+ return await next();
3911
+ }
3912
+ if (options?.playground) {
3913
+ const indexHtml = await readFile(join(process.cwd(), "./playground/index.html"), "utf-8");
3914
+ return c2.newResponse(indexHtml, 200, { "Content-Type": "text/html" });
3915
+ }
3916
+ return c2.newResponse(html2, 200, { "Content-Type": "text/html" });
3917
+ });
3918
+ return app;
3919
+ }
3920
+ async function createNodeServer(mastra, options = {}) {
3921
+ const app = await createHonoServer(mastra, options);
3922
+ const serverOptions = mastra.getServer();
3923
+ const port = serverOptions?.port ?? (Number(process.env.PORT) || 4111);
3924
+ const server = serve(
3925
+ {
3926
+ fetch: app.fetch,
3927
+ port
3928
+ },
3929
+ () => {
3930
+ const logger2 = mastra.getLogger();
3931
+ logger2.info(`\u{1F984} Mastra API running on port ${port}/api`);
3932
+ logger2.info(`\u{1F4DA} Open API documentation available at http://localhost:${port}/openapi.json`);
3933
+ if (options?.swaggerUI) {
3934
+ logger2.info(`\u{1F9EA} Swagger UI available at http://localhost:${port}/swagger-ui`);
3935
+ }
3936
+ if (options?.playground) {
3937
+ logger2.info(`\u{1F468}\u200D\u{1F4BB} Playground available at http://localhost:${port}/`);
3938
+ }
3939
+ }
3940
+ );
3941
+ return server;
3942
+ }
3943
+
3944
+ export { createHonoServer, createNodeServer };