sweagent 0.0.2 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1086 -1021
- package/dist/index.cjs +912 -1019
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +526 -955
- package/dist/index.d.ts +526 -955
- package/dist/index.js +912 -1019
- package/dist/index.js.map +1 -1
- package/dist/stdio.d.ts +2 -0
- package/dist/stdio.js +1514 -0
- package/dist/stdio.js.map +1 -0
- package/package.json +9 -3
package/dist/stdio.js
ADDED
|
@@ -0,0 +1,1514 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {McpServer}from'@modelcontextprotocol/sdk/server/mcp.js';import {tool,zodSchema,generateObject,generateText}from'ai';import {createOpenAI}from'@ai-sdk/openai';import {createAnthropic}from'@ai-sdk/anthropic';import {createGoogleGenerativeAI}from'@ai-sdk/google';import {z as z$1}from'zod';import'pino';import*as le from'path';import*as Z from'fs';import oe from'handlebars';var he=class extends Error{constructor(t,o){super(t,o===void 0?void 0:{cause:o}),this.name="LibraryError",o?.stack&&(this.stack=`${this.stack}
|
|
3
|
+
Caused by: ${o.stack}`);}},re=class extends he{constructor(o,r,n){super(o,n);this.provider=r;this.name="ModelError";}},pe=class extends he{constructor(o,r,n){super(o,n);this.toolName=r;this.name="ToolError";}};var Ke=class extends he{constructor(o,r,n){super(o,n);this.iteration=r;this.name="AgentError";}},ye=class extends he{constructor(o,r,n){super(o,n);this.subagentName=r;this.name="SubagentError";}};function Se(e){let{provider:t,modelName:o,getModel:r}=e;return {provider:t,modelName:o,async invoke(n,s){try{let a=await r(),i=s?.tools?Object.fromEntries(Object.entries(s.tools).map(([c,d])=>{let{execute:g,...h}=d;return [c,h]})):void 0,l=await generateText({model:a,messages:n,tools:i,maxOutputTokens:s?.maxOutputTokens,temperature:s?.temperature,stopSequences:s?.stop}),p=l.toolCalls.map(c=>({toolCallId:c.toolCallId,toolName:c.toolName,input:c.input}));return {text:l.text,toolCalls:p,usage:l.usage,finishReason:l.finishReason}}catch(a){let i=a instanceof Error?a:new Error(String(a));throw new re(`Failed to invoke ${t} model`,t,i)}},async generateVision(n,s,a){try{let i=await r(),l=[];for(let d of s)l.push({type:"image",image:`data:${d.mimeType};base64,${d.base64}`,mimeType:d.mimeType});l.push({type:"text",text:n});let p=[];a?.systemPrompt&&p.push({role:"system",content:a.systemPrompt}),p.push({role:"user",content:l});let c=await generateText({model:i,messages:p,maxOutputTokens:a?.maxOutputTokens,temperature:a?.temperature});return {text:c.text,toolCalls:[],usage:c.usage,finishReason:c.finishReason}}catch(i){let l=i instanceof Error?i:new Error(String(i));throw new re("Failed to generate vision response",t,l)}},async invokeObject(n,s,a){try{let i=await r(),l=zodSchema(s),p=await generateObject({model:i,messages:n,schema:l,temperature:a?.temperature,maxOutputTokens:a?.maxOutputTokens});return {data:p.object,usage:p.usage}}catch(i){let l=i instanceof Error?i:new Error(String(i));throw new re(`Failed to invokeObject ${t} model`,t,l)}}}}function cn(e){let{model:t,apiKey:o,baseUrl:r}=e,n=createOpenAI({apiKey:o??process.env.OPENAI_API_KEY,baseURL:r});return Se({provider:"openai",modelName:t,getModel:()=>n.chat(t)})}function pn(e){let{model:t,apiKey:o}=e,r=createAnthropic({apiKey:o??process.env.ANTHROPIC_API_KEY});return Se({provider:"anthropic",modelName:t,getModel:()=>r(t)})}function dn(e){let{model:t,apiKey:o}=e,r=createGoogleGenerativeAI({apiKey:o??process.env.GOOGLE_GENERATIVE_AI_API_KEY});return Se({provider:"google",modelName:t,getModel:()=>r(t)})}function E(e){let{provider:t}=e;switch(t){case "openai":return cn(e);case "anthropic":return pn(e);case "google":return dn(e);default:throw new re(`Unsupported provider: ${t}. Supported providers: openai, anthropic, google`)}}var Os={overview:null,techStack:null,featureDecisions:null,dataModels:null,pagesAndRoutes:null,authFlow:null,apiRoutes:null,implementation:null,executionPlan:null,edgeCases:null,testingChecklist:null};function un(){return {stage:"discovery",projectDescription:null,sections:{...Os},history:[],pendingQuestions:[]}}function mn(e,t){let{sections:o,projectDescription:r,pendingQuestions:n}=t,s={...e.sections};if(o)for(let a of Object.keys(o)){let i=o[a];i!=null&&(s[a]=i);}return {...e,...r!==void 0&&{projectDescription:r},sections:s,...n!==void 0&&{pendingQuestions:n}}}function Ze(e,t,o){let r={role:t,content:o};return {...e,history:[...e.history,r]}}function mo(e){let t=["discovery","requirements","design","complete"],o=t.indexOf(e.stage),n=(o>=0&&o<t.length-1?t[o+1]:void 0)??e.stage;return {...e,stage:n}}function et(e){let t=e.trim().toLowerCase();return ["continue","yes","yeah","yep","looks good","good","ok","okay","next","proceed","sure"].some(r=>t===r||t.startsWith(r+" "))}var W=`You are a senior software architect creating a single, implementation-ready plan that a developer can follow without ambiguity.
|
|
4
|
+
|
|
5
|
+
CRITICAL RULES:
|
|
6
|
+
- Output ONLY raw markdown text. Use code blocks ONLY for: request/response JSON examples, file/directory trees, and env or config snippets. No JSON or structured data outside those code blocks.
|
|
7
|
+
- Use consistent structure: ## for main sections, ### for subsections, #### for per-item headings (e.g. per route, per endpoint). Use **bold** for labels (e.g. **Purpose**, **Request Body**, **Response on Success**).
|
|
8
|
+
- Be concrete and actionable: include validation rules, HTTP status codes, redirects, field-level data model descriptions, and step-by-step auth flows. Every section should give enough detail to implement from the plan alone.`;var go=`You are in the discovery stage. Your goal is to understand what the user wants to build.
|
|
9
|
+
|
|
10
|
+
Respond in natural language only. Do NOT output JSON.
|
|
11
|
+
|
|
12
|
+
- If you need more information: ask 1-3 short, specific questions. Focus on tech choices (REST vs GraphQL, MongoDB vs PostgreSQL) and any gaps that block design.
|
|
13
|
+
- When you have enough to proceed: output the project overview in this exact pro format so it matches the rest of the plan:
|
|
14
|
+
- **## Overview** \u2014 One paragraph (2\u20134 sentences) summarizing the project and its purpose.
|
|
15
|
+
- **## Core Features** \u2014 Numbered list: 1. **Feature Name** - Short description. (one line per feature)
|
|
16
|
+
- **## Tech Stack** \u2014 Bullet list with category labels: - **Frontend**: ... (versions if known), - **Database**: ..., - **Authentication**: ..., - **API**: ..., - **Backend**: ... Include versions and key libraries where relevant.
|
|
17
|
+
|
|
18
|
+
When the user says "continue", "yes", "looks good", or similar, treat it as confirmation to proceed. Do NOT keep asking questions. Make reasonable assumptions for any missing details (choose sensible defaults for tech stack, features, scope, etc.) and immediately output the project overview in the format above.`,gn=`## Current user message:
|
|
19
|
+
{userMessage}
|
|
20
|
+
|
|
21
|
+
## Prior conversation (if any):
|
|
22
|
+
{history}
|
|
23
|
+
|
|
24
|
+
Respond in plain markdown. Either ask clarifying questions, or if you have enough information, output the project overview in pro format: ## Overview (one paragraph), ## Core Features (numbered list with **Feature Name** - description), ## Tech Stack (bullets with **Category**: detail). Do NOT output JSON.`;function fo(e,t){return gn.replace("{userMessage}",e).replace("{history}",t||"(No prior messages)")}var tt=`## Project description / context:
|
|
25
|
+
{context}`,fn=`${tt}
|
|
26
|
+
|
|
27
|
+
Using the project description above, write two markdown sections in this exact format:
|
|
28
|
+
|
|
29
|
+
1. **## Overview** \u2014 One paragraph only (2\u20134 sentences) summarizing the project and its purpose.
|
|
30
|
+
2. **## Tech Stack** \u2014 Bullet list with category labels: - **Frontend**: ... (include framework and versions if applicable, e.g. Next.js 16, React 19, TypeScript, Tailwind v4), - **Database**: ... (e.g. MongoDB with Mongoose), - **Authentication**: ... (e.g. JWT in HTTP-only cookies, bcrypt), - **API**: ... (REST or GraphQL), - **Backend**: ... Include versions and key libraries where applicable.
|
|
31
|
+
|
|
32
|
+
Output only these two sections in markdown. Do NOT output JSON.`,hn=`${tt}
|
|
33
|
+
|
|
34
|
+
## Already written (Overview + Tech Stack):
|
|
35
|
+
{overviewAndTechStack}
|
|
36
|
+
|
|
37
|
+
Write the next two markdown sections in this exact format:
|
|
38
|
+
|
|
39
|
+
1. **## Feature Decisions** \u2014 Use ### per feature/area (e.g. ### Workout Tracking, ### Nutrition Tracking). Under each, bullets for key product decisions; use sub-bullets for options where relevant (e.g. goal types: weight, strength, consistency, custom).
|
|
40
|
+
2. **## Data Models** \u2014 For each entity use ### EntityName. For each field use exactly one line: \`field_name\`: description (type, required/optional, unique if applicable). For references write "Reference to EntityName". Include User, profile/settings, and all domain entities.
|
|
41
|
+
|
|
42
|
+
Output only markdown. Do NOT output JSON.`;function ho(e){return fn.replace("{context}",e)}function yo(e,t){return hn.replace("{context}",e).replace("{overviewAndTechStack}",t)}var yn=`## Project context (all sections so far):
|
|
43
|
+
{priorSections}`,Sn=`${yn}
|
|
44
|
+
|
|
45
|
+
## API Routes (already written):
|
|
46
|
+
{apiRoutes}
|
|
47
|
+
|
|
48
|
+
Write the next markdown section in this exact format:
|
|
49
|
+
|
|
50
|
+
**## Implementation Details**
|
|
51
|
+
- **### File Structure** \u2014 Full directory tree in a **code block** (e.g. src/app/(auth)/login/page.tsx, src/app/api/auth/signup/route.ts, src/components/..., src/lib/, src/models/). Show the real layout a developer would create.
|
|
52
|
+
- **### Environment Variables** \u2014 List with comments (e.g. MONGODB_URI=... # connection string, JWT_SECRET=... # change in production).
|
|
53
|
+
- **### Dependencies to Install** \u2014 npm install line and short explanation per dependency (e.g. mongoose: MongoDB ODM; bcryptjs: password hashing; jsonwebtoken: JWT; cookie: cookie parsing).
|
|
54
|
+
- **### Key Setup** \u2014 One subsection per concern: **MongoDB connection** (file path, purpose, 3\u20135 bullets), **JWT utilities** (file path, purpose; cookie name, maxAge, httpOnly, secure; generateToken/verifyToken/setAuthCookie/clearAuthCookie), **Auth middleware** (file path, authenticateRequest behavior), **External API client** if any (file path, purpose).
|
|
55
|
+
- If the plan is UI-heavy, add **### UI Component Guidelines** (controlled inputs, validation, loading/error states) and **### Error Handling Standards** (API error JSON shape, HTTP status codes: 200, 201, 400, 401, 403, 404, 500).
|
|
56
|
+
|
|
57
|
+
Output only markdown. Do NOT output JSON.`;function So(e,t){return Sn.replace("{priorSections}",e).replace("{apiRoutes}",t)}var _s=`## Full plan so far (all sections):
|
|
58
|
+
{priorSections}`,bo="You are in the complete stage. You have the full implementation plan. Output the final sections in markdown, in the exact order specified below, so they can be assembled into the plan.",bn=`${_s}
|
|
59
|
+
|
|
60
|
+
Write the following sections in this exact order. Output only markdown. Do NOT output JSON.
|
|
61
|
+
|
|
62
|
+
**Block 1 \u2014 Implementation Order, Current State, Desired End State**
|
|
63
|
+
|
|
64
|
+
1. **## Implementation Order** \u2014 Phased: ### Phase 1: Foundation, ### Phase 2: Authentication, etc. Under each phase, numbered steps (e.g. "1. Install dependencies", "2. Create User model", "3. Implement POST /api/auth/signup", "4. Create login page"). Be concrete so a developer can follow step-by-step.
|
|
65
|
+
|
|
66
|
+
2. **## Current State Analysis** \u2014 What the project starts with (e.g. vanilla Next.js, no DB, no auth). Then a short bullet list: "What needs to be built from scratch" (all auth, models, API routes, pages, etc.).
|
|
67
|
+
|
|
68
|
+
3. **## Desired End State** \u2014 Short subsections or bullets: (1) For users: what they can do when the app is done; (2) Technical verification: what must work (DB connected, auth working, endpoints returning correct data, etc.); (3) Testing approach: manual flows, API checks, DB checks.
|
|
69
|
+
|
|
70
|
+
**Block 2 \u2014 Edge Cases, Security, Performance, Future Enhancements**
|
|
71
|
+
|
|
72
|
+
4. **## Edge Cases and Considerations** \u2014 ### per area (e.g. ### Authentication, ### Workouts, ### Nutrition, ### Goals, ### Profile, ### General). Under each, bullets for edge cases and how to handle them (e.g. "Email already exists: return 400 with clear message"; "External API down: show error, allow manual entry").
|
|
73
|
+
|
|
74
|
+
5. **## Security Considerations** \u2014 Numbered list: passwords (bcrypt, min length); JWT (HTTP-only cookie, secure flag, strong secret, expiry); API (verify JWT on protected routes, check resource ownership); env (never commit secrets, different values in production).
|
|
75
|
+
|
|
76
|
+
6. **## Performance Considerations** \u2014 Numbered list: DB (index user id and date fields, lean queries, avoid N+1); API (debounce search, cache external API if applicable); frontend (RSC where possible, lazy load heavy components); optional future caching.
|
|
77
|
+
|
|
78
|
+
7. **## Future Enhancements (Not in Current Scope)** \u2014 Short grouped list (e.g. Social, Analytics, Integrations, Mobile, Premium) so scope is clear. One line per group is enough.
|
|
79
|
+
|
|
80
|
+
**Block 3 \u2014 Manual Testing Checklist**
|
|
81
|
+
|
|
82
|
+
8. **## Manual Testing Checklist** \u2014 ### per flow (e.g. ### Authentication Flow, ### Workout Flow, ### Nutrition Flow, ### Goals Flow, ### Profile Flow). Under each, checklist items: - [ ] Description of what to verify (e.g. "- [ ] Sign up with valid credentials creates account", "- [ ] Login with invalid credentials shows error").
|
|
83
|
+
|
|
84
|
+
Output all eight sections in the order above. Do NOT output JSON.`;function xo(e){return bn.replace("{priorSections}",e)}function js(e){let t=e.trim();if(t.length<100)return false;if(t.includes("## Overview")||t.includes("## Core Features"))return true;let o=t.toLowerCase();return !!((o.includes("overview")||o.includes("core features"))&&(o.includes("tech stack")||o.includes("technology")))}async function To(e,t,o,r){r?.debug("Discovery stage started",{historyLength:t.history.length});let s=t.history.slice(0,-1).map(L=>`${L.role}: ${L.content}`).slice(-10).join(`
|
|
85
|
+
`),a=fo(e,s),l=[{role:"system",content:`${W}
|
|
86
|
+
|
|
87
|
+
${go}`},{role:"user",content:a}],c=(await o.invoke(l,{temperature:.4,maxOutputTokens:4096})).text?.trim()??"",d=js(c),g=et(e),h=g&&t.history.length>=7&&c.length>50,u=d&&(t.projectDescription==null||g)||g&&t.projectDescription!=null||h,J=d||h&&c.length>50;return r?.debug("Discovery stage complete",{advance:u,hasOverview:d,userConfirmed:g,forceAdvance:h}),{message:c,advance:u,sections:{},...J&&{projectDescription:c}}}var ot=class{stageName="discovery";async process(t,o){return To(o.userMessage,t,o.model,o.logger)}canAdvance(t){return t.advance}getNextStageName(){return "requirements"}};var qs={noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},Fs={textTokens:void 0,reasoningTokens:void 0};function Po(e){let t=0,o=0,r=0;for(let n of e)n&&(t+=n.inputTokens??0,o+=n.outputTokens??0,r+=n.totalTokens??0);return {inputTokens:t,outputTokens:o,totalTokens:r,inputTokenDetails:qs,outputTokenDetails:Fs}}function S(e){let{name:t,description:o,input:r,handler:n}=e;return tool({description:o,inputSchema:r,execute:async s=>{let a=r.safeParse(s);if(!a.success)throw new pe(`Invalid input: ${a.error.message}`,t,a.error);try{return await n(a.data,void 0)}catch(i){throw i instanceof pe?i:new pe(`Tool "${t}" failed: ${i instanceof Error?i.message:String(i)}`,t,i instanceof Error?i:void 0)}}})}async function xn(e,t,o){let{logger:r}=o??{},n=o?.toolName??("name"in e&&typeof e.name=="string"?e.name:"unknown");if(!e.execute)return r?.error("Tool has no execute function",{toolName:n}),{success:false,error:"Tool has no execute function"};r?.debug("Executing tool",{toolName:n,toolCallId:o?.toolCallId});try{let s=await e.execute(t,{toolCallId:o?.toolCallId??"",messages:[],abortSignal:o?.abortSignal});return r?.info("Tool completed",{toolName:n,toolCallId:o?.toolCallId}),{success:!0,output:s}}catch(s){let a=s instanceof Error?s.message:String(s);return r?.error("Tool failed",{toolName:n,toolCallId:o?.toolCallId,error:a}),{success:false,error:a}}}async function Ro(e,t,o,r){let n=e[t];if(!n)throw r?.logger?.error("Tool not found",{name:t,availableTools:Object.keys(e)}),new pe(`Tool not found: ${t}`);return xn(n,o,{...r,toolName:t})}function I(e,t,o,r="json"){return S({name:e,description:o,input:z$1.object({[r]:z$1.string().describe("JSON string to validate")}),handler:async n=>{let s=n[r]??"";try{let a=JSON.parse(s);return t.parse(a),{valid:!0}}catch(a){return a instanceof z$1.ZodError?{valid:false,errors:a.issues.map(i=>`${i.path.join(".")}: ${i.message}`)}:a instanceof SyntaxError?{valid:false,errors:[`Invalid JSON: ${a.message}`]}:{valid:false,errors:[String(a)]}}}})}function vo(e,t){e?.forEach(o=>o.onStep?.(t));}function Tn(e,t,o){e?.forEach(r=>r.onToolExecution?.(t,o));}function Pn(e,t){e?.forEach(o=>o.onError?.(t));}async function N(e){let{model:t,tools:o,systemPrompt:r,input:n,maxIterations:s=10,onStep:a,observers:i,logger:l}=e;l?.info("Starting agent",{maxIterations:s});let p=[{role:"system",content:r},{role:"user",content:n}],c=[];for(let g=0;g<s;g++){g>0&&g>=s-2&&l?.warn("Approaching max iterations",{iteration:g,maxIterations:s}),l?.debug("Agent iteration",{iteration:g});let h=await t.invoke(p,{tools:o}),u={iteration:g,content:h.text,toolCalls:h.toolCalls,usage:h.usage};if(h.text&&l?.debug("Model response",{iteration:g,textLength:h.text.length}),!h.toolCalls?.length)return c.push(u),a?.(u),vo(i,u),l?.info("Agent completed",{steps:c.length,totalUsage:Po(c.map(k=>k.usage))}),{output:h.text,steps:c,totalUsage:Po(c.map(k=>k.usage)),messages:p};l?.debug("Tool calls",{iteration:g,toolCalls:h.toolCalls.map(k=>({name:k.toolName,toolCallId:k.toolCallId}))});let J=[...h.text?[{type:"text",text:h.text}]:[],...h.toolCalls.map(k=>({type:"tool-call",toolCallId:k.toolCallId,toolName:k.toolName,input:k.input}))];p.push({role:"assistant",content:J});let L=[];for(let k of h.toolCalls){let fe=await Ro(o,k.toolName,k.input,{toolCallId:k.toolCallId,logger:l}),ce={toolCallId:k.toolCallId,toolName:k.toolName,output:fe.success?fe.output:fe.error,isError:!fe.success};L.push(ce),Tn(i,k.toolName,ce.output);let Rs=ce.isError?{type:"error-text",value:String(ce.output)}:{type:"text",value:typeof ce.output=="string"?ce.output:JSON.stringify(ce.output)};p.push({role:"tool",content:[{type:"tool-result",toolCallId:k.toolCallId,toolName:k.toolName,output:Rs}]});}u.toolResults=L,c.push(u),a?.(u),vo(i,u);}let d=new Ke(`Agent reached maximum iterations (${s}) without completing`,s-1);throw Pn(i,d),l?.error("Agent failed: max iterations reached",{maxIterations:s,error:d}),d}var Ls=/^[a-z0-9]+(-[a-z0-9]+)*$/;function f(e){if(!e.name.trim())throw new ye("Subagent name is required",void 0);if(!Ls.test(e.name))throw new ye(`Subagent name must be kebab-case (lowercase letters, numbers, hyphens): ${e.name}`,e.name);return {...e}}function Gs(e,t){if(e.tools!=null&&Object.keys(e.tools).length>0)return e.tools;let o=t??{},r=new Set(e.disallowedTools??[]),n={};for(let[s,a]of Object.entries(o))s.startsWith("subagent_")||r.has(s)||(n[s]=a);return n}async function $(e,t,o){let{parentTools:r,parentModel:n}=o??{},s=Gs(e,r),a=e.model==null?n:E(e.model);if(!a)throw new ye("Subagent has no model: set definition.model or pass parentModel in options",e.name);return {...await N({model:a,tools:s,systemPrompt:e.systemPrompt,input:t,maxIterations:e.maxIterations??10,onStep:e.onStep}),subagentName:e.name}}function wn(e,t){let o=`subagent_${e.name}`;return S({name:o,description:e.description,input:z$1.object({prompt:z$1.string().describe("The task or question to delegate to this subagent")}),handler:async({prompt:r})=>(await $(e,r,{parentTools:t?.parentTools,parentModel:t?.parentModel})).output})}function q(e,t){let o={};for(let r of e){let n=wn(r,t);o[`subagent_${r.name}`]=n;}return o}var Bs=`You are an expert database entity analyst. Your job is to extract data model signals from requirements.
|
|
88
|
+
|
|
89
|
+
Perform these analyses:
|
|
90
|
+
|
|
91
|
+
## Entity Discovery
|
|
92
|
+
- List every entity implied by the requirements (users, domain objects, settings, logs).
|
|
93
|
+
- For each entity: name, purpose, key fields (with types), and which user type owns it.
|
|
94
|
+
- Identify status enums from flow transitions (e.g. pending -> active -> completed).
|
|
95
|
+
|
|
96
|
+
## Field Analysis
|
|
97
|
+
- For each entity, list fields with: name, likely type, required/optional, unique constraints.
|
|
98
|
+
- Identify computed vs stored fields.
|
|
99
|
+
- Note fields that need indexing (lookups, sorting, filtering).
|
|
100
|
+
|
|
101
|
+
## Relationship Signals
|
|
102
|
+
- List entity pairs that reference each other.
|
|
103
|
+
- Note ownership direction (which entity "belongs to" which).
|
|
104
|
+
- Identify potential M:N relationships that may need join tables.
|
|
105
|
+
|
|
106
|
+
Respond with a clear, structured analysis using headings and bullet points. Do NOT return JSON.`,ne=f({name:"entity-analyzer",description:"Analyzes requirements to extract entities, fields, relationships, and data model signals. Use when you need to understand the data before designing the schema.",systemPrompt:Bs,tools:{},maxIterations:2});var Js=`You are a database relationship specialist. Given a list of entities and their fields, you determine:
|
|
107
|
+
|
|
108
|
+
## Cardinality Analysis
|
|
109
|
+
- For every entity pair that references each other, classify: 1:1, 1:N, or M:N.
|
|
110
|
+
- Explain the reasoning (e.g. "A User has many Orders, but an Order belongs to one User -> 1:N").
|
|
111
|
+
|
|
112
|
+
## Foreign Key / Reference Strategy
|
|
113
|
+
- For MongoDB: recommend ObjectId references vs embedding. Embed when: data is small, always read together, rarely updated independently.
|
|
114
|
+
- For PostgreSQL: define foreign key columns, ON DELETE behavior (CASCADE, SET NULL, RESTRICT).
|
|
115
|
+
|
|
116
|
+
## Join Table Design (M:N)
|
|
117
|
+
- When M:N is detected, design the join table with: both foreign keys, any extra fields (e.g. role in a membership), indexes.
|
|
118
|
+
|
|
119
|
+
## Index Recommendations
|
|
120
|
+
- Suggest compound indexes for common query patterns.
|
|
121
|
+
- Suggest unique indexes for natural keys (email, slug, etc.).
|
|
122
|
+
- Note partial indexes where applicable (e.g. only active records).
|
|
123
|
+
|
|
124
|
+
Respond with structured analysis. Do NOT return JSON.`,rt=f({name:"relationship-mapper",description:"Maps cardinality (1:1, 1:N, M:N), foreign keys, join tables, and index recommendations for entity relationships. Use after entity analysis.",systemPrompt:Js,tools:{},maxIterations:2});var Ys=`You are an expert database schema reviewer. Your job is to:
|
|
125
|
+
|
|
126
|
+
1. Validate the schema structure: every entity has fields, indexes, and relations properly defined.
|
|
127
|
+
2. Check completeness: all entities from requirements are present, all relationships are bidirectional where needed.
|
|
128
|
+
3. Check normalization: no redundant data, proper use of references vs embedding.
|
|
129
|
+
4. Check performance: indexes cover common query patterns, no missing indexes on foreign keys.
|
|
130
|
+
5. Check security: passwords are marked as hashed, sensitive fields noted, no plaintext secrets.
|
|
131
|
+
6. Check conventions: consistent naming (camelCase or snake_case), timestamps on all entities.
|
|
132
|
+
|
|
133
|
+
If you have access to the validate_schema tool, use it first. Then provide a detailed review with:
|
|
134
|
+
- Issues found (with severity: critical, warning, suggestion)
|
|
135
|
+
- Specific fixes for each issue
|
|
136
|
+
- Overall assessment (ready / needs work)
|
|
137
|
+
|
|
138
|
+
Respond with structured analysis. Do NOT return JSON.`;function be(){return f({name:"schema-refiner",description:"Reviews a data model schema for completeness, normalization, performance, and security. Has access to validate_schema tool.",systemPrompt:Ys,tools:{},maxIterations:3})}var zs=`You are a UX-focused frontend architect. You design detailed page specifications.
|
|
139
|
+
|
|
140
|
+
## Page Planning
|
|
141
|
+
For each page in the application:
|
|
142
|
+
|
|
143
|
+
### Route Definition
|
|
144
|
+
- Path (e.g. /login, /dashboard, /workouts/:id)
|
|
145
|
+
- Access level: public (no auth) or protected (requires auth)
|
|
146
|
+
- Page name and purpose (one sentence)
|
|
147
|
+
|
|
148
|
+
### Page Detail
|
|
149
|
+
- **Form fields**: name, type (text, email, password, number, select, textarea, date, checkbox), required flag, validation rule.
|
|
150
|
+
- **Actions**: buttons and what they do (e.g. "Submit form", "Delete item", "Export CSV").
|
|
151
|
+
- **Empty state**: what to show when there's no data (e.g. "No workouts yet. Click + to add one.").
|
|
152
|
+
- **Error state**: how to handle errors (e.g. "Show inline validation errors", "Toast notification").
|
|
153
|
+
- **Redirect on success**: where to go after successful action (e.g. "/dashboard").
|
|
154
|
+
- **Key UI elements**: cards, tables, charts, sidebar, modals, tabs.
|
|
155
|
+
|
|
156
|
+
### Page Grouping
|
|
157
|
+
- Group by access: public pages first, then protected.
|
|
158
|
+
- Order by user flow: signup -> login -> dashboard -> feature pages -> settings -> admin.
|
|
159
|
+
|
|
160
|
+
Respond with structured page specs. Do NOT return JSON.`,xe=f({name:"page-planner",description:"Designs detailed page specifications with routes, form fields, actions, states, and UI elements. Use for frontend page design.",systemPrompt:zs,tools:{},maxIterations:2});var $s=`You are a component design specialist. Given page specifications, you identify reusable components and shared patterns.
|
|
161
|
+
|
|
162
|
+
## Component Identification
|
|
163
|
+
- **Layout components**: main layout (with nav, sidebar, content area), auth layout (centered form), admin layout.
|
|
164
|
+
- **Navigation components**: navbar, sidebar, breadcrumbs, mobile menu.
|
|
165
|
+
- **Form components**: reusable form inputs, form wrappers, validation display.
|
|
166
|
+
- **Display components**: cards, tables, lists, stat widgets, charts, badges.
|
|
167
|
+
- **Shared components**: modals, toasts, loading spinners, empty state illustrations, error boundaries.
|
|
168
|
+
|
|
169
|
+
## Component Analysis
|
|
170
|
+
For each component:
|
|
171
|
+
- Name (PascalCase)
|
|
172
|
+
- Type: layout, shared, form, display, navigation
|
|
173
|
+
- Purpose (one sentence)
|
|
174
|
+
- Props it accepts (e.g. "user", "items", "onSubmit", "isLoading")
|
|
175
|
+
- Which pages use it
|
|
176
|
+
|
|
177
|
+
## State Management
|
|
178
|
+
- Identify which state is per-page (form state, UI state) vs global (auth state, user preferences).
|
|
179
|
+
- Recommend server vs client state strategy.
|
|
180
|
+
- Identify data fetching patterns (on mount, on action, real-time).
|
|
181
|
+
|
|
182
|
+
Respond with structured analysis. Do NOT return JSON.`,nt=f({name:"component-analyzer",description:"Identifies reusable components, shared layouts, and state management patterns from page specifications. Use after page planning.",systemPrompt:$s,tools:{},maxIterations:2});var Qs=`You are a frontend technology advisor. Given project requirements, you recommend the best frontend framework.
|
|
183
|
+
|
|
184
|
+
## Decision Criteria
|
|
185
|
+
|
|
186
|
+
### Choose "react-vite" (Vite + React SPA) when:
|
|
187
|
+
- The app is a single-page application (SPA) behind authentication
|
|
188
|
+
- No SEO requirements (admin dashboards, internal tools, B2B apps)
|
|
189
|
+
- Backend is a separate API (GraphQL or REST) already built
|
|
190
|
+
- Simple routing with client-side navigation
|
|
191
|
+
- Team prefers traditional React patterns (hooks, context)
|
|
192
|
+
|
|
193
|
+
### Choose "nextjs" (Next.js App Router) when:
|
|
194
|
+
- SEO is important (marketing pages, blogs, e-commerce storefronts)
|
|
195
|
+
- Need server-side rendering (SSR) or static site generation (SSG)
|
|
196
|
+
- Want unified frontend + API in one project (server actions, API routes)
|
|
197
|
+
- Need streaming and progressive rendering
|
|
198
|
+
- Complex data fetching with caching requirements
|
|
199
|
+
- Mix of public and authenticated pages
|
|
200
|
+
|
|
201
|
+
## Output Format
|
|
202
|
+
State your recommendation clearly:
|
|
203
|
+
- Framework: react-vite | nextjs
|
|
204
|
+
- Reasoning: 2-3 sentences explaining why
|
|
205
|
+
- Trade-offs: what you would lose with the alternative
|
|
206
|
+
|
|
207
|
+
Respond with structured analysis. Do NOT return JSON.`,Ao=f({name:"framework-selector",description:"Analyzes project requirements and recommends React/Vite SPA or Next.js. Use to determine the frontend framework before delegating to a builder.",systemPrompt:Qs,tools:{},maxIterations:2});var Hs=`You are a web security specialist. You analyze project requirements for security concerns and design security policies.
|
|
208
|
+
|
|
209
|
+
## Authentication Analysis
|
|
210
|
+
- Determine the best auth strategy (JWT, session, OAuth) based on requirements.
|
|
211
|
+
- JWT: token expiry, refresh strategy, cookie vs header, httpOnly/secure/sameSite flags.
|
|
212
|
+
- Session: session store (memory, Redis, DB), cookie config, session expiry.
|
|
213
|
+
- OAuth: which providers, callback flow, token exchange, account linking.
|
|
214
|
+
|
|
215
|
+
## Password Security
|
|
216
|
+
- Hashing algorithm (bcrypt recommended), cost factor (10+ rounds).
|
|
217
|
+
- Password requirements: minimum length, complexity rules.
|
|
218
|
+
- Password reset flow: token generation, expiry, one-time use.
|
|
219
|
+
|
|
220
|
+
## Authorization Analysis
|
|
221
|
+
- Identify role hierarchy (e.g. admin > moderator > user).
|
|
222
|
+
- Map roles to permissions per resource (CRUD matrix).
|
|
223
|
+
- Resource ownership checks (users can only modify their own data).
|
|
224
|
+
|
|
225
|
+
## Threat Analysis
|
|
226
|
+
- Rate limiting: login attempts, API calls, password reset requests.
|
|
227
|
+
- CORS: allowed origins, methods, headers.
|
|
228
|
+
- Input sanitization: XSS prevention, SQL injection prevention.
|
|
229
|
+
- Brute force protection: account lockout, exponential backoff.
|
|
230
|
+
|
|
231
|
+
Respond with structured analysis. Do NOT return JSON.`,at=f({name:"security-analyzer",description:"Analyzes security requirements, threat vectors, and designs security policies. Use to understand auth needs before designing flows.",systemPrompt:Hs,tools:{},maxIterations:2});var Vs=`You are an authentication flow architect. You design detailed, numbered step-by-step auth flows.
|
|
232
|
+
|
|
233
|
+
For each flow (signup, login, logout, password reset, protected route middleware, API auth middleware):
|
|
234
|
+
|
|
235
|
+
## Flow Design Pattern
|
|
236
|
+
1. Number each step sequentially.
|
|
237
|
+
2. Mark each step as "frontend" or "backend".
|
|
238
|
+
3. Describe the action clearly (e.g. "Frontend sends POST to /api/auth/signup with { name, email, password }").
|
|
239
|
+
4. Include implementation details (e.g. "Backend hashes password with bcrypt (10 rounds)").
|
|
240
|
+
|
|
241
|
+
## Signup Flow
|
|
242
|
+
- Frontend: form validation, submit request.
|
|
243
|
+
- Backend: validate input, check existing user, hash password, create user + profile, generate token, set cookie.
|
|
244
|
+
- Frontend: redirect to dashboard.
|
|
245
|
+
|
|
246
|
+
## Login Flow
|
|
247
|
+
- Frontend: form validation, submit credentials.
|
|
248
|
+
- Backend: find user, compare password hash, generate token, set cookie.
|
|
249
|
+
- Frontend: redirect to dashboard.
|
|
250
|
+
|
|
251
|
+
## Password Reset Flow
|
|
252
|
+
- Frontend: request reset (email).
|
|
253
|
+
- Backend: generate reset token, send email.
|
|
254
|
+
- Frontend: enter new password with token.
|
|
255
|
+
- Backend: validate token, hash new password, update user, invalidate token.
|
|
256
|
+
|
|
257
|
+
## Middleware Flows
|
|
258
|
+
- Protected route: check cookie/header, verify token, attach user to request, reject if invalid.
|
|
259
|
+
- API auth: same as above but for API routes, return 401 JSON.
|
|
260
|
+
|
|
261
|
+
Respond with structured numbered flows. Do NOT return JSON.`,Te=f({name:"flow-designer",description:"Designs detailed step-by-step authentication flows (signup, login, logout, password reset, middleware). Use after security analysis.",systemPrompt:Vs,tools:{},maxIterations:2});function vn(e,t,o){let r=[{role:"system",content:t},{role:"user",content:o}];return e.invoke(r,{temperature:.3,maxOutputTokens:8192}).then(n=>n.text?.trim()??"")}function Ws(e){let t=e.indexOf("## Tech Stack");return t<0?{overview:e,techStack:""}:{overview:e.slice(0,t).trim(),techStack:e.slice(t).trim()}}function Xs(e){let t=e.indexOf("## Data Models");return t<0?{featureDecisions:e,dataModels:""}:{featureDecisions:e.slice(0,t).trim(),dataModels:e.slice(t).trim()}}async function Eo(e,t,o,r){r?.debug("Requirements stage started (specialist agents)");let n=t.projectDescription??"";if(!n)return {message:"No project description yet. Complete discovery first.",advance:false,sections:{}};let s=`${W}
|
|
262
|
+
|
|
263
|
+
Output only markdown. Do NOT output JSON.`,a=await vn(o,s,ho(n)),{overview:i,techStack:l}=Ws(a),p=await vn(o,s,yo(n,a)),{featureDecisions:c}=Xs(p);r?.info("Delegating to data-modeler specialist");let g=(await $(ne,`Analyze the data model for this project:
|
|
264
|
+
|
|
265
|
+
${n}
|
|
266
|
+
|
|
267
|
+
Features:
|
|
268
|
+
${c}`,{parentModel:o})).output;r?.info("Delegating to frontend-architect specialist");let h=[a,c,g].join(`
|
|
269
|
+
|
|
270
|
+
---
|
|
271
|
+
|
|
272
|
+
`),J=(await $(xe,`Design the pages and routes for this project:
|
|
273
|
+
|
|
274
|
+
${n}
|
|
275
|
+
|
|
276
|
+
Context:
|
|
277
|
+
${h}`,{parentModel:o})).output;r?.info("Delegating to auth-designer specialist");let L=[h,J].join(`
|
|
278
|
+
|
|
279
|
+
---
|
|
280
|
+
|
|
281
|
+
`),fe=(await $(Te,`Design the authentication flows for this project:
|
|
282
|
+
|
|
283
|
+
${n}
|
|
284
|
+
|
|
285
|
+
Context:
|
|
286
|
+
${L}`,{parentModel:o})).output;return r?.info("Requirements stage complete (specialist agents)"),{message:"Requirements generated via specialist agents (Data Modeler, Frontend Architect, Auth Designer).",advance:true,sections:{overview:i,techStack:l,featureDecisions:c,dataModels:g,pagesAndRoutes:J,authFlow:fe}}}var st=class{stageName="requirements";async process(t,o){return Eo(o.userMessage,t,o.model,o.logger)}canAdvance(t){return t.advance}getNextStageName(){return "design"}};var Ks=`You are an API endpoint analyst. Given a data model and requirements, you derive the complete API surface.
|
|
287
|
+
|
|
288
|
+
## Endpoint Discovery
|
|
289
|
+
- For each entity in the data model, determine CRUD operations: create, read (by ID), list (with filters/pagination), update, delete.
|
|
290
|
+
- From user stories/flows, identify custom operations beyond CRUD (e.g. searchUsers, bulkImport, exportCsv, toggleStatus).
|
|
291
|
+
- Group endpoints by resource name (pluralized entity name).
|
|
292
|
+
|
|
293
|
+
## Route Design
|
|
294
|
+
- Design RESTful routes: POST /resource, GET /resource/:id, GET /resource, PUT /resource/:id, DELETE /resource/:id.
|
|
295
|
+
- For nested resources: GET /users/:userId/orders, POST /users/:userId/orders.
|
|
296
|
+
- For custom operations: POST /resource/:id/actions/activate, GET /resource/search.
|
|
297
|
+
|
|
298
|
+
## Auth Annotations
|
|
299
|
+
- Mark which endpoints require authentication.
|
|
300
|
+
- Mark which endpoints require specific roles (admin, owner).
|
|
301
|
+
- Identify resource-ownership checks (user can only access their own data).
|
|
302
|
+
|
|
303
|
+
Respond with structured analysis using headings and bullet points. Do NOT return JSON.`,Pe=f({name:"endpoint-analyzer",description:"Analyzes data model and requirements to derive API endpoints, routes, and auth annotations. Use before generating the API design.",systemPrompt:Ks,tools:{},maxIterations:2});var Zs=`You are an API contract specialist. Given endpoints and a data model, you design detailed request/response contracts.
|
|
304
|
+
|
|
305
|
+
## Request Design
|
|
306
|
+
- For each endpoint, define: required fields, optional fields, field types, validation rules.
|
|
307
|
+
- Validation rules: required, min/max length, email format, enum values, numeric ranges.
|
|
308
|
+
- For list endpoints: pagination (page, limit, offset), sorting (sortBy, order), filtering (query params).
|
|
309
|
+
|
|
310
|
+
## Response Design
|
|
311
|
+
- Success responses: HTTP status (200, 201, 204), response body shape.
|
|
312
|
+
- For list endpoints: { items: T[], total: number, page: number, limit: number }.
|
|
313
|
+
- For single item: the entity shape with all fields.
|
|
314
|
+
|
|
315
|
+
## Error Responses
|
|
316
|
+
- 400: validation errors with field-level messages.
|
|
317
|
+
- 401: unauthenticated (missing or invalid token).
|
|
318
|
+
- 403: forbidden (insufficient role or not resource owner).
|
|
319
|
+
- 404: resource not found.
|
|
320
|
+
- 409: conflict (duplicate unique field).
|
|
321
|
+
- 500: internal server error.
|
|
322
|
+
|
|
323
|
+
## Naming Conventions
|
|
324
|
+
- Use consistent field naming (camelCase for JSON, snake_case for query params if preferred).
|
|
325
|
+
- Use ISO 8601 for dates in responses.
|
|
326
|
+
|
|
327
|
+
Respond with structured analysis. Do NOT return JSON.`,Re=f({name:"contract-designer",description:"Designs detailed request/response contracts, validation rules, and error responses per API endpoint. Use after endpoint analysis.",systemPrompt:Zs,tools:{},maxIterations:2});function ei(e){let t=[];e.projectDescription&&t.push(e.projectDescription);let o=e.sections;return o.overview&&t.push(o.overview),o.techStack&&t.push(o.techStack),o.featureDecisions&&t.push(o.featureDecisions),o.dataModels&&t.push(o.dataModels),o.pagesAndRoutes&&t.push(o.pagesAndRoutes),o.authFlow&&t.push(o.authFlow),t.join(`
|
|
328
|
+
|
|
329
|
+
---
|
|
330
|
+
|
|
331
|
+
`)}async function Mo(e,t,o,r){r?.debug("Design stage started (specialist agents)");let n=ei(t);if(!n)return {message:"No prior sections. Complete discovery and requirements first.",advance:false,sections:{}};r?.info("Delegating to api-designer endpoint-analyzer specialist");let a=(await $(Pe,`Design the API routes for this project:
|
|
332
|
+
|
|
333
|
+
${n}`,{parentModel:o})).output;r?.info("Delegating to api-designer contract-designer specialist");let i=await $(Re,`Design detailed request/response contracts for these API endpoints:
|
|
334
|
+
|
|
335
|
+
${a}
|
|
336
|
+
|
|
337
|
+
Project context:
|
|
338
|
+
${n}`,{parentModel:o}),l=`${W}
|
|
339
|
+
|
|
340
|
+
Output only markdown. Do NOT output JSON.`,p=await o.invoke([{role:"system",content:l},{role:"user",content:So(n,a+`
|
|
341
|
+
|
|
342
|
+
`+i.output)}],{temperature:.3,maxOutputTokens:8192}).then(c=>c.text?.trim()??"");return r?.info("Design stage complete (specialist agents)"),{message:"Design generated via specialist agents (Endpoint Analyzer, Contract Designer).",advance:true,sections:{apiRoutes:a,implementation:p}}}var it=class{stageName="design";async process(t,o){return Mo(o.userMessage,t,o.model,o.logger)}canAdvance(t){return t.advance}getNextStageName(){return "complete"}};function Oo(e,t){return [`# ${e} Implementation Plan
|
|
343
|
+
`,t.overview,t.techStack,t.featureDecisions,"---",t.dataModels,"---",t.pagesAndRoutes,"---",t.authFlow,"---",t.apiRoutes,"---",t.implementation,"---",t.executionPlan,"---",t.edgeCases,"---",t.testingChecklist].filter(Boolean).join(`
|
|
344
|
+
|
|
345
|
+
`)}var ti=`You are a QA-minded tech lead. You identify edge cases that developers often miss.
|
|
346
|
+
|
|
347
|
+
For each domain area (Authentication, Data, API, Frontend, Integrations):
|
|
348
|
+
|
|
349
|
+
## Edge Case Analysis
|
|
350
|
+
- **Scenario**: Describe the edge case concretely (e.g. "User submits signup form with email that already exists").
|
|
351
|
+
- **Handling**: How to handle it (e.g. "Return 400 with message 'Email already in use'").
|
|
352
|
+
- **Severity**: critical (must handle or app breaks), warning (should handle for good UX), info (nice to have).
|
|
353
|
+
|
|
354
|
+
## Common Areas to Check
|
|
355
|
+
- **Authentication**: duplicate email, invalid credentials, expired token, concurrent sessions, password reset with invalid token.
|
|
356
|
+
- **Data**: empty collections, max field lengths, special characters in input, date timezone issues, null references.
|
|
357
|
+
- **API**: missing required fields, invalid field types, unauthorized access, rate limiting, pagination edge (page 0, negative page).
|
|
358
|
+
- **Frontend**: empty states, loading states, network errors, form resubmission, back button behavior.
|
|
359
|
+
- **Integrations**: external API down, timeout, rate limited, invalid response format.
|
|
360
|
+
|
|
361
|
+
Respond with structured edge cases grouped by area. Do NOT return JSON.`,we=f({name:"edge-case-analyzer",description:"Identifies edge cases per domain area with scenarios, handling strategies, and severity levels. Use for comprehensive edge case analysis.",systemPrompt:ti,tools:{},maxIterations:2});var oi=`You are a testing strategy specialist. You design comprehensive manual testing checklists.
|
|
362
|
+
|
|
363
|
+
## Testing Checklist Design
|
|
364
|
+
Group test items by flow (Authentication, CRUD operations, Edge cases, etc.).
|
|
365
|
+
|
|
366
|
+
For each test item:
|
|
367
|
+
- **Flow name**: which feature flow this tests (e.g. "Authentication Flow", "Workout CRUD Flow").
|
|
368
|
+
- **Test item**: what to verify (e.g. "Sign up with valid credentials creates account").
|
|
369
|
+
- **Expected result**: what should happen (e.g. "User created in DB, JWT cookie set, redirected to /dashboard").
|
|
370
|
+
|
|
371
|
+
## Coverage Areas
|
|
372
|
+
- **Happy paths**: normal user flows work end-to-end.
|
|
373
|
+
- **Validation**: invalid inputs are rejected with clear messages.
|
|
374
|
+
- **Authorization**: users can only access what they should.
|
|
375
|
+
- **Error handling**: errors are caught and displayed properly.
|
|
376
|
+
- **Data integrity**: data is saved correctly, relationships maintained.
|
|
377
|
+
- **UI states**: loading, empty, error, success states display correctly.
|
|
378
|
+
|
|
379
|
+
## Checklist Format
|
|
380
|
+
Present as grouped checklist items using markdown checkboxes:
|
|
381
|
+
### Flow Name
|
|
382
|
+
- [ ] Test item description -> Expected result
|
|
383
|
+
|
|
384
|
+
Respond with structured checklist. Do NOT return JSON.`,ve=f({name:"testing-strategist",description:"Designs comprehensive manual testing checklists grouped by feature flow. Use for testing strategy and QA planning.",systemPrompt:oi,tools:{},maxIterations:2});function ri(e){let t=[];e.projectDescription&&t.push(e.projectDescription);let o=e.sections;return [o.overview,o.techStack,o.featureDecisions,o.dataModels,o.pagesAndRoutes,o.authFlow,o.apiRoutes,o.implementation].forEach(r=>{r&&t.push(r);}),t.join(`
|
|
385
|
+
|
|
386
|
+
---
|
|
387
|
+
|
|
388
|
+
`)}function ni(e){let o=(e.sections.overview??e.projectDescription??"").split(`
|
|
389
|
+
`)[0]?.trim()??"",n=/^#+\s*(.+?)(?:\s+Implementation Plan)?$/i.exec(o);return n?.[1]?n[1].trim():o.length>0&&o.length<80?o.replace(/^#+\s*/,"").trim():"Project Implementation Plan"}async function Co(e,t,o,r){r?.debug("Synthesis stage started (specialist agents)");let n=ri(t);if(!n)return {message:"No prior sections. Complete earlier stages first.",advance:false,sections:{}};let s=`${W}
|
|
390
|
+
|
|
391
|
+
${bo}
|
|
392
|
+
|
|
393
|
+
Output only markdown. Do NOT output JSON.`,a=await o.invoke([{role:"system",content:s},{role:"user",content:xo(n)}],{temperature:.3,maxOutputTokens:8192}).then(u=>u.text?.trim()??"");r?.info("Delegating to execution-planner edge-case-analyzer specialist");let l=(await $(we,`Identify edge cases for this project:
|
|
394
|
+
|
|
395
|
+
${n}`,{parentModel:o})).output;r?.info("Delegating to execution-planner testing-strategist specialist");let c=(await $(ve,`Design the manual testing checklist for this project:
|
|
396
|
+
|
|
397
|
+
${n}`,{parentModel:o})).output,d=ni(t),g={...t.sections,executionPlan:a||null,edgeCases:l||null,testingChecklist:c||null},h=Oo(d,g);return r?.info("Synthesis stage complete (specialist agents)",{projectName:d}),{message:`Plan complete: ${d}. Generated via specialist agents.`,advance:true,sections:{executionPlan:a,edgeCases:l,testingChecklist:c},planMarkdown:h}}var lt=class{stageName="complete";async process(t,o){return Co(o.userMessage,t,o.model,o.logger)}canAdvance(t){return t.advance}getNextStageName(){return null}};var ai={discovery:new ot,requirements:new st,design:new it,complete:new lt};function Do(e){return ai[e]}async function An(e,t,o,r,n){n?.debug("Stage processor invoked",{stage:e});let a=await Do(e).process(o,{userMessage:t,model:r,logger:n}),i=mn(o,a),l={...i,pendingQuestions:a.pendingQuestions??i.pendingQuestions};return n?.debug("Stage result",{stage:e,advance:a.advance,hasPlanMarkdown:!!a.planMarkdown}),{message:a.message,pendingQuestions:a.pendingQuestions??i.pendingQuestions,advance:a.advance,data:l,planMarkdown:a.planMarkdown}}var No=["discovery","requirements","design","complete"];async function Ie(e,t,o){let{logger:r}=o,n=o.model??{provider:"openai",model:"gpt-4o-mini"},s=E(n),a=t??un();a=Ze(a,"user",e),r?.info("Planning chat turn",{stage:a.stage,messageLength:e.length});let i="",l=[],p=null,c=async h=>{let u=await An(h,e,a,s,r);return i=u.message,l=u.pendingQuestions,a=u.data,u.planMarkdown&&(p=u.planMarkdown),{advance:u.advance,planMarkdown:u.planMarkdown}},d=a.stage;r?.info("Stage",{stage:d});let g=await c(d);for(;g.advance&&!p;){let h=No.indexOf(d),u=h>=0&&h<No.length-1?No[h+1]:void 0;if(u===void 0)break;r?.info("Stage transition",{from:d,to:u}),d=u,a=mo(a),a={...a,stage:d},r?.info("Stage",{stage:d}),g=await c(d);}return a=Ze(a,"assistant",i),r?.info("Planning chat turn done",{stage:d,hasPlanMarkdown:!!p}),{message:i,context:a,pendingQuestions:l,planMarkdown:p}}var En=10;async function _o(e){let{input:t,model:o,onStep:r,logger:n}=e;n?.info("Starting planning agent",{maxTurns:En});let s=null,a=await Ie(t,s,{model:o,logger:n});s=a.context;let i=1;for(;!a.planMarkdown&&i<En;){n?.debug("Planning agent turn",{turn:i});let c=`continue - proceed with the project: "${t}". Make reasonable assumptions for any unresolved details and produce the required output format.`;a=await Ie(c,s,{model:o,logger:n}),s=a.context,i++;}let l=a.planMarkdown??a.message,p=s.history.map(c=>({role:c.role,content:c.content}));return n?.info("Planning agent completed",{turns:i,hasPlanMarkdown:!!a.planMarkdown}),{output:l,steps:[],totalUsage:void 0,messages:p}}var Ae=z$1.object({id:z$1.string(),name:z$1.string(),description:z$1.string(),goals:z$1.array(z$1.string())}),ct=z$1.object({actors:z$1.array(Ae),message:z$1.string()});var Ee=z$1.object({id:z$1.string(),actorId:z$1.string(),name:z$1.string(),description:z$1.string(),trigger:z$1.string(),outcome:z$1.string()}),pt=z$1.object({flows:z$1.array(Ee),message:z$1.string()});var Me=z$1.object({id:z$1.string(),flowId:z$1.string(),actor:z$1.string(),action:z$1.string(),benefit:z$1.string(),preconditions:z$1.array(z$1.string()),postconditions:z$1.array(z$1.string()),dataInvolved:z$1.array(z$1.string())}),dt=z$1.object({stories:z$1.array(Me),message:z$1.string()});var Mn=z$1.object({id:z$1.string(),name:z$1.string(),operation:z$1.enum(["create","read","readAll","update","delete"]),description:z$1.string(),inputs:z$1.array(z$1.string()),outputs:z$1.array(z$1.string())}),Oe=z$1.object({id:z$1.string(),name:z$1.string(),description:z$1.string(),entity:z$1.string(),apis:z$1.array(Mn)}),ut=z$1.object({modules:z$1.array(Oe),summary:z$1.object({totalModules:z$1.number(),totalApis:z$1.number()}),message:z$1.string()});var On=z$1.object({name:z$1.string(),type:z$1.string(),required:z$1.boolean(),unique:z$1.boolean(),description:z$1.string(),default:z$1.string().optional()}),Cn=z$1.object({name:z$1.string(),fields:z$1.array(z$1.string()),unique:z$1.boolean()}),Dn=z$1.object({field:z$1.string(),references:z$1.string(),description:z$1.string()}),Nn=z$1.object({name:z$1.string(),description:z$1.string(),fields:z$1.array(On),indexes:z$1.array(Cn),relations:z$1.array(Dn)}),de=z$1.object({type:z$1.enum(["mongodb","postgresql"]),reasoning:z$1.string(),entities:z$1.array(Nn)});var Ce=z$1.object({name:z$1.string(),goal:z$1.string(),features:z$1.array(z$1.string()),domain:z$1.string(),database:z$1.enum(["mongodb","postgresql"]),backendRuntime:z$1.literal("nodejs"),apiStyle:z$1.enum(["rest","graphql"])}),mt=z$1.object({id:z$1.string(),question:z$1.string(),context:z$1.string(),suggestions:z$1.array(z$1.string()),multiSelect:z$1.boolean(),required:z$1.boolean()}),_n=z$1.object({role:z$1.enum(["user","assistant"]),content:z$1.string()});z$1.object({stage:z$1.enum(["discovery","requirements","design","complete"]),projectBrief:Ce.nullable(),actors:z$1.array(Ae),flows:z$1.array(Ee),stories:z$1.array(Me),modules:z$1.array(Oe),database:de.nullable(),history:z$1.array(_n),pendingQuestions:z$1.array(mt)});var kn=z$1.object({totalActors:z$1.number(),totalFlows:z$1.number(),totalStories:z$1.number(),totalModules:z$1.number(),totalEntities:z$1.number(),overview:z$1.string()}),ko=z$1.object({project:Ce,actors:z$1.array(Ae),flows:z$1.array(Ee),stories:z$1.array(Me),modules:z$1.array(Oe),database:de,summary:kn});var ue=`You are a senior fullstack developer helping scope and plan a project. Your role is to understand what the user wants to build and produce a clear, actionable requirement document.
|
|
398
|
+
|
|
399
|
+
You work in stages: discovery (understand the project and tech preferences), requirements (actors, flows, stories, modules), design (database + APIs), and complete (final document).
|
|
400
|
+
|
|
401
|
+
Think about the project the way a developer would: core problem, user interactions, data model, auth, integrations, real-time needs. Do NOT ask generic template questions (e.g. scale, complexity level, "how many users?"). Ask only questions that directly unblock design decisions.
|
|
402
|
+
|
|
403
|
+
Guidelines:
|
|
404
|
+
- For tech choices (API style: REST vs GraphQL; database: MongoDB vs PostgreSQL), offer predefined options and ask what the user is comfortable with.
|
|
405
|
+
- For everything else, ask open-ended, context-specific questions based on what the user described. Leave suggestions empty for those.
|
|
406
|
+
- Never repeat a question already answered in the conversation history.
|
|
407
|
+
- When the user says "continue", "yes", "looks good", or similar, treat it as confirmation and advance.
|
|
408
|
+
- Return valid JSON only when the prompt asks for JSON (no markdown code fences unless specified).
|
|
409
|
+
- Backend is Node.js only; database is MongoDB or PostgreSQL per user preference.`;var Io=`You are in the discovery stage. Parse the user's message (and prior context) into a structured project brief. Ask clarifying questions only when something genuinely blocks design decisions.
|
|
410
|
+
|
|
411
|
+
Determine from the user's words:
|
|
412
|
+
- Project name and goal
|
|
413
|
+
- Key features (array of strings)
|
|
414
|
+
- Domain (e.g. e-commerce, healthcare, saas)
|
|
415
|
+
- API style: "rest" | "graphql" \u2014 infer from context or ask with predefined options
|
|
416
|
+
- Database: "mongodb" | "postgresql" \u2014 ask which they are comfortable with, with predefined options
|
|
417
|
+
- Backend is always "nodejs"
|
|
418
|
+
|
|
419
|
+
Question rules:
|
|
420
|
+
- Tech stack (API style, database): Always provide "suggestions" with predefined options (e.g. ["REST", "GraphQL"], ["MongoDB", "PostgreSQL"]). Frame as "which are you comfortable with?"
|
|
421
|
+
- All other questions: Use "suggestions": []. Ask open-ended, specific to what the user described (e.g. file uploads, real-time features, auth provider, core user action).
|
|
422
|
+
- Never ask: scale, "how many users?", "what's the complexity?", or generic intake-form questions.
|
|
423
|
+
- Before asking, check conversation history \u2014 never repeat something already answered.
|
|
424
|
+
- If the user's message is clear enough (e.g. "Instagram clone with photo sharing, messaging, stories"), infer the obvious and ask only about genuine gaps. If you have enough for the brief, set needsClarification to false and empty questions.`,In=`## Current user message:
|
|
425
|
+
{userMessage}
|
|
426
|
+
|
|
427
|
+
## Prior conversation (if any):
|
|
428
|
+
{history}
|
|
429
|
+
|
|
430
|
+
Analyze the message and prior context. If you have enough to fill the project brief, return it and set needsClarification to false. Otherwise ask 1-3 short, problem-focused questions.
|
|
431
|
+
|
|
432
|
+
Return ONLY valid JSON (no markdown, no explanation) in this shape:
|
|
433
|
+
{
|
|
434
|
+
"needsClarification": boolean,
|
|
435
|
+
"questions": [
|
|
436
|
+
{
|
|
437
|
+
"id": "q1",
|
|
438
|
+
"question": "Question text",
|
|
439
|
+
"context": "Why this helps",
|
|
440
|
+
"suggestions": [],
|
|
441
|
+
"multiSelect": false,
|
|
442
|
+
"required": true
|
|
443
|
+
}
|
|
444
|
+
],
|
|
445
|
+
"conversationalMessage": "Brief friendly message to the user",
|
|
446
|
+
"projectBrief": {
|
|
447
|
+
"name": "string",
|
|
448
|
+
"goal": "string",
|
|
449
|
+
"features": ["string"],
|
|
450
|
+
"domain": "string",
|
|
451
|
+
"database": "mongodb" | "postgresql",
|
|
452
|
+
"backendRuntime": "nodejs",
|
|
453
|
+
"apiStyle": "rest" | "graphql"
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
For tech choices (API style, database), populate "suggestions" with the predefined options. For all other questions, use "suggestions": [].
|
|
458
|
+
If needsClarification is true, projectBrief can have empty/default values. If false, projectBrief must be complete.`;function jo(e,t){return In.replace("{userMessage}",e).replace("{history}",t||"(No prior messages)")}var gt=`## Project:
|
|
459
|
+
- **Name**: {projectName}
|
|
460
|
+
- **Goal**: {projectGoal}
|
|
461
|
+
- **Features**: {projectFeatures}`,jn=`${gt}
|
|
462
|
+
|
|
463
|
+
Identify ALL distinct user types (actors) who will use this system. 2-5 actors. Include unauthenticated and admin roles if applicable.
|
|
464
|
+
|
|
465
|
+
Return ONLY valid JSON:
|
|
466
|
+
{
|
|
467
|
+
"actors": [
|
|
468
|
+
{ "id": "actor-1", "name": "Name", "description": "Who they are", "goals": ["goal1", "goal2"] }
|
|
469
|
+
],
|
|
470
|
+
"message": "Brief explanation"
|
|
471
|
+
}`,qn=`${gt}
|
|
472
|
+
|
|
473
|
+
## Actors (JSON):
|
|
474
|
+
{actors}
|
|
475
|
+
|
|
476
|
+
For EACH actor, identify 2-5 key user journeys (flows). Each flow: id, actorId, name, description, trigger, outcome.
|
|
477
|
+
|
|
478
|
+
Return ONLY valid JSON:
|
|
479
|
+
{
|
|
480
|
+
"flows": [
|
|
481
|
+
{ "id": "flow-1", "actorId": "actor-1", "name": "Flow Name", "description": "...", "trigger": "...", "outcome": "..." }
|
|
482
|
+
],
|
|
483
|
+
"message": "Brief explanation"
|
|
484
|
+
}`,Fn=`${gt}
|
|
485
|
+
|
|
486
|
+
## Actors: {actors}
|
|
487
|
+
|
|
488
|
+
## Flows (JSON):
|
|
489
|
+
{flows}
|
|
490
|
+
|
|
491
|
+
For EACH flow, generate 2-5 user stories. Each story MUST include dataInvolved (entity.field names) for DB design. Include preconditions, postconditions.
|
|
492
|
+
|
|
493
|
+
Return ONLY valid JSON:
|
|
494
|
+
{
|
|
495
|
+
"stories": [
|
|
496
|
+
{ "id": "story-1", "flowId": "flow-1", "actor": "ActorName", "action": "...", "benefit": "...", "preconditions": [], "postconditions": [], "dataInvolved": ["User.email", "Order.total"] }
|
|
497
|
+
],
|
|
498
|
+
"message": "Brief explanation"
|
|
499
|
+
}`,Un=`${gt}
|
|
500
|
+
|
|
501
|
+
## Actors: {actors}
|
|
502
|
+
## Flows: {flows}
|
|
503
|
+
## Stories (JSON):
|
|
504
|
+
{stories}
|
|
505
|
+
|
|
506
|
+
Extract modules (one per major entity). Each module has apis: create, read, readAll, update, delete plus any extra (e.g. searchUsers). CamelCase names. Clear inputs/outputs.
|
|
507
|
+
|
|
508
|
+
Return ONLY valid JSON:
|
|
509
|
+
{
|
|
510
|
+
"modules": [
|
|
511
|
+
{ "id": "module-1", "name": "User", "description": "...", "entity": "User", "apis": [ { "id": "api-1-1", "name": "createUser", "operation": "create", "description": "...", "inputs": [], "outputs": [] } ] }
|
|
512
|
+
],
|
|
513
|
+
"summary": { "totalModules": 0, "totalApis": 0 },
|
|
514
|
+
"message": "Brief explanation"
|
|
515
|
+
}`;function qo(e,t,o){return jn.replace("{projectName}",e).replace("{projectGoal}",t).replace("{projectFeatures}",o)}function Fo(e,t,o,r){return qn.replace("{projectName}",e).replace("{projectGoal}",t).replace("{projectFeatures}",o).replace("{actors}",r)}function Uo(e,t,o,r,n){return Fn.replace("{projectName}",e).replace("{projectGoal}",t).replace("{projectFeatures}",o).replace("{actors}",r).replace("{flows}",n)}function Lo(e,t,o,r,n,s){return Un.replace("{projectName}",e).replace("{projectGoal}",t).replace("{projectFeatures}",o).replace("{actors}",r).replace("{flows}",n).replace("{stories}",s)}var ii=`You are a database architect. The project brief includes a "database" field (mongodb or postgresql)\u2014use that database. Do not choose a different one. Output a single JSON object.
|
|
516
|
+
|
|
517
|
+
## Project brief (includes database: "mongodb" | "postgresql"):
|
|
518
|
+
{projectBrief}
|
|
519
|
+
|
|
520
|
+
## Modules (entities and CRUD):
|
|
521
|
+
{modules}
|
|
522
|
+
|
|
523
|
+
## User stories (data involved):
|
|
524
|
+
{stories}
|
|
525
|
+
|
|
526
|
+
Design the schema for the chosen database. For MongoDB use types like ObjectId, string, number, date, array; for PostgreSQL use varchar(n), text, integer, uuid, timestamp, jsonb, and proper foreign key relations.
|
|
527
|
+
|
|
528
|
+
Return ONLY valid JSON (no markdown) in this exact shape. Set "type" to the database from the project brief.
|
|
529
|
+
{
|
|
530
|
+
"type": "mongodb" | "postgresql",
|
|
531
|
+
"reasoning": "2-4 sentences on how the schema fits the project",
|
|
532
|
+
"entities": [
|
|
533
|
+
{
|
|
534
|
+
"name": "EntityName",
|
|
535
|
+
"description": "Brief description",
|
|
536
|
+
"fields": [
|
|
537
|
+
{ "name": "fieldName", "type": "DB-native type", "required": true, "unique": false, "description": "..." }
|
|
538
|
+
],
|
|
539
|
+
"indexes": [ { "name": "index_name", "fields": ["field1"], "unique": false } ],
|
|
540
|
+
"relations": [ { "field": "refField", "references": "OtherEntity", "description": "..." } ]
|
|
541
|
+
}
|
|
542
|
+
]
|
|
543
|
+
}`;var Go="You output only valid JSON. No markdown, no explanation.";function Bo(e,t,o){return ii.replace("{projectBrief}",e).replace("{modules}",t).replace("{stories}",o)}var Jo="You are in the complete stage. You have the full context: project brief, actors, flows, stories, modules, and database design. Your job is to produce a single final requirement document (JSON) that matches the FinalRequirement schema, with a summary that includes totalActors, totalFlows, totalStories, totalModules, totalEntities, and a short overview paragraph.",Ln=`## Project brief (JSON):
|
|
544
|
+
{projectBrief}
|
|
545
|
+
|
|
546
|
+
## Actors (JSON):
|
|
547
|
+
{actors}
|
|
548
|
+
|
|
549
|
+
## Flows (JSON):
|
|
550
|
+
{flows}
|
|
551
|
+
|
|
552
|
+
## Stories (JSON):
|
|
553
|
+
{stories}
|
|
554
|
+
|
|
555
|
+
## Modules (JSON):
|
|
556
|
+
{modules}
|
|
557
|
+
|
|
558
|
+
## Database design (JSON):
|
|
559
|
+
{database}
|
|
560
|
+
|
|
561
|
+
Compile the above into one FinalRequirement JSON. Include a "summary" object with: totalActors, totalFlows, totalStories, totalModules, totalEntities (from database.entities.length), and "overview" (2-4 sentence paragraph summarizing the project and tech choices).
|
|
562
|
+
|
|
563
|
+
Return ONLY valid JSON in this shape (no markdown, no extra text):
|
|
564
|
+
{
|
|
565
|
+
"project": { ... },
|
|
566
|
+
"actors": [ ... ],
|
|
567
|
+
"flows": [ ... ],
|
|
568
|
+
"stories": [ ... ],
|
|
569
|
+
"modules": [ ... ],
|
|
570
|
+
"database": { ... },
|
|
571
|
+
"summary": {
|
|
572
|
+
"totalActors": 0,
|
|
573
|
+
"totalFlows": 0,
|
|
574
|
+
"totalStories": 0,
|
|
575
|
+
"totalModules": 0,
|
|
576
|
+
"totalEntities": 0,
|
|
577
|
+
"overview": "string"
|
|
578
|
+
}
|
|
579
|
+
}`;function Yo(e,t,o,r,n,s){return Ln.replace("{projectBrief}",e).replace("{actors}",t).replace("{flows}",o).replace("{stories}",r).replace("{modules}",n).replace("{database}",s)}function zo(){return {stage:"discovery",projectBrief:null,actors:[],flows:[],stories:[],modules:[],database:null,history:[],pendingQuestions:[]}}function $o(e,t){let o=t.data;return {...e,...o.stage!==void 0&&{stage:o.stage},...o.projectBrief!==void 0&&{projectBrief:o.projectBrief},...o.actors!==void 0&&{actors:o.actors},...o.flows!==void 0&&{flows:o.flows},...o.stories!==void 0&&{stories:o.stories},...o.modules!==void 0&&{modules:o.modules},...o.database!==void 0&&{database:o.database},...o.pendingQuestions!==void 0&&{pendingQuestions:o.pendingQuestions}}}function je(e,t,o){let r={role:t,content:o};return {...e,history:[...e.history,r]}}function ft(e){let t=["discovery","requirements","design","complete"],o=t.indexOf(e.stage),n=(o>=0&&o<t.length-1?t[o+1]:void 0)??e.stage;return {...e,stage:n}}function Gn(e){return e.map(t=>`${t.name}: ${t.entity} (${t.apis.length} APIs)`).join(`
|
|
580
|
+
`)}function Bn(e){return e.map(t=>`- ${t.actor}: ${t.action}`).join(`
|
|
581
|
+
`)}function H(e){let t=e.trim(),o=/```(?:json)?\s*([\s\S]*?)```/.exec(t);return o?.[1]?o[1].trim():t}function V(e){try{return {success:!0,data:JSON.parse(e)}}catch(t){return {success:false,error:t instanceof Error?t.message:String(t)}}}async function ht(e,t,o,r){r?.debug("Discovery stage started",{historyLength:t.history.length});let n=t.history.map(L=>`${L.role}: ${L.content}`).slice(-10).join(`
|
|
582
|
+
`),s=jo(e,n),i=[{role:"system",content:`${ue}
|
|
583
|
+
|
|
584
|
+
${Io}`},{role:"user",content:s}],l=await o.invoke(i,{temperature:.4,maxOutputTokens:4096}),p=H(l.text),c=V(p);if(!c.success)return r?.warn("Discovery response was not valid JSON",{error:c.error}),{message:"I couldn't parse that. Could you describe your project in a few sentences?",advance:false,data:{}};let d=c.data,g=d.conversationalMessage??l.text?.slice(0,500)??"Thanks for the details.",h=d.needsClarification===true,u=[];if(Array.isArray(d.questions))for(let L of d.questions){let k=mt.safeParse(L);k.success&&u.push(k.data);}let J=null;if(d.projectBrief&&!h){let L=Ce.safeParse(d.projectBrief);L.success&&(J=L.data);}return r?.debug("Discovery stage complete",{advance:!h&&J!==null,hasProjectBrief:!!J,questionsCount:u.length}),{message:g,questions:u.length?u:void 0,advance:!h&&J!==null,data:{...J&&{projectBrief:J},pendingQuestions:u}}}async function Jn(e,t,o){if(e.invokeObject)return (await e.invokeObject(t,ct,{temperature:.4,maxOutputTokens:4096})).data;let r=await e.invoke(t,{temperature:.4,maxOutputTokens:4096}),n=V(H(r.text));if(!n.success)throw new Error(`Actors: ${n.error}`);let s=ct.safeParse(n.data);if(!s.success)throw new Error(`Actors schema: ${s.error.message}`);return s.data}async function Yn(e,t,o,r){if(e.invokeObject)return (await e.invokeObject(t,pt,{temperature:.4,maxOutputTokens:8192})).data;let n=await e.invoke(t,{temperature:.4,maxOutputTokens:8192}),s=V(H(n.text));if(!s.success)throw new Error(`Flows: ${s.error}`);let a=pt.safeParse(s.data);if(!a.success)throw new Error(`Flows schema: ${a.error.message}`);return a.data}async function zn(e,t,o,r,n){if(e.invokeObject)return (await e.invokeObject(t,dt,{temperature:.4,maxOutputTokens:16384})).data;let s=await e.invoke(t,{temperature:.4,maxOutputTokens:16384}),a=V(H(s.text));if(!a.success)throw new Error(`Stories: ${a.error}`);let i=dt.safeParse(a.data);if(!i.success)throw new Error(`Stories schema: ${i.error.message}`);return i.data}async function $n(e,t,o,r,n,s){if(e.invokeObject)return (await e.invokeObject(t,ut,{temperature:.4,maxOutputTokens:16384})).data;let a=await e.invoke(t,{temperature:.4,maxOutputTokens:16384}),i=V(H(a.text));if(!i.success)throw new Error(`Modules: ${i.error}`);let l=ut.safeParse(i.data);if(!l.success)throw new Error(`Modules schema: ${l.error.message}`);return l.data}async function yt(e,t,o,r){r?.debug("Requirements stage started");let n=t.projectBrief;if(!n)return {message:"Project brief is missing. Complete discovery first.",advance:false,data:{}};let s=n.name,a=n.goal,i=n.features.join(". "),l=[{role:"system",content:ue}];try{l.push({role:"user",content:qo(s,a,i)});let c=(await Jn(o,l,r)).actors;r?.debug("Requirements: actors",{count:c.length}),l.push({role:"assistant",content:`[Extracted ${c.length} actors]`}),l.push({role:"user",content:Fo(s,a,i,JSON.stringify(c))});let g=(await Yn(o,l,c,r)).flows;r?.debug("Requirements: flows",{count:g.length}),l.push({role:"assistant",content:`[Generated ${g.length} flows]`}),l.push({role:"user",content:Uo(s,a,i,JSON.stringify(c),JSON.stringify(g))});let u=(await zn(o,l,c,g,r)).stories;r?.debug("Requirements: stories",{count:u.length}),l.push({role:"assistant",content:`[Generated ${u.length} stories]`}),l.push({role:"user",content:Lo(s,a,i,JSON.stringify(c),JSON.stringify(g),JSON.stringify(u))});let L=(await $n(o,l,c,g,u,r)).modules;return r?.debug("Requirements stage complete",{actors:c.length,flows:g.length,stories:u.length,modules:L.length}),{message:`I've identified ${c.length} actors, ${g.length} flows, ${u.length} stories, and ${L.length} modules. Proceeding to technical design.`,advance:!0,data:{actors:c,flows:g,stories:u,modules:L,pendingQuestions:[]}}}catch(p){let c=p instanceof Error?p.message:String(p);return r?.warn("Requirements stage failed",{error:c}),{message:`Requirements step failed: ${c}. Please try again.`,advance:false,data:{}}}}async function St(e,t,o,r){let n=t.projectBrief;if(!n)return {message:"Project brief is missing.",advance:false,data:{}};if(!t.modules.length||!t.stories.length)return {message:"Requirements (modules and stories) are missing. Run requirements stage first.",advance:false,data:{}};r?.info("Design stage: database design",{modules:t.modules.length,stories:t.stories.length});let s=JSON.stringify(n),a=Gn(t.modules),i=Bn(t.stories),l=Bo(s,a,i),p=[{role:"system",content:Go},{role:"user",content:l}],c=await o.invoke(p,{temperature:.3,maxOutputTokens:8192}),d=H(c.text),g=V(d);if(!g.success)return r?.warn("Database design response was not valid JSON",{error:g.error}),{message:"Failed to parse database design response. Please try again.",advance:false,data:{}};let h=de.safeParse(g.data);if(!h.success){let J=h.error;return r?.warn("Database design schema validation failed",{error:z$1.treeifyError(J)}),{message:"Failed to produce database design. Please try again.",advance:false,data:{}}}let u=h.data;return {message:`Database design complete: ${u.type}. API design will be handled by the api-designer module.`,advance:true,data:{database:u,pendingQuestions:[]}}}async function bt(e,t,o,r){r?.debug("Synthesis stage started");let n=t.projectBrief;if(!n||!t.database)return {message:"Missing project brief or database design. Complete earlier stages first.",advance:false,data:{}};let s=Yo(JSON.stringify(n),JSON.stringify(t.actors),JSON.stringify(t.flows),JSON.stringify(t.stories),JSON.stringify(t.modules),JSON.stringify(t.database)),i=[{role:"system",content:`${ue}
|
|
585
|
+
|
|
586
|
+
${Jo}`},{role:"user",content:s}],l=await o.invoke(i,{temperature:.3,maxOutputTokens:16384}),p=H(l.text),c=V(p);if(!c.success)return r?.warn("Synthesis response was not valid JSON",{error:c.error}),{message:"Failed to compile final requirement document. Please try again.",advance:false,data:{}};let d=ko.safeParse(c.data);if(!d.success)return r?.warn("Synthesis: final requirement schema validation failed",{error:d.error.message}),{message:"Final document did not match schema. "+(l.text?.slice(0,300)??""),advance:false,data:{}};let g=d.data;return r?.info("Synthesis stage complete",{overview:g.summary?.overview}),{message:`Requirement document ready. ${g.summary.overview}`,advance:true,data:{finalRequirement:g}}}var xt=class{stageName="discovery";async process(t,o){return ht(o.userMessage,t,o.model,o.logger)}canAdvance(t){return t.advance}getNextStageName(){return "requirements"}};var Tt=class{stageName="requirements";async process(t,o){return yt(o.userMessage,t,o.model,o.logger)}canAdvance(t){return t.advance}getNextStageName(){return "design"}};var Pt=class{stageName="design";async process(t,o){return St(o.userMessage,t,o.model,o.logger)}canAdvance(t){return t.advance}getNextStageName(){return "complete"}};var Rt=class{stageName="complete";async process(t,o){return bt(o.userMessage,t,o.model,o.logger)}canAdvance(t){return t.advance}getNextStageName(){return null}};var ci={discovery:new xt,requirements:new Tt,design:new Pt,complete:new Rt};function Qo(e){return ci[e]}async function Qn(e,t,o,r,n){n?.debug("Stage processor invoked",{stage:e});let a=await Qo(e).process(o,{userMessage:t,model:r,logger:n}),i=$o(o,a),l="finalRequirement"in a.data?a.data.finalRequirement:void 0;n?.debug("Stage result",{stage:e,advance:a.advance,hasFinalRequirement:!!l});let p={...i,pendingQuestions:a.questions??i.pendingQuestions};return {message:a.message,questions:a.questions??i.pendingQuestions,advance:a.advance,data:p,finalRequirement:l}}var Ho=["discovery","requirements","design","complete"];async function wt(e,t,o){let{logger:r}=o,n=o.model??{provider:"openai",model:"gpt-4o-mini"},s=E(n),a=t??zo();a=je(a,"user",e),r?.info("Chat turn",{stage:a.stage,messageLength:e.length});let i="",l=[],p=null,c=async h=>{let u=await Qn(h,e,a,s,r);return i=u.message,l=u.questions,a=u.data,u.finalRequirement&&(p=u.finalRequirement),{advance:u.advance,finalReq:u.finalRequirement}},d=a.stage;r?.info("Stage",{stage:d});let g=await c(d);for(a={...a,pendingQuestions:l};g.advance&&!p;){let h=Ho.indexOf(d),u=h>=0&&h<Ho.length-1?Ho[h+1]:void 0;if(u===void 0)break;r?.info("Stage transition",{from:d,to:u}),d=u,a=ft(a),a={...a,stage:d},r?.info("Stage",{stage:d}),g=await c(d),a={...a,pendingQuestions:l};}return a=je(a,"assistant",i),r?.info("Chat turn done",{stage:d,hasFinalRequirement:!!p}),{message:i,context:a,questions:l,finalRequirement:p}}var Hn=10;async function Vo(e){let{input:t,model:o,onStep:r,logger:n}=e;n?.info("Starting requirement gatherer agent",{maxTurns:Hn});let s=null,a=await wt(t,s,{model:o,logger:n});s=a.context;let i=1;for(;!a.finalRequirement&&i<Hn;)n?.debug("Requirement gatherer turn",{turn:i}),a=await wt("continue",s,{model:o,logger:n}),s=a.context,i++;let l=a.finalRequirement?JSON.stringify(a.finalRequirement,null,2):a.message,p=s.history.map(c=>({role:c.role,content:c.content}));return n?.info("Requirement gatherer agent completed",{turns:i,hasFinalRequirement:!!a.finalRequirement}),{output:l,steps:[],totalUsage:void 0,messages:p}}var Wo=z$1.object({name:z$1.string(),type:z$1.string(),required:z$1.coerce.boolean().default(false),unique:z$1.coerce.boolean().default(false),description:z$1.string().default(""),default:z$1.string().optional()}),Vn=z$1.object({name:z$1.string().default(""),fields:z$1.array(z$1.string()).default([]),unique:z$1.coerce.boolean().default(false)}),di=z$1.string().transform(e=>{let t=e.toLowerCase().replace(/[\s_-]+/g,"");return ["1:1","onetoone"].includes(t)?"1:1":["1:n","1:m","n:1","onetomany","manytoone"].includes(t)?"1:N":["m:n","n:m","manytomany"].includes(t)?"M:N":e}).pipe(z$1.enum(["1:1","1:N","M:N"])),Wn=z$1.object({field:z$1.string(),references:z$1.string(),type:di,description:z$1.string().default("")}),Xo=z$1.object({name:z$1.string(),description:z$1.string().default(""),fields:z$1.union([z$1.array(Wo),z$1.record(z$1.string(),z$1.unknown())]).transform((e,t)=>{if(Array.isArray(e))return e;let o=[];for(let[r,n]of Object.entries(e)){let s=typeof n=="object"&&n!==null?{...n}:{};s.name||(s.name=r);let a=Wo.safeParse(s);if(a.success)o.push(a.data);else for(let i of a.error.issues)t.addIssue({...i,path:[r,...i.path]});}return o}),indexes:z$1.array(Vn).default([]),relations:z$1.array(Wn).default([])}),ui=z$1.string().transform(e=>e.toLowerCase().trim()).pipe(z$1.enum(["mongodb","postgresql"])),K=z$1.object({type:ui,reasoning:z$1.string().default(""),entities:z$1.array(Xo).default([])});var De=z$1.object({fieldName:z$1.string().describe("fieldName must be in camelCase"),fieldType:z$1.string().default("string").transform(e=>{let t=e.toLowerCase().trim();return ["string","text","varchar"].includes(t)?"string":["number","int","integer","float","double","decimal"].includes(t)?"number":["boolean","bool"].includes(t)?"boolean":["types.objectid","objectid","ref","reference"].includes(t)?"Types.ObjectId":["date","datetime","timestamp"].includes(t)?"Date":["object","json","mixed"].includes(t)?"object":["email"].includes(t)?"email":["password","hash"].includes(t)?"password":["enum","select"].includes(t)?"enum":("string")}).pipe(z$1.enum(["string","number","boolean","Types.ObjectId","Date","object","email","password","enum"])),isArray:z$1.coerce.boolean().default(false),isRequired:z$1.coerce.boolean().default(true),isUnique:z$1.coerce.boolean().default(false),values:z$1.array(z$1.string()).default([]).describe("Enum values if fieldType is enum, else empty array"),defaultVal:z$1.union([z$1.string(),z$1.boolean(),z$1.number(),z$1.null()]).optional(),relationTo:z$1.string().optional().describe("Module name for relations"),relationType:z$1.string().transform(e=>{let t=e.toLowerCase().replace(/[\s_]+/g,"-");return ["one-to-one","1:1","1-to-1"].includes(t)?"one-to-one":["many-to-one","n:1","n-to-1","many-to-1","*:1"].includes(t)?"many-to-one":""}).pipe(z$1.enum(["one-to-one","many-to-one",""])).optional(),isPrivate:z$1.coerce.boolean().default(false).describe("True if password field, else false")});var Ne=z$1.object({moduleName:z$1.string().describe("camelCase, single word, never auth/authentication"),isUserModule:z$1.coerce.boolean().default(false),authMethod:z$1.string().transform(e=>{let t=e.toUpperCase().replace(/[\s-]+/g,"_");return ["EMAIL_AND_PASSWORD","EMAIL_PASSWORD","EMAIL"].includes(t)?"EMAIL_AND_PASSWORD":["PHONE_AND_OTP","PHONE_OTP","PHONE","SMS"].includes(t)?"PHONE_AND_OTP":""}).pipe(z$1.enum(["EMAIL_AND_PASSWORD","PHONE_AND_OTP",""])).optional(),emailField:z$1.string().optional(),passwordField:z$1.string().optional(),phoneField:z$1.string().optional(),roleField:z$1.string().optional(),permissions:z$1.record(z$1.string(),z$1.array(z$1.enum(["CREATE","READ","UPDATE","DELETE"]))).optional().describe("Permissions per role"),fields:z$1.union([z$1.array(De),z$1.record(z$1.string(),z$1.unknown())]).transform((e,t)=>{if(Array.isArray(e))return e;let o=[];for(let[r,n]of Object.entries(e)){let s=typeof n=="object"&&n!==null?{...n}:{};s.fieldName||(s.fieldName=r);let a=De.safeParse(s);if(a.success)o.push(a.data);else for(let i of a.error.issues)t.addIssue({...i,path:[r,...i.path]});}return o})});var ae=z$1.object({projectName:z$1.string().default("project").describe("projectName must be in kebab-case"),projectDescription:z$1.string().default(""),modules:z$1.union([z$1.array(Ne),z$1.record(z$1.string(),z$1.unknown())]).transform((e,t)=>{if(Array.isArray(e))return e;let o=[];for(let[r,n]of Object.entries(e)){let s=typeof n=="object"&&n!==null?{...n}:{};s.moduleName||(s.moduleName=r);let a=Ne.safeParse(s);if(a.success)o.push(a.data);else for(let i of a.error.issues)t.addIssue({...i,path:[r,...i.path]});}return o}),author:z$1.string().default("sijeeshmiziha")});var vt=`You are a senior database architect specializing in both MongoDB and PostgreSQL schema design.
|
|
587
|
+
|
|
588
|
+
You analyze requirements and produce enterprise-quality data models with:
|
|
589
|
+
- Properly typed fields (MongoDB: ObjectId, string, number, date, array; PostgreSQL: uuid, varchar, text, integer, timestamp, jsonb)
|
|
590
|
+
- Indexes optimized for query patterns
|
|
591
|
+
- Relationships with correct cardinality (1:1, 1:N, M:N)
|
|
592
|
+
- Validation constraints and default values
|
|
593
|
+
- Security considerations (hashed passwords, encrypted fields)
|
|
594
|
+
|
|
595
|
+
Output only valid JSON unless instructed otherwise.`;var Xn=`## Requirements:
|
|
596
|
+
{requirement}
|
|
597
|
+
|
|
598
|
+
Design the database schema. Determine the best database type (mongodb or postgresql) based on the requirements, or use the one specified.
|
|
599
|
+
|
|
600
|
+
For MongoDB use types: ObjectId, string, number, boolean, date, array, mixed.
|
|
601
|
+
For PostgreSQL use types: uuid, varchar(n), text, integer, bigint, boolean, timestamp, jsonb, and proper foreign key relations.
|
|
602
|
+
|
|
603
|
+
Return ONLY valid JSON:
|
|
604
|
+
{
|
|
605
|
+
"type": "mongodb" | "postgresql",
|
|
606
|
+
"reasoning": "2-4 sentences explaining the choice and design approach",
|
|
607
|
+
"entities": [
|
|
608
|
+
{
|
|
609
|
+
"name": "EntityName",
|
|
610
|
+
"description": "Brief description",
|
|
611
|
+
"fields": [
|
|
612
|
+
{ "name": "fieldName", "type": "DB-native type", "required": true, "unique": false, "description": "..." }
|
|
613
|
+
],
|
|
614
|
+
"indexes": [ { "name": "idx_name", "fields": ["field1"], "unique": false } ],
|
|
615
|
+
"relations": [ { "field": "refField", "references": "OtherEntity", "type": "1:N", "description": "..." } ]
|
|
616
|
+
}
|
|
617
|
+
]
|
|
618
|
+
}`,Kn=`## Current Schema (JSON):
|
|
619
|
+
{existingSchema}
|
|
620
|
+
|
|
621
|
+
## Feedback:
|
|
622
|
+
{feedback}
|
|
623
|
+
|
|
624
|
+
Update the schema based on the feedback. Return the complete updated schema as valid JSON in the same format.`;function Ko(e){return Xn.replace("{requirement}",e)}function Zo(e,t){return Kn.replace("{existingSchema}",e).replace("{feedback}",t)}var Zn=`## Project: {projectName}
|
|
625
|
+
## Goal: {projectGoal}
|
|
626
|
+
## Database: {databaseType}
|
|
627
|
+
|
|
628
|
+
## Context:
|
|
629
|
+
{context}
|
|
630
|
+
|
|
631
|
+
Apply the 5-phase enterprise data modeling process:
|
|
632
|
+
|
|
633
|
+
### Phase 1: Entity Discovery
|
|
634
|
+
- Extract every entity from the context (user types, domain objects, settings, logs).
|
|
635
|
+
- Identify status enums from flow transitions.
|
|
636
|
+
|
|
637
|
+
### Phase 2: Relationship Mapping
|
|
638
|
+
- For each entity pair, determine ownership and cardinality (1:1, 1:N, M:N).
|
|
639
|
+
- Note bidirectional references and join tables (PostgreSQL) or embedded arrays (MongoDB).
|
|
640
|
+
|
|
641
|
+
### Phase 3: Permission Derivation
|
|
642
|
+
- Map actor types to role names.
|
|
643
|
+
- From actions, derive which role can CRUD which entity.
|
|
644
|
+
|
|
645
|
+
### Phase 4: Schema Generation
|
|
646
|
+
- Generate fields with DB-native types, required/unique flags, defaults.
|
|
647
|
+
- Add indexes for common queries (user lookups, date ranges, foreign keys).
|
|
648
|
+
- Include timestamps (createdAt, updatedAt) on all entities.
|
|
649
|
+
|
|
650
|
+
### Phase 5: Validation
|
|
651
|
+
- Verify every entity referenced in relations exists.
|
|
652
|
+
- Verify no orphan fields or missing indexes.
|
|
653
|
+
|
|
654
|
+
Return ONLY valid JSON in the DataModelDesign format.`;function er(e,t,o,r){return Zn.replace("{projectName}",e).replace("{projectGoal}",t).replace("{databaseType}",o).replace("{context}",r)}var At=I("validate_data_model",K,"Validates a data model JSON string against the DataModelDesign schema. Returns valid: true or valid: false with errors.","schema");function yi(e){let t=e.trim(),o=/```(?:json)?\s*([\s\S]*?)```/.exec(t);return o?.[1]?o[1].trim():t}function M(e,t){let o=yi(e),r;try{r=JSON.parse(o);}catch(s){let a=o.length>300?o.slice(0,300)+"...":o;throw new Error(`Failed to parse model response as JSON: ${s instanceof Error?s.message:String(s)}. Preview: ${a}`)}let n=t.safeParse(r);if(!n.success){let s=n.error.issues.slice(0,5).map(a=>` ${a.path.join(".")}: ${a.message}`).join(`
|
|
655
|
+
`);throw new Error(`Model JSON does not match expected schema:
|
|
656
|
+
${s}`)}return n.data}function _e(e,t){try{return JSON.parse(e)}catch(o){let r=e.length>200?e.slice(0,200)+"...":e;throw new Error(`Invalid JSON${t?` for ${t}`:""}: ${o instanceof Error?o.message:String(o)}. Preview: ${r}`)}}function Et(e){return S({name:"design_schema",description:"Generate a database schema (MongoDB or PostgreSQL) from plain text requirements. Returns the full data model as JSON.",input:z$1.object({requirement:z$1.string().describe("Plain text description of the data modeling requirements")}),handler:async({requirement:t})=>{let o=Ko(t),r=[{role:"system",content:"You are a database schema expert. Return only valid JSON."},{role:"user",content:o}],n=await e.invoke(r,{temperature:.3,maxOutputTokens:8192});return M(n.text,K)}})}function Mt(e){return S({name:"design_schema_pro",description:"Generate an enterprise-quality database schema using 5-phase analysis (Entity Discovery, Relationship Mapping, Permission Derivation, Schema Generation, Validation). Use when structured context is available.",input:z$1.object({projectName:z$1.string().describe("Project name"),projectGoal:z$1.string().describe("Project goal / purpose"),databaseType:z$1.enum(["mongodb","postgresql"]).describe("Target database type"),context:z$1.string().describe("Full project context: features, actors, flows, stories")}),handler:async({projectName:t,projectGoal:o,databaseType:r,context:n})=>{let s=er(t,o,r,n),a=[{role:"system",content:"You are a database schema expert. Return only valid JSON."},{role:"user",content:s}],i=await e.invoke(a,{temperature:.2,maxOutputTokens:16384});return M(i.text,K)}})}function Ot(e){return S({name:"refine_schema",description:"Update an existing data model schema based on user feedback. Provide the current schema JSON and feedback describing desired changes.",input:z$1.object({existingSchema:z$1.string().describe("Current data model schema as JSON string"),feedback:z$1.string().describe("Feedback describing desired changes")}),handler:async({existingSchema:t,feedback:o})=>{let r=Zo(t,o),n=[{role:"system",content:"You are a database schema expert. Return only valid JSON."},{role:"user",content:r}],s=await e.invoke(n,{temperature:.3,maxOutputTokens:8192});return M(s.text,K)}})}I("validate_schema",ae,"Validates a MongoDB project schema JSON string against the expected schema. Returns valid: true or valid: false with errors.","schema");z$1.object({projectName:z$1.string(),projectGoal:z$1.string(),projectDescription:z$1.string().optional(),actors:z$1.array(z$1.object({id:z$1.string(),name:z$1.string(),description:z$1.string(),goals:z$1.array(z$1.string())})),flows:z$1.array(z$1.object({id:z$1.string(),actorId:z$1.string(),name:z$1.string(),description:z$1.string(),trigger:z$1.string(),outcome:z$1.string()})),stories:z$1.array(z$1.object({id:z$1.string(),flowId:z$1.string(),actor:z$1.string(),action:z$1.string(),benefit:z$1.string(),preconditions:z$1.array(z$1.string()),postconditions:z$1.array(z$1.string()),dataInvolved:z$1.array(z$1.string())})),technicalRequirements:z$1.object({authentication:z$1.string().transform(e=>{let t=e.toLowerCase().replace(/[\s_-]+/g,"");return ["none","no",""].includes(t)?"none":["email","emailpassword","emailandpassword"].includes(t)?"email":["oauth","oauth2","social"].includes(t)?"oauth":["phone","phoneotp","sms"].includes(t)?"phone":["emailandphone","emailphone","both"].includes(t)?"email_and_phone":"email"}).pipe(z$1.enum(["none","email","oauth","phone","email_and_phone"])),authorization:z$1.coerce.boolean().default(false),roles:z$1.array(z$1.string()).optional(),integrations:z$1.array(z$1.string()).optional(),realtime:z$1.boolean().optional(),fileUpload:z$1.boolean().optional(),search:z$1.boolean().optional()}).optional()});function sr(e){return {validate_data_model:At,design_schema:Et(e),design_schema_pro:Mt(e),refine_schema:Ot(e)}}var Si=`${vt}
|
|
657
|
+
|
|
658
|
+
You are the data modeling orchestrator. When the user asks for a data model:
|
|
659
|
+
|
|
660
|
+
1. **Analyze first**: Use subagent_entity-analyzer to extract entities, fields, and relationships from the requirements.
|
|
661
|
+
2. **Map relationships**: Use subagent_relationship-mapper with the entity analysis to determine cardinality, foreign keys, and indexes.
|
|
662
|
+
3. **Generate schema**: Use design_schema (plain text) or design_schema_pro (when structured context is available) to produce the data model.
|
|
663
|
+
4. **Refine (optional)**: Use subagent_schema-refiner to validate and suggest improvements to the generated schema.
|
|
664
|
+
5. **Validate**: Use validate_data_model to check the final schema JSON before returning.
|
|
665
|
+
|
|
666
|
+
Respond with the final data model schema as JSON.`;async function ir(e){let{input:t,model:o,maxIterations:r=15,onStep:n,logger:s}=e,a=E(o??{provider:"openai",model:"gpt-4o-mini"}),i=sr(a),l=be(),p=q([ne,rt,l],{parentModel:a}),c={...i,...p};return N({model:a,tools:c,systemPrompt:Si,input:t,maxIterations:r,onStep:n,logger:s})}var xi=z$1.union([z$1.enum(["GET","POST","PUT","PATCH","DELETE"]),z$1.string()]).transform(e=>typeof e=="string"?e.toUpperCase():e).pipe(z$1.enum(["GET","POST","PUT","PATCH","DELETE"])),lr=z$1.record(z$1.string(),z$1.unknown()).optional().default({}).transform(e=>Object.fromEntries(Object.entries(e??{}).map(([t,o])=>[t,typeof o=="string"?o:String(o)]))),ia=z$1.array(z$1.unknown()).default([]).transform(e=>e.map(t=>typeof t=="string"?t:JSON.stringify(t))),cr=z$1.object({id:z$1.string(),resource:z$1.string(),method:xi,path:z$1.string(),description:z$1.string(),auth:z$1.coerce.boolean(),roles:z$1.array(z$1.string()).default([]),requestBody:lr,responseBody:lr,queryParams:lr,validation:ia,errorResponses:ia}),pr=z$1.object({name:z$1.string(),type:z$1.enum(["query","mutation","subscription"]),description:z$1.string(),auth:z$1.coerce.boolean(),roles:z$1.array(z$1.string()).default([]),args:z$1.array(z$1.object({name:z$1.string(),type:z$1.string(),required:z$1.coerce.boolean()})),returnType:z$1.string()}),Ti=z$1.unknown().transform(e=>(typeof e=="string"?e.toLowerCase().trim():"rest").includes("graphql")?"graphql":"rest"),ie=z$1.object({style:Ti,baseUrl:z$1.string().default("/api/v1"),endpoints:z$1.array(cr).default([]),graphqlOperations:z$1.array(pr).default([])});var Ct=`You are a senior API architect specializing in REST and GraphQL API design.
|
|
667
|
+
|
|
668
|
+
You analyze data models and requirements to produce enterprise-quality API designs with:
|
|
669
|
+
- RESTful endpoints grouped by resource with proper HTTP methods
|
|
670
|
+
- Request/response contracts with field types and validation rules
|
|
671
|
+
- Error responses with appropriate HTTP status codes (400, 401, 403, 404, 500)
|
|
672
|
+
- Pagination, filtering, and sorting patterns
|
|
673
|
+
- Authentication and authorization annotations per endpoint
|
|
674
|
+
- GraphQL types, queries, mutations, and subscriptions when applicable
|
|
675
|
+
|
|
676
|
+
Output only valid JSON unless instructed otherwise.`;var la=`## Requirements:
|
|
677
|
+
{requirement}
|
|
678
|
+
|
|
679
|
+
Design the API. Determine the best API style (rest or graphql) based on the requirements, or use the one specified.
|
|
680
|
+
|
|
681
|
+
For REST: group endpoints by resource. Each endpoint needs method, path, description, auth flag, roles, requestBody, responseBody, queryParams, validation rules, and error responses.
|
|
682
|
+
For GraphQL: define operations (queries, mutations, subscriptions) with args and return types.
|
|
683
|
+
|
|
684
|
+
Return ONLY valid JSON:
|
|
685
|
+
{
|
|
686
|
+
"style": "rest" | "graphql",
|
|
687
|
+
"baseUrl": "/api/v1",
|
|
688
|
+
"endpoints": [
|
|
689
|
+
{ "id": "ep-1", "resource": "users", "method": "POST", "path": "/api/v1/users", "description": "Create user", "auth": false, "roles": [], "requestBody": {}, "responseBody": {}, "queryParams": {}, "validation": [], "errorResponses": [] }
|
|
690
|
+
],
|
|
691
|
+
"graphqlOperations": []
|
|
692
|
+
}`,ca=`## Project: {projectName}
|
|
693
|
+
## API Style: {apiStyle}
|
|
694
|
+
## Data Model:
|
|
695
|
+
{dataModel}
|
|
696
|
+
## Requirements:
|
|
697
|
+
{context}
|
|
698
|
+
|
|
699
|
+
Design a comprehensive API surface from the data model and requirements. For each entity in the data model, generate CRUD endpoints plus any custom operations implied by the requirements.
|
|
700
|
+
|
|
701
|
+
Include per-endpoint: validation rules (required fields, formats, lengths), error responses (400 validation, 401 unauthenticated, 403 forbidden, 404 not found, 500 server error), and auth/role annotations.
|
|
702
|
+
|
|
703
|
+
Return ONLY valid JSON in the ApiDesign format.`;function dr(e){return la.replace("{requirement}",e)}function ur(e,t,o,r){return ca.replace("{projectName}",e).replace("{apiStyle}",t).replace("{dataModel}",o).replace("{context}",r)}var Dt=I("validate_api",ie,"Validates an API design JSON string against the ApiDesign schema. Returns valid: true or valid: false with errors.","design");function Nt(e){return S({name:"design_api",description:"Generate an API design (REST or GraphQL) from plain text requirements. Returns the full API design as JSON.",input:z$1.object({requirement:z$1.string().describe("Plain text description of the API requirements")}),handler:async({requirement:t})=>{let o=dr(t),r=[{role:"system",content:"You are an API architect. Return only valid JSON."},{role:"user",content:o}],n=await e.invoke(r,{temperature:.3,maxOutputTokens:8192});return M(n.text,ie)}})}function _t(e){return S({name:"design_api_pro",description:"Generate a comprehensive API design from a data model and project context. Produces detailed endpoints with validation, error responses, and auth annotations.",input:z$1.object({projectName:z$1.string().describe("Project name"),apiStyle:z$1.enum(["rest","graphql"]).describe("Target API style"),dataModel:z$1.string().describe("Data model JSON or description"),context:z$1.string().describe("Project context: features, actors, stories")}),handler:async({projectName:t,apiStyle:o,dataModel:r,context:n})=>{let s=ur(t,o,r,n),a=[{role:"system",content:"You are an API architect. Return only valid JSON."},{role:"user",content:s}],i=await e.invoke(a,{temperature:.2,maxOutputTokens:16384});return M(i.text,ie)}})}function mr(e){return {validate_api:Dt,design_api:Nt(e),design_api_pro:_t(e)}}var Pi=`${Ct}
|
|
704
|
+
|
|
705
|
+
You are the API design orchestrator. When the user asks for an API design:
|
|
706
|
+
|
|
707
|
+
1. **Analyze endpoints**: Use subagent_endpoint-analyzer to derive endpoints from the data model and requirements.
|
|
708
|
+
2. **Design contracts**: Use subagent_contract-designer to design request/response contracts, validation rules, and error responses.
|
|
709
|
+
3. **Generate design**: Use design_api (plain text) or design_api_pro (when data model and structured context are available) to produce the API design.
|
|
710
|
+
4. **Validate**: Use validate_api to check the final API design JSON before returning.
|
|
711
|
+
|
|
712
|
+
Respond with the final API design as JSON.`;async function gr(e){let{input:t,model:o,maxIterations:r=15,onStep:n,logger:s}=e,a=E(o??{provider:"openai",model:"gpt-4o-mini"}),i=mr(a),l=q([Pe,Re],{parentModel:a}),p={...i,...l};return N({model:a,tools:p,systemPrompt:Pi,input:t,maxIterations:r,onStep:n,logger:s})}var da=z$1.object({order:z$1.number(),side:z$1.enum(["frontend","backend"]),action:z$1.string(),details:z$1.string()}),ua=z$1.object({name:z$1.string(),description:z$1.string(),steps:z$1.array(da)}),ma=z$1.object({name:z$1.string(),purpose:z$1.string(),behavior:z$1.array(z$1.string())}),ga=z$1.object({name:z$1.string(),description:z$1.string(),permissions:z$1.array(z$1.string())}),fa=z$1.object({area:z$1.string(),rules:z$1.array(z$1.string())}),Ue=z$1.object({strategy:z$1.enum(["jwt","session","oauth"]),flows:z$1.array(ua),middleware:z$1.array(ma),roles:z$1.array(ga),policies:z$1.array(fa)});var fr=`You are a senior security engineer specializing in authentication, authorization, and web security.
|
|
713
|
+
|
|
714
|
+
You design enterprise-quality auth systems with:
|
|
715
|
+
- Step-by-step auth flows (signup, login, logout, password reset) with both frontend and backend steps
|
|
716
|
+
- JWT or session strategy with proper cookie configuration (httpOnly, secure, sameSite, maxAge)
|
|
717
|
+
- Role-based access control (RBAC) with permission matrices
|
|
718
|
+
- Middleware chains for route protection and API authentication
|
|
719
|
+
- Security policies: password hashing (bcrypt), rate limiting, CORS, input sanitization, brute force protection
|
|
720
|
+
- OAuth integration patterns when needed
|
|
721
|
+
|
|
722
|
+
Output only valid JSON unless instructed otherwise.`;var ha=`## Requirements:
|
|
723
|
+
{requirement}
|
|
724
|
+
|
|
725
|
+
Design the authentication and authorization system. Include:
|
|
726
|
+
|
|
727
|
+
1. Strategy: jwt, session, or oauth (choose based on requirements).
|
|
728
|
+
2. Flows: signup, login, logout, password reset (if applicable). Each flow with numbered steps, frontend/backend side, action, and details.
|
|
729
|
+
3. Middleware: route protection middleware, API auth middleware. Each with name, purpose, and behavior list.
|
|
730
|
+
4. Roles: role definitions with name, description, and permissions list.
|
|
731
|
+
5. Policies: security policies grouped by area (passwords, tokens, CORS, rate limiting, etc.).
|
|
732
|
+
|
|
733
|
+
Return ONLY valid JSON:
|
|
734
|
+
{
|
|
735
|
+
"strategy": "jwt" | "session" | "oauth",
|
|
736
|
+
"flows": [{ "name": "signup", "description": "...", "steps": [{ "order": 1, "side": "frontend", "action": "...", "details": "..." }] }],
|
|
737
|
+
"middleware": [{ "name": "authenticateRequest", "purpose": "...", "behavior": ["..."] }],
|
|
738
|
+
"roles": [{ "name": "user", "description": "...", "permissions": ["..."] }],
|
|
739
|
+
"policies": [{ "area": "passwords", "rules": ["..."] }]
|
|
740
|
+
}`;function hr(e){return ha.replace("{requirement}",e)}var kt=I("validate_auth",Ue,"Validates an auth design JSON string against the AuthDesign schema. Returns valid: true or valid: false with errors.","design");function It(e){return S({name:"design_auth",description:"Generate a complete authentication and authorization design from project requirements. Returns auth flows, middleware, roles, and security policies as JSON.",input:z$1.object({requirement:z$1.string().describe("Project context and auth requirements")}),handler:async({requirement:t})=>{let o=hr(t),r=[{role:"system",content:"You are a security engineer. Return only valid JSON."},{role:"user",content:o}],n=await e.invoke(r,{temperature:.3,maxOutputTokens:8192});return M(n.text,Ue)}})}function yr(e){return {validate_auth:kt,design_auth:It(e)}}var Ri=`${fr}
|
|
741
|
+
|
|
742
|
+
You are the auth design orchestrator. When the user asks for an auth design:
|
|
743
|
+
|
|
744
|
+
1. **Analyze security**: Use subagent_security-analyzer to analyze security requirements, determine auth strategy, and identify threat vectors.
|
|
745
|
+
2. **Design flows**: Use subagent_flow-designer to design step-by-step auth flows (signup, login, logout, password reset, middleware).
|
|
746
|
+
3. **Generate design**: Use design_auth to produce the complete auth design with flows, middleware, roles, and security policies.
|
|
747
|
+
4. **Validate**: Use validate_auth to check the final auth design JSON before returning.
|
|
748
|
+
|
|
749
|
+
Respond with the final auth design as JSON.`;async function Sr(e){let{input:t,model:o,maxIterations:r=15,onStep:n,logger:s}=e,a=E(o??{provider:"openai",model:"gpt-4o-mini"}),i=yr(a),l=q([at,Te],{parentModel:a}),p={...i,...l};return N({model:a,tools:p,systemPrompt:Ri,input:t,maxIterations:r,onStep:n,logger:s})}var Sa=e=>z$1.string().transform(t=>t.toLowerCase().trim()).pipe(z$1.enum(e)),ba=z$1.object({name:z$1.string(),purpose:z$1.string(),appliesTo:z$1.string().default("global").transform(e=>{let t=e.toLowerCase().trim();return ["global","all","app","application","every","server"].includes(t)?"global":["route","routes","specific","specific routes","endpoint","endpoints","path"].includes(t)?"route":["resource","entity","module","controller","model"].includes(t)?"resource":"global"}).pipe(z$1.enum(["global","route","resource"])),config:z$1.record(z$1.string(),z$1.unknown()).default({})}),xa=z$1.object({name:z$1.string(),entity:z$1.string(),operations:z$1.array(z$1.string()).default([]),dependencies:z$1.array(z$1.string()).default([])}),wi=z$1.string().transform(e=>e.toUpperCase().trim()).pipe(z$1.enum(["GET","POST","PUT","PATCH","DELETE"])),Ta=z$1.object({resource:z$1.string(),basePath:z$1.string(),endpoints:z$1.array(z$1.object({method:wi,path:z$1.string(),handler:z$1.string(),auth:z$1.coerce.boolean().default(true),roles:z$1.array(z$1.string()).default([])})).default([])}),Le=z$1.object({framework:Sa(["express","apollo","both"]),language:Sa(["typescript","javascript"]).default("typescript"),database:z$1.string().default("mongodb"),services:z$1.array(xa).default([]),middleware:z$1.array(ba).default([]),routes:z$1.array(Ta).default([]),folderStructure:z$1.array(z$1.string()).default([]),envVars:z$1.array(z$1.string()).default([]),notes:z$1.string().default("")});var br=`You are a senior backend architect specializing in Node.js server design.
|
|
750
|
+
|
|
751
|
+
You analyze data models, API designs, and auth requirements to produce enterprise-quality backend architectures with:
|
|
752
|
+
- Framework selection (Express REST, Apollo GraphQL, or both)
|
|
753
|
+
- Service layer design with clear operation contracts per entity
|
|
754
|
+
- Middleware stack (auth, validation, error handling, CORS, rate limiting)
|
|
755
|
+
- Route/resolver organization grouped by resource
|
|
756
|
+
- Folder structure following domain-driven conventions
|
|
757
|
+
- Environment variable inventory
|
|
758
|
+
- Database connection and ORM/ODM strategy
|
|
759
|
+
|
|
760
|
+
When "both" is selected (Express + Apollo), use the Apollo Gateway pattern:
|
|
761
|
+
- Apollo Gateway as the single public entry point for GraphQL queries
|
|
762
|
+
- Subgraphs as internal services composed via IntrospectAndCompose
|
|
763
|
+
- RemoteGraphQLDataSource for header forwarding (auth tokens, service tokens)
|
|
764
|
+
- Express for webhooks, file uploads, and health checks only
|
|
765
|
+
- Gateway has no business logic, all logic lives in subgraphs
|
|
766
|
+
|
|
767
|
+
Output only valid JSON unless instructed otherwise.`;var Pa=`## Requirements:
|
|
768
|
+
{requirement}
|
|
769
|
+
|
|
770
|
+
Design the backend architecture. Include:
|
|
771
|
+
|
|
772
|
+
1. Framework: choose "express" (REST API), "apollo" (GraphQL subgraph), or "both" (Apollo subgraph + Express gateway).
|
|
773
|
+
2. Services: one per entity with CRUD operations and dependencies.
|
|
774
|
+
3. Middleware: auth (JWT/session), validation (Zod/Joi), error handling, CORS, rate limiting.
|
|
775
|
+
4. Routes (if Express): RESTful routes grouped by resource with method, path, handler, auth, and roles.
|
|
776
|
+
5. Folder structure: list of directories and key files.
|
|
777
|
+
6. Env vars: list all required environment variables.
|
|
778
|
+
|
|
779
|
+
Return ONLY valid JSON:
|
|
780
|
+
{
|
|
781
|
+
"framework": "express" | "apollo" | "both",
|
|
782
|
+
"language": "typescript",
|
|
783
|
+
"database": "mongodb",
|
|
784
|
+
"services": [{ "name": "UserService", "entity": "User", "operations": ["create", "findById", "findAll", "update", "delete"], "dependencies": [] }],
|
|
785
|
+
"middleware": [{ "name": "authMiddleware", "purpose": "JWT token verification", "appliesTo": "global", "config": {} }],
|
|
786
|
+
"routes": [{ "resource": "users", "basePath": "/api/users", "endpoints": [{ "method": "GET", "path": "/", "handler": "getAll", "auth": true, "roles": ["admin"] }] }],
|
|
787
|
+
"folderStructure": ["src/", "src/routes/", "src/services/", "src/middleware/", "src/models/", "src/config/"],
|
|
788
|
+
"envVars": ["PORT", "DATABASE_URL", "JWT_SECRET"],
|
|
789
|
+
"notes": ""
|
|
790
|
+
}`;function xr(e){return Pa.replace("{requirement}",e)}var jt=I("validate_backend",Le,"Validates a backend design JSON string against the BackendDesign schema. Returns valid: true or valid: false with errors.","design");function qt(e){return S({name:"design_backend",description:"Generate a complete backend architecture design from requirements. Returns framework, services, middleware, routes, and folder structure as JSON.",input:z$1.object({requirement:z$1.string().describe("Data model, API design, and project requirements")}),handler:async({requirement:t})=>{let o=xr(t),r=[{role:"system",content:"You are a backend architect. Return only valid JSON."},{role:"user",content:o}],n=await e.invoke(r,{temperature:.3,maxOutputTokens:16384});return M(n.text,Le)}})}function Tr(e){return {validate_backend:jt,design_backend:qt(e)}}var vi=`You are a backend service architect. Given a data model and API design, you plan the service layer.
|
|
791
|
+
|
|
792
|
+
## Service Design
|
|
793
|
+
For each entity:
|
|
794
|
+
- Service name (PascalCase + "Service")
|
|
795
|
+
- CRUD operations: create, findById, findAll, update, delete
|
|
796
|
+
- Custom operations from user flows (e.g. searchByName, bulkImport)
|
|
797
|
+
- Dependencies on other services (e.g. OrderService depends on UserService)
|
|
798
|
+
|
|
799
|
+
## Middleware Stack
|
|
800
|
+
- Authentication middleware: JWT verification, session check
|
|
801
|
+
- Authorization middleware: role-based access, resource ownership
|
|
802
|
+
- Validation middleware: request body/params validation
|
|
803
|
+
- Error handling: centralized error handler with typed errors
|
|
804
|
+
- Logging: request/response logging
|
|
805
|
+
- Rate limiting: per-IP or per-user limits
|
|
806
|
+
- CORS: origin whitelist
|
|
807
|
+
|
|
808
|
+
## Folder Structure
|
|
809
|
+
Recommend a clean folder layout:
|
|
810
|
+
- src/services/ (one file per service)
|
|
811
|
+
- src/middleware/ (one file per middleware)
|
|
812
|
+
- src/models/ (one file per entity)
|
|
813
|
+
- src/routes/ or src/modules/ (grouped by resource)
|
|
814
|
+
- src/config/ (env, database, auth config)
|
|
815
|
+
- src/utils/ (shared helpers)
|
|
816
|
+
|
|
817
|
+
Respond with structured analysis. Do NOT return JSON.`,Ft=f({name:"service-planner",description:"Plans service layer, middleware stack, and folder structure for a backend project. Use before generating the backend design.",systemPrompt:vi,tools:{},maxIterations:2});var Ai=`You are a backend technology advisor. Given project requirements, you recommend the best backend framework.
|
|
818
|
+
|
|
819
|
+
## Decision Criteria
|
|
820
|
+
|
|
821
|
+
### Choose "express" (REST API) when:
|
|
822
|
+
- The API is primarily CRUD with RESTful resources
|
|
823
|
+
- The frontend is a traditional SPA (React/Vue) consuming REST
|
|
824
|
+
- Simple request/response patterns without complex data fetching
|
|
825
|
+
- No need for real-time subscriptions
|
|
826
|
+
- Team is more familiar with REST
|
|
827
|
+
|
|
828
|
+
### Choose "apollo" (GraphQL subgraph) when:
|
|
829
|
+
- The frontend needs flexible data fetching (avoid over/under-fetching)
|
|
830
|
+
- Multiple frontends consume the same API (web, mobile, admin)
|
|
831
|
+
- Complex nested data relationships
|
|
832
|
+
- Need for real-time subscriptions
|
|
833
|
+
- Part of a federated GraphQL architecture
|
|
834
|
+
|
|
835
|
+
### Choose "both" when:
|
|
836
|
+
- Apollo subgraph for main data API + Express for webhooks, file uploads, health checks
|
|
837
|
+
- Need both REST endpoints (for external integrations) and GraphQL (for frontend)
|
|
838
|
+
- When "both" is selected, an Apollo Gateway is used to compose subgraphs into a unified API:
|
|
839
|
+
- Gateway is the only public entry point for GraphQL
|
|
840
|
+
- Subgraphs are internal services, not exposed to clients directly
|
|
841
|
+
- Gateway uses IntrospectAndCompose for schema discovery
|
|
842
|
+
- RemoteGraphQLDataSource forwards auth headers to subgraphs
|
|
843
|
+
- Express handles non-GraphQL concerns (webhooks, file uploads)
|
|
844
|
+
|
|
845
|
+
## Output Format
|
|
846
|
+
State your recommendation clearly:
|
|
847
|
+
- Framework: express | apollo | both
|
|
848
|
+
- Reasoning: 2-3 sentences explaining why
|
|
849
|
+
- Trade-offs: what you'd lose with the alternative
|
|
850
|
+
- If "both": describe which concerns go to Express vs Apollo Gateway vs subgraphs
|
|
851
|
+
|
|
852
|
+
Respond with structured analysis. Do NOT return JSON.`,Ut=f({name:"framework-selector",description:"Analyzes project requirements and recommends Express, Apollo, or both. Use to determine the backend framework before designing.",systemPrompt:Ai,tools:{},maxIterations:2});var Ei=`${br}
|
|
853
|
+
|
|
854
|
+
You are the backend architecture orchestrator. When the user provides requirements:
|
|
855
|
+
|
|
856
|
+
1. **Select framework**: Use subagent_framework-selector to analyze requirements and recommend Express, Apollo, or both.
|
|
857
|
+
2. **Plan services**: Use subagent_service-planner to design the service layer, middleware stack, and folder structure.
|
|
858
|
+
3. **Generate design**: Use design_backend to produce the complete backend architecture as JSON.
|
|
859
|
+
4. **Validate**: Use validate_backend to check the final design JSON before returning.
|
|
860
|
+
|
|
861
|
+
After generating the design, note the "framework" field in the result:
|
|
862
|
+
- If "express": the downstream express-builder should be used to scaffold the project.
|
|
863
|
+
- If "apollo": the downstream apollo-builder should be used to scaffold the project.
|
|
864
|
+
- If "both": both builders should be invoked sequentially.
|
|
865
|
+
|
|
866
|
+
Respond with the final backend design as JSON.`;async function Pr(e){let{input:t,model:o,maxIterations:r=15,onStep:n,logger:s}=e,a=E(o??{provider:"openai",model:"gpt-4o-mini"}),i=Tr(a),l=q([Ft,Ut],{parentModel:a}),p={...i,...l};return N({model:a,tools:p,systemPrompt:Ei,input:t,maxIterations:r,onStep:n,logger:s})}var wa=z$1.object({name:z$1.string(),type:z$1.string(),required:z$1.coerce.boolean(),validation:z$1.string()}),va=z$1.object({path:z$1.string(),name:z$1.string(),access:z$1.string().transform(e=>e.toLowerCase().trim()).pipe(z$1.enum(["public","protected"])),purpose:z$1.string(),formFields:z$1.array(wa).default([]),actions:z$1.array(z$1.string()).default([]),emptyState:z$1.string().default(""),errorState:z$1.string().default(""),redirectOnSuccess:z$1.string().default(""),keyUiElements:z$1.array(z$1.string()).default([])}),Aa=z$1.object({name:z$1.string(),type:z$1.string().transform(e=>e.toLowerCase().trim()).pipe(z$1.enum(["layout","shared","form","display","navigation"])),purpose:z$1.string(),props:z$1.array(z$1.string()).default([]),usedIn:z$1.array(z$1.string()).default([])}),Ge=z$1.object({pages:z$1.array(va).default([]),components:z$1.array(Aa).default([]),stateManagement:z$1.string().default(""),routingNotes:z$1.string().default("")});var Rr=`You are a senior frontend architect specializing in page design, routing, and component architecture.
|
|
867
|
+
|
|
868
|
+
You design enterprise-quality frontend architectures targeting a Vite + React 19 + TypeScript stack with:
|
|
869
|
+
- **UI Library**: ShadCN UI (Radix-based components in src/components/ui/)
|
|
870
|
+
- **Styling**: Tailwind CSS v4 with OKLCH color space and dark mode support
|
|
871
|
+
- **Routing**: React Router v7 with private route guards
|
|
872
|
+
- **Forms**: React Hook Form + Zod validation
|
|
873
|
+
- **GraphQL**: Apollo Client with CodeGen-typed hooks
|
|
874
|
+
- **Path Aliases**: @/{appName}/* mapping to ./src/*
|
|
875
|
+
|
|
876
|
+
Architecture outputs:
|
|
877
|
+
- Public and protected pages with detailed route definitions
|
|
878
|
+
- Per-page specifications: purpose, form fields with validation, actions, empty/error states, redirects
|
|
879
|
+
- Component taxonomy: layout (sidebar, navbar), shared (data tables, dialogs), form (inputs, selects), display (cards, badges), navigation (breadcrumbs, tabs)
|
|
880
|
+
- State management strategy (per-page vs global, Apollo cache vs local state)
|
|
881
|
+
|
|
882
|
+
Output only valid JSON unless instructed otherwise.`;var Ea=`## Requirements:
|
|
883
|
+
{requirement}
|
|
884
|
+
|
|
885
|
+
Design the frontend architecture. Include:
|
|
886
|
+
|
|
887
|
+
1. Pages: public and protected pages. For each page: path, name, access level, purpose, form fields (with validation), actions, empty state, error state, redirect on success, key UI elements.
|
|
888
|
+
2. Components: reusable components. For each: name, type (layout/shared/form/display/navigation), purpose, props, and which pages use it.
|
|
889
|
+
3. State management: describe the state strategy (e.g. React Server Components for data, client state for forms).
|
|
890
|
+
4. Routing notes: any special routing behavior (redirects, guards, nested routes).
|
|
891
|
+
|
|
892
|
+
Return ONLY valid JSON:
|
|
893
|
+
{
|
|
894
|
+
"pages": [{ "path": "/login", "name": "Login", "access": "public", "purpose": "...", "formFields": [{ "name": "email", "type": "email", "required": true, "validation": "valid email format" }], "actions": ["Submit login form"], "emptyState": "", "errorState": "Show error message", "redirectOnSuccess": "/dashboard", "keyUiElements": ["Email input", "Password input", "Submit button"] }],
|
|
895
|
+
"components": [{ "name": "Navbar", "type": "navigation", "purpose": "...", "props": ["user"], "usedIn": ["/dashboard", "/profile"] }],
|
|
896
|
+
"stateManagement": "...",
|
|
897
|
+
"routingNotes": "..."
|
|
898
|
+
}`;function wr(e){return Ea.replace("{requirement}",e)}var Lt=I("validate_frontend",Ge,"Validates a frontend design JSON string against the FrontendDesign schema. Returns valid: true or valid: false with errors.","design");function Gt(e){return S({name:"design_frontend",description:"Generate a complete frontend architecture design from project requirements. Returns pages, components, state management, and routing as JSON.",input:z$1.object({requirement:z$1.string().describe("Project context, API surface, and frontend requirements")}),handler:async({requirement:t})=>{let o=wr(t),r=[{role:"system",content:"You are a frontend architect. Return only valid JSON."},{role:"user",content:o}],n=await e.invoke(r,{temperature:.3,maxOutputTokens:16384});return M(n.text,Ge)}})}function vr(e){return {validate_frontend:Lt,design_frontend:Gt(e)}}var Mi=f({name:"react-builder",description:"Generates a Vite + React SPA configuration from a frontend design and GraphQL schema. Use when the framework-selector recommends react-vite.",systemPrompt:"You are a React/Vite frontend builder. Generate a complete frontend config JSON from the requirements.",tools:{},maxIterations:5}),Oi=f({name:"nextjs-builder",description:"Generates a Next.js App Router configuration from a frontend design. Use when the framework-selector recommends nextjs.",systemPrompt:"You are a Next.js App Router builder. Generate a complete Next.js config JSON from the requirements.",tools:{},maxIterations:5}),Ci=`${Rr}
|
|
899
|
+
|
|
900
|
+
You are the frontend architecture routing orchestrator. When the user asks for a frontend design:
|
|
901
|
+
|
|
902
|
+
1. **Select framework**: Use subagent_framework-selector to analyze requirements (SPA vs SSR, SEO needs, API structure) and recommend React/Vite or Next.js.
|
|
903
|
+
2. **Plan pages**: Use subagent_page-planner to design detailed page specifications with routes, forms, actions, and states.
|
|
904
|
+
3. **Analyze components**: Use subagent_component-analyzer to identify reusable components, layouts, and state management patterns.
|
|
905
|
+
4. **Generate design**: Use design_frontend to produce the complete frontend architecture as JSON.
|
|
906
|
+
5. **Validate**: Use validate_frontend to check the final design JSON before returning.
|
|
907
|
+
6. **Delegate to builder**: Based on the framework-selector recommendation:
|
|
908
|
+
- If "react-vite": use subagent_react-builder with the design to generate a Vite + React SPA config.
|
|
909
|
+
- If "nextjs": use subagent_nextjs-builder with the design to generate a Next.js App Router config.
|
|
910
|
+
|
|
911
|
+
Respond with the final frontend design as JSON, including the builder output.`;async function Ar(e){let{input:t,model:o,maxIterations:r=15,onStep:n,logger:s}=e,a=E(o??{provider:"openai",model:"gpt-4o-mini"}),i=vr(a),l=q([xe,nt,Ao,Mi,Oi],{parentModel:a}),p={...i,...l};return N({model:a,tools:p,systemPrompt:Ci,input:t,maxIterations:r,onStep:n,logger:s})}var Di=z$1.string().transform(e=>e.toUpperCase().trim()).pipe(z$1.enum(["GET","POST","PUT","PATCH","DELETE"])),Oa=z$1.object({name:z$1.string(),httpMethod:Di,path:z$1.string(),auth:z$1.coerce.boolean().default(true),roles:z$1.array(z$1.string()).default([]),validation:z$1.string().default(""),description:z$1.string().default("")}),Ca=z$1.object({name:z$1.string(),resource:z$1.string(),basePath:z$1.string(),methods:z$1.array(Oa).default([])}),Da=z$1.object({name:z$1.string(),type:z$1.string(),required:z$1.coerce.boolean().default(false),unique:z$1.coerce.boolean().default(false),ref:z$1.string().optional(),default:z$1.string().optional()}),Na=z$1.object({name:z$1.string(),collection:z$1.string(),fields:z$1.array(Da).default([]),timestamps:z$1.coerce.boolean().default(true),indexes:z$1.array(z$1.string()).default([])}),_a=z$1.object({name:z$1.string(),type:z$1.string().transform(e=>{let t=e.toLowerCase().replace(/[\s_-]+/g,"");return ["auth","authentication","jwt","token"].includes(t)?"auth":["validation","validate","validator","input"].includes(t)?"validation":["errorhandler","error","errorhandling","errors"].includes(t)?"errorHandler":["cors","crossorigin"].includes(t)?"cors":["ratelimit","ratelimiter","ratelimiting","throttle"].includes(t)?"rateLimit":["logging","logger","log","morgan"].includes(t)?"logging":"custom"}).pipe(z$1.enum(["auth","validation","errorHandler","cors","rateLimit","logging","custom"])),config:z$1.record(z$1.string(),z$1.unknown()).default({})}),Be=z$1.object({appName:z$1.string().default("app"),port:z$1.number().default(3e3),database:z$1.string().default("mongodb"),routers:z$1.array(Ca).default([]),models:z$1.array(Na).default([]),middleware:z$1.array(_a).default([]),envVars:z$1.array(z$1.string()).default([])});var Er=`You are an expert Express.js backend architect.
|
|
912
|
+
|
|
913
|
+
You generate production-ready Express application configurations from data models and API designs:
|
|
914
|
+
- Co-located router pattern: each feature lives in src/routers/{name}/ with {name}.controller.ts, {name}.router.ts, and {name}.spec.ts
|
|
915
|
+
- Mongoose/Prisma models with field types, validation, and relationships
|
|
916
|
+
- Middleware stack (auth JWT, validation Zod, error handler, CORS, rate limiting)
|
|
917
|
+
- Route organization with proper HTTP methods and paths
|
|
918
|
+
- Health check endpoint at /health (included by default)
|
|
919
|
+
- Jest tests per router using supertest
|
|
920
|
+
- Environment variable inventory
|
|
921
|
+
|
|
922
|
+
Output only valid JSON unless instructed otherwise.`;var ka=`## Requirements:
|
|
923
|
+
{requirement}
|
|
924
|
+
|
|
925
|
+
Generate an Express.js application configuration. Include:
|
|
926
|
+
|
|
927
|
+
1. Routers: one per resource, co-located with controller and test spec. Each router has RESTful methods (GET, POST, PUT, DELETE).
|
|
928
|
+
2. Health check: a default /health router is always included.
|
|
929
|
+
3. Models: Mongoose models with fields, types, required, unique, refs, defaults, indexes.
|
|
930
|
+
4. Middleware: auth (JWT), validation (Zod), error handler, CORS, rate limiting, logging.
|
|
931
|
+
5. Env vars: PORT, DATABASE_URL, JWT_SECRET, NODE_ENV, etc.
|
|
932
|
+
6. Folder structure: src/routers/{name}/ with {name}.controller.ts, {name}.router.ts, {name}.spec.ts per feature.
|
|
933
|
+
|
|
934
|
+
Return ONLY valid JSON:
|
|
935
|
+
{
|
|
936
|
+
"appName": "my-api",
|
|
937
|
+
"port": 3000,
|
|
938
|
+
"database": "mongodb",
|
|
939
|
+
"routers": [{
|
|
940
|
+
"name": "users",
|
|
941
|
+
"resource": "users",
|
|
942
|
+
"basePath": "/api/users",
|
|
943
|
+
"methods": [{
|
|
944
|
+
"name": "getAll",
|
|
945
|
+
"httpMethod": "GET",
|
|
946
|
+
"path": "/",
|
|
947
|
+
"auth": true,
|
|
948
|
+
"roles": ["admin"],
|
|
949
|
+
"validation": "",
|
|
950
|
+
"description": "Get all users with pagination"
|
|
951
|
+
}]
|
|
952
|
+
}],
|
|
953
|
+
"models": [{
|
|
954
|
+
"name": "User",
|
|
955
|
+
"collection": "users",
|
|
956
|
+
"fields": [{ "name": "email", "type": "String", "required": true, "unique": true }],
|
|
957
|
+
"timestamps": true,
|
|
958
|
+
"indexes": ["email"]
|
|
959
|
+
}],
|
|
960
|
+
"middleware": [{ "name": "authMiddleware", "type": "auth", "config": {} }],
|
|
961
|
+
"envVars": ["PORT", "DATABASE_URL", "JWT_SECRET", "NODE_ENV"]
|
|
962
|
+
}`;function Mr(e){return ka.replace("{requirement}",e)}var Bt=I("validate_express",Be,"Validates an Express config JSON string against the ExpressConfig schema. Returns valid: true or valid: false with errors.","config");function Jt(e){return S({name:"generate_express",description:"Generate a complete Express.js application configuration from data model and API design. Returns routers, models, middleware, and env vars as JSON.",input:z$1.object({requirement:z$1.string().describe("Data model, API design, and project requirements")}),handler:async({requirement:t})=>{let o=Mr(t),r=[{role:"system",content:"You are an Express.js architect. Return only valid JSON."},{role:"user",content:o}],n=await e.invoke(r,{temperature:.3,maxOutputTokens:16384});return M(n.text,Be)}})}function ja(e,t){return oe.compile(e,{noEscape:true})(t)}function qa(e,t=e){let o=[];if(!Z.existsSync(e))return o;let r=Z.readdirSync(e,{withFileTypes:true});for(let n of r){let s=le.join(e,n.name);n.isDirectory()?o.push(...qa(s,t)):n.name.endsWith(".hbs")&&o.push(le.relative(t,s));}return o}function Ni(e){return e.replace(/\.hbs$/,"")}function _i(e,t){for(let o of t)if(new RegExp("^"+o.replace(/\./g,"\\.").replace(/\*\*/g,"<<GLOBSTAR>>").replace(/\*/g,"[^/]*").replace(/<<GLOBSTAR>>/g,".*")+"$").test(e))return true;return false}async function me(e){let{templateDir:t,outputDir:o,context:r,skipPatterns:n=[]}=e,s=qa(t),a=[],i=[];for(let l of s){if(_i(l,n))continue;let p=Ni(l),c=le.join(t,l),d=le.join(o,p);try{let g=Z.readFileSync(c,"utf-8"),h=ja(g,r);Z.mkdirSync(le.dirname(d),{recursive:!0}),Z.writeFileSync(d,h,"utf-8"),a.push(p);}catch(g){i.push({file:l,message:g instanceof Error?g.message:String(g)});}}return {fileCount:a.length,files:a,errors:i}}function Fa(){oe.registerHelper("eq",(e,t)=>e===t),oe.registerHelper("neq",(e,t)=>e!==t),oe.registerHelper("json",e=>JSON.stringify(e,null,2)),oe.registerHelper("uppercase",e=>typeof e=="string"?e.toUpperCase():""),oe.registerHelper("lowercase",e=>typeof e=="string"?e.toLowerCase():""),oe.registerHelper("capitalize",e=>typeof e=="string"?e.charAt(0).toUpperCase()+e.slice(1):""),oe.registerHelper("camelCase",e=>typeof e!="string"?"":e.replace(/[-_\s]+(.)?/g,(t,o)=>o?o.toUpperCase():"").replace(/^(.)/,t=>t.toLowerCase())),oe.registerHelper("pascalCase",e=>typeof e!="string"?"":e.replace(/[-_\s]+(.)?/g,(t,o)=>o?o.toUpperCase():"").replace(/^(.)/,t=>t.toUpperCase()));}Fa();function ki(e){return {appName:e.appName,port:e.port,database:e.database,routers:e.routers,models:e.models,middleware:e.middleware,envVars:e.envVars,modules:e.routers.map(t=>({name:t.resource,pascalName:t.name.charAt(0).toUpperCase()+t.name.slice(1),camelName:t.resource,methods:t.methods}))}}var Yt=S({name:"scaffold_express",description:"Scaffold an Express.js project from a validated config. Compiles Handlebars templates and writes the project to the output directory.",input:z$1.object({config:z$1.string().describe("JSON string of the validated Express config"),outputDir:z$1.string().describe("Absolute path to the output directory")}),handler:async({config:e,outputDir:t})=>{let o=_e(e,"express config"),r=le.resolve(process.cwd(),".ref/templates/express"),n=ki(o);return me({templateDir:r,outputDir:t,context:n})}});function Cr(e){return {validate_express:Bt,generate_express:Jt(e),scaffold_express:Yt}}var Ii=`You are an Express.js route specialist. Given an API design, you generate route definitions using a co-located router pattern.
|
|
963
|
+
|
|
964
|
+
## Co-located Router Pattern
|
|
965
|
+
Each feature lives in src/routers/{name}/ with three files:
|
|
966
|
+
- {name}.router.ts -- Express Router with route definitions
|
|
967
|
+
- {name}.controller.ts -- Request handler logic
|
|
968
|
+
- {name}.spec.ts -- Jest tests using supertest
|
|
969
|
+
|
|
970
|
+
## Route Design
|
|
971
|
+
For each resource:
|
|
972
|
+
- Base path: /api/{resource} (pluralized, lowercase)
|
|
973
|
+
- GET / -> list all (with pagination: page, limit, sort query params)
|
|
974
|
+
- GET /:id -> get by ID
|
|
975
|
+
- POST / -> create new
|
|
976
|
+
- PUT /:id -> update by ID
|
|
977
|
+
- DELETE /:id -> delete by ID
|
|
978
|
+
- Custom routes for non-CRUD operations
|
|
979
|
+
|
|
980
|
+
## Health Check
|
|
981
|
+
Every app includes a /health router in src/routers/health/:
|
|
982
|
+
- health.router.ts -- GET /health returning server status
|
|
983
|
+
- health.controller.ts -- Health check handler
|
|
984
|
+
- health.spec.ts -- Health check tests
|
|
985
|
+
|
|
986
|
+
## Route Organization
|
|
987
|
+
- One router directory per resource with co-located controller and spec
|
|
988
|
+
- Central src/routers/index.ts mounts all routers
|
|
989
|
+
- Middleware applied per-route or per-router
|
|
990
|
+
|
|
991
|
+
## Controller Mapping
|
|
992
|
+
- Each route maps to a controller method in the co-located controller file
|
|
993
|
+
- Controller method name follows convention: getAll, getById, create, update, delete
|
|
994
|
+
|
|
995
|
+
## Validation
|
|
996
|
+
- Request body validation using Zod schemas
|
|
997
|
+
- Param validation (e.g. valid ObjectId)
|
|
998
|
+
- Query param parsing and defaults
|
|
999
|
+
|
|
1000
|
+
Respond with structured route definitions. Do NOT return JSON.`,zt=f({name:"route-generator",description:"Generates Express route definitions from API design using the co-located router pattern ({name}.router.ts, {name}.controller.ts, {name}.spec.ts). Use before generating the Express config.",systemPrompt:Ii,tools:{},maxIterations:2});var ji=`You are an Express.js middleware specialist. You design the complete middleware stack.
|
|
1001
|
+
|
|
1002
|
+
## Core Middleware
|
|
1003
|
+
1. **CORS**: Configure allowed origins, methods, headers, credentials
|
|
1004
|
+
2. **Body parser**: JSON and URL-encoded body parsing with size limits
|
|
1005
|
+
3. **Helmet**: Security headers (CSP, HSTS, X-Frame-Options)
|
|
1006
|
+
4. **Morgan/Logger**: Request logging with format and stream
|
|
1007
|
+
|
|
1008
|
+
## Auth Middleware
|
|
1009
|
+
1. **JWT verification**: Extract token from Authorization header or cookie
|
|
1010
|
+
2. **Role check**: Verify user role against required roles
|
|
1011
|
+
3. **Resource ownership**: Check if user owns the resource they're accessing
|
|
1012
|
+
|
|
1013
|
+
## Validation Middleware
|
|
1014
|
+
1. **Request validation**: Validate body, params, query using Zod schemas
|
|
1015
|
+
2. **Sanitization**: Strip HTML, trim whitespace
|
|
1016
|
+
|
|
1017
|
+
## Error Handling
|
|
1018
|
+
1. **Not found handler**: 404 for unmatched routes
|
|
1019
|
+
2. **Error handler**: Centralized error response with status codes
|
|
1020
|
+
3. **Async wrapper**: Catch async errors without try-catch
|
|
1021
|
+
|
|
1022
|
+
## Rate Limiting
|
|
1023
|
+
1. **Global**: Limit requests per IP per time window
|
|
1024
|
+
2. **Auth routes**: Stricter limits on login/signup
|
|
1025
|
+
|
|
1026
|
+
Respond with structured middleware analysis. Do NOT return JSON.`,$t=f({name:"middleware-configurator",description:"Designs the Express middleware stack including auth, validation, error handling, CORS, and rate limiting. Use before generating the Express config.",systemPrompt:ji,tools:{},maxIterations:2});var qi=`${Er}
|
|
1027
|
+
|
|
1028
|
+
You are the Express builder orchestrator. When the user provides requirements:
|
|
1029
|
+
|
|
1030
|
+
1. **Generate routes**: Use subagent_route-generator to design route definitions from the API design.
|
|
1031
|
+
2. **Configure middleware**: Use subagent_middleware-configurator to design the middleware stack.
|
|
1032
|
+
3. **Generate config**: Use generate_express to produce the complete Express configuration as JSON.
|
|
1033
|
+
4. **Validate**: Use validate_express to check the config JSON before returning.
|
|
1034
|
+
5. **Scaffold (optional)**: If an output directory is provided, use scaffold_express to compile templates.
|
|
1035
|
+
|
|
1036
|
+
Respond with the final Express config as JSON.`;async function Dr(e){let{input:t,model:o,maxIterations:r=15,onStep:n,logger:s}=e,a=E(o??{provider:"openai",model:"gpt-4o-mini"}),i=Cr(a),l=q([zt,$t],{parentModel:a}),p={...i,...l};return N({model:a,tools:p,systemPrompt:qi,input:t,maxIterations:r,onStep:n,logger:s})}var La=e=>z$1.string().transform(t=>t.toLowerCase().trim()).pipe(z$1.enum(e)),Nr=z$1.object({name:z$1.string(),type:z$1.string(),nullable:z$1.coerce.boolean().default(false),isList:z$1.coerce.boolean().default(false),description:z$1.string().default("")}),_r=z$1.object({name:z$1.string(),kind:La(["type","input","enum","interface","union"]),fields:z$1.array(Nr).default([]),values:z$1.array(z$1.string()).default([]),description:z$1.string().default(""),isEntity:z$1.coerce.boolean().default(false),keyFields:z$1.array(z$1.string()).default([])}),Ga=z$1.object({name:z$1.string(),type:La(["query","mutation","subscription"]),args:z$1.array(Nr).default([]),returnType:z$1.string(),auth:z$1.coerce.boolean().default(true),roles:z$1.array(z$1.string()).default([]),description:z$1.string().default("")}),Ba=z$1.object({name:z$1.string(),entity:z$1.string(),types:z$1.array(_r).default([]),operations:z$1.array(Ga).default([]),datasource:z$1.string().default(""),loader:z$1.string().default("")}),Je=z$1.object({appName:z$1.string().default("app"),port:z$1.number().default(4e3),database:z$1.string().default("mongodb"),modules:z$1.array(Ba).default([]),sharedTypes:z$1.array(_r).default([]),authDirective:z$1.coerce.boolean().default(true),cacheDirective:z$1.coerce.boolean().default(false),envVars:z$1.array(z$1.string()).default([])});var kr=`You are an expert Apollo GraphQL subgraph architect using Apollo Federation v2.
|
|
1037
|
+
|
|
1038
|
+
You generate production-ready Apollo subgraph configurations from data models and API designs:
|
|
1039
|
+
- 4-file module pattern per entity: {module}.graphql, {module}.resolver.ts, {module}.datasource.ts, {module}.loader.ts
|
|
1040
|
+
- GraphQL type definitions with proper nullability, lists, and descriptions
|
|
1041
|
+
- Input types for mutations with validation annotations
|
|
1042
|
+
- Enum types from domain values
|
|
1043
|
+
- Federation directives: @key for entity references, @external for fields owned by other subgraphs, @requires for field dependencies, @provides for fields resolvable by this subgraph
|
|
1044
|
+
- __resolveReference for cross-subgraph entity resolution via buildSubgraphSchema
|
|
1045
|
+
- DataLoader per module for batching and caching database lookups (solves N+1)
|
|
1046
|
+
- Query and mutation resolvers with auth/role requirements
|
|
1047
|
+
- Datasource classes per entity (MongoDB datasource pattern)
|
|
1048
|
+
- Auth directive (@auth) configuration
|
|
1049
|
+
- Redis cache directives: @cacheSet on queries, @cachePurge on mutations
|
|
1050
|
+
- GraphQL CodeGen for TypeScript types (generates base-types.ts)
|
|
1051
|
+
- Module-based organization (one module per entity/domain)
|
|
1052
|
+
|
|
1053
|
+
Output only valid JSON unless instructed otherwise.`;var Ja=`## Requirements:
|
|
1054
|
+
{requirement}
|
|
1055
|
+
|
|
1056
|
+
Generate an Apollo GraphQL subgraph configuration (Federation v2). Include:
|
|
1057
|
+
|
|
1058
|
+
1. Modules: one per entity with 4 files each ({module}.graphql, {module}.resolver.ts, {module}.datasource.ts, {module}.loader.ts).
|
|
1059
|
+
2. Types: GraphQL object types with isEntity/keyFields for federation, input types, enums with fields/values.
|
|
1060
|
+
3. Operations: queries (getById, getAll, search) and mutations (create, update, delete) per module.
|
|
1061
|
+
4. Auth: mark which operations require authentication and which roles.
|
|
1062
|
+
5. DataLoader: one loader per module for batching lookups (loader name).
|
|
1063
|
+
6. Shared types: types used across modules (e.g. Pagination, SortOrder).
|
|
1064
|
+
7. Cache: set cacheDirective to true if Redis caching (@cacheSet/@cachePurge) is needed.
|
|
1065
|
+
8. Env vars: PORT, DATABASE_URL, JWT_SECRET, REDIS_URL, etc.
|
|
1066
|
+
|
|
1067
|
+
Return ONLY valid JSON:
|
|
1068
|
+
{
|
|
1069
|
+
"appName": "my-subgraph",
|
|
1070
|
+
"port": 4000,
|
|
1071
|
+
"database": "mongodb",
|
|
1072
|
+
"modules": [{
|
|
1073
|
+
"name": "user",
|
|
1074
|
+
"entity": "User",
|
|
1075
|
+
"types": [{ "name": "User", "kind": "type", "fields": [{ "name": "id", "type": "ID", "nullable": false }], "isEntity": true, "keyFields": ["id"] }],
|
|
1076
|
+
"operations": [{ "name": "getUser", "type": "query", "args": [{ "name": "id", "type": "ID", "nullable": false }], "returnType": "User", "auth": true, "roles": [] }],
|
|
1077
|
+
"datasource": "UserDataSource",
|
|
1078
|
+
"loader": "UserLoader"
|
|
1079
|
+
}],
|
|
1080
|
+
"sharedTypes": [],
|
|
1081
|
+
"authDirective": true,
|
|
1082
|
+
"cacheDirective": false,
|
|
1083
|
+
"envVars": ["PORT", "DATABASE_URL", "JWT_SECRET", "REDIS_URL"]
|
|
1084
|
+
}`;function Ir(e){return Ja.replace("{requirement}",e)}var Qt=I("validate_subgraph",Je,"Validates a subgraph config JSON string against the SubgraphConfig schema. Returns valid: true or valid: false with errors.","config");function Ht(e){return S({name:"generate_subgraph",description:"Generate a complete Apollo GraphQL subgraph configuration from data model and API design. Returns modules, types, operations, and datasources as JSON.",input:z$1.object({requirement:z$1.string().describe("Data model, API design, and project requirements")}),handler:async({requirement:t})=>{let o=Ir(t),r=[{role:"system",content:"You are an Apollo GraphQL architect. Return only valid JSON."},{role:"user",content:o}],n=await e.invoke(r,{temperature:.3,maxOutputTokens:16384});return M(n.text,Je)}})}function Fi(e){return {appName:e.appName,port:e.port,database:e.database,modules:e.modules.map(t=>({name:t.name,pascalName:t.name.charAt(0).toUpperCase()+t.name.slice(1),camelName:t.name.charAt(0).toLowerCase()+t.name.slice(1),entity:t.entity,datasource:t.datasource,types:t.types,operations:t.operations})),authDirective:e.authDirective,envVars:e.envVars,sharedTypes:e.sharedTypes}}var Vt=S({name:"scaffold_subgraph",description:"Scaffold an Apollo GraphQL subgraph project from a validated config. Compiles Handlebars templates and writes the project to the output directory.",input:z$1.object({config:z$1.string().describe("JSON string of the validated subgraph config"),outputDir:z$1.string().describe("Absolute path to the output directory")}),handler:async({config:e,outputDir:t})=>{let o=_e(e,"subgraph config"),r=le.resolve(process.cwd(),".ref/templates/subgraph"),n=Fi(o);return me({templateDir:r,outputDir:t,context:n})}});function qr(e){return {validate_subgraph:Qt,generate_subgraph:Ht(e),scaffold_subgraph:Vt}}var Ui=`You are a GraphQL schema specialist for Apollo Federation v2 subgraphs. Given a data model, you generate GraphQL type definitions using buildSubgraphSchema.
|
|
1085
|
+
|
|
1086
|
+
## Type Generation
|
|
1087
|
+
For each entity in the data model:
|
|
1088
|
+
- Create the main object type with all fields mapped to GraphQL scalars (String, Int, Float, Boolean, ID)
|
|
1089
|
+
- Create input types for create and update mutations (omit auto-generated fields like id, createdAt)
|
|
1090
|
+
- Create enum types for status fields and role fields
|
|
1091
|
+
- Add proper nullability (! for required fields)
|
|
1092
|
+
- Add [Type] for array/list fields
|
|
1093
|
+
|
|
1094
|
+
## Federation Directives
|
|
1095
|
+
- @key(fields: "id") on entity types that can be referenced across subgraphs
|
|
1096
|
+
- @external marks a field as owned by another subgraph
|
|
1097
|
+
- @requires(fields: "weight") declares fields needed from the entity to resolve a field
|
|
1098
|
+
- @provides(fields: "name") declares fields on a return type that this subgraph can resolve
|
|
1099
|
+
- @auth directive on types/fields that require authentication
|
|
1100
|
+
|
|
1101
|
+
## Cache Directives (Redis)
|
|
1102
|
+
- @cacheSet(type: "Entity", identifier: "_id") on query resolvers
|
|
1103
|
+
- @cachePurge(type: "Entity", identifier: "_id") on mutation resolvers
|
|
1104
|
+
|
|
1105
|
+
## Relationships
|
|
1106
|
+
- Reference types for foreign keys (e.g. author: User instead of authorId: ID)
|
|
1107
|
+
- Use [Type] for one-to-many relationships
|
|
1108
|
+
|
|
1109
|
+
## Naming Conventions
|
|
1110
|
+
- Types: PascalCase (User, BlogPost)
|
|
1111
|
+
- Fields: camelCase (firstName, createdAt)
|
|
1112
|
+
- Inputs: PascalCase + Input suffix (CreateUserInput, UpdateUserInput)
|
|
1113
|
+
- Enums: SCREAMING_SNAKE_CASE values (ADMIN, ACTIVE)
|
|
1114
|
+
|
|
1115
|
+
Respond with the full GraphQL SDL. Do NOT return JSON.`,Wt=f({name:"schema-generator",description:"Generates GraphQL type definitions, input types, and enums from a data model. Use before generating the subgraph config.",systemPrompt:Ui,tools:{},maxIterations:2});var Li=`You are a GraphQL resolver architect for Apollo Federation v2 subgraphs. Given types and operations, you plan resolver implementations.
|
|
1116
|
+
|
|
1117
|
+
## 4-File Module Pattern
|
|
1118
|
+
Each module has four files:
|
|
1119
|
+
- {module}.graphql -- Type definitions with federation directives
|
|
1120
|
+
- {module}.resolver.ts -- Query/Mutation/Field resolvers including __resolveReference
|
|
1121
|
+
- {module}.datasource.ts -- Business logic and database access
|
|
1122
|
+
- {module}.loader.ts -- DataLoader for batching and caching lookups
|
|
1123
|
+
|
|
1124
|
+
## Resolver Planning
|
|
1125
|
+
For each module/entity:
|
|
1126
|
+
|
|
1127
|
+
### __resolveReference (Federation)
|
|
1128
|
+
- Every entity type with @key must implement __resolveReference
|
|
1129
|
+
- Called by the gateway when another subgraph references this entity
|
|
1130
|
+
- Receives { __typename, id } and returns the full entity from datasource
|
|
1131
|
+
|
|
1132
|
+
### Query Resolvers
|
|
1133
|
+
- getById: fetch single record by ID from datasource
|
|
1134
|
+
- getAll: fetch paginated list with filters and sorting
|
|
1135
|
+
- search: text search across relevant fields
|
|
1136
|
+
|
|
1137
|
+
### Mutation Resolvers
|
|
1138
|
+
- create: validate input, create record, return created entity
|
|
1139
|
+
- update: validate input, find existing, merge changes, return updated entity
|
|
1140
|
+
- delete: find existing, remove, return success status
|
|
1141
|
+
|
|
1142
|
+
### Field Resolvers
|
|
1143
|
+
- For relationship fields: resolve references via DataLoader (NOT direct DB calls)
|
|
1144
|
+
- For computed fields: calculate from existing data
|
|
1145
|
+
|
|
1146
|
+
## DataLoader Pattern
|
|
1147
|
+
Each module has a loader file that creates DataLoader instances:
|
|
1148
|
+
- Batches multiple lookups into a single database query
|
|
1149
|
+
- Caches results within a single request to solve the N+1 problem
|
|
1150
|
+
- Created per-request in the context, not shared across requests
|
|
1151
|
+
|
|
1152
|
+
## Datasource Pattern
|
|
1153
|
+
- Each module has a datasource class extending MongoDataSource or similar
|
|
1154
|
+
- Datasource handles all database operations
|
|
1155
|
+
- Resolvers call datasource methods, never touch the DB directly
|
|
1156
|
+
|
|
1157
|
+
## Auth Integration
|
|
1158
|
+
- Check auth context in resolver before executing
|
|
1159
|
+
- Verify role permissions per operation
|
|
1160
|
+
- Resource ownership checks for user-specific data
|
|
1161
|
+
|
|
1162
|
+
Respond with structured analysis per module. Do NOT return JSON.`,Xt=f({name:"resolver-planner",description:"Plans resolver implementations, datasource methods, and auth integration per GraphQL module. Use after schema generation.",systemPrompt:Li,tools:{},maxIterations:2});var Gi=`${kr}
|
|
1163
|
+
|
|
1164
|
+
You are the Apollo subgraph builder orchestrator. When the user provides requirements:
|
|
1165
|
+
|
|
1166
|
+
1. **Generate schema**: Use subagent_schema-generator to create GraphQL type definitions from the data model.
|
|
1167
|
+
2. **Plan resolvers**: Use subagent_resolver-planner to design resolver implementations per module.
|
|
1168
|
+
3. **Generate config**: Use generate_subgraph to produce the complete subgraph configuration as JSON.
|
|
1169
|
+
4. **Validate**: Use validate_subgraph to check the config JSON before returning.
|
|
1170
|
+
5. **Scaffold (optional)**: If an output directory is provided, use scaffold_subgraph to compile templates.
|
|
1171
|
+
|
|
1172
|
+
Respond with the final subgraph config as JSON.`;async function Fr(e){let{input:t,model:o,maxIterations:r=15,onStep:n,logger:s}=e,a=E(o??{provider:"openai",model:"gpt-4o-mini"}),i=qr(a),l=q([Wt,Xt],{parentModel:a}),p={...i,...l};return N({model:a,tools:p,systemPrompt:Gi,input:t,maxIterations:r,onStep:n,logger:s})}var Ur=z$1.object({brandName:z$1.string().describe("The brand's display name"),primaryColor:z$1.string().describe("The brand's primary color code (e.g., #FFFFFF)"),secondaryColor:z$1.string().describe("The brand's secondary color code (e.g., #000000)"),logo:z$1.url().describe("URL pointing to the brand's logo")});var Lr=z$1.object({name:z$1.string().describe("Application name"),description:z$1.string().describe("Brief description of the application"),author:z$1.string().describe("Author or owner of the application").default("sijeeshmiziha (HubSpire)"),branding:Ur.describe("Branding information for the application"),apiEndpoint:z$1.url().describe("URL endpoint for the app's API calls")});var $a=z$1.object({minLength:z$1.number().optional().describe("Minimum length requirement"),zodString:z$1.string().describe("Raw Zod string validation (e.g. regex)")}),Qa=z$1.object({hookName:z$1.string().optional().describe("Name of the hook for dynamic field options"),queryString:z$1.string().optional().describe("Optional query string for fetching field options"),labelKey:z$1.string().optional().describe("Key used as label when displaying options"),valueKey:z$1.string().optional().describe("Key used as value for a field when selecting options"),values:z$1.array(z$1.string()).optional().describe("Static list of possible field values")}),Kt=z$1.object({name:z$1.string().describe("The field's key or identifier"),type:z$1.enum(["text","email","password","number","multiSelect","textarea","hidden","select","date","image"]).describe('Type of input field. If it has options, it should not be "hidden". If the field is required, it should not be hidden unless it serves as the current user.'),required:z$1.boolean().optional().describe("Whether this field must be filled"),validation:$a.optional().describe("Optional field validation requirements"),defaultValue:z$1.union([z$1.string(),z$1.number(),z$1.boolean()]).optional().describe("Default value can be string, number, or boolean"),options:Qa.optional().describe("Additional dynamic or static options for this field")}),Gr=z$1.object({field:z$1.string().describe("Key or name of the data field in the table"),label:z$1.string().describe("User-friendly label to show on the table header")});var Jr=z$1.object({type:z$1.string().describe("Indicates the response type (e.g., 'object')"),properties:z$1.record(z$1.string(),z$1.object({type:z$1.string().describe("Property type as returned by the API")})).describe("Key-value record describing each field in the response")}).optional().describe("Describes the expected structure of an API response"),Ha=z$1.object({type:z$1.enum(["list","create","update","delete","getById"]).describe("Type of API call for CRUD operations"),graphqlHook:z$1.string().describe("Name of the GraphQL hook (e.g. useGetAllUserQuery, useCreateUserMutation)"),queryString:z$1.string().describe("Actual GraphQL query string"),responseType:Jr.describe("Optional schema describing shape of the API response")}),Va=z$1.object({type:z$1.enum(["login","currentUser","forgotPassword","resetPassword"]).describe("Type of API call"),graphqlHook:z$1.string().describe("Name of the GraphQL hook (e.g. useLoginMutation)"),queryString:z$1.string().describe("Actual GraphQL query string"),responseType:Jr.describe("Optional schema describing shape of the API response")}),Br=z$1.object({title:z$1.string().describe("Title displayed on the drawer"),graphqlHook:z$1.string().describe("Name of the GraphQL hook (e.g. useCreateUserMutation, useDeleteOneUserMutation)"),fields:z$1.array(Kt).describe("List of fields displayed within the drawer")}),Wa=z$1.object({name:z$1.enum(["LoginPage","ForgotPasswordPage","ResetPasswordPage"]).describe("Internal name of the auth page"),type:z$1.enum(["EmailPassword","ForgotPassword","ResetPassword"]).describe("Type of authentication page"),route:z$1.string().describe("URL route for this page (e.g., '/login')"),isPrivate:z$1.boolean().describe("Whether this page requires an authenticated session"),api:z$1.array(Va).describe("List of API calls involved in this page"),fields:z$1.array(Kt).optional().describe("Optional form fields needed on this auth page")}),Xa=z$1.object({type:z$1.literal("Listing").describe("Indicates that this page is a listing-type page"),name:z$1.string().describe("Internal name of the listing page"),route:z$1.string().describe("URL route for this listing page"),isPrivate:z$1.boolean().describe("Whether this page is private (requires auth)"),api:z$1.array(Ha).describe("List of API calls that power this listing page"),columns:z$1.array(Gr).describe("Table columns displayed on the listing page"),actions:z$1.array(z$1.string()).describe("List of possible actions on each row (e.g., create, edit, delete, view)"),drawerCreate:Br.describe("Drawer configuration for creating new records"),drawerUpdate:Br.describe("Drawer configuration for editing existing records")}),Yr=z$1.discriminatedUnion("type",[Wa,Xa]);var Ka=z$1.object({name:z$1.string().describe("Name of the module"),pages:z$1.array(Yr).describe("Pages included within this module")}),Qe=z$1.object({app:Lr.describe("Overall application configuration"),modules:z$1.array(Ka).describe("List of modules that make up the application. Ensure all modules use every available CRUD GraphQL query and mutation from the schema.")});z$1.object({email:z$1.email().describe("User's email address, must be valid format"),password:z$1.string().min(8).describe("User's password, minimum length of 8")});var Za=z$1.object({_id:z$1.string().describe("Unique identifier of the specialization, type: string"),title:z$1.string().describe("Display title for the specialization, type: string")});z$1.object({_id:z$1.string().describe("Unique ID of the user, type: string"),firstName:z$1.string().min(2).max(30).describe("First name, 2-30 characters, type: string"),lastName:z$1.string().min(2).max(30).describe("Last name, 2-30 characters, type: string"),email:z$1.email().describe("Email address in valid format, type: string"),phoneNumber:z$1.string().min(10).describe("User's phone number, at least 10 digits, type: string"),profileImage:z$1.string().optional().describe("Optional URL to user's profile image, type: string, optional"),role:z$1.enum(["ADMIN","TRAINER","CLIENT"]).describe("User's role in the system (ADMIN, TRAINER, CLIENT)"),rate:z$1.number().min(1).optional().describe("User's rate (e.g., hourly, etc.), type: number, optional"),specializations:z$1.array(Za).optional().describe("Array of specialization objects, optional"),languages:z$1.array(z$1.string()).optional().describe("Array of languages the user speaks, type: string[], optional"),about:z$1.string().min(20).max(500).optional().describe("Brief bio or description (20-500 chars), type: string, optional"),gender:z$1.string().optional().describe("User's gender, type: string, optional"),timezone:z$1.string().optional().describe("User's timezone, type: string, optional"),averageRating:z$1.number().optional().describe("Average rating for this user, type: number, optional")});z$1.object({firstName:z$1.string().min(2).max(30).describe("First name, 2-30 characters, type: string"),lastName:z$1.string().min(2).max(30).describe("Last name, 2-30 characters, type: string"),email:z$1.email().describe("Valid email for the new user, type: string"),phoneNumber:z$1.string().min(10).describe("Phone number (at least 10 digits), type: string"),password:z$1.string().min(8).describe("Password with min length 8, type: string"),role:z$1.enum(["ADMIN","TRAINER","CLIENT"]).describe("Role of the new user (ADMIN, TRAINER, CLIENT)"),rate:z$1.number().min(1).optional().describe("Rate for the new user, type: number, optional"),specializationIds:z$1.array(z$1.string()).min(1).optional().describe("Array of specialization IDs, optional"),languages:z$1.array(z$1.string()).min(1).optional().describe("List of languages user speaks, optional"),about:z$1.string().min(20).max(500).optional().describe("User's about/bio field, 20-500 chars, optional")});z$1.object({_id:z$1.string().describe("ID of the user to be updated, type: string"),firstName:z$1.string().min(2).max(30).optional().describe("Updated first name, type: string, optional"),lastName:z$1.string().min(2).max(30).optional().describe("Updated last name, type: string, optional"),email:z$1.email().optional().describe("Updated email, type: string, optional"),phoneNumber:z$1.string().min(10).optional().describe("Updated phone number, at least 10 digits, optional"),rate:z$1.number().min(1).optional().describe("Updated rate, type: number, optional"),specializationIds:z$1.array(z$1.string()).min(1).optional().describe("Updated array of specialization IDs, optional"),languages:z$1.array(z$1.string()).min(1).optional().describe("Updated list of languages, optional"),about:z$1.string().min(20).max(500).optional().describe("Updated about/bio (20-500 chars), optional")});z$1.object({email:z$1.email().describe("Email to initiate the password reset process, type: string")});z$1.object({type:z$1.enum(["EMAIL","SMS"]).describe("How the reset code was sent (EMAIL or SMS)"),resetTicket:z$1.string().describe("Token/ticket to validate the reset request, type: string"),newPassword:z$1.string().min(8).describe("The new password, min length 8, type: string")});var He=`You are an expert GraphQL-to-frontend configuration converter. Transform the provided GraphQL schema into a structured JSON configuration for a React + Vite frontend application.
|
|
1173
|
+
|
|
1174
|
+
## Target Tech Stack
|
|
1175
|
+
The generated configuration will be consumed by a Vite + React 19 + TypeScript template with:
|
|
1176
|
+
- **UI Components**: ShadCN UI (Radix-based) from src/components/ui/
|
|
1177
|
+
- **Styling**: Tailwind CSS v4 with OKLCH color space
|
|
1178
|
+
- **Routing**: React Router v7 with private route support
|
|
1179
|
+
- **Forms**: React Hook Form + Zod validation (zodResolver)
|
|
1180
|
+
- **GraphQL Client**: Apollo Client with typed hooks from CodeGen
|
|
1181
|
+
- **Path Aliases**: @/{appName}/* maps to ./src/*
|
|
1182
|
+
|
|
1183
|
+
**Your output must be valid JSON only.** No markdown code fences, no explanations. Return the raw JSON object matching the application schema (app with name, description, author, branding, apiEndpoint; modules array with name and pages; each page has type, name, route, isPrivate, api, and for listing pages: columns, actions, drawerCreate, drawerUpdate; for auth pages: fields when needed).
|
|
1184
|
+
|
|
1185
|
+
Strict guidelines:
|
|
1186
|
+
- Use every available CRUD GraphQL query and mutation from the project schema.
|
|
1187
|
+
- Map GraphQL types to frontend modules and pages.
|
|
1188
|
+
- EmailAddress \u2192 "type": "email" with validation; DateTime \u2192 "type": "date"; enums \u2192 select with options.values.
|
|
1189
|
+
- Relationships \u2192 multiSelect with query-based options where appropriate.
|
|
1190
|
+
- Add isPrivate: true for authenticated operations (route guarded by React Router).
|
|
1191
|
+
- Form fields should map to React Hook Form + Zod validation schemas.
|
|
1192
|
+
- Maintain camelCase. Ensure valid JSON syntax.`;var Zt=`
|
|
1193
|
+
Act as an expert GraphQL-to-frontend configuration converter. Transform the provided schema into a structured JSON configuration for rapid app development.
|
|
1194
|
+
|
|
1195
|
+
**Conversion Process**
|
|
1196
|
+
|
|
1197
|
+
1. Schema Analysis:
|
|
1198
|
+
- Identify all modules using 100% of available CRUD operations
|
|
1199
|
+
- Catalog all Query/Mutation operations with arguments
|
|
1200
|
+
- Map GraphQL types to frontend modules
|
|
1201
|
+
- Detect @auth directives and role requirements
|
|
1202
|
+
- Analyze relationships through nested types
|
|
1203
|
+
|
|
1204
|
+
2. Field Mapping:
|
|
1205
|
+
- EmailAddress \u2192 "type": "email" with Zod email validation
|
|
1206
|
+
- DateTime \u2192 "type": "date"
|
|
1207
|
+
- Enums \u2192 dropdowns with options.values
|
|
1208
|
+
- Relationships \u2192 multiSelect with query-based options
|
|
1209
|
+
|
|
1210
|
+
3. API Operations:
|
|
1211
|
+
- For each Query/Mutation: determine CRUD type, generate query string with variables, map to React Hook, define response type shape
|
|
1212
|
+
|
|
1213
|
+
4. Validation:
|
|
1214
|
+
- Generate Zod schemas from @required directives, scalar types (Password \u2192 min 8 chars), custom directives
|
|
1215
|
+
- Include validation error messages
|
|
1216
|
+
|
|
1217
|
+
5. Security:
|
|
1218
|
+
- Add isPrivate: true for authenticated operations
|
|
1219
|
+
- Implement role checks from @auth directives
|
|
1220
|
+
|
|
1221
|
+
6. Output:
|
|
1222
|
+
- Generate complete CRUD pages with table column mappings, validated Create/Update forms, API hooks
|
|
1223
|
+
- Include Zod validation strings, maintain camelCase, valid JSON only
|
|
1224
|
+
`.trim();function zr(){return Zt}var es=`
|
|
1225
|
+
type Query {
|
|
1226
|
+
getCurrentUser: User
|
|
1227
|
+
getAllUser(limit: Int, offset: Int): [User]!
|
|
1228
|
+
}
|
|
1229
|
+
type Mutation {
|
|
1230
|
+
login(data: LoginInput!): Login!
|
|
1231
|
+
createUser(data: CreateUserInput!): User!
|
|
1232
|
+
}
|
|
1233
|
+
type User {
|
|
1234
|
+
_id: ID!
|
|
1235
|
+
firstName: String!
|
|
1236
|
+
lastName: String!
|
|
1237
|
+
email: String!
|
|
1238
|
+
role: Role!
|
|
1239
|
+
}
|
|
1240
|
+
enum Role { ADMIN TRAINER CLIENT }
|
|
1241
|
+
input LoginInput { email: String! password: String! }
|
|
1242
|
+
input CreateUserInput { firstName: String! lastName: String! email: String! role: Role! }
|
|
1243
|
+
`.trim(),ts=`{
|
|
1244
|
+
"app": {
|
|
1245
|
+
"name": "my-app",
|
|
1246
|
+
"description": "App description",
|
|
1247
|
+
"author": "Author",
|
|
1248
|
+
"branding": {
|
|
1249
|
+
"brandName": "MyBrand",
|
|
1250
|
+
"primaryColor": "#333",
|
|
1251
|
+
"secondaryColor": "#fff",
|
|
1252
|
+
"logo": "https://example.com/logo.png"
|
|
1253
|
+
},
|
|
1254
|
+
"apiEndpoint": "http://localhost:4000/graphql"
|
|
1255
|
+
},
|
|
1256
|
+
"modules": [
|
|
1257
|
+
{
|
|
1258
|
+
"name": "auth",
|
|
1259
|
+
"pages": [
|
|
1260
|
+
{
|
|
1261
|
+
"name": "LoginPage",
|
|
1262
|
+
"type": "EmailPassword",
|
|
1263
|
+
"route": "/login",
|
|
1264
|
+
"isPrivate": false,
|
|
1265
|
+
"api": [
|
|
1266
|
+
{ "type": "login", "graphqlHook": "useLoginMutation", "queryString": "mutation Login($data: LoginInput!) { login(data: $data) { accessToken } }" }
|
|
1267
|
+
]
|
|
1268
|
+
}
|
|
1269
|
+
]
|
|
1270
|
+
},
|
|
1271
|
+
{
|
|
1272
|
+
"name": "user",
|
|
1273
|
+
"pages": [
|
|
1274
|
+
{
|
|
1275
|
+
"type": "Listing",
|
|
1276
|
+
"name": "UserListPage",
|
|
1277
|
+
"route": "/users",
|
|
1278
|
+
"isPrivate": true,
|
|
1279
|
+
"api": [
|
|
1280
|
+
{ "type": "list", "graphqlHook": "useGetAllUserQuery", "queryString": "query GetAllUser { getAllUser { _id firstName email } }" },
|
|
1281
|
+
{ "type": "create", "graphqlHook": "useCreateUserMutation", "queryString": "mutation CreateUser($data: CreateUserInput!) { createUser(data: $data) { _id } }" }
|
|
1282
|
+
],
|
|
1283
|
+
"columns": [{ "field": "firstName", "label": "First Name" }, { "field": "email", "label": "Email" }],
|
|
1284
|
+
"actions": ["create", "edit", "delete"],
|
|
1285
|
+
"drawerCreate": { "title": "Create User", "graphqlHook": "useCreateUserMutation", "fields": [{ "name": "firstName", "type": "text", "required": true }, { "name": "email", "type": "email", "required": true }] },
|
|
1286
|
+
"drawerUpdate": { "title": "Edit User", "graphqlHook": "useUpdateUserMutation", "fields": [{ "name": "firstName", "type": "text" }, { "name": "email", "type": "email" }] }
|
|
1287
|
+
}
|
|
1288
|
+
]
|
|
1289
|
+
}
|
|
1290
|
+
]
|
|
1291
|
+
}`;function $r(){return `
|
|
1292
|
+
**Reference Conversion Example**
|
|
1293
|
+
|
|
1294
|
+
EXAMPLE GRAPHQL INPUT:
|
|
1295
|
+
\`\`\`graphql
|
|
1296
|
+
${es}
|
|
1297
|
+
\`\`\`
|
|
1298
|
+
|
|
1299
|
+
EXPECTED JSON OUTPUT:
|
|
1300
|
+
\`\`\`json
|
|
1301
|
+
${ts}
|
|
1302
|
+
\`\`\`
|
|
1303
|
+
`.trim()}var ke=I("validate_frontend_config",Qe,"Validates a frontend configuration JSON string against the ApplicationSchema. Returns valid: true or valid: false with errors array.","config");function Hi(e,t){let o=zr(),r=$r(),n=t?`
|
|
1304
|
+
**Project context:**
|
|
1305
|
+
- name: ${t.projectName??"project"}
|
|
1306
|
+
- description: ${t.projectDescription??""}
|
|
1307
|
+
- modules: ${t.modules??""}
|
|
1308
|
+
- apiEndpoint: ${t.apiEndpoint??"http://localhost:4000/graphql"}
|
|
1309
|
+
`:"";return `${o}
|
|
1310
|
+
|
|
1311
|
+
${r}
|
|
1312
|
+
${n}
|
|
1313
|
+
|
|
1314
|
+
**Current Project GraphQL Schema:**
|
|
1315
|
+
\`\`\`graphql
|
|
1316
|
+
${e}
|
|
1317
|
+
\`\`\`
|
|
1318
|
+
|
|
1319
|
+
Generate the Frontend Config JSON. Use every available CRUD GraphQL query and mutation. Return ONLY valid JSON.`}function eo(e){return S({name:"generate_frontend",description:"Convert a GraphQL schema into a frontend configuration JSON (app, modules, pages, fields, API hooks). Optionally provide app info (project name, description, apiEndpoint). Returns the full application config as JSON.",input:z$1.object({graphqlSchema:z$1.string().describe("The GraphQL schema string to convert"),appInfo:z$1.object({projectName:z$1.string().optional(),projectDescription:z$1.string().optional(),modules:z$1.string().optional(),apiEndpoint:z$1.string().optional()}).optional().describe("Optional project/app context")}),handler:async({graphqlSchema:t,appInfo:o})=>{let r=Hi(t,o),n=[{role:"system",content:He},{role:"user",content:r}],s=await e.invoke(n,{temperature:.2,maxOutputTokens:16384});return M(s.text,Qe)}})}function to(e){return S({name:"generate_feature_breakdown",description:"Analyze a GraphQL schema and produce a feature/component breakdown: list of modules, CRUD operations, and suggested pages. Returns a structured summary (not the full frontend JSON).",input:z$1.object({graphqlSchema:z$1.string().describe("The GraphQL schema string to analyze")}),handler:async({graphqlSchema:t})=>{let o=`${Zt}
|
|
1320
|
+
|
|
1321
|
+
**Schema to analyze:**
|
|
1322
|
+
\`\`\`graphql
|
|
1323
|
+
${t}
|
|
1324
|
+
\`\`\`
|
|
1325
|
+
|
|
1326
|
+
Respond with a structured breakdown only (no full JSON config): list modules, list Query/Mutation operations, and suggested pages for each module. Use clear headings and bullet points.`,r=[{role:"system",content:"You are a GraphQL schema analyst. Return a clear, structured text breakdown."},{role:"user",content:o}];return {summary:(await e.invoke(r,{temperature:.3,maxOutputTokens:4096})).text,modules:[],operations:[],suggestedPages:[]}}})}function Vi(e){return {appName:e.app.name,description:e.app.description,apiEndpoint:e.app.apiEndpoint,branding:{brandName:e.app.branding.brandName,primaryColor:e.app.branding.primaryColor,secondaryColor:e.app.branding.secondaryColor,logo:e.app.branding.logo},modules:e.modules.map(t=>({name:t.name,pascalName:t.name.charAt(0).toUpperCase()+t.name.slice(1),camelName:t.name.charAt(0).toLowerCase()+t.name.slice(1)})),author:e.app.author,pages:e.modules.flatMap(t=>t.pages)}}var Hr=S({name:"scaffold_vite",description:"Scaffold a Vite + React project from a validated ApplicationSchema config. Compiles Handlebars templates from .ref/templates/vite/ and writes the project to the output directory.",input:z$1.object({config:z$1.string().describe("JSON string of the validated ApplicationSchema config"),outputDir:z$1.string().describe("Absolute path to the output directory")}),handler:async({config:e,outputDir:t})=>{let o=_e(e,"application schema config"),r=le.resolve(process.cwd(),".ref/templates/vite"),n=Vi(o);return me({templateDir:r,outputDir:t,context:n})}});function Vr(e){return {validate_frontend_config:ke,generate_frontend:eo(e),generate_feature_breakdown:to(e),scaffold_vite:Hr}}var Wi=`You are an expert at analyzing GraphQL schemas. Your job is to:
|
|
1327
|
+
|
|
1328
|
+
1. **Types**: List all object types, enums, scalars, and input types.
|
|
1329
|
+
2. **Queries**: List every Query field with arguments and return type.
|
|
1330
|
+
3. **Mutations**: List every Mutation field with arguments and return type.
|
|
1331
|
+
4. **Relationships**: Identify types that reference other types (e.g. User has role: Role, or Order has customer: User).
|
|
1332
|
+
5. **Auth/directives**: Note any @auth, @directive usage that affects access control.
|
|
1333
|
+
|
|
1334
|
+
Respond with a clear, structured analysis (headings and bullet points). The user will use this to generate a frontend configuration.`,oo=f({name:"graphql-analyzer",description:"Analyzes a GraphQL schema to extract types, queries, mutations, and relationships. Use when you need to understand the schema before generating frontend config. Returns structured analysis (no JSON).",systemPrompt:Wi,tools:{},maxIterations:2});var Xi=`You are a frontend configuration validator. Your job is to:
|
|
1335
|
+
|
|
1336
|
+
1. Validate the provided frontend config JSON using the validate_frontend_config tool.
|
|
1337
|
+
2. Compare the config against the GraphQL schema (if provided) and check that all CRUD operations are covered.
|
|
1338
|
+
3. Report any missing modules, pages, or API hooks.
|
|
1339
|
+
|
|
1340
|
+
When the user gives you a config (as JSON string) and optionally the GraphQL schema, first call validate_frontend_config to check structure. Then summarize completeness.`;function ro(){return f({name:"config-validator",description:"Validates a frontend configuration JSON and checks completeness against the GraphQL schema. Use when you have a draft config and want to validate it. Has access to validate_frontend_config tool.",systemPrompt:Xi,tools:{validate_frontend_config:ke},maxIterations:5})}var Ki=`${He}
|
|
1341
|
+
|
|
1342
|
+
You are the React frontend builder orchestrator. When the user provides a GraphQL schema and asks for a frontend configuration:
|
|
1343
|
+
|
|
1344
|
+
1. **Analyze (optional)**: For complex schemas, use subagent_graphql-analyzer with a prompt that includes the schema to get a structured analysis of types, queries, and mutations.
|
|
1345
|
+
2. **Generate**: Use generate_frontend with the GraphQL schema (and optional appInfo) to produce the frontend config JSON.
|
|
1346
|
+
3. **Validate (optional)**: Use subagent_config-validator with the generated config (and schema) to check structure and completeness.
|
|
1347
|
+
4. **Validate directly**: You can use validate_frontend_config to check any config JSON.
|
|
1348
|
+
5. **Feature breakdown**: Use generate_feature_breakdown to get a module/operation breakdown before generating.
|
|
1349
|
+
|
|
1350
|
+
Respond with the final frontend config (as JSON) or a clear summary and the config. If the user gives feedback, use generate_frontend again with the same schema and consider their feedback in your instructions.`;async function Wr(e){let{input:t,model:o,maxIterations:r=15,onStep:n,logger:s}=e,a=E(o??{provider:"openai",model:"gpt-4o-mini"}),i=Vr(a),l=ro(),p=q([oo,l],{parentModel:a}),c={...i,...p};return N({model:a,tools:c,systemPrompt:Ki,input:t,maxIterations:r,onStep:n,logger:s})}var ns=e=>z$1.string().transform(t=>t.toLowerCase().trim()).pipe(z$1.enum(e)),Zi=z$1.string().transform(e=>e.toUpperCase().trim()).pipe(z$1.enum(["GET","POST","PUT","PATCH","DELETE"])),as=z$1.object({path:z$1.string(),name:z$1.string(),access:ns(["public","protected"]),routeGroup:z$1.string().default(""),purpose:z$1.string(),hasForm:z$1.coerce.boolean().default(false),formFields:z$1.array(z$1.string()).default([]),dataFetching:ns(["server","client","hybrid"]).default("server"),actions:z$1.array(z$1.string()).default([])}),ss=z$1.object({name:z$1.string(),path:z$1.string(),routeGroup:z$1.string().default(""),components:z$1.array(z$1.string()).default([]),purpose:z$1.string()}),is=z$1.object({path:z$1.string(),methods:z$1.array(Zi).default([]),auth:z$1.coerce.boolean().default(true),description:z$1.string()}),ls=z$1.object({name:z$1.string(),module:z$1.string(),description:z$1.string(),revalidates:z$1.array(z$1.string()).default([])}),Ve=z$1.object({appName:z$1.string().default("app"),pages:z$1.array(as).default([]),layouts:z$1.array(ss).default([]),apiRoutes:z$1.array(is).default([]),serverActions:z$1.array(ls).default([]),middleware:z$1.array(z$1.string()).default([]),envVars:z$1.array(z$1.string()).default([]),packages:z$1.array(z$1.string()).default([])});var Xr=`You are an expert Next.js application architect using the App Router.
|
|
1351
|
+
|
|
1352
|
+
You generate production-ready Next.js configurations from frontend designs and API designs:
|
|
1353
|
+
- App Router file structure with route groups, layouts, pages, loading, and error boundaries
|
|
1354
|
+
- Server Components by default, Client Components only when interactivity is needed
|
|
1355
|
+
- Server Actions for mutations (form submissions, data writes)
|
|
1356
|
+
- API Route Handlers for external integrations, webhooks, and file uploads
|
|
1357
|
+
- Next.js middleware for auth guards and redirects
|
|
1358
|
+
- Data fetching strategy (server vs client vs hybrid per page)
|
|
1359
|
+
- Package recommendations (next-auth, prisma, tailwindcss, shadcn/ui)
|
|
1360
|
+
|
|
1361
|
+
Output only valid JSON unless instructed otherwise.`;var cs=`## Requirements:
|
|
1362
|
+
{requirement}
|
|
1363
|
+
|
|
1364
|
+
Generate a Next.js App Router application configuration. Include:
|
|
1365
|
+
|
|
1366
|
+
1. Pages: app router pages with path, name, access level, route group, purpose, data fetching strategy.
|
|
1367
|
+
2. Layouts: shared layouts with route groups (e.g. (auth), (dashboard)), components they include.
|
|
1368
|
+
3. API Routes: route handlers with path, HTTP methods, auth requirement, description.
|
|
1369
|
+
4. Server Actions: named actions with module, description, and paths they revalidate.
|
|
1370
|
+
5. Middleware: list of middleware behaviors (e.g. "redirect unauthenticated to /login").
|
|
1371
|
+
6. Env vars: NEXTAUTH_SECRET, DATABASE_URL, etc.
|
|
1372
|
+
7. Packages: recommended npm packages.
|
|
1373
|
+
|
|
1374
|
+
Return ONLY valid JSON:
|
|
1375
|
+
{
|
|
1376
|
+
"appName": "my-app",
|
|
1377
|
+
"pages": [{
|
|
1378
|
+
"path": "/dashboard",
|
|
1379
|
+
"name": "Dashboard",
|
|
1380
|
+
"access": "protected",
|
|
1381
|
+
"routeGroup": "(dashboard)",
|
|
1382
|
+
"purpose": "Main dashboard with stats",
|
|
1383
|
+
"hasForm": false,
|
|
1384
|
+
"formFields": [],
|
|
1385
|
+
"dataFetching": "server",
|
|
1386
|
+
"actions": []
|
|
1387
|
+
}],
|
|
1388
|
+
"layouts": [{
|
|
1389
|
+
"name": "DashboardLayout",
|
|
1390
|
+
"path": "app/(dashboard)/layout.tsx",
|
|
1391
|
+
"routeGroup": "(dashboard)",
|
|
1392
|
+
"components": ["Sidebar", "Header"],
|
|
1393
|
+
"purpose": "Shared layout for authenticated pages"
|
|
1394
|
+
}],
|
|
1395
|
+
"apiRoutes": [{
|
|
1396
|
+
"path": "/api/users",
|
|
1397
|
+
"methods": ["GET", "POST"],
|
|
1398
|
+
"auth": true,
|
|
1399
|
+
"description": "User CRUD endpoints"
|
|
1400
|
+
}],
|
|
1401
|
+
"serverActions": [{
|
|
1402
|
+
"name": "createUser",
|
|
1403
|
+
"module": "users",
|
|
1404
|
+
"description": "Create a new user",
|
|
1405
|
+
"revalidates": ["/dashboard/users"]
|
|
1406
|
+
}],
|
|
1407
|
+
"middleware": ["Redirect unauthenticated users to /login"],
|
|
1408
|
+
"envVars": ["DATABASE_URL", "NEXTAUTH_SECRET"],
|
|
1409
|
+
"packages": ["next-auth", "prisma", "@prisma/client", "tailwindcss"]
|
|
1410
|
+
}`;function Kr(e){return cs.replace("{requirement}",e)}var no=I("validate_nextjs",Ve,"Validates a Next.js config JSON string against the NextjsConfig schema. Returns valid: true or valid: false with errors.","config");function ao(e){return S({name:"generate_nextjs",description:"Generate a complete Next.js App Router configuration from frontend design and requirements. Returns pages, layouts, API routes, server actions, and middleware as JSON.",input:z$1.object({requirement:z$1.string().describe("Frontend design, API design, and project requirements")}),handler:async({requirement:t})=>{let o=Kr(t),r=[{role:"system",content:"You are a Next.js architect. Return only valid JSON."},{role:"user",content:o}],n=await e.invoke(r,{temperature:.3,maxOutputTokens:16384});return M(n.text,Ve)}})}function Zr(e){return {validate_nextjs:no,generate_nextjs:ao(e)}}var el=`You are a Next.js App Router specialist. Given page specs, you plan the file structure.
|
|
1411
|
+
|
|
1412
|
+
## Route Groups
|
|
1413
|
+
- (auth) for public auth pages: login, signup, forgot-password
|
|
1414
|
+
- (dashboard) or (app) for protected pages
|
|
1415
|
+
- (marketing) for public landing pages
|
|
1416
|
+
|
|
1417
|
+
## File Structure Per Route
|
|
1418
|
+
- page.tsx: the page component (Server Component by default)
|
|
1419
|
+
- layout.tsx: shared layout for the route group
|
|
1420
|
+
- loading.tsx: Suspense fallback
|
|
1421
|
+
- error.tsx: error boundary (must be Client Component)
|
|
1422
|
+
- not-found.tsx: 404 page
|
|
1423
|
+
|
|
1424
|
+
## Data Fetching
|
|
1425
|
+
- Server Components: fetch data directly in the component (async function)
|
|
1426
|
+
- Client Components: use SWR or React Query for client-side fetching
|
|
1427
|
+
- Server Actions: for form submissions and mutations
|
|
1428
|
+
|
|
1429
|
+
## Conventions
|
|
1430
|
+
- Use lowercase kebab-case for route segments
|
|
1431
|
+
- Dynamic segments: [id], [slug]
|
|
1432
|
+
- Catch-all: [...slug]
|
|
1433
|
+
- Parallel routes: @modal, @sidebar
|
|
1434
|
+
- Intercepting routes: (.)photo, (..)details
|
|
1435
|
+
|
|
1436
|
+
Respond with the full file tree and route structure. Do NOT return JSON.`,so=f({name:"route-planner",description:"Plans Next.js App Router file structure with route groups, layouts, and page files. Use before generating the Next.js config.",systemPrompt:el,tools:{},maxIterations:2});var tl=`You are a Next.js API specialist. Given an API design, you plan route handlers and server actions.
|
|
1437
|
+
|
|
1438
|
+
## API Route Handlers (app/api/)
|
|
1439
|
+
For external integrations, webhooks, and file uploads:
|
|
1440
|
+
- One route.ts file per resource: app/api/[resource]/route.ts
|
|
1441
|
+
- Export named functions: GET, POST, PUT, DELETE
|
|
1442
|
+
- Use NextRequest and NextResponse
|
|
1443
|
+
- Add auth checks using next-auth getServerSession
|
|
1444
|
+
|
|
1445
|
+
## Server Actions (preferred for mutations)
|
|
1446
|
+
For form submissions and data writes:
|
|
1447
|
+
- Define in separate files: app/actions/[module].ts
|
|
1448
|
+
- Use 'use server' directive
|
|
1449
|
+
- Use revalidatePath or revalidateTag after mutations
|
|
1450
|
+
- Return typed results with error handling
|
|
1451
|
+
|
|
1452
|
+
## When to Use Which
|
|
1453
|
+
- Server Actions: form submissions, data CRUD, anything triggered by user action
|
|
1454
|
+
- API Routes: webhooks from external services, file uploads, OAuth callbacks, public APIs
|
|
1455
|
+
|
|
1456
|
+
## Auth Integration
|
|
1457
|
+
- API Routes: check session with getServerSession
|
|
1458
|
+
- Server Actions: check session at the start of each action
|
|
1459
|
+
- Middleware: protect route groups with matcher patterns
|
|
1460
|
+
|
|
1461
|
+
Respond with structured analysis per module. Do NOT return JSON.`,io=f({name:"api-route-generator",description:"Generates Next.js API route handlers and server actions from API design. Use after route planning.",systemPrompt:tl,tools:{},maxIterations:2});var ol=`${Xr}
|
|
1462
|
+
|
|
1463
|
+
You are the Next.js builder orchestrator. When the user provides requirements:
|
|
1464
|
+
|
|
1465
|
+
1. **Plan routes**: Use subagent_route-planner to design the App Router file structure with route groups and layouts.
|
|
1466
|
+
2. **Generate API routes**: Use subagent_api-route-generator to design API route handlers and server actions.
|
|
1467
|
+
3. **Generate config**: Use generate_nextjs to produce the complete Next.js configuration as JSON.
|
|
1468
|
+
4. **Validate**: Use validate_nextjs to check the config JSON before returning.
|
|
1469
|
+
|
|
1470
|
+
Respond with the final Next.js config as JSON.`;async function en(e){let{input:t,model:o,maxIterations:r=15,onStep:n,logger:s}=e,a=E(o??{provider:"openai",model:"gpt-4o-mini"}),i=Zr(a),l=q([so,io],{parentModel:a}),p={...i,...l};return N({model:a,tools:p,systemPrompt:ol,input:t,maxIterations:r,onStep:n,logger:s})}var ds=z$1.object({order:z$1.number(),action:z$1.string(),details:z$1.string()}),us=z$1.object({name:z$1.string(),description:z$1.string(),steps:z$1.array(ds)}),ms=z$1.object({area:z$1.string(),scenario:z$1.string(),handling:z$1.string(),severity:z$1.string().transform(e=>e.toLowerCase().trim()).pipe(z$1.enum(["critical","warning","info"]))}),gs=z$1.object({flow:z$1.string(),item:z$1.string(),expectedResult:z$1.string()}),We=z$1.object({phases:z$1.array(us).default([]),currentState:z$1.string().default(""),desiredEndState:z$1.string().default(""),edgeCases:z$1.array(ms).default([]),securityNotes:z$1.array(z$1.string()).default([]),performanceNotes:z$1.array(z$1.string()).default([]),testingChecklist:z$1.array(gs).default([])});var tn=`You are a senior tech lead specializing in implementation strategy and project execution planning.
|
|
1471
|
+
|
|
1472
|
+
You create enterprise-quality execution plans with:
|
|
1473
|
+
- Phased implementation order with concrete, numbered steps per phase
|
|
1474
|
+
- Current state analysis and desired end state definition
|
|
1475
|
+
- Edge cases per domain area with handling strategies and severity levels
|
|
1476
|
+
- Security considerations (passwords, tokens, CORS, input validation)
|
|
1477
|
+
- Performance considerations (indexing, caching, lazy loading, N+1 prevention)
|
|
1478
|
+
- Manual testing checklists grouped by feature flow
|
|
1479
|
+
|
|
1480
|
+
Output only valid JSON unless instructed otherwise.`;var fs=`## Full Plan Context:
|
|
1481
|
+
{context}
|
|
1482
|
+
|
|
1483
|
+
Create a comprehensive execution plan. Include:
|
|
1484
|
+
|
|
1485
|
+
1. **phases**: Implementation phases (Foundation, Auth, Core Features, etc.). Each phase has numbered steps with concrete actions (e.g. "1. Install dependencies", "2. Create User model").
|
|
1486
|
+
2. **currentState**: What the project starts with (e.g. "vanilla Next.js, no DB, no auth").
|
|
1487
|
+
3. **desiredEndState**: What must work when done (user capabilities + technical verification).
|
|
1488
|
+
4. **edgeCases**: Edge cases per area with scenario, handling strategy, and severity (critical/warning/info).
|
|
1489
|
+
5. **securityNotes**: Security considerations (password hashing, JWT config, rate limiting, etc.).
|
|
1490
|
+
6. **performanceNotes**: Performance considerations (indexing, caching, lazy loading, etc.).
|
|
1491
|
+
7. **testingChecklist**: Manual testing items per flow with expected results.
|
|
1492
|
+
|
|
1493
|
+
Return ONLY valid JSON:
|
|
1494
|
+
{
|
|
1495
|
+
"phases": [{ "name": "Phase 1: Foundation", "description": "...", "steps": [{ "order": 1, "action": "Install dependencies", "details": "npm install mongoose bcryptjs jsonwebtoken" }] }],
|
|
1496
|
+
"currentState": "...",
|
|
1497
|
+
"desiredEndState": "...",
|
|
1498
|
+
"edgeCases": [{ "area": "Authentication", "scenario": "Email already exists", "handling": "Return 400 with clear message", "severity": "critical" }],
|
|
1499
|
+
"securityNotes": ["..."],
|
|
1500
|
+
"performanceNotes": ["..."],
|
|
1501
|
+
"testingChecklist": [{ "flow": "Auth Flow", "item": "Sign up with valid credentials", "expectedResult": "Account created, redirected to dashboard" }]
|
|
1502
|
+
}`;function on(e){return fs.replace("{context}",e)}var lo=I("validate_execution_plan",We,"Validates an execution plan JSON string against the ExecutionPlan schema. Returns valid: true or valid: false with errors.","plan");function co(e){return S({name:"create_execution_plan",description:"Generate a comprehensive execution plan with phases, edge cases, and testing checklist from the full plan context.",input:z$1.object({context:z$1.string().describe("Full plan context: all sections generated so far")}),handler:async({context:t})=>{let o=on(t),r=[{role:"system",content:"You are a tech lead. Return only valid JSON."},{role:"user",content:o}],n=await e.invoke(r,{temperature:.3,maxOutputTokens:16384});return M(n.text,We)}})}function rn(e){return {validate_execution_plan:lo,create_execution_plan:co(e)}}var rl=`${tn}
|
|
1503
|
+
|
|
1504
|
+
You are the execution planning orchestrator. When the user provides plan sections:
|
|
1505
|
+
|
|
1506
|
+
1. **Analyze edge cases**: Use subagent_edge-case-analyzer to identify edge cases per domain area with handling strategies.
|
|
1507
|
+
2. **Design testing**: Use subagent_testing-strategist to design manual testing checklists grouped by feature flow.
|
|
1508
|
+
3. **Generate plan**: Use create_execution_plan to produce the complete execution plan with phases, edge cases, and testing checklist.
|
|
1509
|
+
4. **Validate**: Use validate_execution_plan to check the final plan JSON before returning.
|
|
1510
|
+
|
|
1511
|
+
Respond with the final execution plan as JSON.`;async function nn(e){let{input:t,model:o,maxIterations:r=15,onStep:n,logger:s}=e,a=E(o??{provider:"openai",model:"gpt-4o-mini"}),i=rn(a),l=q([we,ve],{parentModel:a}),p={...i,...l};return N({model:a,tools:p,systemPrompt:rl,input:t,maxIterations:r,onStep:n,logger:s})}var an=S({name:"hello_world",description:"Returns a greeting message for the given name",input:z$1.object({name:z$1.string().describe("Name to greet")}),handler:async({name:e})=>({greeting:`Hello, ${e}! Welcome to sweagent.`})});var nl="You are a friendly greeter. Use the hello_world tool to greet users.";async function sn(e){let{input:t,model:o,systemPrompt:r=nl,maxIterations:n=3,onStep:s,logger:a}=e,i=E(o??{provider:"openai",model:"gpt-4o-mini"});return N({model:i,tools:{hello_world:an},systemPrompt:r,input:t,maxIterations:n,onStep:s,logger:a})}function z(e,t,o){return {name:e,description:t,handler:(r,n,s)=>o({input:r,model:n,onStep:s})}}var po=[z("plan","Generate a full software plan (discovery, requirements, design, synthesis) from a project description.",_o),z("gather_requirements","Extract structured requirements (actors, flows, stories, modules) from a project description.",Vo),z("design_data_model","Design a database schema (MongoDB or PostgreSQL) with entities, relations, and indexes.",ir),z("design_api","Design REST or GraphQL API contracts (endpoints, request/response schemas) from requirements.",gr),z("design_auth","Design authentication and authorization strategy (providers, roles, permissions, flows).",Sr),z("architect_backend","Design backend architecture (folder structure, services, middleware, deployment) from requirements.",Pr),z("architect_frontend","Design frontend architecture (components, state management, routing, styling) from requirements.",Ar),z("build_express","Generate Express.js REST API configuration and boilerplate from an API design.",Dr),z("build_apollo","Generate Apollo GraphQL subgraph configuration and resolvers from an API design.",Fr),z("build_react","Generate React + Vite application configuration and components from a GraphQL schema.",Wr),z("build_nextjs","Generate Next.js App Router configuration and pages from requirements.",en),z("plan_execution","Create a phased execution plan with edge-case analysis and testing strategy.",nn),z("hello_world","Test agent that greets users. Use to verify the MCP server is working.",sn)];var Ss={input:z$1.string().describe("Natural language description of what to build or design"),provider:z$1.enum(["openai","anthropic","google"]).optional().describe("LLM provider (defaults to openai)"),model:z$1.string().optional().describe("Model name, e.g. gpt-4o-mini, claude-3-5-sonnet-20241022"),temperature:z$1.number().min(0).max(1).optional().describe("Sampling temperature (0-1)")};function bs(e){if(!(!e.provider&&!e.model))return {provider:e.provider??"openai",model:e.model??"gpt-4o-mini",temperature:e.temperature}}var sl="sweagent",il="0.0.3",Xe=e=>{process.stderr.write(`[sweagent] ${e}
|
|
1512
|
+
`);},xs=200;function ll(e){return t=>{let o=`${e} \u2014 step ${t.iteration+1}`;if(t.content){let r=t.content.length>xs?t.content.slice(0,xs)+"\u2026":t.content;Xe(`${o}: ${r}`);}else {let r=t.toolCalls?.map(n=>n.toolName).join(", ");Xe(`${o}${r?` (tools: ${r})`:""}`);}}}function Ts(){let e=new McpServer({name:sl,version:il},{capabilities:{tools:{}}});for(let t of po)e.registerTool(t.name,{description:t.description,inputSchema:Ss},async o=>{Xe(`${t.name} \u2014 started`);try{let r=bs(o),n=ll(t.name),s=await t.handler(o.input,r,n);return Xe(`${t.name} \u2014 completed`),{content:[{type:"text",text:s.output}]}}catch(r){let n=r instanceof Error?r.message:String(r);return Xe(`${t.name} \u2014 error: ${n}`),{content:[{type:"text",text:n}],isError:true}}});return e}var Ps=e=>{process.stderr.write(`[sweagent] ${e}
|
|
1513
|
+
`);};try{let e=Ts(),t=new StdioServerTransport;await e.connect(t),Ps(`MCP server running (stdio) \u2014 ${po.length} tools registered`);}catch(e){Ps(`Failed to start: ${e}`),process.exit(1);}//# sourceMappingURL=stdio.js.map
|
|
1514
|
+
//# sourceMappingURL=stdio.js.map
|