@mastra/deployer 0.0.0-storage-20250225005900

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 (73) hide show
  1. package/.turbo/turbo-build.log +30 -0
  2. package/CHANGELOG.md +855 -0
  3. package/LICENSE +44 -0
  4. package/README.md +159 -0
  5. package/dist/_tsup-dts-rollup.d.ts +360 -0
  6. package/dist/build/analyze.d.ts +1 -0
  7. package/dist/build/analyze.js +2 -0
  8. package/dist/build/bundler.d.ts +2 -0
  9. package/dist/build/bundler.js +2 -0
  10. package/dist/build/index.d.ts +10 -0
  11. package/dist/build/index.js +5 -0
  12. package/dist/bundler/index.d.ts +1 -0
  13. package/dist/bundler/index.js +5 -0
  14. package/dist/chunk-AXS5WSIK.js +290 -0
  15. package/dist/chunk-BTUQ6UBB.js +254 -0
  16. package/dist/chunk-IHPQAB7O.js +113 -0
  17. package/dist/chunk-KXS4XYEJ.js +251 -0
  18. package/dist/chunk-SESHBX76.js +267 -0
  19. package/dist/chunk-YNXJO2XU.js +69 -0
  20. package/dist/index.d.ts +6 -0
  21. package/dist/index.js +131 -0
  22. package/dist/server/index.d.ts +2 -0
  23. package/dist/server/index.js +4907 -0
  24. package/dist/templates/instrumentation-template.js +86 -0
  25. package/eslint.config.js +6 -0
  26. package/global.d.ts +0 -0
  27. package/package.json +84 -0
  28. package/public/templates/instrumentation-template.js +86 -0
  29. package/src/build/analyze.ts +271 -0
  30. package/src/build/babel/fix-libsql.ts +41 -0
  31. package/src/build/babel/get-deployer.ts +54 -0
  32. package/src/build/babel/get-telemetry-config.ts +62 -0
  33. package/src/build/babel/remove-deployer.ts +43 -0
  34. package/src/build/bundle.ts +139 -0
  35. package/src/build/bundler.ts +126 -0
  36. package/src/build/deployer.ts +67 -0
  37. package/src/build/deps.ts +149 -0
  38. package/src/build/env.ts +76 -0
  39. package/src/build/fs.ts +66 -0
  40. package/src/build/index.ts +7 -0
  41. package/src/build/isNodeBuiltin.ts +7 -0
  42. package/src/build/plugins/fix-libsql.ts +69 -0
  43. package/src/build/plugins/hono-alias.ts +17 -0
  44. package/src/build/plugins/pino.ts +93 -0
  45. package/src/build/plugins/remove-deployer.ts +37 -0
  46. package/src/build/plugins/telemetry-fix.ts +54 -0
  47. package/src/build/telemetry.ts +76 -0
  48. package/src/build/utils.ts +12 -0
  49. package/src/build/watcher.ts +43 -0
  50. package/src/bundler/index.ts +145 -0
  51. package/src/deploy/base.ts +30 -0
  52. package/src/deploy/index.ts +2 -0
  53. package/src/deploy/log.ts +61 -0
  54. package/src/index.ts +3 -0
  55. package/src/server/handlers/agents.ts +210 -0
  56. package/src/server/handlers/client.ts +36 -0
  57. package/src/server/handlers/error.ts +29 -0
  58. package/src/server/handlers/logs.ts +53 -0
  59. package/src/server/handlers/memory.ts +196 -0
  60. package/src/server/handlers/prompt.ts +128 -0
  61. package/src/server/handlers/root.ts +6 -0
  62. package/src/server/handlers/telemetry.ts +48 -0
  63. package/src/server/handlers/tools.ts +107 -0
  64. package/src/server/handlers/utils.ts +15 -0
  65. package/src/server/handlers/vector.ts +149 -0
  66. package/src/server/handlers/workflows.ts +104 -0
  67. package/src/server/index.ts +1355 -0
  68. package/src/server/openapi.json +434 -0
  69. package/src/server/openapi.script.js +22 -0
  70. package/src/server/types.ts +4 -0
  71. package/src/server/welcome.ts +105 -0
  72. package/tsconfig.json +5 -0
  73. package/vitest.config.ts +8 -0
@@ -0,0 +1,210 @@
1
+ import type { Mastra } from '@mastra/core';
2
+ import type { Context } from 'hono';
3
+ import { stringify } from 'superjson';
4
+ import zodToJsonSchema from 'zod-to-json-schema';
5
+
6
+ import { HTTPException } from 'hono/http-exception';
7
+
8
+ import { handleError } from './error';
9
+ import { validateBody } from './utils';
10
+
11
+ // Agent handlers
12
+ export async function getAgentsHandler(c: Context) {
13
+ try {
14
+ const mastra: Mastra = c.get('mastra');
15
+ const agents = mastra.getAgents();
16
+
17
+ const serializedAgents = Object.entries(agents).reduce<any>((acc, [_id, _agent]) => {
18
+ const agent = _agent as any;
19
+ const serializedAgentTools = Object.entries(agent?.tools || {}).reduce<any>((acc, [key, tool]) => {
20
+ const _tool = tool as any;
21
+ acc[key] = {
22
+ ..._tool,
23
+ inputSchema: _tool.inputSchema ? stringify(zodToJsonSchema(_tool.inputSchema)) : undefined,
24
+ outputSchema: _tool.outputSchema ? stringify(zodToJsonSchema(_tool.outputSchema)) : undefined,
25
+ };
26
+ return acc;
27
+ }, {});
28
+ acc[_id] = {
29
+ name: agent.name,
30
+ instructions: agent.instructions,
31
+ tools: serializedAgentTools,
32
+ provider: agent.llm?.getProvider(),
33
+ modelId: agent.llm?.getModelId(),
34
+ };
35
+ return acc;
36
+ }, {});
37
+
38
+ return c.json(serializedAgents);
39
+ } catch (error) {
40
+ return handleError(error, 'Error getting agents');
41
+ }
42
+ }
43
+
44
+ export async function getAgentByIdHandler(c: Context) {
45
+ try {
46
+ const mastra: Mastra = c.get('mastra');
47
+ const agentId = c.req.param('agentId');
48
+ const agent = mastra.getAgent(agentId);
49
+
50
+ if (!agent) {
51
+ throw new HTTPException(404, { message: 'Agent not found' });
52
+ }
53
+
54
+ const serializedAgentTools = Object.entries(agent?.tools || {}).reduce<any>((acc, [key, tool]) => {
55
+ const _tool = tool as any;
56
+ acc[key] = {
57
+ ..._tool,
58
+ inputSchema: _tool.inputSchema ? stringify(zodToJsonSchema(_tool.inputSchema)) : undefined,
59
+ outputSchema: _tool.outputSchema ? stringify(zodToJsonSchema(_tool.outputSchema)) : undefined,
60
+ };
61
+ return acc;
62
+ }, {});
63
+
64
+ return c.json({
65
+ name: agent.name,
66
+ instructions: agent.instructions,
67
+ tools: serializedAgentTools,
68
+ provider: agent.llm?.getProvider(),
69
+ modelId: agent.llm?.getModelId(),
70
+ });
71
+ } catch (error) {
72
+ return handleError(error, 'Error getting agent');
73
+ }
74
+ }
75
+
76
+ export async function getEvalsByAgentIdHandler(c: Context) {
77
+ try {
78
+ const mastra: Mastra = c.get('mastra');
79
+ const agentId = c.req.param('agentId');
80
+ const agent = mastra.getAgent(agentId);
81
+ const evals = (await mastra.storage?.getEvalsByAgentName?.(agent.name, 'test')) || [];
82
+ return c.json({
83
+ id: agentId,
84
+ name: agent.name,
85
+ instructions: agent.instructions,
86
+ evals,
87
+ });
88
+ } catch (error) {
89
+ return handleError(error, 'Error getting test evals');
90
+ }
91
+ }
92
+
93
+ export async function getLiveEvalsByAgentIdHandler(c: Context) {
94
+ try {
95
+ const mastra: Mastra = c.get('mastra');
96
+ const agentId = c.req.param('agentId');
97
+ const agent = mastra.getAgent(agentId);
98
+ const evals = (await mastra.storage?.getEvalsByAgentName?.(agent.name, 'live')) || [];
99
+
100
+ return c.json({
101
+ id: agentId,
102
+ name: agent.name,
103
+ instructions: agent.instructions,
104
+ evals,
105
+ });
106
+ } catch (error) {
107
+ return handleError(error, 'Error getting live evals');
108
+ }
109
+ }
110
+
111
+ export async function generateHandler(c: Context) {
112
+ try {
113
+ const mastra = c.get('mastra');
114
+ const agentId = c.req.param('agentId');
115
+ const agent = mastra.getAgent(agentId);
116
+
117
+ if (!agent) {
118
+ throw new HTTPException(404, { message: 'Agent not found' });
119
+ }
120
+
121
+ const { messages, threadId, resourceid, resourceId, output, runId } = await c.req.json();
122
+ validateBody({ messages });
123
+
124
+ if (!Array.isArray(messages)) {
125
+ throw new HTTPException(400, { message: 'Messages should be an array' });
126
+ }
127
+
128
+ // Use resourceId if provided, fall back to resourceid (deprecated)
129
+ const finalResourceId = resourceId ?? resourceid;
130
+
131
+ const result = await agent.generate(messages, { threadId, resourceId: finalResourceId, output, runId });
132
+
133
+ return c.json(result);
134
+ } catch (error) {
135
+ return handleError(error, 'Error generating from agent');
136
+ }
137
+ }
138
+
139
+ export async function streamGenerateHandler(c: Context): Promise<Response | undefined> {
140
+ try {
141
+ const mastra = c.get('mastra');
142
+ const agentId = c.req.param('agentId');
143
+ const agent = mastra.getAgent(agentId);
144
+
145
+ if (!agent) {
146
+ throw new HTTPException(404, { message: 'Agent not found' });
147
+ }
148
+
149
+ const { messages, threadId, resourceid, resourceId, output, runId } = await c.req.json();
150
+
151
+ validateBody({ messages });
152
+
153
+ if (!Array.isArray(messages)) {
154
+ throw new HTTPException(400, { message: 'Messages should be an array' });
155
+ }
156
+
157
+ // Use resourceId if provided, fall back to resourceid (deprecated)
158
+ const finalResourceId = resourceId ?? resourceid;
159
+
160
+ const streamResult = await agent.stream(messages, { threadId, resourceId: finalResourceId, output, runId });
161
+
162
+ const streamResponse = output
163
+ ? streamResult.toTextStreamResponse()
164
+ : streamResult.toDataStreamResponse({
165
+ sendUsage: true,
166
+ sendReasoning: true,
167
+ getErrorMessage: (error: any) => {
168
+ return `An error occurred while processing your request. ${error instanceof Error ? error.message : JSON.stringify(error)}`;
169
+ },
170
+ });
171
+
172
+ return streamResponse;
173
+ } catch (error) {
174
+ return handleError(error, 'Error streaming from agent');
175
+ }
176
+ }
177
+
178
+ export async function setAgentInstructionsHandler(c: Context) {
179
+ try {
180
+ // Check if this is a playground request
181
+ const isPlayground = c.get('playground') === true;
182
+ if (!isPlayground) {
183
+ return c.json({ error: 'This API is only available in the playground environment' }, 403);
184
+ }
185
+
186
+ const agentId = c.req.param('agentId');
187
+ const { instructions } = await c.req.json();
188
+
189
+ if (!agentId || !instructions) {
190
+ return c.json({ error: 'Missing required fields' }, 400);
191
+ }
192
+
193
+ const mastra: Mastra = c.get('mastra');
194
+ const agent = mastra.getAgent(agentId);
195
+ if (!agent) {
196
+ return c.json({ error: 'Agent not found' }, 404);
197
+ }
198
+
199
+ agent.__updateInstructions(instructions);
200
+
201
+ return c.json(
202
+ {
203
+ instructions,
204
+ },
205
+ 200,
206
+ );
207
+ } catch (error) {
208
+ return handleError(error, 'Error setting agent instructions');
209
+ }
210
+ }
@@ -0,0 +1,36 @@
1
+ import type { Context } from 'hono';
2
+
3
+ const clients = new Set<ReadableStreamDefaultController>();
4
+
5
+ export function handleClientsRefresh(c: Context): Response {
6
+ const stream = new ReadableStream({
7
+ start(controller) {
8
+ clients.add(controller);
9
+ controller.enqueue('data: connected\n\n');
10
+
11
+ c.req.raw.signal.addEventListener('abort', () => {
12
+ clients.delete(controller);
13
+ });
14
+ },
15
+ });
16
+
17
+ return new Response(stream, {
18
+ headers: {
19
+ 'Content-Type': 'text/event-stream',
20
+ 'Cache-Control': 'no-cache',
21
+ Connection: 'keep-alive',
22
+ 'Access-Control-Allow-Origin': '*',
23
+ },
24
+ });
25
+ }
26
+
27
+ export function handleTriggerClientsRefresh(c: Context) {
28
+ clients.forEach(controller => {
29
+ try {
30
+ controller.enqueue('data: refresh\n\n');
31
+ } catch {
32
+ clients.delete(controller);
33
+ }
34
+ });
35
+ return c.json({ success: true, clients: clients.size });
36
+ }
@@ -0,0 +1,29 @@
1
+ import type { Context } from 'hono';
2
+
3
+ import { HTTPException } from 'hono/http-exception';
4
+ import type { ContentfulStatusCode } from 'hono/utils/http-status';
5
+
6
+ import type { ApiError } from '../types';
7
+
8
+ // Helper to handle errors consistently
9
+ export function handleError(error: unknown, defaultMessage: string): Promise<Response> {
10
+ console.error(defaultMessage, error);
11
+ const apiError = error as ApiError;
12
+ throw new HTTPException((apiError.status || 500) as ContentfulStatusCode, {
13
+ message: apiError.message || defaultMessage,
14
+ });
15
+ }
16
+
17
+ // Error handlers
18
+ export function notFoundHandler() {
19
+ throw new HTTPException(404, { message: 'Not Found' });
20
+ }
21
+
22
+ export function errorHandler(err: Error, c: Context): Response {
23
+ if (err instanceof HTTPException) {
24
+ return c.json({ error: err.message }, err.status);
25
+ }
26
+
27
+ console.error(err);
28
+ return c.json({ error: 'Internal Server Error' }, 500);
29
+ }
@@ -0,0 +1,53 @@
1
+ import type { Mastra } from '@mastra/core';
2
+ import type { Context } from 'hono';
3
+
4
+ import { HTTPException } from 'hono/http-exception';
5
+
6
+ import { handleError } from './error';
7
+
8
+ export async function getLogsHandler(c: Context) {
9
+ try {
10
+ const mastra: Mastra = c.get('mastra');
11
+ const transportId = c.req.query('transportId');
12
+
13
+ if (!transportId) {
14
+ throw new HTTPException(400, { message: 'transportId is required' });
15
+ }
16
+
17
+ const logs = await mastra.getLogs(transportId);
18
+ return c.json(logs);
19
+ } catch (error) {
20
+ return handleError(error, 'Error getting logs');
21
+ }
22
+ }
23
+
24
+ export async function getLogsByRunIdHandler(c: Context) {
25
+ try {
26
+ const mastra: Mastra = c.get('mastra');
27
+ const runId = c.req.param('runId');
28
+ const transportId = c.req.query('transportId');
29
+
30
+ if (!transportId) {
31
+ throw new HTTPException(400, { message: 'transportId is required' });
32
+ }
33
+
34
+ const logs = await mastra.getLogsByRunId({ runId, transportId });
35
+ return c.json(logs);
36
+ } catch (error) {
37
+ return handleError(error, 'Error getting logs by run ID');
38
+ }
39
+ }
40
+
41
+ export async function getLogTransports(c: Context) {
42
+ console.log('here');
43
+ try {
44
+ const mastra: Mastra = c.get('mastra');
45
+ const logger = mastra.getLogger();
46
+ const transports = logger.transports;
47
+ return c.json({
48
+ transports: Object.keys(transports),
49
+ });
50
+ } catch (e) {
51
+ return handleError(e, 'Error getting log Transports ');
52
+ }
53
+ }
@@ -0,0 +1,196 @@
1
+ import type { MastraMemory } from '@mastra/core/memory';
2
+ import type { Context } from 'hono';
3
+
4
+ import { HTTPException } from 'hono/http-exception';
5
+
6
+ import { handleError } from './error';
7
+ import { validateBody } from './utils';
8
+
9
+ function getMemoryFromContext(c: Context): MastraMemory | null | undefined {
10
+ const mastra = c.get('mastra');
11
+ const agentId = c.req.query('agentId');
12
+ const agent = agentId ? mastra.getAgent(agentId) : null;
13
+
14
+ if (agentId && !agent) {
15
+ throw new HTTPException(404, { message: 'Agent not found' });
16
+ }
17
+
18
+ const memory = agent?.getMemory?.() || mastra.memory;
19
+
20
+ return memory;
21
+ }
22
+
23
+ // Memory handlers
24
+ export async function getMemoryStatusHandler(c: Context) {
25
+ try {
26
+ const memory = getMemoryFromContext(c);
27
+
28
+ if (!memory) {
29
+ return c.json({ result: false });
30
+ }
31
+
32
+ return c.json({ result: true });
33
+ } catch (error) {
34
+ return handleError(error, 'Error getting memory status');
35
+ }
36
+ }
37
+
38
+ export async function getThreadsHandler(c: Context) {
39
+ try {
40
+ const { resourceid } = c.req.query();
41
+ const memory = getMemoryFromContext(c);
42
+
43
+ if (!memory) {
44
+ throw new HTTPException(400, { message: 'Memory is not initialized' });
45
+ }
46
+
47
+ if (!resourceid) {
48
+ throw new HTTPException(400, { message: 'Resource ID is required' });
49
+ }
50
+
51
+ const threads = await memory.getThreadsByResourceId({ resourceId: resourceid });
52
+ return c.json(threads);
53
+ } catch (error) {
54
+ return handleError(error, 'Error getting threads');
55
+ }
56
+ }
57
+
58
+ export async function getThreadByIdHandler(c: Context) {
59
+ try {
60
+ const memory = getMemoryFromContext(c);
61
+ const threadId = c.req.param('threadId');
62
+
63
+ if (!memory) {
64
+ throw new HTTPException(400, { message: 'Memory is not initialized' });
65
+ }
66
+
67
+ const thread = await memory.getThreadById({ threadId });
68
+ if (!thread) {
69
+ throw new HTTPException(404, { message: 'Thread not found' });
70
+ }
71
+
72
+ return c.json(thread);
73
+ } catch (error) {
74
+ return handleError(error, 'Error getting thread');
75
+ }
76
+ }
77
+
78
+ export async function saveMessagesHandler(c: Context) {
79
+ try {
80
+ const memory = getMemoryFromContext(c);
81
+ const { messages } = await c.req.json();
82
+
83
+ if (!memory) {
84
+ throw new HTTPException(400, { message: 'Memory is not initialized' });
85
+ }
86
+
87
+ validateBody({ messages });
88
+
89
+ if (!Array.isArray(messages)) {
90
+ throw new HTTPException(400, { message: 'Messages should be an array' });
91
+ }
92
+
93
+ const processedMessages = messages.map(message => ({
94
+ ...message,
95
+ id: memory.generateId(),
96
+ createdAt: message.createdAt ? new Date(message.createdAt) : new Date(),
97
+ }));
98
+
99
+ const result = await memory.saveMessages({ messages: processedMessages, memoryConfig: {} });
100
+ return c.json(result);
101
+ } catch (error) {
102
+ return handleError(error, 'Error saving messages');
103
+ }
104
+ }
105
+
106
+ export async function createThreadHandler(c: Context) {
107
+ try {
108
+ const memory = getMemoryFromContext(c);
109
+ const { title, metadata, resourceid, threadId } = await c.req.json();
110
+
111
+ if (!memory) {
112
+ throw new HTTPException(400, { message: 'Memory is not initialized' });
113
+ }
114
+
115
+ validateBody({ resourceid });
116
+
117
+ const result = await memory.createThread({ resourceId: resourceid, title, metadata, threadId });
118
+ return c.json(result);
119
+ } catch (error) {
120
+ return handleError(error, 'Error saving thread to memory');
121
+ }
122
+ }
123
+
124
+ export async function updateThreadHandler(c: Context) {
125
+ try {
126
+ const memory = getMemoryFromContext(c);
127
+ const threadId = c.req.param('threadId');
128
+ const { title, metadata, resourceid } = await c.req.json();
129
+ const updatedAt = new Date();
130
+
131
+ if (!memory) {
132
+ throw new HTTPException(400, { message: 'Memory is not initialized' });
133
+ }
134
+
135
+ const thread = await memory.getThreadById({ threadId });
136
+ if (!thread) {
137
+ throw new HTTPException(404, { message: 'Thread not found' });
138
+ }
139
+
140
+ const updatedThread = {
141
+ ...thread,
142
+ title: title || thread.title,
143
+ metadata: metadata || thread.metadata,
144
+ resourceId: resourceid || thread.resourceId,
145
+ createdAt: thread.createdAt,
146
+ updatedAt,
147
+ };
148
+
149
+ const result = await memory.saveThread({ thread: updatedThread });
150
+ return c.json(result);
151
+ } catch (error) {
152
+ return handleError(error, 'Error updating thread');
153
+ }
154
+ }
155
+
156
+ export async function deleteThreadHandler(c: Context) {
157
+ try {
158
+ const memory = getMemoryFromContext(c);
159
+ const threadId = c.req.param('threadId');
160
+
161
+ if (!memory) {
162
+ throw new HTTPException(400, { message: 'Memory is not initialized' });
163
+ }
164
+
165
+ const thread = await memory.getThreadById({ threadId });
166
+ if (!thread) {
167
+ throw new HTTPException(404, { message: 'Thread not found' });
168
+ }
169
+
170
+ await memory.deleteThread(threadId);
171
+ return c.json({ result: 'Thread deleted' });
172
+ } catch (error) {
173
+ return handleError(error, 'Error deleting thread');
174
+ }
175
+ }
176
+
177
+ export async function getMessagesHandler(c: Context) {
178
+ try {
179
+ const memory = getMemoryFromContext(c);
180
+ const threadId = c.req.param('threadId');
181
+
182
+ if (!memory) {
183
+ return c.json({ error: 'Memory is not initialized' }, 400);
184
+ }
185
+
186
+ const thread = await memory.getThreadById({ threadId });
187
+ if (!thread) {
188
+ return c.json({ error: 'Thread not found' }, 404);
189
+ }
190
+
191
+ const result = await memory.query({ threadId });
192
+ return c.json(result);
193
+ } catch (error) {
194
+ return handleError(error, 'Error getting messages');
195
+ }
196
+ }
@@ -0,0 +1,128 @@
1
+ import type { Mastra } from '@mastra/core';
2
+ import { Agent } from '@mastra/core/agent';
3
+ import type { Context } from 'hono';
4
+ import { z } from 'zod';
5
+
6
+ import { handleError } from './error';
7
+
8
+ export async function generateSystemPromptHandler(c: Context) {
9
+ try {
10
+ // Check if this is a playground request
11
+ const agentId = c.req.param('agentId');
12
+ const isPlayground = c.get('playground') === true;
13
+ if (!isPlayground) {
14
+ return c.json({ error: 'This API is only available in the playground environment' }, 403);
15
+ }
16
+
17
+ const { instructions, comment } = await c.req.json();
18
+
19
+ if (!instructions) {
20
+ return c.json({ error: 'Missing instructions in request body' }, 400);
21
+ }
22
+
23
+ const mastra: Mastra<any> = c.get('mastra');
24
+ const agent = mastra.getAgent(agentId);
25
+
26
+ if (!agent) {
27
+ return c.json({ error: 'Agent not found' }, 404);
28
+ }
29
+
30
+ let evalSummary = '';
31
+
32
+ try {
33
+ // Get both test and live evals
34
+ const testEvals = (await mastra.storage?.getEvalsByAgentName?.(agent.name, 'test')) || [];
35
+ const liveEvals = (await mastra.storage?.getEvalsByAgentName?.(agent.name, 'live')) || [];
36
+ // Format eval results for the prompt
37
+ const evalsMapped = [...testEvals, ...liveEvals].filter(
38
+ ({ instructions: evalInstructions }) => evalInstructions === instructions,
39
+ );
40
+
41
+ evalSummary = evalsMapped
42
+ .map(
43
+ ({ input, output, result }) => `
44
+ Input: ${input}\n
45
+ Output: ${output}\n
46
+ Result: ${JSON.stringify(result)}
47
+
48
+ `,
49
+ )
50
+ .join('');
51
+ } catch (error) {
52
+ mastra.getLogger().error(`Error fetching evals`, { error });
53
+ }
54
+
55
+ const ENHANCE_SYSTEM_PROMPT_INSTRUCTIONS = `
56
+ 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.
57
+ Follow these steps to analyze and enhance the instructions:
58
+ 1. ANALYSIS PHASE
59
+ - Identify the core purpose and goals
60
+ - Extract key constraints and requirements
61
+ - Recognize domain-specific terminology and concepts
62
+ - Note any implicit assumptions that should be made explicit
63
+ 2. PROMPT STRUCTURE
64
+ Create a system prompt with these components:
65
+ a) ROLE DEFINITION
66
+ - Clear statement of the AI's role and purpose
67
+ - Key responsibilities and scope
68
+ - Primary stakeholders and users
69
+ b) CORE CAPABILITIES
70
+ - Main functions and abilities
71
+ - Specific domain knowledge required
72
+ - Tools and resources available
73
+ c) BEHAVIORAL GUIDELINES
74
+ - Communication style and tone
75
+ - Decision-making framework
76
+ - Error handling approach
77
+ - Ethical considerations
78
+ d) CONSTRAINTS & BOUNDARIES
79
+ - Explicit limitations
80
+ - Out-of-scope activities
81
+ - Security and privacy considerations
82
+ e) SUCCESS CRITERIA
83
+ - Quality standards
84
+ - Expected outcomes
85
+ - Performance metrics
86
+ 3. QUALITY CHECKS
87
+ Ensure the prompt is:
88
+ - Clear and unambiguous
89
+ - Comprehensive yet concise
90
+ - Properly scoped
91
+ - Technically accurate
92
+ - Ethically sound
93
+ 4. OUTPUT FORMAT
94
+ Return a structured response with:
95
+ - Enhanced system prompt
96
+ - Analysis of key components
97
+ - Identified goals and constraints
98
+ - Core domain concepts
99
+ Remember: A good system prompt should be specific enough to guide behavior but flexible enough to handle edge cases.
100
+ Focus on creating prompts that are clear, actionable, and aligned with the intended use case.
101
+ `;
102
+
103
+ const systemPromptAgent = new Agent({
104
+ name: 'system-prompt-enhancer',
105
+ instructions: ENHANCE_SYSTEM_PROMPT_INSTRUCTIONS,
106
+ model: agent.llm?.getModel(),
107
+ });
108
+
109
+ const result = await systemPromptAgent.generate(
110
+ `
111
+ We need to improve the system prompt.
112
+ Current: ${instructions}
113
+ ${comment ? `User feedback: ${comment}` : ''}
114
+ ${evalSummary ? `\nEvaluation Results:\n${evalSummary}` : ''}
115
+ `,
116
+ {
117
+ output: z.object({
118
+ new_prompt: z.string(),
119
+ explanation: z.string(),
120
+ }),
121
+ },
122
+ );
123
+
124
+ return c.json(result?.object || {});
125
+ } catch (error) {
126
+ return handleError(error, 'Error generating system prompt');
127
+ }
128
+ }
@@ -0,0 +1,6 @@
1
+ import type { Context } from 'hono';
2
+
3
+ // Root handler
4
+ export async function rootHandler(c: Context) {
5
+ return c.text('Hello to the Mastra API!');
6
+ }