sweagent 0.0.3 → 0.0.5
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 +287 -64
- package/dist/index.cjs +747 -746
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +121 -58
- package/dist/index.d.ts +121 -58
- package/dist/index.js +747 -746
- package/dist/index.js.map +1 -1
- package/dist/stdio.d.ts +2 -0
- package/dist/stdio.js +1512 -0
- package/dist/stdio.js.map +1 -0
- package/package.json +9 -3
package/dist/index.cjs
CHANGED
|
@@ -1,395 +1,12 @@
|
|
|
1
|
-
'use strict';var
|
|
2
|
-
Caused by: ${o.stack}`);}},
|
|
1
|
+
'use strict';var No=require('pino'),zod=require('zod'),ai=require('ai'),openai=require('@ai-sdk/openai'),anthropic=require('@ai-sdk/anthropic'),google=require('@ai-sdk/google'),Z=require('fs'),Pe=require('path'),re=require('handlebars'),client=require('@modelcontextprotocol/sdk/client'),module$1=require('module'),url=require('url'),mcp_js=require('@modelcontextprotocol/sdk/server/mcp.js'),promises=require('fs/promises');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var No__default=/*#__PURE__*/_interopDefault(No);var Z__namespace=/*#__PURE__*/_interopNamespace(Z);var Pe__namespace=/*#__PURE__*/_interopNamespace(Pe);var re__default=/*#__PURE__*/_interopDefault(re);var ue=class extends Error{constructor(e,o){super(e,o===void 0?void 0:{cause:o}),this.name="LibraryError",o?.stack&&(this.stack=`${this.stack}
|
|
2
|
+
Caused by: ${o.stack}`);}},ie=class extends ue{constructor(o,r,n){super(o,n);this.provider=r;this.name="ModelError";}},H=class extends ue{constructor(o,r,n){super(o,n);this.toolName=r;this.name="ToolError";}},Fn=class extends ue{constructor(o,r){super(o);this.errors=r;this.name="ValidationError";}},rt=class extends ue{constructor(o,r,n){super(o,n);this.iteration=r;this.name="AgentError";}},be=class extends ue{constructor(o,r,n){super(o,n);this.subagentName=r;this.name="SubagentError";}};function Wa(t){let e=t.trim(),o=/```(?:json)?\s*([\s\S]*?)```/.exec(e);return o?.[1]?o[1].trim():e}function M(t,e){let o=Wa(t),r;try{r=JSON.parse(o);}catch(a){let s=o.length>300?o.slice(0,300)+"...":o;throw new Error(`Failed to parse model response as JSON: ${a instanceof Error?a.message:String(a)}. Preview: ${s}`)}let n=e.safeParse(r);if(!n.success){let a=n.error.issues.slice(0,5).map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
|
|
3
3
|
`);throw new Error(`Model JSON does not match expected schema:
|
|
4
|
-
${a}`)}return n.data}function be(t,e){try{return JSON.parse(t)}catch(o){let r=t.length>200?t.slice(0,200)+"...":t;throw new Error(`Invalid JSON${e?` for ${e}`:""}: ${o instanceof Error?o.message:String(o)}. Preview: ${r}`)}}var Sn={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},child:()=>Sn};function Jl(t={}){if(t.enabled===false)return Sn;let{name:e,level:o="info",pretty:r=false,file:n,stream:a,destination:s}=t,i=a==="stderr"?2:a==="stdout"?1:r?2:1,l;if(s)l=Ao__default.default({name:e,level:o},s);else {let c=[];r?c.push({target:"pino-pretty",options:{colorize:true,destination:i,singleLine:true,ignore:"time,pid,hostname",translateTime:false},level:o}):c.push({target:"pino/file",options:{destination:i},level:o}),n&&c.push({target:"pino/file",options:{destination:n,mkdir:true},level:o});let p=Ao__default.default.transport({targets:c});l=Ao__default.default({name:e,level:o},p);}return bn(l)}function Bl(t={}){let e=process.env,o=(e.SWE_LOG_ENABLED??"true").trim().toLowerCase(),r=o!=="0"&&o!=="false"&&o!=="no"&&o!=="disabled",n=(e.SWE_LOG_LEVEL??"info").trim().toLowerCase(),a=n==="debug"||n==="info"||n==="warn"||n==="error"?n:"info",s=(e.SWE_LOG_STREAM??"").trim().toLowerCase(),i=(e.SWE_LOG_PRETTY??"0").trim().toLowerCase(),l=i==="1"||i==="true"||i==="yes",c=s==="stdout"?"stdout":s==="stderr"||l?"stderr":"stdout",p=e.SWE_LOG_FILE?.trim()||void 0,d=e.SWE_LOG_NAME?.trim()||void 0;return {enabled:r,level:a,stream:c,pretty:l,...p&&{file:p},...d&&{name:d},...t}}function bn(t){return {debug:(e,o)=>{t.debug(o??{},e);},info:(e,o)=>{t.info(o??{},e);},warn:(e,o)=>{t.warn(o??{},e);},error:(e,o)=>{o instanceof Error?t.error({err:o},e):t.error(o??{},e);},child:e=>bn(t.child(e))}}var Oa={noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},Ca={textTokens:void 0,reasoningTokens:void 0};function Mo(t){let e=0,o=0,r=0;for(let n of t)n&&(e+=n.inputTokens??0,o+=n.outputTokens??0,r+=n.totalTokens??0);return {inputTokens:e,outputTokens:o,totalTokens:r,inputTokenDetails:Oa,outputTokenDetails:Ca}}function h(t){let{name:e,description:o,input:r,handler:n}=t;return ai$1.tool({description:o,inputSchema:r,execute:async a=>{let s=r.safeParse(a);if(!s.success)throw new $(`Invalid input: ${s.error.message}`,e,s.error);try{return await n(s.data,void 0)}catch(i){throw i instanceof $?i:new $(`Tool "${e}" failed: ${i instanceof Error?i.message:String(i)}`,e,i instanceof Error?i:void 0)}}})}function _(t){return t}function xn(t){return Object.values(t)}function Tn(t,e){return t[e]}async function Oo(t,e,o){let{logger:r}=o??{},n=o?.toolName??("name"in t&&typeof t.name=="string"?t.name:"unknown");if(!t.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 a=await t.execute(e,{toolCallId:o?.toolCallId??"",messages:[],abortSignal:o?.abortSignal});return r?.info("Tool completed",{toolName:n,toolCallId:o?.toolCallId}),{success:!0,output:a}}catch(a){let s=a instanceof Error?a.message:String(a);return r?.error("Tool failed",{toolName:n,toolCallId:o?.toolCallId,error:s}),{success:false,error:s}}}async function tt(t,e,o,r){let n=t[e];if(!n)throw r?.logger?.error("Tool not found",{name:e,availableTools:Object.keys(t)}),new $(`Tool not found: ${e}`);return Oo(n,o,{...r,toolName:e})}function q(t,e,o,r="json"){return h({name:t,description:o,input:zod.z.object({[r]:zod.z.string().describe("JSON string to validate")}),handler:async n=>{let a=n[r]??"";try{let s=JSON.parse(a);return e.parse(s),{valid:!0}}catch(s){return s instanceof zod.z.ZodError?{valid:false,errors:s.issues.map(i=>`${i.path.join(".")}: ${i.message}`)}:s instanceof SyntaxError?{valid:false,errors:[`Invalid JSON: ${s.message}`]}:{valid:false,errors:[String(s)]}}}})}function No(t,e){t?.forEach(o=>o.onStep?.(e));}function Pn(t,e,o){t?.forEach(r=>r.onToolExecution?.(e,o));}function Rn(t,e){t?.forEach(o=>o.onError?.(e));}async function C(t){let{model:e,tools:o,systemPrompt:r,input:n,maxIterations:a=10,onStep:s,observers:i,logger:l}=t;l?.info("Starting agent",{maxIterations:a});let c=[{role:"system",content:r},{role:"user",content:n}],p=[];for(let u=0;u<a;u++){u>0&&u>=a-2&&l?.warn("Approaching max iterations",{iteration:u,maxIterations:a}),l?.debug("Agent iteration",{iteration:u});let y=await e.invoke(c,{tools:o}),m={iteration:u,content:y.text,toolCalls:y.toolCalls,usage:y.usage};if(y.text&&l?.debug("Model response",{iteration:u,textLength:y.text.length}),!y.toolCalls?.length)return p.push(m),s?.(m),No(i,m),l?.info("Agent completed",{steps:p.length,totalUsage:Mo(p.map(j=>j.usage))}),{output:y.text,steps:p,totalUsage:Mo(p.map(j=>j.usage)),messages:c};l?.debug("Tool calls",{iteration:u,toolCalls:y.toolCalls.map(j=>({name:j.toolName,toolCallId:j.toolCallId}))});let B=[...y.text?[{type:"text",text:y.text}]:[],...y.toolCalls.map(j=>({type:"tool-call",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input}))];c.push({role:"assistant",content:B});let L=[];for(let j of y.toolCalls){let ye=await tt(o,j.toolName,j.input,{toolCallId:j.toolCallId,logger:l}),pe={toolCallId:j.toolCallId,toolName:j.toolName,output:ye.success?ye.output:ye.error,isError:!ye.success};L.push(pe),Pn(i,j.toolName,pe.output);let Aa=pe.isError?{type:"error-text",value:String(pe.output)}:{type:"text",value:typeof pe.output=="string"?pe.output:JSON.stringify(pe.output)};c.push({role:"tool",content:[{type:"tool-result",toolCallId:j.toolCallId,toolName:j.toolName,output:Aa}]});}m.toolResults=L,p.push(m),s?.(m),No(i,m);}let d=new et(`Agent reached maximum iterations (${a}) without completing`,a-1);throw Rn(i,d),l?.error("Agent failed: max iterations reached",{maxIterations:a,error:d}),d}function xe(t){let{provider:e,modelName:o,getModel:r}=t;return {provider:e,modelName:o,async invoke(n,a){try{let s=await r(),i=a?.tools?Object.fromEntries(Object.entries(a.tools).map(([p,d])=>{let{execute:u,...y}=d;return [p,y]})):void 0,l=await ai$1.generateText({model:s,messages:n,tools:i,maxOutputTokens:a?.maxOutputTokens,temperature:a?.temperature,stopSequences:a?.stop}),c=l.toolCalls.map(p=>({toolCallId:p.toolCallId,toolName:p.toolName,input:p.input}));return {text:l.text,toolCalls:c,usage:l.usage,finishReason:l.finishReason}}catch(s){let i=s instanceof Error?s:new Error(String(s));throw new ae(`Failed to invoke ${e} model`,e,i)}},async generateVision(n,a,s){try{let i=await r(),l=[];for(let d of a)l.push({type:"image",image:`data:${d.mimeType};base64,${d.base64}`,mimeType:d.mimeType});l.push({type:"text",text:n});let c=[];s?.systemPrompt&&c.push({role:"system",content:s.systemPrompt}),c.push({role:"user",content:l});let p=await ai$1.generateText({model:i,messages:c,maxOutputTokens:s?.maxOutputTokens,temperature:s?.temperature});return {text:p.text,toolCalls:[],usage:p.usage,finishReason:p.finishReason}}catch(i){let l=i instanceof Error?i:new Error(String(i));throw new ae("Failed to generate vision response",e,l)}},async invokeObject(n,a,s){try{let i=await r(),l=ai$1.zodSchema(a),c=await ai$1.generateObject({model:i,messages:n,schema:l,temperature:s?.temperature,maxOutputTokens:s?.maxOutputTokens});return {data:c.object,usage:c.usage}}catch(i){let l=i instanceof Error?i:new Error(String(i));throw new ae(`Failed to invokeObject ${e} model`,e,l)}}}}function ot(t){let{model:e,apiKey:o,baseUrl:r}=t,n=openai.createOpenAI({apiKey:o??process.env.OPENAI_API_KEY,baseURL:r});return xe({provider:"openai",modelName:e,getModel:()=>n.chat(e)})}function rt(t){let{model:e,apiKey:o}=t,r=anthropic.createAnthropic({apiKey:o??process.env.ANTHROPIC_API_KEY});return xe({provider:"anthropic",modelName:e,getModel:()=>r(e)})}function nt(t){let{model:e,apiKey:o}=t,r=google.createGoogleGenerativeAI({apiKey:o??process.env.GOOGLE_GENERATIVE_AI_API_KEY});return xe({provider:"google",modelName:e,getModel:()=>r(e)})}function v(t){let{provider:e}=t;switch(e){case "openai":return ot(t);case "anthropic":return rt(t);case "google":return nt(t);default:throw new ae(`Unsupported provider: ${e}. Supported providers: openai, anthropic, google`)}}var Ua=/^[a-z0-9]+(-[a-z0-9]+)*$/;function f(t){if(!t.name.trim())throw new Se("Subagent name is required",void 0);if(!Ua.test(t.name))throw new Se(`Subagent name must be kebab-case (lowercase letters, numbers, hyphens): ${t.name}`,t.name);return {...t}}function La(t,e){if(t.tools!=null&&Object.keys(t.tools).length>0)return t.tools;let o=e??{},r=new Set(t.disallowedTools??[]),n={};for(let[a,s]of Object.entries(o))a.startsWith("subagent_")||r.has(a)||(n[a]=s);return n}async function z(t,e,o){let{parentTools:r,parentModel:n}=o??{},a=La(t,r),s=t.model==null?n:v(t.model);if(!s)throw new Se("Subagent has no model: set definition.model or pass parentModel in options",t.name);return {...await C({model:s,tools:a,systemPrompt:t.systemPrompt,input:e,maxIterations:t.maxIterations??10,onStep:t.onStep}),subagentName:t.name}}function Do(t,e){let o=`subagent_${t.name}`;return h({name:o,description:t.description,input:zod.z.object({prompt:zod.z.string().describe("The task or question to delegate to this subagent")}),handler:async({prompt:r})=>(await z(t,r,{parentTools:e?.parentTools,parentModel:e?.parentModel})).output})}function I(t,e){let o={};for(let r of t){let n=Do(r,e);o[`subagent_${r.name}`]=n;}return o}function ko(t,e){return oe__default.default.compile(t,{noEscape:true})(e)}function En(t,e=t){let o=[];if(!X__namespace.existsSync(t))return o;let r=X__namespace.readdirSync(t,{withFileTypes:true});for(let n of r){let a=Te__namespace.join(t,n.name);n.isDirectory()?o.push(...En(a,e)):n.name.endsWith(".hbs")&&o.push(Te__namespace.relative(e,a));}return o}function Ga(t){return t.replace(/\.hbs$/,"")}function Ja(t,e){for(let o of e)if(new RegExp("^"+o.replace(/\./g,"\\.").replace(/\*\*/g,"<<GLOBSTAR>>").replace(/\*/g,"[^/]*").replace(/<<GLOBSTAR>>/g,".*")+"$").test(t))return true;return false}async function le(t){let{templateDir:e,outputDir:o,context:r,skipPatterns:n=[]}=t,a=En(e),s=[],i=[];for(let l of a){if(Ja(l,n))continue;let c=Ga(l),p=Te__namespace.join(e,l),d=Te__namespace.join(o,c);try{let u=X__namespace.readFileSync(p,"utf-8"),y=ko(u,r);X__namespace.mkdirSync(Te__namespace.dirname(d),{recursive:!0}),X__namespace.writeFileSync(d,y,"utf-8"),s.push(c);}catch(u){i.push({file:l,message:u instanceof Error?u.message:String(u)});}}return {fileCount:s.length,files:s,errors:i}}function _o(){oe__default.default.registerHelper("eq",(t,e)=>t===e),oe__default.default.registerHelper("neq",(t,e)=>t!==e),oe__default.default.registerHelper("json",t=>JSON.stringify(t,null,2)),oe__default.default.registerHelper("uppercase",t=>typeof t=="string"?t.toUpperCase():""),oe__default.default.registerHelper("lowercase",t=>typeof t=="string"?t.toLowerCase():""),oe__default.default.registerHelper("capitalize",t=>typeof t=="string"?t.charAt(0).toUpperCase()+t.slice(1):""),oe__default.default.registerHelper("camelCase",t=>typeof t!="string"?"":t.replace(/[-_\s]+(.)?/g,(e,o)=>o?o.toUpperCase():"").replace(/^(.)/,e=>e.toLowerCase())),oe__default.default.registerHelper("pascalCase",t=>typeof t!="string"?"":t.replace(/[-_\s]+(.)?/g,(e,o)=>o?o.toUpperCase():"").replace(/^(.)/,e=>e.toUpperCase()));}_o();function Ya(){let e=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))).resolve("@modelcontextprotocol/sdk/client");return Te__namespace.default.dirname(Te__namespace.default.dirname(Te__namespace.default.dirname(Te__namespace.default.dirname(e))))}var Mn=Ya();function On(t){let e=t.content;if(!e?.length)return {};let o=e[0];if(o?.type==="text"&&typeof o.text=="string"){let r=o.text.trim();if(r.startsWith("{")||r.startsWith("["))try{return JSON.parse(r)}catch{return {raw:r}}return {text:r}}return t}async function Cn(t,e){let o=Te__namespace.default.join(Mn,"dist","esm","client","streamableHttp.js"),r=await import(url.pathToFileURL(o).href),n=e?{headers:new Headers(e)}:void 0;return new r.StreamableHTTPClientTransport(new URL(t),n?{requestInit:n}:void 0)}async function Nn(t,e){let o=Te__namespace.default.join(Mn,"dist","esm","client","stdio.js"),r=await import(url.pathToFileURL(o).href);return new r.StdioClientTransport({command:t,args:e})}var st=class{info;config;client=null;transport=null;connectPromise=null;constructor(e,o){this.info=e,this.config=o;}static resolveConfig(e,o={envPrefix:"MCP"}){let{envPrefix:r,serverLabel:n,apiKeyHeader:a}=o,s=e?.url??process.env[`${r}_URL`],i=process.env[`${r}_API_KEY`],l=e?.command??process.env[`${r}_COMMAND`],c=process.env[`${r}_ARGS`],p=e?.args??(c?c.split(",").map(u=>u.trim()):void 0),d=e?.headers?{...e.headers}:void 0;if(i){let u=a??"Authorization";d=d??{},d[u]=u==="Authorization"?`Bearer ${i}`:i;}if(s)return {url:s,headers:d};if(l)return {command:l,args:p?.length?p:[]};throw new $(`${n??r} uses MCP only. Set ${r}_URL or ${r}_COMMAND (and optionally ${r}_ARGS).`,"mcp_client")}async ensureConnected(){if(this.client)return this.client;if(this.connectPromise){if(await this.connectPromise,!this.client)throw new $("MCP connection failed.","mcp_client");return this.client}if(this.connectPromise=this.doConnect(),await this.connectPromise,this.connectPromise=null,!this.client)throw new $("MCP connection failed.","mcp_client");return this.client}async doConnect(){let e=new client.Client({name:this.info.name,version:this.info.version},{capabilities:{}});if(this.config.url)this.transport=await Cn(this.config.url,this.config.headers);else if(this.config.command)this.transport=await Nn(this.config.command,this.config.args??[]);else throw new $("MCP config missing: provide url or command.","mcp_client");await e.connect(this.transport),this.client=e;}async callTool(e,o={}){let n=await(await this.ensureConnected()).callTool({name:e,arguments:o});return n&&typeof n=="object"&&"content"in n?On(n):n}async close(){this.transport&&(await this.transport.close(),this.transport=null),this.client=null,this.connectPromise=null;}};var Io=h({name:"hello_world",description:"Returns a greeting message for the given name",input:zod.z.object({name:zod.z.string().describe("Name to greet")}),handler:async({name:t})=>({greeting:`Hello, ${t}! Welcome to sweagent.`})});var $a="You are a friendly greeter. Use the hello_world tool to greet users.";async function Ha(t){let{input:e,model:o,systemPrompt:r=$a,maxIterations:n=3,onStep:a,logger:s}=t,i=v(o??{provider:"openai",model:"gpt-4o-mini"});return C({model:i,tools:{hello_world:Io},systemPrompt:r,input:e,maxIterations:n,onStep:a,logger:s})}var jo=zod.z.object({brandName:zod.z.string().describe("The brand's display name"),primaryColor:zod.z.string().describe("The brand's primary color code (e.g., #FFFFFF)"),secondaryColor:zod.z.string().describe("The brand's secondary color code (e.g., #000000)"),logo:zod.z.url().describe("URL pointing to the brand's logo")});var qo=zod.z.object({name:zod.z.string().describe("Application name"),description:zod.z.string().describe("Brief description of the application"),author:zod.z.string().describe("Author or owner of the application").default("sijeeshmiziha (HubSpire)"),branding:jo.describe("Branding information for the application"),apiEndpoint:zod.z.url().describe("URL endpoint for the app's API calls")});var kn=zod.z.object({minLength:zod.z.number().optional().describe("Minimum length requirement"),zodString:zod.z.string().describe("Raw Zod string validation (e.g. regex)")}),_n=zod.z.object({hookName:zod.z.string().optional().describe("Name of the hook for dynamic field options"),queryString:zod.z.string().optional().describe("Optional query string for fetching field options"),labelKey:zod.z.string().optional().describe("Key used as label when displaying options"),valueKey:zod.z.string().optional().describe("Key used as value for a field when selecting options"),values:zod.z.array(zod.z.string()).optional().describe("Static list of possible field values")}),at=zod.z.object({name:zod.z.string().describe("The field's key or identifier"),type:zod.z.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:zod.z.boolean().optional().describe("Whether this field must be filled"),validation:kn.optional().describe("Optional field validation requirements"),defaultValue:zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean()]).optional().describe("Default value can be string, number, or boolean"),options:_n.optional().describe("Additional dynamic or static options for this field")}),Fo=zod.z.object({field:zod.z.string().describe("Key or name of the data field in the table"),label:zod.z.string().describe("User-friendly label to show on the table header")});var Lo=zod.z.object({type:zod.z.string().describe("Indicates the response type (e.g., 'object')"),properties:zod.z.record(zod.z.string(),zod.z.object({type:zod.z.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"),In=zod.z.object({type:zod.z.enum(["list","create","update","delete","getById"]).describe("Type of API call for CRUD operations"),graphqlHook:zod.z.string().describe("Name of the GraphQL hook (e.g. useGetAllUserQuery, useCreateUserMutation)"),queryString:zod.z.string().describe("Actual GraphQL query string"),responseType:Lo.describe("Optional schema describing shape of the API response")}),jn=zod.z.object({type:zod.z.enum(["login","currentUser","forgotPassword","resetPassword"]).describe("Type of API call"),graphqlHook:zod.z.string().describe("Name of the GraphQL hook (e.g. useLoginMutation)"),queryString:zod.z.string().describe("Actual GraphQL query string"),responseType:Lo.describe("Optional schema describing shape of the API response")}),Uo=zod.z.object({title:zod.z.string().describe("Title displayed on the drawer"),graphqlHook:zod.z.string().describe("Name of the GraphQL hook (e.g. useCreateUserMutation, useDeleteOneUserMutation)"),fields:zod.z.array(at).describe("List of fields displayed within the drawer")}),qn=zod.z.object({name:zod.z.enum(["LoginPage","ForgotPasswordPage","ResetPasswordPage"]).describe("Internal name of the auth page"),type:zod.z.enum(["EmailPassword","ForgotPassword","ResetPassword"]).describe("Type of authentication page"),route:zod.z.string().describe("URL route for this page (e.g., '/login')"),isPrivate:zod.z.boolean().describe("Whether this page requires an authenticated session"),api:zod.z.array(jn).describe("List of API calls involved in this page"),fields:zod.z.array(at).optional().describe("Optional form fields needed on this auth page")}),Fn=zod.z.object({type:zod.z.literal("Listing").describe("Indicates that this page is a listing-type page"),name:zod.z.string().describe("Internal name of the listing page"),route:zod.z.string().describe("URL route for this listing page"),isPrivate:zod.z.boolean().describe("Whether this page is private (requires auth)"),api:zod.z.array(In).describe("List of API calls that power this listing page"),columns:zod.z.array(Fo).describe("Table columns displayed on the listing page"),actions:zod.z.array(zod.z.string()).describe("List of possible actions on each row (e.g., create, edit, delete, view)"),drawerCreate:Uo.describe("Drawer configuration for creating new records"),drawerUpdate:Uo.describe("Drawer configuration for editing existing records")}),Go=zod.z.discriminatedUnion("type",[qn,Fn]);var Un=zod.z.object({name:zod.z.string().describe("Name of the module"),pages:zod.z.array(Go).describe("Pages included within this module")}),Ue=zod.z.object({app:qo.describe("Overall application configuration"),modules:zod.z.array(Un).describe("List of modules that make up the application. Ensure all modules use every available CRUD GraphQL query and mutation from the schema.")});var Qa=zod.z.object({email:zod.z.email().describe("User's email address, must be valid format"),password:zod.z.string().min(8).describe("User's password, minimum length of 8")}),Ln=zod.z.object({_id:zod.z.string().describe("Unique identifier of the specialization, type: string"),title:zod.z.string().describe("Display title for the specialization, type: string")}),Va=zod.z.object({_id:zod.z.string().describe("Unique ID of the user, type: string"),firstName:zod.z.string().min(2).max(30).describe("First name, 2-30 characters, type: string"),lastName:zod.z.string().min(2).max(30).describe("Last name, 2-30 characters, type: string"),email:zod.z.email().describe("Email address in valid format, type: string"),phoneNumber:zod.z.string().min(10).describe("User's phone number, at least 10 digits, type: string"),profileImage:zod.z.string().optional().describe("Optional URL to user's profile image, type: string, optional"),role:zod.z.enum(["ADMIN","TRAINER","CLIENT"]).describe("User's role in the system (ADMIN, TRAINER, CLIENT)"),rate:zod.z.number().min(1).optional().describe("User's rate (e.g., hourly, etc.), type: number, optional"),specializations:zod.z.array(Ln).optional().describe("Array of specialization objects, optional"),languages:zod.z.array(zod.z.string()).optional().describe("Array of languages the user speaks, type: string[], optional"),about:zod.z.string().min(20).max(500).optional().describe("Brief bio or description (20-500 chars), type: string, optional"),gender:zod.z.string().optional().describe("User's gender, type: string, optional"),timezone:zod.z.string().optional().describe("User's timezone, type: string, optional"),averageRating:zod.z.number().optional().describe("Average rating for this user, type: number, optional")}),Wa=zod.z.object({firstName:zod.z.string().min(2).max(30).describe("First name, 2-30 characters, type: string"),lastName:zod.z.string().min(2).max(30).describe("Last name, 2-30 characters, type: string"),email:zod.z.email().describe("Valid email for the new user, type: string"),phoneNumber:zod.z.string().min(10).describe("Phone number (at least 10 digits), type: string"),password:zod.z.string().min(8).describe("Password with min length 8, type: string"),role:zod.z.enum(["ADMIN","TRAINER","CLIENT"]).describe("Role of the new user (ADMIN, TRAINER, CLIENT)"),rate:zod.z.number().min(1).optional().describe("Rate for the new user, type: number, optional"),specializationIds:zod.z.array(zod.z.string()).min(1).optional().describe("Array of specialization IDs, optional"),languages:zod.z.array(zod.z.string()).min(1).optional().describe("List of languages user speaks, optional"),about:zod.z.string().min(20).max(500).optional().describe("User's about/bio field, 20-500 chars, optional")}),Ka=zod.z.object({_id:zod.z.string().describe("ID of the user to be updated, type: string"),firstName:zod.z.string().min(2).max(30).optional().describe("Updated first name, type: string, optional"),lastName:zod.z.string().min(2).max(30).optional().describe("Updated last name, type: string, optional"),email:zod.z.email().optional().describe("Updated email, type: string, optional"),phoneNumber:zod.z.string().min(10).optional().describe("Updated phone number, at least 10 digits, optional"),rate:zod.z.number().min(1).optional().describe("Updated rate, type: number, optional"),specializationIds:zod.z.array(zod.z.string()).min(1).optional().describe("Updated array of specialization IDs, optional"),languages:zod.z.array(zod.z.string()).min(1).optional().describe("Updated list of languages, optional"),about:zod.z.string().min(20).max(500).optional().describe("Updated about/bio (20-500 chars), optional")}),Xa=zod.z.object({email:zod.z.email().describe("Email to initiate the password reset process, type: string")}),Za=zod.z.object({type:zod.z.enum(["EMAIL","SMS"]).describe("How the reset code was sent (EMAIL or SMS)"),resetTicket:zod.z.string().describe("Token/ticket to validate the reset request, type: string"),newPassword:zod.z.string().min(8).describe("The new password, min length 8, type: string")});var Le=`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.
|
|
5
|
-
|
|
6
|
-
## Target Tech Stack
|
|
7
|
-
The generated configuration will be consumed by a Vite + React 19 + TypeScript template with:
|
|
8
|
-
- **UI Components**: ShadCN UI (Radix-based) from src/components/ui/
|
|
9
|
-
- **Styling**: Tailwind CSS v4 with OKLCH color space
|
|
10
|
-
- **Routing**: React Router v7 with private route support
|
|
11
|
-
- **Forms**: React Hook Form + Zod validation (zodResolver)
|
|
12
|
-
- **GraphQL Client**: Apollo Client with typed hooks from CodeGen
|
|
13
|
-
- **Path Aliases**: @/{appName}/* maps to ./src/*
|
|
14
|
-
|
|
15
|
-
**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).
|
|
16
|
-
|
|
17
|
-
Strict guidelines:
|
|
18
|
-
- Use every available CRUD GraphQL query and mutation from the project schema.
|
|
19
|
-
- Map GraphQL types to frontend modules and pages.
|
|
20
|
-
- EmailAddress \u2192 "type": "email" with validation; DateTime \u2192 "type": "date"; enums \u2192 select with options.values.
|
|
21
|
-
- Relationships \u2192 multiSelect with query-based options where appropriate.
|
|
22
|
-
- Add isPrivate: true for authenticated operations (route guarded by React Router).
|
|
23
|
-
- Form fields should map to React Hook Form + Zod validation schemas.
|
|
24
|
-
- Maintain camelCase. Ensure valid JSON syntax.`;var it=`
|
|
25
|
-
Act as an expert GraphQL-to-frontend configuration converter. Transform the provided schema into a structured JSON configuration for rapid app development.
|
|
26
|
-
|
|
27
|
-
**Conversion Process**
|
|
28
|
-
|
|
29
|
-
1. Schema Analysis:
|
|
30
|
-
- Identify all modules using 100% of available CRUD operations
|
|
31
|
-
- Catalog all Query/Mutation operations with arguments
|
|
32
|
-
- Map GraphQL types to frontend modules
|
|
33
|
-
- Detect @auth directives and role requirements
|
|
34
|
-
- Analyze relationships through nested types
|
|
35
|
-
|
|
36
|
-
2. Field Mapping:
|
|
37
|
-
- EmailAddress \u2192 "type": "email" with Zod email validation
|
|
38
|
-
- DateTime \u2192 "type": "date"
|
|
39
|
-
- Enums \u2192 dropdowns with options.values
|
|
40
|
-
- Relationships \u2192 multiSelect with query-based options
|
|
41
|
-
|
|
42
|
-
3. API Operations:
|
|
43
|
-
- For each Query/Mutation: determine CRUD type, generate query string with variables, map to React Hook, define response type shape
|
|
44
|
-
|
|
45
|
-
4. Validation:
|
|
46
|
-
- Generate Zod schemas from @required directives, scalar types (Password \u2192 min 8 chars), custom directives
|
|
47
|
-
- Include validation error messages
|
|
48
|
-
|
|
49
|
-
5. Security:
|
|
50
|
-
- Add isPrivate: true for authenticated operations
|
|
51
|
-
- Implement role checks from @auth directives
|
|
52
|
-
|
|
53
|
-
6. Output:
|
|
54
|
-
- Generate complete CRUD pages with table column mappings, validated Create/Update forms, API hooks
|
|
55
|
-
- Include Zod validation strings, maintain camelCase, valid JSON only
|
|
56
|
-
`.trim();function Jo(){return it}var Gn=`
|
|
57
|
-
type Query {
|
|
58
|
-
getCurrentUser: User
|
|
59
|
-
getAllUser(limit: Int, offset: Int): [User]!
|
|
60
|
-
}
|
|
61
|
-
type Mutation {
|
|
62
|
-
login(data: LoginInput!): Login!
|
|
63
|
-
createUser(data: CreateUserInput!): User!
|
|
64
|
-
}
|
|
65
|
-
type User {
|
|
66
|
-
_id: ID!
|
|
67
|
-
firstName: String!
|
|
68
|
-
lastName: String!
|
|
69
|
-
email: String!
|
|
70
|
-
role: Role!
|
|
71
|
-
}
|
|
72
|
-
enum Role { ADMIN TRAINER CLIENT }
|
|
73
|
-
input LoginInput { email: String! password: String! }
|
|
74
|
-
input CreateUserInput { firstName: String! lastName: String! email: String! role: Role! }
|
|
75
|
-
`.trim(),Jn=`{
|
|
76
|
-
"app": {
|
|
77
|
-
"name": "my-app",
|
|
78
|
-
"description": "App description",
|
|
79
|
-
"author": "Author",
|
|
80
|
-
"branding": {
|
|
81
|
-
"brandName": "MyBrand",
|
|
82
|
-
"primaryColor": "#333",
|
|
83
|
-
"secondaryColor": "#fff",
|
|
84
|
-
"logo": "https://example.com/logo.png"
|
|
85
|
-
},
|
|
86
|
-
"apiEndpoint": "http://localhost:4000/graphql"
|
|
87
|
-
},
|
|
88
|
-
"modules": [
|
|
89
|
-
{
|
|
90
|
-
"name": "auth",
|
|
91
|
-
"pages": [
|
|
92
|
-
{
|
|
93
|
-
"name": "LoginPage",
|
|
94
|
-
"type": "EmailPassword",
|
|
95
|
-
"route": "/login",
|
|
96
|
-
"isPrivate": false,
|
|
97
|
-
"api": [
|
|
98
|
-
{ "type": "login", "graphqlHook": "useLoginMutation", "queryString": "mutation Login($data: LoginInput!) { login(data: $data) { accessToken } }" }
|
|
99
|
-
]
|
|
100
|
-
}
|
|
101
|
-
]
|
|
102
|
-
},
|
|
103
|
-
{
|
|
104
|
-
"name": "user",
|
|
105
|
-
"pages": [
|
|
106
|
-
{
|
|
107
|
-
"type": "Listing",
|
|
108
|
-
"name": "UserListPage",
|
|
109
|
-
"route": "/users",
|
|
110
|
-
"isPrivate": true,
|
|
111
|
-
"api": [
|
|
112
|
-
{ "type": "list", "graphqlHook": "useGetAllUserQuery", "queryString": "query GetAllUser { getAllUser { _id firstName email } }" },
|
|
113
|
-
{ "type": "create", "graphqlHook": "useCreateUserMutation", "queryString": "mutation CreateUser($data: CreateUserInput!) { createUser(data: $data) { _id } }" }
|
|
114
|
-
],
|
|
115
|
-
"columns": [{ "field": "firstName", "label": "First Name" }, { "field": "email", "label": "Email" }],
|
|
116
|
-
"actions": ["create", "edit", "delete"],
|
|
117
|
-
"drawerCreate": { "title": "Create User", "graphqlHook": "useCreateUserMutation", "fields": [{ "name": "firstName", "type": "text", "required": true }, { "name": "email", "type": "email", "required": true }] },
|
|
118
|
-
"drawerUpdate": { "title": "Edit User", "graphqlHook": "useUpdateUserMutation", "fields": [{ "name": "firstName", "type": "text" }, { "name": "email", "type": "email" }] }
|
|
119
|
-
}
|
|
120
|
-
]
|
|
121
|
-
}
|
|
122
|
-
]
|
|
123
|
-
}`;function Bo(){return `
|
|
124
|
-
**Reference Conversion Example**
|
|
125
|
-
|
|
126
|
-
EXAMPLE GRAPHQL INPUT:
|
|
127
|
-
\`\`\`graphql
|
|
128
|
-
${Gn}
|
|
129
|
-
\`\`\`
|
|
130
|
-
|
|
131
|
-
EXPECTED JSON OUTPUT:
|
|
132
|
-
\`\`\`json
|
|
133
|
-
${Jn}
|
|
134
|
-
\`\`\`
|
|
135
|
-
`.trim()}function ei(t,e){return `
|
|
136
|
-
Review the user feedback carefully to understand the required updates.
|
|
137
|
-
|
|
138
|
-
The user feedback for updating the generated Frontend Config JSON is provided below:
|
|
139
|
-
"""
|
|
140
|
-
${t}
|
|
141
|
-
"""
|
|
142
|
-
|
|
143
|
-
Now, generate the Frontend Config JSON for this project based on the provided feedback.
|
|
144
|
-
|
|
145
|
-
**Project GRAPHQL SCHEMA INPUT:**
|
|
146
|
-
\`\`\`graphql
|
|
147
|
-
${e}
|
|
148
|
-
\`\`\`
|
|
149
|
-
|
|
150
|
-
Update the Frontend Config JSON to incorporate the requested changes. Return ONLY valid JSON, no markdown code blocks.
|
|
151
|
-
`.trim()}var Pe=q("validate_frontend_config",Ue,"Validates a frontend configuration JSON string against the ApplicationSchema. Returns valid: true or valid: false with errors array.","config");function ti(t,e){let o=Jo(),r=Bo(),n=e?`
|
|
152
|
-
**Project context:**
|
|
153
|
-
- name: ${e.projectName??"project"}
|
|
154
|
-
- description: ${e.projectDescription??""}
|
|
155
|
-
- modules: ${e.modules??""}
|
|
156
|
-
- apiEndpoint: ${e.apiEndpoint??"http://localhost:4000/graphql"}
|
|
157
|
-
`:"";return `${o}
|
|
158
|
-
|
|
159
|
-
${r}
|
|
160
|
-
${n}
|
|
161
|
-
|
|
162
|
-
**Current Project GraphQL Schema:**
|
|
163
|
-
\`\`\`graphql
|
|
164
|
-
${t}
|
|
165
|
-
\`\`\`
|
|
166
|
-
|
|
167
|
-
Generate the Frontend Config JSON. Use every available CRUD GraphQL query and mutation. Return ONLY valid JSON.`}function lt(t){return h({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:zod.z.object({graphqlSchema:zod.z.string().describe("The GraphQL schema string to convert"),appInfo:zod.z.object({projectName:zod.z.string().optional(),projectDescription:zod.z.string().optional(),modules:zod.z.string().optional(),apiEndpoint:zod.z.string().optional()}).optional().describe("Optional project/app context")}),handler:async({graphqlSchema:e,appInfo:o})=>{let r=ti(e,o),n=[{role:"system",content:Le},{role:"user",content:r}],a=await t.invoke(n,{temperature:.2,maxOutputTokens:16384});return M(a.text,Ue)}})}function ct(t){return h({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:zod.z.object({graphqlSchema:zod.z.string().describe("The GraphQL schema string to analyze")}),handler:async({graphqlSchema:e})=>{let o=`${it}
|
|
168
|
-
|
|
169
|
-
**Schema to analyze:**
|
|
170
|
-
\`\`\`graphql
|
|
171
|
-
${e}
|
|
172
|
-
\`\`\`
|
|
173
|
-
|
|
174
|
-
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 t.invoke(r,{temperature:.3,maxOutputTokens:4096})).text,modules:[],operations:[],suggestedPages:[]}}})}function oi(t){return {appName:t.app.name,description:t.app.description,apiEndpoint:t.app.apiEndpoint,branding:{brandName:t.app.branding.brandName,primaryColor:t.app.branding.primaryColor,secondaryColor:t.app.branding.secondaryColor,logo:t.app.branding.logo},modules:t.modules.map(e=>({name:e.name,pascalName:e.name.charAt(0).toUpperCase()+e.name.slice(1),camelName:e.name.charAt(0).toLowerCase()+e.name.slice(1)})),author:t.app.author,pages:t.modules.flatMap(e=>e.pages)}}var zo=h({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:zod.z.object({config:zod.z.string().describe("JSON string of the validated ApplicationSchema config"),outputDir:zod.z.string().describe("Absolute path to the output directory")}),handler:async({config:t,outputDir:e})=>{let o=be(t,"application schema config"),r=Te__namespace.resolve(process.cwd(),".ref/templates/vite"),n=oi(o);return le({templateDir:r,outputDir:e,context:n})}});function $o(t){return {validate_frontend_config:Pe,generate_frontend:lt(t),generate_feature_breakdown:ct(t),scaffold_vite:zo}}var ri=`You are an expert at analyzing GraphQL schemas. Your job is to:
|
|
175
|
-
|
|
176
|
-
1. **Types**: List all object types, enums, scalars, and input types.
|
|
177
|
-
2. **Queries**: List every Query field with arguments and return type.
|
|
178
|
-
3. **Mutations**: List every Mutation field with arguments and return type.
|
|
179
|
-
4. **Relationships**: Identify types that reference other types (e.g. User has role: Role, or Order has customer: User).
|
|
180
|
-
5. **Auth/directives**: Note any @auth, @directive usage that affects access control.
|
|
181
|
-
|
|
182
|
-
Respond with a clear, structured analysis (headings and bullet points). The user will use this to generate a frontend configuration.`,pt=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:ri,tools:{},maxIterations:2});var ni=`You are a frontend configuration validator. Your job is to:
|
|
183
|
-
|
|
184
|
-
1. Validate the provided frontend config JSON using the validate_frontend_config tool.
|
|
185
|
-
2. Compare the config against the GraphQL schema (if provided) and check that all CRUD operations are covered.
|
|
186
|
-
3. Report any missing modules, pages, or API hooks.
|
|
187
|
-
|
|
188
|
-
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 dt(){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:ni,tools:{validate_frontend_config:Pe},maxIterations:5})}var si=`${Le}
|
|
189
|
-
|
|
190
|
-
You are the React frontend builder orchestrator. When the user provides a GraphQL schema and asks for a frontend configuration:
|
|
191
|
-
|
|
192
|
-
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.
|
|
193
|
-
2. **Generate**: Use generate_frontend with the GraphQL schema (and optional appInfo) to produce the frontend config JSON.
|
|
194
|
-
3. **Validate (optional)**: Use subagent_config-validator with the generated config (and schema) to check structure and completeness.
|
|
195
|
-
4. **Validate directly**: You can use validate_frontend_config to check any config JSON.
|
|
196
|
-
5. **Feature breakdown**: Use generate_feature_breakdown to get a module/operation breakdown before generating.
|
|
197
|
-
|
|
198
|
-
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 ai(t){let{input:e,model:o,maxIterations:r=15,onStep:n,logger:a}=t,s=v(o??{provider:"openai",model:"gpt-4o-mini"}),i=$o(s),l=dt(),c=I([pt,l],{parentModel:s}),p={...i,...c};return C({model:s,tools:p,systemPrompt:si,input:e,maxIterations:r,onStep:n,logger:a})}var Re=zod.z.object({id:zod.z.string(),name:zod.z.string(),description:zod.z.string(),goals:zod.z.array(zod.z.string())}),ut=zod.z.object({actors:zod.z.array(Re),message:zod.z.string()});var we=zod.z.object({id:zod.z.string(),actorId:zod.z.string(),name:zod.z.string(),description:zod.z.string(),trigger:zod.z.string(),outcome:zod.z.string()}),mt=zod.z.object({flows:zod.z.array(we),message:zod.z.string()});var ve=zod.z.object({id:zod.z.string(),flowId:zod.z.string(),actor:zod.z.string(),action:zod.z.string(),benefit:zod.z.string(),preconditions:zod.z.array(zod.z.string()),postconditions:zod.z.array(zod.z.string()),dataInvolved:zod.z.array(zod.z.string())}),gt=zod.z.object({stories:zod.z.array(ve),message:zod.z.string()});var zn=zod.z.object({id:zod.z.string(),name:zod.z.string(),operation:zod.z.enum(["create","read","readAll","update","delete"]),description:zod.z.string(),inputs:zod.z.array(zod.z.string()),outputs:zod.z.array(zod.z.string())}),Ee=zod.z.object({id:zod.z.string(),name:zod.z.string(),description:zod.z.string(),entity:zod.z.string(),apis:zod.z.array(zn)}),ft=zod.z.object({modules:zod.z.array(Ee),summary:zod.z.object({totalModules:zod.z.number(),totalApis:zod.z.number()}),message:zod.z.string()});var $n=zod.z.object({name:zod.z.string(),type:zod.z.string(),required:zod.z.boolean(),unique:zod.z.boolean(),description:zod.z.string(),default:zod.z.string().optional()}),Hn=zod.z.object({name:zod.z.string(),fields:zod.z.array(zod.z.string()),unique:zod.z.boolean()}),Qn=zod.z.object({field:zod.z.string(),references:zod.z.string(),description:zod.z.string()}),Vn=zod.z.object({name:zod.z.string(),description:zod.z.string(),fields:zod.z.array($n),indexes:zod.z.array(Hn),relations:zod.z.array(Qn)}),me=zod.z.object({type:zod.z.enum(["mongodb","postgresql"]),reasoning:zod.z.string(),entities:zod.z.array(Vn)});var Ae=zod.z.object({name:zod.z.string(),goal:zod.z.string(),features:zod.z.array(zod.z.string()),domain:zod.z.string(),database:zod.z.enum(["mongodb","postgresql"]),backendRuntime:zod.z.literal("nodejs"),apiStyle:zod.z.enum(["rest","graphql"])}),ht=zod.z.object({id:zod.z.string(),question:zod.z.string(),context:zod.z.string(),suggestions:zod.z.array(zod.z.string()),multiSelect:zod.z.boolean(),required:zod.z.boolean()}),Wn=zod.z.object({role:zod.z.enum(["user","assistant"]),content:zod.z.string()}),ii=zod.z.object({stage:zod.z.enum(["discovery","requirements","design","complete"]),projectBrief:Ae.nullable(),actors:zod.z.array(Re),flows:zod.z.array(we),stories:zod.z.array(ve),modules:zod.z.array(Ee),database:me.nullable(),history:zod.z.array(Wn),pendingQuestions:zod.z.array(ht)});var Kn=zod.z.object({totalActors:zod.z.number(),totalFlows:zod.z.number(),totalStories:zod.z.number(),totalModules:zod.z.number(),totalEntities:zod.z.number(),overview:zod.z.string()}),Ho=zod.z.object({project:Ae,actors:zod.z.array(Re),flows:zod.z.array(we),stories:zod.z.array(ve),modules:zod.z.array(Ee),database:me,summary:Kn});var ge=`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.
|
|
199
|
-
|
|
200
|
-
You work in stages: discovery (understand the project and tech preferences), requirements (actors, flows, stories, modules), design (database + APIs), and complete (final document).
|
|
201
|
-
|
|
202
|
-
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.
|
|
203
|
-
|
|
204
|
-
Guidelines:
|
|
205
|
-
- For tech choices (API style: REST vs GraphQL; database: MongoDB vs PostgreSQL), offer predefined options and ask what the user is comfortable with.
|
|
206
|
-
- For everything else, ask open-ended, context-specific questions based on what the user described. Leave suggestions empty for those.
|
|
207
|
-
- Never repeat a question already answered in the conversation history.
|
|
208
|
-
- When the user says "continue", "yes", "looks good", or similar, treat it as confirmation and advance.
|
|
209
|
-
- Return valid JSON only when the prompt asks for JSON (no markdown code fences unless specified).
|
|
210
|
-
- Backend is Node.js only; database is MongoDB or PostgreSQL per user preference.`;var Qo=`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.
|
|
211
|
-
|
|
212
|
-
Determine from the user's words:
|
|
213
|
-
- Project name and goal
|
|
214
|
-
- Key features (array of strings)
|
|
215
|
-
- Domain (e.g. e-commerce, healthcare, saas)
|
|
216
|
-
- API style: "rest" | "graphql" \u2014 infer from context or ask with predefined options
|
|
217
|
-
- Database: "mongodb" | "postgresql" \u2014 ask which they are comfortable with, with predefined options
|
|
218
|
-
- Backend is always "nodejs"
|
|
219
|
-
|
|
220
|
-
Question rules:
|
|
221
|
-
- Tech stack (API style, database): Always provide "suggestions" with predefined options (e.g. ["REST", "GraphQL"], ["MongoDB", "PostgreSQL"]). Frame as "which are you comfortable with?"
|
|
222
|
-
- 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).
|
|
223
|
-
- Never ask: scale, "how many users?", "what's the complexity?", or generic intake-form questions.
|
|
224
|
-
- Before asking, check conversation history \u2014 never repeat something already answered.
|
|
225
|
-
- 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.`,Xn=`## Current user message:
|
|
226
|
-
{userMessage}
|
|
227
|
-
|
|
228
|
-
## Prior conversation (if any):
|
|
229
|
-
{history}
|
|
230
|
-
|
|
231
|
-
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.
|
|
232
|
-
|
|
233
|
-
Return ONLY valid JSON (no markdown, no explanation) in this shape:
|
|
234
|
-
{
|
|
235
|
-
"needsClarification": boolean,
|
|
236
|
-
"questions": [
|
|
237
|
-
{
|
|
238
|
-
"id": "q1",
|
|
239
|
-
"question": "Question text",
|
|
240
|
-
"context": "Why this helps",
|
|
241
|
-
"suggestions": [],
|
|
242
|
-
"multiSelect": false,
|
|
243
|
-
"required": true
|
|
244
|
-
}
|
|
245
|
-
],
|
|
246
|
-
"conversationalMessage": "Brief friendly message to the user",
|
|
247
|
-
"projectBrief": {
|
|
248
|
-
"name": "string",
|
|
249
|
-
"goal": "string",
|
|
250
|
-
"features": ["string"],
|
|
251
|
-
"domain": "string",
|
|
252
|
-
"database": "mongodb" | "postgresql",
|
|
253
|
-
"backendRuntime": "nodejs",
|
|
254
|
-
"apiStyle": "rest" | "graphql"
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
For tech choices (API style, database), populate "suggestions" with the predefined options. For all other questions, use "suggestions": [].
|
|
259
|
-
If needsClarification is true, projectBrief can have empty/default values. If false, projectBrief must be complete.`;function Vo(t,e){return Xn.replace("{userMessage}",t).replace("{history}",e||"(No prior messages)")}var yt=`## Project:
|
|
260
|
-
- **Name**: {projectName}
|
|
261
|
-
- **Goal**: {projectGoal}
|
|
262
|
-
- **Features**: {projectFeatures}`,Zn=`${yt}
|
|
263
|
-
|
|
264
|
-
Identify ALL distinct user types (actors) who will use this system. 2-5 actors. Include unauthenticated and admin roles if applicable.
|
|
265
|
-
|
|
266
|
-
Return ONLY valid JSON:
|
|
267
|
-
{
|
|
268
|
-
"actors": [
|
|
269
|
-
{ "id": "actor-1", "name": "Name", "description": "Who they are", "goals": ["goal1", "goal2"] }
|
|
270
|
-
],
|
|
271
|
-
"message": "Brief explanation"
|
|
272
|
-
}`,es=`${yt}
|
|
273
|
-
|
|
274
|
-
## Actors (JSON):
|
|
275
|
-
{actors}
|
|
276
|
-
|
|
277
|
-
For EACH actor, identify 2-5 key user journeys (flows). Each flow: id, actorId, name, description, trigger, outcome.
|
|
278
|
-
|
|
279
|
-
Return ONLY valid JSON:
|
|
280
|
-
{
|
|
281
|
-
"flows": [
|
|
282
|
-
{ "id": "flow-1", "actorId": "actor-1", "name": "Flow Name", "description": "...", "trigger": "...", "outcome": "..." }
|
|
283
|
-
],
|
|
284
|
-
"message": "Brief explanation"
|
|
285
|
-
}`,ts=`${yt}
|
|
286
|
-
|
|
287
|
-
## Actors: {actors}
|
|
288
|
-
|
|
289
|
-
## Flows (JSON):
|
|
290
|
-
{flows}
|
|
291
|
-
|
|
292
|
-
For EACH flow, generate 2-5 user stories. Each story MUST include dataInvolved (entity.field names) for DB design. Include preconditions, postconditions.
|
|
293
|
-
|
|
294
|
-
Return ONLY valid JSON:
|
|
295
|
-
{
|
|
296
|
-
"stories": [
|
|
297
|
-
{ "id": "story-1", "flowId": "flow-1", "actor": "ActorName", "action": "...", "benefit": "...", "preconditions": [], "postconditions": [], "dataInvolved": ["User.email", "Order.total"] }
|
|
298
|
-
],
|
|
299
|
-
"message": "Brief explanation"
|
|
300
|
-
}`,os=`${yt}
|
|
301
|
-
|
|
302
|
-
## Actors: {actors}
|
|
303
|
-
## Flows: {flows}
|
|
304
|
-
## Stories (JSON):
|
|
305
|
-
{stories}
|
|
306
|
-
|
|
307
|
-
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.
|
|
308
|
-
|
|
309
|
-
Return ONLY valid JSON:
|
|
310
|
-
{
|
|
311
|
-
"modules": [
|
|
312
|
-
{ "id": "module-1", "name": "User", "description": "...", "entity": "User", "apis": [ { "id": "api-1-1", "name": "createUser", "operation": "create", "description": "...", "inputs": [], "outputs": [] } ] }
|
|
313
|
-
],
|
|
314
|
-
"summary": { "totalModules": 0, "totalApis": 0 },
|
|
315
|
-
"message": "Brief explanation"
|
|
316
|
-
}`;function Wo(t,e,o){return Zn.replace("{projectName}",t).replace("{projectGoal}",e).replace("{projectFeatures}",o)}function Ko(t,e,o,r){return es.replace("{projectName}",t).replace("{projectGoal}",e).replace("{projectFeatures}",o).replace("{actors}",r)}function Xo(t,e,o,r,n){return ts.replace("{projectName}",t).replace("{projectGoal}",e).replace("{projectFeatures}",o).replace("{actors}",r).replace("{flows}",n)}function Zo(t,e,o,r,n,a){return os.replace("{projectName}",t).replace("{projectGoal}",e).replace("{projectFeatures}",o).replace("{actors}",r).replace("{flows}",n).replace("{stories}",a)}var li=`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.
|
|
317
|
-
|
|
318
|
-
## Project brief (includes database: "mongodb" | "postgresql"):
|
|
319
|
-
{projectBrief}
|
|
320
|
-
|
|
321
|
-
## Modules (entities and CRUD):
|
|
322
|
-
{modules}
|
|
323
|
-
|
|
324
|
-
## User stories (data involved):
|
|
325
|
-
{stories}
|
|
326
|
-
|
|
327
|
-
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.
|
|
328
|
-
|
|
329
|
-
Return ONLY valid JSON (no markdown) in this exact shape. Set "type" to the database from the project brief.
|
|
330
|
-
{
|
|
331
|
-
"type": "mongodb" | "postgresql",
|
|
332
|
-
"reasoning": "2-4 sentences on how the schema fits the project",
|
|
333
|
-
"entities": [
|
|
334
|
-
{
|
|
335
|
-
"name": "EntityName",
|
|
336
|
-
"description": "Brief description",
|
|
337
|
-
"fields": [
|
|
338
|
-
{ "name": "fieldName", "type": "DB-native type", "required": true, "unique": false, "description": "..." }
|
|
339
|
-
],
|
|
340
|
-
"indexes": [ { "name": "index_name", "fields": ["field1"], "unique": false } ],
|
|
341
|
-
"relations": [ { "field": "refField", "references": "OtherEntity", "description": "..." } ]
|
|
342
|
-
}
|
|
343
|
-
]
|
|
344
|
-
}`;var er="You output only valid JSON. No markdown, no explanation.";function tr(t,e,o){return li.replace("{projectBrief}",t).replace("{modules}",e).replace("{stories}",o)}var or="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.",rs=`## Project brief (JSON):
|
|
345
|
-
{projectBrief}
|
|
346
|
-
|
|
347
|
-
## Actors (JSON):
|
|
348
|
-
{actors}
|
|
349
|
-
|
|
350
|
-
## Flows (JSON):
|
|
351
|
-
{flows}
|
|
352
|
-
|
|
353
|
-
## Stories (JSON):
|
|
354
|
-
{stories}
|
|
355
|
-
|
|
356
|
-
## Modules (JSON):
|
|
357
|
-
{modules}
|
|
358
|
-
|
|
359
|
-
## Database design (JSON):
|
|
360
|
-
{database}
|
|
361
|
-
|
|
362
|
-
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).
|
|
363
|
-
|
|
364
|
-
Return ONLY valid JSON in this shape (no markdown, no extra text):
|
|
365
|
-
{
|
|
366
|
-
"project": { ... },
|
|
367
|
-
"actors": [ ... ],
|
|
368
|
-
"flows": [ ... ],
|
|
369
|
-
"stories": [ ... ],
|
|
370
|
-
"modules": [ ... ],
|
|
371
|
-
"database": { ... },
|
|
372
|
-
"summary": {
|
|
373
|
-
"totalActors": 0,
|
|
374
|
-
"totalFlows": 0,
|
|
375
|
-
"totalStories": 0,
|
|
376
|
-
"totalModules": 0,
|
|
377
|
-
"totalEntities": 0,
|
|
378
|
-
"overview": "string"
|
|
379
|
-
}
|
|
380
|
-
}`;function rr(t,e,o,r,n,a){return rs.replace("{projectBrief}",t).replace("{actors}",e).replace("{flows}",o).replace("{stories}",r).replace("{modules}",n).replace("{database}",a)}function nr(){return {stage:"discovery",projectBrief:null,actors:[],flows:[],stories:[],modules:[],database:null,history:[],pendingQuestions:[]}}function sr(t,e){let o=e.data;return {...t,...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 Ge(t,e,o){let r={role:e,content:o};return {...t,history:[...t.history,r]}}function St(t){let e=["discovery","requirements","design","complete"],o=e.indexOf(t.stage),n=(o>=0&&o<e.length-1?e[o+1]:void 0)??t.stage;return {...t,stage:n}}function ns(t){return t.map(e=>`${e.name}: ${e.entity} (${e.apis.length} APIs)`).join(`
|
|
381
|
-
`)}function ss(t){return t.map(e=>`- ${e.actor}: ${e.action}`).join(`
|
|
382
|
-
`)}function Q(t){let e=t.trim(),o=/```(?:json)?\s*([\s\S]*?)```/.exec(e);return o?.[1]?o[1].trim():e}function V(t){try{return {success:!0,data:JSON.parse(t)}}catch(e){return {success:false,error:e instanceof Error?e.message:String(e)}}}async function bt(t,e,o,r){r?.debug("Discovery stage started",{historyLength:e.history.length});let n=e.history.map(L=>`${L.role}: ${L.content}`).slice(-10).join(`
|
|
383
|
-
`),a=Vo(t,n),i=[{role:"system",content:`${ge}
|
|
384
|
-
|
|
385
|
-
${Qo}`},{role:"user",content:a}],l=await o.invoke(i,{temperature:.4,maxOutputTokens:4096}),c=Q(l.text),p=V(c);if(!p.success)return r?.warn("Discovery response was not valid JSON",{error:p.error}),{message:"I couldn't parse that. Could you describe your project in a few sentences?",advance:false,data:{}};let d=p.data,u=d.conversationalMessage??l.text?.slice(0,500)??"Thanks for the details.",y=d.needsClarification===true,m=[];if(Array.isArray(d.questions))for(let L of d.questions){let j=ht.safeParse(L);j.success&&m.push(j.data);}let B=null;if(d.projectBrief&&!y){let L=Ae.safeParse(d.projectBrief);L.success&&(B=L.data);}return r?.debug("Discovery stage complete",{advance:!y&&B!==null,hasProjectBrief:!!B,questionsCount:m.length}),{message:u,questions:m.length?m:void 0,advance:!y&&B!==null,data:{...B&&{projectBrief:B},pendingQuestions:m}}}async function as(t,e,o){if(t.invokeObject)return (await t.invokeObject(e,ut,{temperature:.4,maxOutputTokens:4096})).data;let r=await t.invoke(e,{temperature:.4,maxOutputTokens:4096}),n=V(Q(r.text));if(!n.success)throw new Error(`Actors: ${n.error}`);let a=ut.safeParse(n.data);if(!a.success)throw new Error(`Actors schema: ${a.error.message}`);return a.data}async function is(t,e,o,r){if(t.invokeObject)return (await t.invokeObject(e,mt,{temperature:.4,maxOutputTokens:8192})).data;let n=await t.invoke(e,{temperature:.4,maxOutputTokens:8192}),a=V(Q(n.text));if(!a.success)throw new Error(`Flows: ${a.error}`);let s=mt.safeParse(a.data);if(!s.success)throw new Error(`Flows schema: ${s.error.message}`);return s.data}async function ls(t,e,o,r,n){if(t.invokeObject)return (await t.invokeObject(e,gt,{temperature:.4,maxOutputTokens:16384})).data;let a=await t.invoke(e,{temperature:.4,maxOutputTokens:16384}),s=V(Q(a.text));if(!s.success)throw new Error(`Stories: ${s.error}`);let i=gt.safeParse(s.data);if(!i.success)throw new Error(`Stories schema: ${i.error.message}`);return i.data}async function cs(t,e,o,r,n,a){if(t.invokeObject)return (await t.invokeObject(e,ft,{temperature:.4,maxOutputTokens:16384})).data;let s=await t.invoke(e,{temperature:.4,maxOutputTokens:16384}),i=V(Q(s.text));if(!i.success)throw new Error(`Modules: ${i.error}`);let l=ft.safeParse(i.data);if(!l.success)throw new Error(`Modules schema: ${l.error.message}`);return l.data}async function xt(t,e,o,r){r?.debug("Requirements stage started");let n=e.projectBrief;if(!n)return {message:"Project brief is missing. Complete discovery first.",advance:false,data:{}};let a=n.name,s=n.goal,i=n.features.join(". "),l=[{role:"system",content:ge}];try{l.push({role:"user",content:Wo(a,s,i)});let p=(await as(o,l,r)).actors;r?.debug("Requirements: actors",{count:p.length}),l.push({role:"assistant",content:`[Extracted ${p.length} actors]`}),l.push({role:"user",content:Ko(a,s,i,JSON.stringify(p))});let u=(await is(o,l,p,r)).flows;r?.debug("Requirements: flows",{count:u.length}),l.push({role:"assistant",content:`[Generated ${u.length} flows]`}),l.push({role:"user",content:Xo(a,s,i,JSON.stringify(p),JSON.stringify(u))});let m=(await ls(o,l,p,u,r)).stories;r?.debug("Requirements: stories",{count:m.length}),l.push({role:"assistant",content:`[Generated ${m.length} stories]`}),l.push({role:"user",content:Zo(a,s,i,JSON.stringify(p),JSON.stringify(u),JSON.stringify(m))});let L=(await cs(o,l,p,u,m,r)).modules;return r?.debug("Requirements stage complete",{actors:p.length,flows:u.length,stories:m.length,modules:L.length}),{message:`I've identified ${p.length} actors, ${u.length} flows, ${m.length} stories, and ${L.length} modules. Proceeding to technical design.`,advance:!0,data:{actors:p,flows:u,stories:m,modules:L,pendingQuestions:[]}}}catch(c){let p=c instanceof Error?c.message:String(c);return r?.warn("Requirements stage failed",{error:p}),{message:`Requirements step failed: ${p}. Please try again.`,advance:false,data:{}}}}async function Tt(t,e,o,r){let n=e.projectBrief;if(!n)return {message:"Project brief is missing.",advance:false,data:{}};if(!e.modules.length||!e.stories.length)return {message:"Requirements (modules and stories) are missing. Run requirements stage first.",advance:false,data:{}};r?.info("Design stage: database design",{modules:e.modules.length,stories:e.stories.length});let a=JSON.stringify(n),s=ns(e.modules),i=ss(e.stories),l=tr(a,s,i),c=[{role:"system",content:er},{role:"user",content:l}],p=await o.invoke(c,{temperature:.3,maxOutputTokens:8192}),d=Q(p.text),u=V(d);if(!u.success)return r?.warn("Database design response was not valid JSON",{error:u.error}),{message:"Failed to parse database design response. Please try again.",advance:false,data:{}};let y=me.safeParse(u.data);if(!y.success){let B=y.error;return r?.warn("Database design schema validation failed",{error:zod.z.treeifyError(B)}),{message:"Failed to produce database design. Please try again.",advance:false,data:{}}}let m=y.data;return {message:`Database design complete: ${m.type}. API design will be handled by the api-designer module.`,advance:true,data:{database:m,pendingQuestions:[]}}}async function Pt(t,e,o,r){r?.debug("Synthesis stage started");let n=e.projectBrief;if(!n||!e.database)return {message:"Missing project brief or database design. Complete earlier stages first.",advance:false,data:{}};let a=rr(JSON.stringify(n),JSON.stringify(e.actors),JSON.stringify(e.flows),JSON.stringify(e.stories),JSON.stringify(e.modules),JSON.stringify(e.database)),i=[{role:"system",content:`${ge}
|
|
386
|
-
|
|
387
|
-
${or}`},{role:"user",content:a}],l=await o.invoke(i,{temperature:.3,maxOutputTokens:16384}),c=Q(l.text),p=V(c);if(!p.success)return r?.warn("Synthesis response was not valid JSON",{error:p.error}),{message:"Failed to compile final requirement document. Please try again.",advance:false,data:{}};let d=Ho.safeParse(p.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 u=d.data;return r?.info("Synthesis stage complete",{overview:u.summary?.overview}),{message:`Requirement document ready. ${u.summary.overview}`,advance:true,data:{finalRequirement:u}}}var Rt=class{stageName="discovery";async process(e,o){return bt(o.userMessage,e,o.model,o.logger)}canAdvance(e){return e.advance}getNextStageName(){return "requirements"}};var wt=class{stageName="requirements";async process(e,o){return xt(o.userMessage,e,o.model,o.logger)}canAdvance(e){return e.advance}getNextStageName(){return "design"}};var vt=class{stageName="design";async process(e,o){return Tt(o.userMessage,e,o.model,o.logger)}canAdvance(e){return e.advance}getNextStageName(){return "complete"}};var Et=class{stageName="complete";async process(e,o){return Pt(o.userMessage,e,o.model,o.logger)}canAdvance(e){return e.advance}getNextStageName(){return null}};var pi={discovery:new Rt,requirements:new wt,design:new vt,complete:new Et};function ar(t){return pi[t]}async function ps(t,e,o,r,n){n?.debug("Stage processor invoked",{stage:t});let s=await ar(t).process(o,{userMessage:e,model:r,logger:n}),i=sr(o,s),l="finalRequirement"in s.data?s.data.finalRequirement:void 0;n?.debug("Stage result",{stage:t,advance:s.advance,hasFinalRequirement:!!l});let c={...i,pendingQuestions:s.questions??i.pendingQuestions};return {message:s.message,questions:s.questions??i.pendingQuestions,advance:s.advance,data:c,finalRequirement:l}}var ir=["discovery","requirements","design","complete"];async function At(t,e,o){let{logger:r}=o,n=o.model??{provider:"openai",model:"gpt-4o-mini"},a=v(n),s=e??nr();s=Ge(s,"user",t),r?.info("Chat turn",{stage:s.stage,messageLength:t.length});let i="",l=[],c=null,p=async y=>{let m=await ps(y,t,s,a,r);return i=m.message,l=m.questions,s=m.data,m.finalRequirement&&(c=m.finalRequirement),{advance:m.advance,finalReq:m.finalRequirement}},d=s.stage;r?.info("Stage",{stage:d});let u=await p(d);for(s={...s,pendingQuestions:l};u.advance&&!c;){let y=ir.indexOf(d),m=y>=0&&y<ir.length-1?ir[y+1]:void 0;if(m===void 0)break;r?.info("Stage transition",{from:d,to:m}),d=m,s=St(s),s={...s,stage:d},r?.info("Stage",{stage:d}),u=await p(d),s={...s,pendingQuestions:l};}return s=Ge(s,"assistant",i),r?.info("Chat turn done",{stage:d,hasFinalRequirement:!!c}),{message:i,context:s,questions:l,finalRequirement:c}}var ds=10;async function ui(t){let{input:e,model:o,onStep:r,logger:n}=t;n?.info("Starting requirement gatherer agent",{maxTurns:ds});let a=null,s=await At(e,a,{model:o,logger:n});a=s.context;let i=1;for(;!s.finalRequirement&&i<ds;)n?.debug("Requirement gatherer turn",{turn:i}),s=await At("continue",a,{model:o,logger:n}),a=s.context,i++;let l=s.finalRequirement?JSON.stringify(s.finalRequirement,null,2):s.message,c=a.history.map(p=>({role:p.role,content:p.content}));return n?.info("Requirement gatherer agent completed",{turns:i,hasFinalRequirement:!!s.finalRequirement}),{output:l,steps:[],totalUsage:void 0,messages:c}}var mi="discovery",Mt=class{data={};withStage(e){return this.data.stage=e,this}withProjectBrief(e){return this.data.projectBrief=e,this}withActors(e){return this.data.actors=e,this}withFlows(e){return this.data.flows=e,this}withStories(e){return this.data.stories=e,this}withModules(e){return this.data.modules=e,this}withDatabase(e){return this.data.database=e,this}withHistory(e){return this.data.history=e,this}withPendingQuestions(e){return this.data.pendingQuestions=e,this}reset(){return this.data={},this}build(){return {stage:this.data.stage??mi,projectBrief:this.data.projectBrief??null,actors:this.data.actors??[],flows:this.data.flows??[],stories:this.data.stories??[],modules:this.data.modules??[],database:this.data.database??null,history:this.data.history??[],pendingQuestions:this.data.pendingQuestions??[]}}};function gi(){return new Mt}var fi={overview:null,techStack:null,featureDecisions:null,dataModels:null,pagesAndRoutes:null,authFlow:null,apiRoutes:null,implementation:null,executionPlan:null,edgeCases:null,testingChecklist:null};function us(){return {stage:"discovery",projectDescription:null,sections:{...fi},history:[],pendingQuestions:[]}}function ms(t,e){let{sections:o,projectDescription:r,pendingQuestions:n}=e,a={...t.sections};if(o)for(let s of Object.keys(o)){let i=o[s];i!=null&&(a[s]=i);}return {...t,...r!==void 0&&{projectDescription:r},sections:a,...n!==void 0&&{pendingQuestions:n}}}function Ot(t,e,o){let r={role:e,content:o};return {...t,history:[...t.history,r]}}function lr(t){let e=["discovery","requirements","design","complete"],o=e.indexOf(t.stage),n=(o>=0&&o<e.length-1?e[o+1]:void 0)??t.stage;return {...t,stage:n}}function Ct(t){let e=t.trim().toLowerCase();return ["continue","yes","yeah","yep","looks good","good","ok","okay","next","proceed","sure"].some(r=>e===r||e.startsWith(r+" "))}var ee=`You are a senior software architect creating a single, implementation-ready plan that a developer can follow without ambiguity.
|
|
4
|
+
${a}`)}return n.data}function xe(t,e){try{return JSON.parse(t)}catch(o){let r=t.length>200?t.slice(0,200)+"...":t;throw new Error(`Invalid JSON${e?` for ${e}`:""}: ${o instanceof Error?o.message:String(o)}. Preview: ${r}`)}}var Un={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},child:()=>Un};function rc(t={}){if(t.enabled===false)return Un;let{name:e,level:o="info",pretty:r=false,file:n,stream:a,destination:s}=t,i=a==="stderr"?2:a==="stdout"?1:r?2:1,l;if(s)l=No__default.default({name:e,level:o},s);else {let c=[];r?c.push({target:"pino-pretty",options:{colorize:true,destination:i,singleLine:true,ignore:"time,pid,hostname",translateTime:false},level:o}):c.push({target:"pino/file",options:{destination:i},level:o}),n&&c.push({target:"pino/file",options:{destination:n,mkdir:true},level:o});let p=No__default.default.transport({targets:c});l=No__default.default({name:e,level:o},p);}return Ln(l)}function nc(t={}){let e=process.env,o=(e.SWE_LOG_ENABLED??"true").trim().toLowerCase(),r=o!=="0"&&o!=="false"&&o!=="no"&&o!=="disabled",n=(e.SWE_LOG_LEVEL??"info").trim().toLowerCase(),a=n==="debug"||n==="info"||n==="warn"||n==="error"?n:"info",s=(e.SWE_LOG_STREAM??"").trim().toLowerCase(),i=(e.SWE_LOG_PRETTY??"0").trim().toLowerCase(),l=i==="1"||i==="true"||i==="yes",c=s==="stdout"?"stdout":s==="stderr"||l?"stderr":"stdout",p=e.SWE_LOG_FILE?.trim()||void 0,d=e.SWE_LOG_NAME?.trim()||void 0;return {enabled:r,level:a,stream:c,pretty:l,...p&&{file:p},...d&&{name:d},...t}}function Ln(t){return {debug:(e,o)=>{t.debug(o??{},e);},info:(e,o)=>{t.info(o??{},e);},warn:(e,o)=>{t.warn(o??{},e);},error:(e,o)=>{o instanceof Error?t.error({err:o},e):t.error(o??{},e);},child:e=>Ln(t.child(e))}}var Xa={noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},Ka={textTokens:void 0,reasoningTokens:void 0};function Do(t){let e=0,o=0,r=0;for(let n of t)n&&(e+=n.inputTokens??0,o+=n.outputTokens??0,r+=n.totalTokens??0);return {inputTokens:e,outputTokens:o,totalTokens:r,inputTokenDetails:Xa,outputTokenDetails:Ka}}function h(t){let{name:e,description:o,input:r,handler:n}=t;return ai.tool({description:o,inputSchema:r,execute:async a=>{let s=r.safeParse(a);if(!s.success)throw new H(`Invalid input: ${s.error.message}`,e,s.error);try{return await n(s.data,void 0)}catch(i){throw i instanceof H?i:new H(`Tool "${e}" failed: ${i instanceof Error?i.message:String(i)}`,e,i instanceof Error?i:void 0)}}})}function k(t){return t}function Gn(t){return Object.values(t)}function Bn(t,e){return t[e]}async function _o(t,e,o){let{logger:r}=o??{},n=o?.toolName??("name"in t&&typeof t.name=="string"?t.name:"unknown");if(!t.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 a=await t.execute(e,{toolCallId:o?.toolCallId??"",messages:[],abortSignal:o?.abortSignal});return r?.info("Tool completed",{toolName:n,toolCallId:o?.toolCallId}),{success:!0,output:a}}catch(a){let s=a instanceof Error?a.message:String(a);return r?.error("Tool failed",{toolName:n,toolCallId:o?.toolCallId,error:s}),{success:false,error:s}}}async function nt(t,e,o,r){let n=t[e];if(!n)throw r?.logger?.error("Tool not found",{name:e,availableTools:Object.keys(t)}),new H(`Tool not found: ${e}`);return _o(n,o,{...r,toolName:e})}function q(t,e,o,r="json"){return h({name:t,description:o,input:zod.z.object({[r]:zod.z.string().describe("JSON string to validate")}),handler:async n=>{let a=n[r]??"";try{let s=JSON.parse(a);return e.parse(s),{valid:!0}}catch(s){return s instanceof zod.z.ZodError?{valid:false,errors:s.issues.map(i=>`${i.path.join(".")}: ${i.message}`)}:s instanceof SyntaxError?{valid:false,errors:[`Invalid JSON: ${s.message}`]}:{valid:false,errors:[String(s)]}}}})}function Io(t,e){t?.forEach(o=>o.onStep?.(e));}function Jn(t,e,o){t?.forEach(r=>r.onToolExecution?.(e,o));}function Yn(t,e){t?.forEach(o=>o.onError?.(e));}async function C(t){let{model:e,tools:o,systemPrompt:r,input:n,maxIterations:a=10,onStep:s,observers:i,logger:l}=t;l?.info("Starting agent",{maxIterations:a});let c=[{role:"system",content:r},{role:"user",content:n}],p=[];for(let u=0;u<a;u++){u>0&&u>=a-2&&l?.warn("Approaching max iterations",{iteration:u,maxIterations:a}),l?.debug("Agent iteration",{iteration:u});let y=await e.invoke(c,{tools:o}),m={iteration:u,content:y.text,toolCalls:y.toolCalls,usage:y.usage};if(y.text&&l?.debug("Model response",{iteration:u,textLength:y.text.length}),!y.toolCalls?.length)return p.push(m),s?.(m),Io(i,m),l?.info("Agent completed",{steps:p.length,totalUsage:Do(p.map(j=>j.usage))}),{output:y.text,steps:p,totalUsage:Do(p.map(j=>j.usage)),messages:c};l?.debug("Tool calls",{iteration:u,toolCalls:y.toolCalls.map(j=>({name:j.toolName,toolCallId:j.toolCallId}))});let J=[...y.text?[{type:"text",text:y.text}]:[],...y.toolCalls.map(j=>({type:"tool-call",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input}))];c.push({role:"assistant",content:J});let L=[];for(let j of y.toolCalls){let Se=await nt(o,j.toolName,j.input,{toolCallId:j.toolCallId,logger:l}),de={toolCallId:j.toolCallId,toolName:j.toolName,output:Se.success?Se.output:Se.error,isError:!Se.success};L.push(de),Jn(i,j.toolName,de.output);let Va=de.isError?{type:"error-text",value:String(de.output)}:{type:"text",value:typeof de.output=="string"?de.output:JSON.stringify(de.output)};c.push({role:"tool",content:[{type:"tool-result",toolCallId:j.toolCallId,toolName:j.toolName,output:Va}]});}m.toolResults=L,p.push(m),s?.(m),Io(i,m);}let d=new rt(`Agent reached maximum iterations (${a}) without completing`,a-1);throw Yn(i,d),l?.error("Agent failed: max iterations reached",{maxIterations:a,error:d}),d}function Te(t){let{provider:e,modelName:o,getModel:r}=t;return {provider:e,modelName:o,async invoke(n,a){try{let s=await r(),i=a?.tools?Object.fromEntries(Object.entries(a.tools).map(([p,d])=>{let{execute:u,...y}=d;return [p,y]})):void 0,l=await ai.generateText({model:s,messages:n,tools:i,maxOutputTokens:a?.maxOutputTokens,temperature:a?.temperature,stopSequences:a?.stop}),c=l.toolCalls.map(p=>({toolCallId:p.toolCallId,toolName:p.toolName,input:p.input}));return {text:l.text,toolCalls:c,usage:l.usage,finishReason:l.finishReason}}catch(s){let i=s instanceof Error?s:new Error(String(s));throw new ie(`Failed to invoke ${e} model`,e,i)}},async generateVision(n,a,s){try{let i=await r(),l=[];for(let d of a)l.push({type:"image",image:`data:${d.mimeType};base64,${d.base64}`,mimeType:d.mimeType});l.push({type:"text",text:n});let c=[];s?.systemPrompt&&c.push({role:"system",content:s.systemPrompt}),c.push({role:"user",content:l});let p=await ai.generateText({model:i,messages:c,maxOutputTokens:s?.maxOutputTokens,temperature:s?.temperature});return {text:p.text,toolCalls:[],usage:p.usage,finishReason:p.finishReason}}catch(i){let l=i instanceof Error?i:new Error(String(i));throw new ie("Failed to generate vision response",e,l)}},async invokeObject(n,a,s){try{let i=await r(),l=ai.zodSchema(a),c=await ai.generateObject({model:i,messages:n,schema:l,temperature:s?.temperature,maxOutputTokens:s?.maxOutputTokens});return {data:c.object,usage:c.usage}}catch(i){let l=i instanceof Error?i:new Error(String(i));throw new ie(`Failed to invokeObject ${e} model`,e,l)}}}}function st(t){let{model:e,apiKey:o,baseUrl:r}=t,n=openai.createOpenAI({apiKey:o??process.env.OPENAI_API_KEY,baseURL:r});return Te({provider:"openai",modelName:e,getModel:()=>n.chat(e)})}function at(t){let{model:e,apiKey:o}=t,r=anthropic.createAnthropic({apiKey:o??process.env.ANTHROPIC_API_KEY});return Te({provider:"anthropic",modelName:e,getModel:()=>r(e)})}function it(t){let{model:e,apiKey:o}=t,r=google.createGoogleGenerativeAI({apiKey:o??process.env.GOOGLE_GENERATIVE_AI_API_KEY});return Te({provider:"google",modelName:e,getModel:()=>r(e)})}function v(t){let{provider:e}=t;switch(e){case "openai":return st(t);case "anthropic":return at(t);case "google":return it(t);default:throw new ie(`Unsupported provider: ${e}. Supported providers: openai, anthropic, google`)}}var ii=/^[a-z0-9]+(-[a-z0-9]+)*$/;function f(t){if(!t.name.trim())throw new be("Subagent name is required",void 0);if(!ii.test(t.name))throw new be(`Subagent name must be kebab-case (lowercase letters, numbers, hyphens): ${t.name}`,t.name);return {...t}}function li(t,e){if(t.tools!=null&&Object.keys(t.tools).length>0)return t.tools;let o=e??{},r=new Set(t.disallowedTools??[]),n={};for(let[a,s]of Object.entries(o))a.startsWith("subagent_")||r.has(a)||(n[a]=s);return n}async function z(t,e,o){let{parentTools:r,parentModel:n}=o??{},a=li(t,r),s=t.model==null?n:v(t.model);if(!s)throw new be("Subagent has no model: set definition.model or pass parentModel in options",t.name);return {...await C({model:s,tools:a,systemPrompt:t.systemPrompt,input:e,maxIterations:t.maxIterations??10,onStep:t.onStep}),subagentName:t.name}}function jo(t,e){let o=`subagent_${t.name}`;return h({name:o,description:t.description,input:zod.z.object({prompt:zod.z.string().describe("The task or question to delegate to this subagent")}),handler:async({prompt:r})=>(await z(t,r,{parentTools:e?.parentTools,parentModel:e?.parentModel})).output})}function I(t,e){let o={};for(let r of t){let n=jo(r,e);o[`subagent_${r.name}`]=n;}return o}function qo(t,e){return re__default.default.compile(t,{noEscape:true})(e)}function Hn(t,e=t){let o=[];if(!Z__namespace.existsSync(t))return o;let r=Z__namespace.readdirSync(t,{withFileTypes:true});for(let n of r){let a=Pe__namespace.join(t,n.name);n.isDirectory()?o.push(...Hn(a,e)):n.name.endsWith(".hbs")&&o.push(Pe__namespace.relative(e,a));}return o}function ci(t){return t.replace(/\.hbs$/,"")}function pi(t,e){for(let o of e)if(new RegExp("^"+o.replace(/\./g,"\\.").replace(/\*\*/g,"<<GLOBSTAR>>").replace(/\*/g,"[^/]*").replace(/<<GLOBSTAR>>/g,".*")+"$").test(t))return true;return false}async function ce(t){let{templateDir:e,outputDir:o,context:r,skipPatterns:n=[]}=t,a=Hn(e),s=[],i=[];for(let l of a){if(pi(l,n))continue;let c=ci(l),p=Pe__namespace.join(e,l),d=Pe__namespace.join(o,c);try{let u=Z__namespace.readFileSync(p,"utf-8"),y=qo(u,r);Z__namespace.mkdirSync(Pe__namespace.dirname(d),{recursive:!0}),Z__namespace.writeFileSync(d,y,"utf-8"),s.push(c);}catch(u){i.push({file:l,message:u instanceof Error?u.message:String(u)});}}return {fileCount:s.length,files:s,errors:i}}function Fo(){re__default.default.registerHelper("eq",(t,e)=>t===e),re__default.default.registerHelper("neq",(t,e)=>t!==e),re__default.default.registerHelper("json",t=>JSON.stringify(t,null,2)),re__default.default.registerHelper("uppercase",t=>typeof t=="string"?t.toUpperCase():""),re__default.default.registerHelper("lowercase",t=>typeof t=="string"?t.toLowerCase():""),re__default.default.registerHelper("capitalize",t=>typeof t=="string"?t.charAt(0).toUpperCase()+t.slice(1):""),re__default.default.registerHelper("camelCase",t=>typeof t!="string"?"":t.replace(/[-_\s]+(.)?/g,(e,o)=>o?o.toUpperCase():"").replace(/^(.)/,e=>e.toLowerCase())),re__default.default.registerHelper("pascalCase",t=>typeof t!="string"?"":t.replace(/[-_\s]+(.)?/g,(e,o)=>o?o.toUpperCase():"").replace(/^(.)/,e=>e.toUpperCase()));}Fo();function ui(){let e=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))).resolve("@modelcontextprotocol/sdk/client");return Pe__namespace.default.dirname(Pe__namespace.default.dirname(Pe__namespace.default.dirname(Pe__namespace.default.dirname(e))))}var Vn=ui();function Wn(t){let e=t.content;if(!e?.length)return {};let o=e[0];if(o?.type==="text"&&typeof o.text=="string"){let r=o.text.trim();if(r.startsWith("{")||r.startsWith("["))try{return JSON.parse(r)}catch{return {raw:r}}return {text:r}}return t}async function Xn(t,e){let o=Pe__namespace.default.join(Vn,"dist","esm","client","streamableHttp.js"),r=await import(url.pathToFileURL(o).href),n=e?{headers:new Headers(e)}:void 0;return new r.StreamableHTTPClientTransport(new URL(t),n?{requestInit:n}:void 0)}async function Kn(t,e){let o=Pe__namespace.default.join(Vn,"dist","esm","client","stdio.js"),r=await import(url.pathToFileURL(o).href);return new r.StdioClientTransport({command:t,args:e})}var lt=class{info;config;client=null;transport=null;connectPromise=null;constructor(e,o){this.info=e,this.config=o;}static resolveConfig(e,o={envPrefix:"MCP"}){let{envPrefix:r,serverLabel:n,apiKeyHeader:a}=o,s=e?.url??process.env[`${r}_URL`],i=process.env[`${r}_API_KEY`],l=e?.command??process.env[`${r}_COMMAND`],c=process.env[`${r}_ARGS`],p=e?.args??(c?c.split(",").map(u=>u.trim()):void 0),d=e?.headers?{...e.headers}:void 0;if(i){let u=a??"Authorization";d=d??{},d[u]=u==="Authorization"?`Bearer ${i}`:i;}if(s)return {url:s,headers:d};if(l)return {command:l,args:p?.length?p:[]};throw new H(`${n??r} uses MCP only. Set ${r}_URL or ${r}_COMMAND (and optionally ${r}_ARGS).`,"mcp_client")}async ensureConnected(){if(this.client)return this.client;if(this.connectPromise){if(await this.connectPromise,!this.client)throw new H("MCP connection failed.","mcp_client");return this.client}if(this.connectPromise=this.doConnect(),await this.connectPromise,this.connectPromise=null,!this.client)throw new H("MCP connection failed.","mcp_client");return this.client}async doConnect(){let e=new client.Client({name:this.info.name,version:this.info.version},{capabilities:{}});if(this.config.url)this.transport=await Xn(this.config.url,this.config.headers);else if(this.config.command)this.transport=await Kn(this.config.command,this.config.args??[]);else throw new H("MCP config missing: provide url or command.","mcp_client");await e.connect(this.transport),this.client=e;}async callTool(e,o={}){let n=await(await this.ensureConnected()).callTool({name:e,arguments:o});return n&&typeof n=="object"&&"content"in n?Wn(n):n}async close(){this.transport&&(await this.transport.close(),this.transport=null),this.client=null,this.connectPromise=null;}};var gi={overview:null,techStack:null,featureDecisions:null,dataModels:null,pagesAndRoutes:null,authFlow:null,apiRoutes:null,implementation:null,executionPlan:null,edgeCases:null,testingChecklist:null};function Zn(){return {stage:"discovery",projectDescription:null,sections:{...gi},history:[],pendingQuestions:[]}}function es(t,e){let{sections:o,projectDescription:r,pendingQuestions:n}=e,a={...t.sections};if(o)for(let s of Object.keys(o)){let i=o[s];i!=null&&(a[s]=i);}return {...t,...r!==void 0&&{projectDescription:r},sections:a,...n!==void 0&&{pendingQuestions:n}}}function ct(t,e,o){let r={role:e,content:o};return {...t,history:[...t.history,r]}}function Uo(t){let e=["discovery","requirements","design","complete"],o=e.indexOf(t.stage),n=(o>=0&&o<e.length-1?e[o+1]:void 0)??t.stage;return {...t,stage:n}}function pt(t){let e=t.trim().toLowerCase();return ["continue","yes","yeah","yep","looks good","good","ok","okay","next","proceed","sure"].some(r=>e===r||e.startsWith(r+" "))}var ee=`You are a senior software architect creating a single, implementation-ready plan that a developer can follow without ambiguity.
|
|
388
5
|
|
|
389
6
|
CRITICAL RULES:
|
|
390
7
|
- 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.
|
|
391
8
|
- 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**).
|
|
392
|
-
- 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
|
|
9
|
+
- 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 Lo=`You are in the discovery stage. Your goal is to understand what the user wants to build.
|
|
393
10
|
|
|
394
11
|
Respond in natural language only. Do NOT output JSON.
|
|
395
12
|
|
|
@@ -399,21 +16,21 @@ Respond in natural language only. Do NOT output JSON.
|
|
|
399
16
|
- **## Core Features** \u2014 Numbered list: 1. **Feature Name** - Short description. (one line per feature)
|
|
400
17
|
- **## Tech Stack** \u2014 Bullet list with category labels: - **Frontend**: ... (versions if known), - **Database**: ..., - **Authentication**: ..., - **API**: ..., - **Backend**: ... Include versions and key libraries where relevant.
|
|
401
18
|
|
|
402
|
-
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.`,
|
|
19
|
+
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.`,ts=`## Current user message:
|
|
403
20
|
{userMessage}
|
|
404
21
|
|
|
405
22
|
## Prior conversation (if any):
|
|
406
23
|
{history}
|
|
407
24
|
|
|
408
|
-
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
|
|
409
|
-
{context}`,
|
|
25
|
+
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 Go(t,e){return ts.replace("{userMessage}",t).replace("{history}",e||"(No prior messages)")}var dt=`## Project description / context:
|
|
26
|
+
{context}`,os=`${dt}
|
|
410
27
|
|
|
411
28
|
Using the project description above, write two markdown sections in this exact format:
|
|
412
29
|
|
|
413
30
|
1. **## Overview** \u2014 One paragraph only (2\u20134 sentences) summarizing the project and its purpose.
|
|
414
31
|
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.
|
|
415
32
|
|
|
416
|
-
Output only these two sections in markdown. Do NOT output JSON.`,
|
|
33
|
+
Output only these two sections in markdown. Do NOT output JSON.`,rs=`${dt}
|
|
417
34
|
|
|
418
35
|
## Already written (Overview + Tech Stack):
|
|
419
36
|
{overviewAndTechStack}
|
|
@@ -423,8 +40,8 @@ Write the next two markdown sections in this exact format:
|
|
|
423
40
|
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).
|
|
424
41
|
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.
|
|
425
42
|
|
|
426
|
-
Output only markdown. Do NOT output JSON.`;function
|
|
427
|
-
{priorSections}`,
|
|
43
|
+
Output only markdown. Do NOT output JSON.`;function Bo(t){return os.replace("{context}",t)}function Jo(t,e){return rs.replace("{context}",t).replace("{overviewAndTechStack}",e)}var ns=`## Project context (all sections so far):
|
|
44
|
+
{priorSections}`,ss=`${ns}
|
|
428
45
|
|
|
429
46
|
## API Routes (already written):
|
|
430
47
|
{apiRoutes}
|
|
@@ -438,8 +55,8 @@ Write the next markdown section in this exact format:
|
|
|
438
55
|
- **### 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).
|
|
439
56
|
- 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).
|
|
440
57
|
|
|
441
|
-
Output only markdown. Do NOT output JSON.`;function
|
|
442
|
-
{priorSections}`,
|
|
58
|
+
Output only markdown. Do NOT output JSON.`;function Yo(t,e){return ss.replace("{priorSections}",t).replace("{apiRoutes}",e)}var Si=`## Full plan so far (all sections):
|
|
59
|
+
{priorSections}`,zo="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.",as=`${Si}
|
|
443
60
|
|
|
444
61
|
Write the following sections in this exact order. Output only markdown. Do NOT output JSON.
|
|
445
62
|
|
|
@@ -465,7 +82,7 @@ Write the following sections in this exact order. Output only markdown. Do NOT o
|
|
|
465
82
|
|
|
466
83
|
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").
|
|
467
84
|
|
|
468
|
-
Output all eight sections in the order above. Do NOT output JSON.`;function
|
|
85
|
+
Output all eight sections in the order above. Do NOT output JSON.`;function $o(t){return as.replace("{priorSections}",t)}var Ho=`You are a senior software architect revising an existing implementation plan.
|
|
469
86
|
|
|
470
87
|
CRITICAL RULES:
|
|
471
88
|
- You will receive the FULL existing plan and the user's feedback or edit instructions.
|
|
@@ -474,7 +91,7 @@ CRITICAL RULES:
|
|
|
474
91
|
- Only modify sections that are affected by the feedback. Leave unrelated sections intact.
|
|
475
92
|
- Use code blocks ONLY for: request/response JSON examples, file/directory trees, and env or config snippets.
|
|
476
93
|
- Be concrete and actionable: include validation rules, HTTP status codes, redirects, field-level data model descriptions, and step-by-step auth flows.
|
|
477
|
-
- If the feedback adds new requirements, integrate them into the appropriate existing sections rather than appending a separate section (unless a new section is clearly needed).`;function
|
|
94
|
+
- If the feedback adds new requirements, integrate them into the appropriate existing sections rather than appending a separate section (unless a new section is clearly needed).`;function Qo(t,e){return `## Existing Plan
|
|
478
95
|
|
|
479
96
|
${t}
|
|
480
97
|
|
|
@@ -482,10 +99,10 @@ ${t}
|
|
|
482
99
|
|
|
483
100
|
## Edit Instructions
|
|
484
101
|
|
|
485
|
-
${e}`}function
|
|
486
|
-
`),s=
|
|
102
|
+
${e}`}function bi(t){let e=t.trim();if(e.length<100)return false;if(e.includes("## Overview")||e.includes("## Core Features"))return true;let o=e.toLowerCase();return !!((o.includes("overview")||o.includes("core features"))&&(o.includes("tech stack")||o.includes("technology")))}async function Vo(t,e,o,r){r?.debug("Discovery stage started",{historyLength:e.history.length});let a=e.history.slice(0,-1).map(L=>`${L.role}: ${L.content}`).slice(-10).join(`
|
|
103
|
+
`),s=Go(t,a),l=[{role:"system",content:`${ee}
|
|
487
104
|
|
|
488
|
-
${
|
|
105
|
+
${Lo}`},{role:"user",content:s}],p=(await o.invoke(l,{temperature:.4,maxOutputTokens:4096})).text?.trim()??"",d=bi(p),u=pt(t),y=u&&e.history.length>=7&&p.length>50,m=d&&(e.projectDescription==null||u)||u&&e.projectDescription!=null||y,J=d||y&&p.length>50;return r?.debug("Discovery stage complete",{advance:m,hasOverview:d,userConfirmed:u,forceAdvance:y}),{message:p,advance:m,sections:{},...J&&{projectDescription:p}}}var ut=class{stageName="discovery";async process(e,o){return Vo(o.userMessage,e,o.model,o.logger)}canAdvance(e){return e.advance}getNextStageName(){return "requirements"}};var xi=`You are an expert database entity analyst. Your job is to extract data model signals from requirements.
|
|
489
106
|
|
|
490
107
|
Perform these analyses:
|
|
491
108
|
|
|
@@ -504,7 +121,7 @@ Perform these analyses:
|
|
|
504
121
|
- Note ownership direction (which entity "belongs to" which).
|
|
505
122
|
- Identify potential M:N relationships that may need join tables.
|
|
506
123
|
|
|
507
|
-
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:
|
|
124
|
+
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:xi,tools:{},maxIterations:2});var Ti=`You are a database relationship specialist. Given a list of entities and their fields, you determine:
|
|
508
125
|
|
|
509
126
|
## Cardinality Analysis
|
|
510
127
|
- For every entity pair that references each other, classify: 1:1, 1:N, or M:N.
|
|
@@ -522,7 +139,7 @@ Respond with a clear, structured analysis using headings and bullet points. Do N
|
|
|
522
139
|
- Suggest unique indexes for natural keys (email, slug, etc.).
|
|
523
140
|
- Note partial indexes where applicable (e.g. only active records).
|
|
524
141
|
|
|
525
|
-
Respond with structured analysis. Do NOT return JSON.`,
|
|
142
|
+
Respond with structured analysis. Do NOT return JSON.`,mt=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:Ti,tools:{},maxIterations:2});var Pi=`You are an expert database schema reviewer. Your job is to:
|
|
526
143
|
|
|
527
144
|
1. Validate the schema structure: every entity has fields, indexes, and relations properly defined.
|
|
528
145
|
2. Check completeness: all entities from requirements are present, all relationships are bidirectional where needed.
|
|
@@ -536,7 +153,7 @@ If you have access to the validate_schema tool, use it first. Then provide a det
|
|
|
536
153
|
- Specific fixes for each issue
|
|
537
154
|
- Overall assessment (ready / needs work)
|
|
538
155
|
|
|
539
|
-
Respond with structured analysis. Do NOT return JSON.`;function
|
|
156
|
+
Respond with structured analysis. Do NOT return JSON.`;function me(){return f({name:"schema-refiner",description:"Reviews a data model schema for completeness, normalization, performance, and security. Has access to validate_schema tool.",systemPrompt:Pi,tools:{},maxIterations:3})}var Ri=`You are a UX-focused frontend architect. You design detailed page specifications.
|
|
540
157
|
|
|
541
158
|
## Page Planning
|
|
542
159
|
For each page in the application:
|
|
@@ -558,7 +175,7 @@ For each page in the application:
|
|
|
558
175
|
- Group by access: public pages first, then protected.
|
|
559
176
|
- Order by user flow: signup -> login -> dashboard -> feature pages -> settings -> admin.
|
|
560
177
|
|
|
561
|
-
Respond with structured page specs. Do NOT return JSON.`,
|
|
178
|
+
Respond with structured page specs. Do NOT return JSON.`,Re=f({name:"page-planner",description:"Designs detailed page specifications with routes, form fields, actions, states, and UI elements. Use for frontend page design.",systemPrompt:Ri,tools:{},maxIterations:2});var wi=`You are a component design specialist. Given page specifications, you identify reusable components and shared patterns.
|
|
562
179
|
|
|
563
180
|
## Component Identification
|
|
564
181
|
- **Layout components**: main layout (with nav, sidebar, content area), auth layout (centered form), admin layout.
|
|
@@ -580,7 +197,7 @@ For each component:
|
|
|
580
197
|
- Recommend server vs client state strategy.
|
|
581
198
|
- Identify data fetching patterns (on mount, on action, real-time).
|
|
582
199
|
|
|
583
|
-
Respond with structured analysis. Do NOT return JSON.`,
|
|
200
|
+
Respond with structured analysis. Do NOT return JSON.`,gt=f({name:"component-analyzer",description:"Identifies reusable components, shared layouts, and state management patterns from page specifications. Use after page planning.",systemPrompt:wi,tools:{},maxIterations:2});var vi=`You are a frontend technology advisor. Given project requirements, you recommend the best frontend framework.
|
|
584
201
|
|
|
585
202
|
## Decision Criteria
|
|
586
203
|
|
|
@@ -605,7 +222,7 @@ State your recommendation clearly:
|
|
|
605
222
|
- Reasoning: 2-3 sentences explaining why
|
|
606
223
|
- Trade-offs: what you would lose with the alternative
|
|
607
224
|
|
|
608
|
-
Respond with structured analysis. Do NOT return JSON.`,
|
|
225
|
+
Respond with structured analysis. Do NOT return JSON.`,Wo=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:vi,tools:{},maxIterations:2});var Ai=`You are a web security specialist. You analyze project requirements for security concerns and design security policies.
|
|
609
226
|
|
|
610
227
|
## Authentication Analysis
|
|
611
228
|
- Determine the best auth strategy (JWT, session, OAuth) based on requirements.
|
|
@@ -629,7 +246,7 @@ Respond with structured analysis. Do NOT return JSON.`,br=f({name:"framework-sel
|
|
|
629
246
|
- Input sanitization: XSS prevention, SQL injection prevention.
|
|
630
247
|
- Brute force protection: account lockout, exponential backoff.
|
|
631
248
|
|
|
632
|
-
Respond with structured analysis. Do NOT return JSON.`,
|
|
249
|
+
Respond with structured analysis. Do NOT return JSON.`,ft=f({name:"security-analyzer",description:"Analyzes security requirements, threat vectors, and designs security policies. Use to understand auth needs before designing flows.",systemPrompt:Ai,tools:{},maxIterations:2});var Ei=`You are an authentication flow architect. You design detailed, numbered step-by-step auth flows.
|
|
633
250
|
|
|
634
251
|
For each flow (signup, login, logout, password reset, protected route middleware, API auth middleware):
|
|
635
252
|
|
|
@@ -659,9 +276,9 @@ For each flow (signup, login, logout, password reset, protected route middleware
|
|
|
659
276
|
- Protected route: check cookie/header, verify token, attach user to request, reject if invalid.
|
|
660
277
|
- API auth: same as above but for API routes, return 401 JSON.
|
|
661
278
|
|
|
662
|
-
Respond with structured numbered flows. Do NOT return JSON.`,
|
|
279
|
+
Respond with structured numbered flows. Do NOT return JSON.`,we=f({name:"flow-designer",description:"Designs detailed step-by-step authentication flows (signup, login, logout, password reset, middleware). Use after security analysis.",systemPrompt:Ei,tools:{},maxIterations:2});function is(t,e,o){let r=[{role:"system",content:e},{role:"user",content:o}];return t.invoke(r,{temperature:.3,maxOutputTokens:8192}).then(n=>n.text?.trim()??"")}function Mi(t){let e=t.indexOf("## Tech Stack");return e<0?{overview:t,techStack:""}:{overview:t.slice(0,e).trim(),techStack:t.slice(e).trim()}}function Oi(t){let e=t.indexOf("## Data Models");return e<0?{featureDecisions:t,dataModels:""}:{featureDecisions:t.slice(0,e).trim(),dataModels:t.slice(e).trim()}}async function Xo(t,e,o,r){r?.debug("Requirements stage started (specialist agents)");let n=e.projectDescription??"";if(!n)return {message:"No project description yet. Complete discovery first.",advance:false,sections:{}};let a=`${ee}
|
|
663
280
|
|
|
664
|
-
Output only markdown. Do NOT output JSON.`,s=await
|
|
281
|
+
Output only markdown. Do NOT output JSON.`,s=await is(o,a,Bo(n)),{overview:i,techStack:l}=Mi(s),c=await is(o,a,Jo(n,s)),{featureDecisions:p}=Oi(c);r?.info("Delegating to data-modeler specialist");let u=(await z(ne,`Analyze the data model for this project:
|
|
665
282
|
|
|
666
283
|
${n}
|
|
667
284
|
|
|
@@ -670,21 +287,21 @@ ${p}`,{parentModel:o})).output;r?.info("Delegating to frontend-architect special
|
|
|
670
287
|
|
|
671
288
|
---
|
|
672
289
|
|
|
673
|
-
`),
|
|
290
|
+
`),J=(await z(Re,`Design the pages and routes for this project:
|
|
674
291
|
|
|
675
292
|
${n}
|
|
676
293
|
|
|
677
294
|
Context:
|
|
678
|
-
${y}`,{parentModel:o})).output;r?.info("Delegating to auth-designer specialist");let L=[y,
|
|
295
|
+
${y}`,{parentModel:o})).output;r?.info("Delegating to auth-designer specialist");let L=[y,J].join(`
|
|
679
296
|
|
|
680
297
|
---
|
|
681
298
|
|
|
682
|
-
`),
|
|
299
|
+
`),Se=(await z(we,`Design the authentication flows for this project:
|
|
683
300
|
|
|
684
301
|
${n}
|
|
685
302
|
|
|
686
303
|
Context:
|
|
687
|
-
${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:p,dataModels:u,pagesAndRoutes:
|
|
304
|
+
${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:p,dataModels:u,pagesAndRoutes:J,authFlow:Se}}}var ht=class{stageName="requirements";async process(e,o){return Xo(o.userMessage,e,o.model,o.logger)}canAdvance(e){return e.advance}getNextStageName(){return "design"}};var Ci=`You are an API endpoint analyst. Given a data model and requirements, you derive the complete API surface.
|
|
688
305
|
|
|
689
306
|
## Endpoint Discovery
|
|
690
307
|
- For each entity in the data model, determine CRUD operations: create, read (by ID), list (with filters/pagination), update, delete.
|
|
@@ -701,7 +318,7 @@ ${L}`,{parentModel:o})).output;return r?.info("Requirements stage complete (spec
|
|
|
701
318
|
- Mark which endpoints require specific roles (admin, owner).
|
|
702
319
|
- Identify resource-ownership checks (user can only access their own data).
|
|
703
320
|
|
|
704
|
-
Respond with structured analysis using headings and bullet points. Do NOT return JSON.`,
|
|
321
|
+
Respond with structured analysis using headings and bullet points. Do NOT return JSON.`,ve=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:Ci,tools:{},maxIterations:2});var Ni=`You are an API contract specialist. Given endpoints and a data model, you design detailed request/response contracts.
|
|
705
322
|
|
|
706
323
|
## Request Design
|
|
707
324
|
- For each endpoint, define: required fields, optional fields, field types, validation rules.
|
|
@@ -725,121 +342,310 @@ Respond with structured analysis using headings and bullet points. Do NOT return
|
|
|
725
342
|
- Use consistent field naming (camelCase for JSON, snake_case for query params if preferred).
|
|
726
343
|
- Use ISO 8601 for dates in responses.
|
|
727
344
|
|
|
728
|
-
Respond with structured analysis. Do NOT return JSON.`,
|
|
345
|
+
Respond with structured analysis. Do NOT return JSON.`,Ae=f({name:"contract-designer",description:"Designs detailed request/response contracts, validation rules, and error responses per API endpoint. Use after endpoint analysis.",systemPrompt:Ni,tools:{},maxIterations:2});function Di(t){let e=[];t.projectDescription&&e.push(t.projectDescription);let o=t.sections;return o.overview&&e.push(o.overview),o.techStack&&e.push(o.techStack),o.featureDecisions&&e.push(o.featureDecisions),o.dataModels&&e.push(o.dataModels),o.pagesAndRoutes&&e.push(o.pagesAndRoutes),o.authFlow&&e.push(o.authFlow),e.join(`
|
|
729
346
|
|
|
730
347
|
---
|
|
731
348
|
|
|
732
|
-
`)}async function
|
|
349
|
+
`)}async function Ko(t,e,o,r){r?.debug("Design stage started (specialist agents)");let n=Di(e);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 s=(await z(ve,`Design the API routes for this project:
|
|
733
350
|
|
|
734
|
-
${n}`,{parentModel:o})).output;r?.info("Delegating to api-designer contract-designer specialist");let i=await z(
|
|
351
|
+
${n}`,{parentModel:o})).output;r?.info("Delegating to api-designer contract-designer specialist");let i=await z(Ae,`Design detailed request/response contracts for these API endpoints:
|
|
735
352
|
|
|
736
353
|
${s}
|
|
737
354
|
|
|
738
355
|
Project context:
|
|
739
356
|
${n}`,{parentModel:o}),l=`${ee}
|
|
740
357
|
|
|
741
|
-
Output only markdown. Do NOT output JSON.`,c=await o.invoke([{role:"system",content:l},{role:"user",content:
|
|
358
|
+
Output only markdown. Do NOT output JSON.`,c=await o.invoke([{role:"system",content:l},{role:"user",content:Yo(n,s+`
|
|
359
|
+
|
|
360
|
+
`+i.output)}],{temperature:.3,maxOutputTokens:8192}).then(p=>p.text?.trim()??"");return r?.info("Design stage complete (specialist agents)"),{message:"Design generated via specialist agents (Endpoint Analyzer, Contract Designer).",advance:true,sections:{apiRoutes:s,implementation:c}}}var yt=class{stageName="design";async process(e,o){return Ko(o.userMessage,e,o.model,o.logger)}canAdvance(e){return e.advance}getNextStageName(){return "complete"}};function Zo(t,e){return [`# ${t} Implementation Plan
|
|
361
|
+
`,e.overview,e.techStack,e.featureDecisions,"---",e.dataModels,"---",e.pagesAndRoutes,"---",e.authFlow,"---",e.apiRoutes,"---",e.implementation,"---",e.executionPlan,"---",e.edgeCases,"---",e.testingChecklist].filter(Boolean).join(`
|
|
362
|
+
|
|
363
|
+
`)}async function ki(t,e){await promises.writeFile(e,t,"utf-8");}var Ii=`You are a QA-minded tech lead. You identify edge cases that developers often miss.
|
|
364
|
+
|
|
365
|
+
For each domain area (Authentication, Data, API, Frontend, Integrations):
|
|
366
|
+
|
|
367
|
+
## Edge Case Analysis
|
|
368
|
+
- **Scenario**: Describe the edge case concretely (e.g. "User submits signup form with email that already exists").
|
|
369
|
+
- **Handling**: How to handle it (e.g. "Return 400 with message 'Email already in use'").
|
|
370
|
+
- **Severity**: critical (must handle or app breaks), warning (should handle for good UX), info (nice to have).
|
|
371
|
+
|
|
372
|
+
## Common Areas to Check
|
|
373
|
+
- **Authentication**: duplicate email, invalid credentials, expired token, concurrent sessions, password reset with invalid token.
|
|
374
|
+
- **Data**: empty collections, max field lengths, special characters in input, date timezone issues, null references.
|
|
375
|
+
- **API**: missing required fields, invalid field types, unauthorized access, rate limiting, pagination edge (page 0, negative page).
|
|
376
|
+
- **Frontend**: empty states, loading states, network errors, form resubmission, back button behavior.
|
|
377
|
+
- **Integrations**: external API down, timeout, rate limited, invalid response format.
|
|
378
|
+
|
|
379
|
+
Respond with structured edge cases grouped by area. Do NOT return JSON.`,Ee=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:Ii,tools:{},maxIterations:2});var ji=`You are a testing strategy specialist. You design comprehensive manual testing checklists.
|
|
380
|
+
|
|
381
|
+
## Testing Checklist Design
|
|
382
|
+
Group test items by flow (Authentication, CRUD operations, Edge cases, etc.).
|
|
383
|
+
|
|
384
|
+
For each test item:
|
|
385
|
+
- **Flow name**: which feature flow this tests (e.g. "Authentication Flow", "Workout CRUD Flow").
|
|
386
|
+
- **Test item**: what to verify (e.g. "Sign up with valid credentials creates account").
|
|
387
|
+
- **Expected result**: what should happen (e.g. "User created in DB, JWT cookie set, redirected to /dashboard").
|
|
388
|
+
|
|
389
|
+
## Coverage Areas
|
|
390
|
+
- **Happy paths**: normal user flows work end-to-end.
|
|
391
|
+
- **Validation**: invalid inputs are rejected with clear messages.
|
|
392
|
+
- **Authorization**: users can only access what they should.
|
|
393
|
+
- **Error handling**: errors are caught and displayed properly.
|
|
394
|
+
- **Data integrity**: data is saved correctly, relationships maintained.
|
|
395
|
+
- **UI states**: loading, empty, error, success states display correctly.
|
|
396
|
+
|
|
397
|
+
## Checklist Format
|
|
398
|
+
Present as grouped checklist items using markdown checkboxes:
|
|
399
|
+
### Flow Name
|
|
400
|
+
- [ ] Test item description -> Expected result
|
|
401
|
+
|
|
402
|
+
Respond with structured checklist. Do NOT return JSON.`,Me=f({name:"testing-strategist",description:"Designs comprehensive manual testing checklists grouped by feature flow. Use for testing strategy and QA planning.",systemPrompt:ji,tools:{},maxIterations:2});function qi(t){let e=[];t.projectDescription&&e.push(t.projectDescription);let o=t.sections;return [o.overview,o.techStack,o.featureDecisions,o.dataModels,o.pagesAndRoutes,o.authFlow,o.apiRoutes,o.implementation].forEach(r=>{r&&e.push(r);}),e.join(`
|
|
403
|
+
|
|
404
|
+
---
|
|
405
|
+
|
|
406
|
+
`)}function Fi(t){let o=(t.sections.overview??t.projectDescription??"").split(`
|
|
407
|
+
`)[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 er(t,e,o,r){r?.debug("Synthesis stage started (specialist agents)");let n=qi(e);if(!n)return {message:"No prior sections. Complete earlier stages first.",advance:false,sections:{}};let a=`${ee}
|
|
408
|
+
|
|
409
|
+
${zo}
|
|
410
|
+
|
|
411
|
+
Output only markdown. Do NOT output JSON.`,s=await o.invoke([{role:"system",content:a},{role:"user",content:$o(n)}],{temperature:.3,maxOutputTokens:8192}).then(m=>m.text?.trim()??"");r?.info("Delegating to execution-planner edge-case-analyzer specialist");let l=(await z(Ee,`Identify edge cases for this project:
|
|
412
|
+
|
|
413
|
+
${n}`,{parentModel:o})).output;r?.info("Delegating to execution-planner testing-strategist specialist");let p=(await z(Me,`Design the manual testing checklist for this project:
|
|
414
|
+
|
|
415
|
+
${n}`,{parentModel:o})).output,d=Fi(e),u={...e.sections,executionPlan:s||null,edgeCases:l||null,testingChecklist:p||null},y=Zo(d,u);return r?.info("Synthesis stage complete (specialist agents)",{projectName:d}),{message:`Plan complete: ${d}. Generated via specialist agents.`,advance:true,sections:{executionPlan:s,edgeCases:l,testingChecklist:p},planMarkdown:y}}var St=class{stageName="complete";async process(e,o){return er(o.userMessage,e,o.model,o.logger)}canAdvance(e){return e.advance}getNextStageName(){return null}};var Ui={discovery:new ut,requirements:new ht,design:new yt,complete:new St};function tr(t){return Ui[t]}async function ls(t,e,o,r,n){n?.debug("Stage processor invoked",{stage:t});let s=await tr(t).process(o,{userMessage:e,model:r,logger:n}),i=es(o,s),l={...i,pendingQuestions:s.pendingQuestions??i.pendingQuestions};return n?.debug("Stage result",{stage:t,advance:s.advance,hasPlanMarkdown:!!s.planMarkdown}),{message:s.message,pendingQuestions:s.pendingQuestions??i.pendingQuestions,advance:s.advance,data:l,planMarkdown:s.planMarkdown}}var or=["discovery","requirements","design","complete"];async function ge(t,e,o){let{logger:r}=o,n=o.model??{provider:"openai",model:"gpt-4o-mini"},a=v(n),s=e??Zn();s=ct(s,"user",t),r?.info("Planning chat turn",{stage:s.stage,messageLength:t.length});let i="",l=[],c=null,p=async y=>{let m=await ls(y,t,s,a,r);return i=m.message,l=m.pendingQuestions,s=m.data,m.planMarkdown&&(c=m.planMarkdown),{advance:m.advance,planMarkdown:m.planMarkdown}},d=s.stage;r?.info("Stage",{stage:d});let u=await p(d);for(;u.advance&&!c;){let y=or.indexOf(d),m=y>=0&&y<or.length-1?or[y+1]:void 0;if(m===void 0)break;r?.info("Stage transition",{from:d,to:m}),d=m,s=Uo(s),s={...s,stage:d},r?.info("Stage",{stage:d}),u=await p(d);}return s=ct(s,"assistant",i),r?.info("Planning chat turn done",{stage:d,hasPlanMarkdown:!!c}),{message:i,context:s,pendingQuestions:l,planMarkdown:c}}var cs=10;async function rr(t){let{input:e,model:o,onStep:r,logger:n}=t;n?.info("Starting planning agent",{maxTurns:cs});let a=null,s=await ge(e,a,{model:o,logger:n});a=s.context;let i=1;for(;!s.planMarkdown&&i<cs;){n?.debug("Planning agent turn",{turn:i});let p=`continue - proceed with the project: "${e}". Make reasonable assumptions for any unresolved details and produce the required output format.`;s=await ge(p,a,{model:o,logger:n}),a=s.context,i++;}let l=s.planMarkdown??s.message,c=a.history.map(p=>({role:p.role,content:p.content}));return n?.info("Planning agent completed",{turns:i,hasPlanMarkdown:!!s.planMarkdown}),{output:l,steps:[],totalUsage:void 0,messages:c}}async function Li(t){let{existingPlan:e,feedback:o,logger:r}=t;if(r?.info("Editing plan",{feedbackLength:o.length}),!e||e.trim().length<50)throw new Error("existingPlan is too short or empty. Provide a valid plan to edit.");if(!o||o.trim().length===0)throw new Error("feedback is empty. Provide edit instructions.");let n=t.model??{provider:"openai",model:"gpt-4o-mini"},i=(await v(n).invoke([{role:"system",content:Ho},{role:"user",content:Qo(e,o)}],{temperature:.3,maxOutputTokens:16384})).text?.trim()??"";if(!i)throw new Error("Model returned empty response when editing plan.");return r?.info("Plan edited successfully",{outputLength:i.length}),i}function Gi(t){return t.fields.length?`| Field | Type | Constraints | Description |
|
|
416
|
+
| --- | --- | --- | --- |
|
|
417
|
+
${t.fields.map(o=>{let r=[o.required?"required":"",o.unique?"unique":""].filter(Boolean).join(", ");return `| ${o.name} | ${o.type} | ${r||"-"} | ${o.description} |`}).join(`
|
|
418
|
+
`)}`:""}function Bi(t){let e=`## Data Models
|
|
419
|
+
|
|
420
|
+
**Database:** ${t.type}
|
|
421
|
+
**Reasoning:** ${t.reasoning}
|
|
422
|
+
`,o=t.entities.map(r=>{let n=Gi(r),a=r.relations.map(c=>c.field+" \u2192 "+c.references+" ("+c.description+")"),s=a.length?`
|
|
423
|
+
**Relations:** `+a.join("; "):"",i=r.indexes.map(c=>c.name+" ["+c.fields.join(", ")+"]"+(c.unique?" (unique)":"")),l=i.length?`
|
|
424
|
+
**Indexes:** `+i.join("; "):"";return `### ${r.name}
|
|
425
|
+
|
|
426
|
+
${r.description}
|
|
427
|
+
|
|
428
|
+
${n}${s}${l}`}).join(`
|
|
429
|
+
|
|
430
|
+
`);return `${e}
|
|
431
|
+
${o}`}function Ji(t){return `## Feature Decisions
|
|
432
|
+
|
|
433
|
+
${t.map(o=>{let r=o.apis.map(n=>` - \`${n.operation}\` ${n.name}: ${n.description}`).join(`
|
|
434
|
+
`);return `### ${o.name}
|
|
435
|
+
|
|
436
|
+
${o.description} (entity: ${o.entity})
|
|
437
|
+
|
|
438
|
+
**APIs:**
|
|
439
|
+
${r}`}).join(`
|
|
440
|
+
|
|
441
|
+
`)}`}function Yi(t){let e=t.project,o=e.features.map(r=>`- ${r}`).join(`
|
|
442
|
+
`);return `# ${e.name}
|
|
443
|
+
|
|
444
|
+
**Goal:** ${e.goal}
|
|
445
|
+
**Domain:** ${e.domain}
|
|
446
|
+
|
|
447
|
+
${t.summary.overview}
|
|
448
|
+
|
|
449
|
+
**Key Features:**
|
|
450
|
+
${o}`}function zi(t){let e=t.project;return ["## Tech Stack","",`- **Database:** ${e.database}`,`- **Backend Runtime:** ${e.backendRuntime}`,`- **API Style:** ${e.apiStyle}`].join(`
|
|
451
|
+
`)}function $i(t,e,o){let r=["## Actors and Flows"];for(let n of t){r.push(`
|
|
452
|
+
### ${n.name}
|
|
453
|
+
${n.description}`);let a=e.filter(s=>s.actorId===n.id);if(a.length){r.push("**Flows:**");for(let s of a)r.push(`- ${s.name}: ${s.description} (trigger: ${s.trigger}, outcome: ${s.outcome})`);}}if(o.length){r.push(`
|
|
454
|
+
### Key User Stories`);for(let n of o.slice(0,10))r.push(`- As **${n.actor}**, I want to **${n.action}**, so that **${n.benefit}**`);o.length>10&&r.push(`- ... and ${o.length-10} more stories`);}return r.join(`
|
|
455
|
+
`)}function ps(t){let e={overview:`## Overview
|
|
456
|
+
|
|
457
|
+
${t.summary.overview}`,techStack:zi(t),featureDecisions:Ji(t.modules),dataModels:Bi(t.database),pagesAndRoutes:null,authFlow:null,apiRoutes:null,implementation:null,executionPlan:null,edgeCases:null,testingChecklist:null};return {stage:"design",projectDescription:Yi(t)+`
|
|
458
|
+
|
|
459
|
+
`+$i(t.actors,t.flows,t.stories),sections:e,history:[],pendingQuestions:[]}}var Hi=8;async function Qi(t){let{requirement:e,model:o,onStep:r,logger:n}=t;n?.info("Starting planning from requirements (fast path)",{project:e.project.name});let a=ps(e),s=`Generate the implementation plan for "${e.project.name}". The project description, tech stack, features, and data models are already provided in context. Proceed with API routes, implementation details, execution plan, edge cases, and testing checklist.`,i=await ge(s,a,{model:o,logger:n}),l=1;for(;!i.planMarkdown&&l<Hi;)n?.debug("Planning from requirements turn",{turn:l}),i=await ge("continue - produce the complete implementation plan.",i.context,{model:o,logger:n}),l++;let c=i.planMarkdown??i.message,p=i.context.history.map(d=>({role:d.role,content:d.content}));return n?.info("Planning from requirements completed",{turns:l,hasPlanMarkdown:!!i.planMarkdown}),{output:c,steps:[],totalUsage:void 0,messages:p}}var Vi="discovery",ds={overview:null,techStack:null,featureDecisions:null,dataModels:null,pagesAndRoutes:null,authFlow:null,apiRoutes:null,implementation:null,executionPlan:null,edgeCases:null,testingChecklist:null},bt=class{data={};withStage(e){return this.data.stage=e,this}withProjectDescription(e){return this.data.projectDescription=e,this}withSections(e){return this.data.sections={...this.data.sections??ds,...e},this}withHistory(e){return this.data.history=e,this}withPendingQuestions(e){return this.data.pendingQuestions=e,this}reset(){return this.data={},this}build(){return {stage:this.data.stage??Vi,projectDescription:this.data.projectDescription??null,sections:this.data.sections??{...ds},history:this.data.history??[],pendingQuestions:this.data.pendingQuestions??[]}}};function Wi(){return new bt}var Oe=zod.z.object({id:zod.z.string(),name:zod.z.string(),description:zod.z.string(),goals:zod.z.array(zod.z.string())}),xt=zod.z.object({actors:zod.z.array(Oe),message:zod.z.string()});var Ce=zod.z.object({id:zod.z.string(),actorId:zod.z.string(),name:zod.z.string(),description:zod.z.string(),trigger:zod.z.string(),outcome:zod.z.string()}),Tt=zod.z.object({flows:zod.z.array(Ce),message:zod.z.string()});var Ne=zod.z.object({id:zod.z.string(),flowId:zod.z.string(),actor:zod.z.string(),action:zod.z.string(),benefit:zod.z.string(),preconditions:zod.z.array(zod.z.string()),postconditions:zod.z.array(zod.z.string()),dataInvolved:zod.z.array(zod.z.string())}),Pt=zod.z.object({stories:zod.z.array(Ne),message:zod.z.string()});var us=zod.z.object({id:zod.z.string(),name:zod.z.string(),operation:zod.z.enum(["create","read","readAll","update","delete"]),description:zod.z.string(),inputs:zod.z.array(zod.z.string()),outputs:zod.z.array(zod.z.string())}),De=zod.z.object({id:zod.z.string(),name:zod.z.string(),description:zod.z.string(),entity:zod.z.string(),apis:zod.z.array(us)}),Rt=zod.z.object({modules:zod.z.array(De),summary:zod.z.object({totalModules:zod.z.number(),totalApis:zod.z.number()}),message:zod.z.string()});var ms=zod.z.object({name:zod.z.string(),type:zod.z.string(),required:zod.z.boolean(),unique:zod.z.boolean(),description:zod.z.string(),default:zod.z.string().optional()}),gs=zod.z.object({name:zod.z.string(),fields:zod.z.array(zod.z.string()),unique:zod.z.boolean()}),fs=zod.z.object({field:zod.z.string(),references:zod.z.string(),description:zod.z.string()}),hs=zod.z.object({name:zod.z.string(),description:zod.z.string(),fields:zod.z.array(ms),indexes:zod.z.array(gs),relations:zod.z.array(fs)}),fe=zod.z.object({type:zod.z.enum(["mongodb","postgresql"]),reasoning:zod.z.string(),entities:zod.z.array(hs)});var _e=zod.z.object({name:zod.z.string(),goal:zod.z.string(),features:zod.z.array(zod.z.string()),domain:zod.z.string(),database:zod.z.enum(["mongodb","postgresql"]),backendRuntime:zod.z.literal("nodejs"),apiStyle:zod.z.enum(["rest","graphql"])}),wt=zod.z.object({id:zod.z.string(),question:zod.z.string(),context:zod.z.string(),suggestions:zod.z.array(zod.z.string()),multiSelect:zod.z.boolean(),required:zod.z.boolean()}),ys=zod.z.object({role:zod.z.enum(["user","assistant"]),content:zod.z.string()}),Xi=zod.z.object({stage:zod.z.enum(["discovery","requirements","design","complete"]),projectBrief:_e.nullable(),actors:zod.z.array(Oe),flows:zod.z.array(Ce),stories:zod.z.array(Ne),modules:zod.z.array(De),database:fe.nullable(),history:zod.z.array(ys),pendingQuestions:zod.z.array(wt)});var Ss=zod.z.object({totalActors:zod.z.number(),totalFlows:zod.z.number(),totalStories:zod.z.number(),totalModules:zod.z.number(),totalEntities:zod.z.number(),overview:zod.z.string()}),nr=zod.z.object({project:_e,actors:zod.z.array(Oe),flows:zod.z.array(Ce),stories:zod.z.array(Ne),modules:zod.z.array(De),database:fe,summary:Ss});var he=`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.
|
|
460
|
+
|
|
461
|
+
You work in stages: discovery (understand the project and tech preferences), requirements (actors, flows, stories, modules), design (database + APIs), and complete (final document).
|
|
462
|
+
|
|
463
|
+
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.
|
|
464
|
+
|
|
465
|
+
Guidelines:
|
|
466
|
+
- For tech choices (API style: REST vs GraphQL; database: MongoDB vs PostgreSQL), offer predefined options and ask what the user is comfortable with.
|
|
467
|
+
- For everything else, ask open-ended, context-specific questions based on what the user described. Leave suggestions empty for those.
|
|
468
|
+
- Never repeat a question already answered in the conversation history.
|
|
469
|
+
- When the user says "continue", "yes", "looks good", or similar, treat it as confirmation and advance.
|
|
470
|
+
- Return valid JSON only when the prompt asks for JSON (no markdown code fences unless specified).
|
|
471
|
+
- Backend is Node.js only; database is MongoDB or PostgreSQL per user preference.`;var sr=`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.
|
|
472
|
+
|
|
473
|
+
Determine from the user's words:
|
|
474
|
+
- Project name and goal
|
|
475
|
+
- Key features (array of strings)
|
|
476
|
+
- Domain (e.g. e-commerce, healthcare, saas)
|
|
477
|
+
- API style: "rest" | "graphql" \u2014 infer from context or ask with predefined options
|
|
478
|
+
- Database: "mongodb" | "postgresql" \u2014 ask which they are comfortable with, with predefined options
|
|
479
|
+
- Backend is always "nodejs"
|
|
480
|
+
|
|
481
|
+
Question rules:
|
|
482
|
+
- Tech stack (API style, database): Always provide "suggestions" with predefined options (e.g. ["REST", "GraphQL"], ["MongoDB", "PostgreSQL"]). Frame as "which are you comfortable with?"
|
|
483
|
+
- 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).
|
|
484
|
+
- Never ask: scale, "how many users?", "what's the complexity?", or generic intake-form questions.
|
|
485
|
+
- Before asking, check conversation history \u2014 never repeat something already answered.
|
|
486
|
+
- 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.`,bs=`## Current user message:
|
|
487
|
+
{userMessage}
|
|
742
488
|
|
|
743
|
-
|
|
744
|
-
|
|
489
|
+
## Prior conversation (if any):
|
|
490
|
+
{history}
|
|
745
491
|
|
|
746
|
-
|
|
492
|
+
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.
|
|
747
493
|
|
|
748
|
-
|
|
494
|
+
Return ONLY valid JSON (no markdown, no explanation) in this shape:
|
|
495
|
+
{
|
|
496
|
+
"needsClarification": boolean,
|
|
497
|
+
"questions": [
|
|
498
|
+
{
|
|
499
|
+
"id": "q1",
|
|
500
|
+
"question": "Question text",
|
|
501
|
+
"context": "Why this helps",
|
|
502
|
+
"suggestions": [],
|
|
503
|
+
"multiSelect": false,
|
|
504
|
+
"required": true
|
|
505
|
+
}
|
|
506
|
+
],
|
|
507
|
+
"conversationalMessage": "Brief friendly message to the user",
|
|
508
|
+
"projectBrief": {
|
|
509
|
+
"name": "string",
|
|
510
|
+
"goal": "string",
|
|
511
|
+
"features": ["string"],
|
|
512
|
+
"domain": "string",
|
|
513
|
+
"database": "mongodb" | "postgresql",
|
|
514
|
+
"backendRuntime": "nodejs",
|
|
515
|
+
"apiStyle": "rest" | "graphql"
|
|
516
|
+
}
|
|
517
|
+
}
|
|
749
518
|
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
- **
|
|
753
|
-
- **
|
|
519
|
+
For tech choices (API style, database), populate "suggestions" with the predefined options. For all other questions, use "suggestions": [].
|
|
520
|
+
If needsClarification is true, projectBrief can have empty/default values. If false, projectBrief must be complete.`;function ar(t,e){return bs.replace("{userMessage}",t).replace("{history}",e||"(No prior messages)")}var vt=`## Project:
|
|
521
|
+
- **Name**: {projectName}
|
|
522
|
+
- **Goal**: {projectGoal}
|
|
523
|
+
- **Features**: {projectFeatures}`,xs=`${vt}
|
|
754
524
|
|
|
755
|
-
|
|
756
|
-
- **Authentication**: duplicate email, invalid credentials, expired token, concurrent sessions, password reset with invalid token.
|
|
757
|
-
- **Data**: empty collections, max field lengths, special characters in input, date timezone issues, null references.
|
|
758
|
-
- **API**: missing required fields, invalid field types, unauthorized access, rate limiting, pagination edge (page 0, negative page).
|
|
759
|
-
- **Frontend**: empty states, loading states, network errors, form resubmission, back button behavior.
|
|
760
|
-
- **Integrations**: external API down, timeout, rate limited, invalid response format.
|
|
525
|
+
Identify ALL distinct user types (actors) who will use this system. 2-5 actors. Include unauthenticated and admin roles if applicable.
|
|
761
526
|
|
|
762
|
-
|
|
527
|
+
Return ONLY valid JSON:
|
|
528
|
+
{
|
|
529
|
+
"actors": [
|
|
530
|
+
{ "id": "actor-1", "name": "Name", "description": "Who they are", "goals": ["goal1", "goal2"] }
|
|
531
|
+
],
|
|
532
|
+
"message": "Brief explanation"
|
|
533
|
+
}`,Ts=`${vt}
|
|
763
534
|
|
|
764
|
-
##
|
|
765
|
-
|
|
535
|
+
## Actors (JSON):
|
|
536
|
+
{actors}
|
|
766
537
|
|
|
767
|
-
For
|
|
768
|
-
- **Flow name**: which feature flow this tests (e.g. "Authentication Flow", "Workout CRUD Flow").
|
|
769
|
-
- **Test item**: what to verify (e.g. "Sign up with valid credentials creates account").
|
|
770
|
-
- **Expected result**: what should happen (e.g. "User created in DB, JWT cookie set, redirected to /dashboard").
|
|
538
|
+
For EACH actor, identify 2-5 key user journeys (flows). Each flow: id, actorId, name, description, trigger, outcome.
|
|
771
539
|
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
540
|
+
Return ONLY valid JSON:
|
|
541
|
+
{
|
|
542
|
+
"flows": [
|
|
543
|
+
{ "id": "flow-1", "actorId": "actor-1", "name": "Flow Name", "description": "...", "trigger": "...", "outcome": "..." }
|
|
544
|
+
],
|
|
545
|
+
"message": "Brief explanation"
|
|
546
|
+
}`,Ps=`${vt}
|
|
779
547
|
|
|
780
|
-
##
|
|
781
|
-
Present as grouped checklist items using markdown checkboxes:
|
|
782
|
-
### Flow Name
|
|
783
|
-
- [ ] Test item description -> Expected result
|
|
548
|
+
## Actors: {actors}
|
|
784
549
|
|
|
785
|
-
|
|
550
|
+
## Flows (JSON):
|
|
551
|
+
{flows}
|
|
786
552
|
|
|
787
|
-
|
|
553
|
+
For EACH flow, generate 2-5 user stories. Each story MUST include dataInvolved (entity.field names) for DB design. Include preconditions, postconditions.
|
|
788
554
|
|
|
789
|
-
|
|
790
|
-
|
|
555
|
+
Return ONLY valid JSON:
|
|
556
|
+
{
|
|
557
|
+
"stories": [
|
|
558
|
+
{ "id": "story-1", "flowId": "flow-1", "actor": "ActorName", "action": "...", "benefit": "...", "preconditions": [], "postconditions": [], "dataInvolved": ["User.email", "Order.total"] }
|
|
559
|
+
],
|
|
560
|
+
"message": "Brief explanation"
|
|
561
|
+
}`,Rs=`${vt}
|
|
791
562
|
|
|
792
|
-
|
|
563
|
+
## Actors: {actors}
|
|
564
|
+
## Flows: {flows}
|
|
565
|
+
## Stories (JSON):
|
|
566
|
+
{stories}
|
|
793
567
|
|
|
794
|
-
|
|
568
|
+
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.
|
|
795
569
|
|
|
796
|
-
|
|
570
|
+
Return ONLY valid JSON:
|
|
571
|
+
{
|
|
572
|
+
"modules": [
|
|
573
|
+
{ "id": "module-1", "name": "User", "description": "...", "entity": "User", "apis": [ { "id": "api-1-1", "name": "createUser", "operation": "create", "description": "...", "inputs": [], "outputs": [] } ] }
|
|
574
|
+
],
|
|
575
|
+
"summary": { "totalModules": 0, "totalApis": 0 },
|
|
576
|
+
"message": "Brief explanation"
|
|
577
|
+
}`;function ir(t,e,o){return xs.replace("{projectName}",t).replace("{projectGoal}",e).replace("{projectFeatures}",o)}function lr(t,e,o,r){return Ts.replace("{projectName}",t).replace("{projectGoal}",e).replace("{projectFeatures}",o).replace("{actors}",r)}function cr(t,e,o,r,n){return Ps.replace("{projectName}",t).replace("{projectGoal}",e).replace("{projectFeatures}",o).replace("{actors}",r).replace("{flows}",n)}function pr(t,e,o,r,n,a){return Rs.replace("{projectName}",t).replace("{projectGoal}",e).replace("{projectFeatures}",o).replace("{actors}",r).replace("{flows}",n).replace("{stories}",a)}var Ki=`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.
|
|
797
578
|
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
${t.fields.map(o=>{let r=[o.required?"required":"",o.unique?"unique":""].filter(Boolean).join(", ");return `| ${o.name} | ${o.type} | ${r||"-"} | ${o.description} |`}).join(`
|
|
801
|
-
`)}`:""}function Yi(t){let e=`## Data Models
|
|
579
|
+
## Project brief (includes database: "mongodb" | "postgresql"):
|
|
580
|
+
{projectBrief}
|
|
802
581
|
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
`,o=t.entities.map(r=>{let n=Bi(r),a=r.relations.map(c=>c.field+" \u2192 "+c.references+" ("+c.description+")"),s=a.length?`
|
|
806
|
-
**Relations:** `+a.join("; "):"",i=r.indexes.map(c=>c.name+" ["+c.fields.join(", ")+"]"+(c.unique?" (unique)":"")),l=i.length?`
|
|
807
|
-
**Indexes:** `+i.join("; "):"";return `### ${r.name}
|
|
582
|
+
## Modules (entities and CRUD):
|
|
583
|
+
{modules}
|
|
808
584
|
|
|
809
|
-
|
|
585
|
+
## User stories (data involved):
|
|
586
|
+
{stories}
|
|
810
587
|
|
|
811
|
-
|
|
588
|
+
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.
|
|
812
589
|
|
|
813
|
-
|
|
814
|
-
|
|
590
|
+
Return ONLY valid JSON (no markdown) in this exact shape. Set "type" to the database from the project brief.
|
|
591
|
+
{
|
|
592
|
+
"type": "mongodb" | "postgresql",
|
|
593
|
+
"reasoning": "2-4 sentences on how the schema fits the project",
|
|
594
|
+
"entities": [
|
|
595
|
+
{
|
|
596
|
+
"name": "EntityName",
|
|
597
|
+
"description": "Brief description",
|
|
598
|
+
"fields": [
|
|
599
|
+
{ "name": "fieldName", "type": "DB-native type", "required": true, "unique": false, "description": "..." }
|
|
600
|
+
],
|
|
601
|
+
"indexes": [ { "name": "index_name", "fields": ["field1"], "unique": false } ],
|
|
602
|
+
"relations": [ { "field": "refField", "references": "OtherEntity", "description": "..." } ]
|
|
603
|
+
}
|
|
604
|
+
]
|
|
605
|
+
}`;var dr="You output only valid JSON. No markdown, no explanation.";function ur(t,e,o){return Ki.replace("{projectBrief}",t).replace("{modules}",e).replace("{stories}",o)}var mr="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.",ws=`## Project brief (JSON):
|
|
606
|
+
{projectBrief}
|
|
815
607
|
|
|
816
|
-
|
|
817
|
-
|
|
608
|
+
## Actors (JSON):
|
|
609
|
+
{actors}
|
|
818
610
|
|
|
819
|
-
|
|
611
|
+
## Flows (JSON):
|
|
612
|
+
{flows}
|
|
820
613
|
|
|
821
|
-
|
|
822
|
-
|
|
614
|
+
## Stories (JSON):
|
|
615
|
+
{stories}
|
|
823
616
|
|
|
824
|
-
|
|
825
|
-
|
|
617
|
+
## Modules (JSON):
|
|
618
|
+
{modules}
|
|
826
619
|
|
|
827
|
-
|
|
828
|
-
|
|
620
|
+
## Database design (JSON):
|
|
621
|
+
{database}
|
|
829
622
|
|
|
830
|
-
|
|
623
|
+
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).
|
|
831
624
|
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
625
|
+
Return ONLY valid JSON in this shape (no markdown, no extra text):
|
|
626
|
+
{
|
|
627
|
+
"project": { ... },
|
|
628
|
+
"actors": [ ... ],
|
|
629
|
+
"flows": [ ... ],
|
|
630
|
+
"stories": [ ... ],
|
|
631
|
+
"modules": [ ... ],
|
|
632
|
+
"database": { ... },
|
|
633
|
+
"summary": {
|
|
634
|
+
"totalActors": 0,
|
|
635
|
+
"totalFlows": 0,
|
|
636
|
+
"totalStories": 0,
|
|
637
|
+
"totalModules": 0,
|
|
638
|
+
"totalEntities": 0,
|
|
639
|
+
"overview": "string"
|
|
640
|
+
}
|
|
641
|
+
}`;function gr(t,e,o,r,n,a){return ws.replace("{projectBrief}",t).replace("{actors}",e).replace("{flows}",o).replace("{stories}",r).replace("{modules}",n).replace("{database}",a)}function fr(){return {stage:"discovery",projectBrief:null,actors:[],flows:[],stories:[],modules:[],database:null,history:[],pendingQuestions:[]}}function hr(t,e){let o=e.data;return {...t,...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 Fe(t,e,o){let r={role:e,content:o};return {...t,history:[...t.history,r]}}function At(t){let e=["discovery","requirements","design","complete"],o=e.indexOf(t.stage),n=(o>=0&&o<e.length-1?e[o+1]:void 0)??t.stage;return {...t,stage:n}}function vs(t){return t.map(e=>`${e.name}: ${e.entity} (${e.apis.length} APIs)`).join(`
|
|
642
|
+
`)}function As(t){return t.map(e=>`- ${e.actor}: ${e.action}`).join(`
|
|
643
|
+
`)}function V(t){let e=t.trim(),o=/```(?:json)?\s*([\s\S]*?)```/.exec(e);return o?.[1]?o[1].trim():e}function W(t){try{return {success:!0,data:JSON.parse(t)}}catch(e){return {success:false,error:e instanceof Error?e.message:String(e)}}}async function Et(t,e,o,r){r?.debug("Discovery stage started",{historyLength:e.history.length});let n=e.history.map(L=>`${L.role}: ${L.content}`).slice(-10).join(`
|
|
644
|
+
`),a=ar(t,n),i=[{role:"system",content:`${he}
|
|
839
645
|
|
|
840
|
-
${t.
|
|
646
|
+
${sr}`},{role:"user",content:a}],l=await o.invoke(i,{temperature:.4,maxOutputTokens:4096}),c=V(l.text),p=W(c);if(!p.success)return r?.warn("Discovery response was not valid JSON",{error:p.error}),{message:"I couldn't parse that. Could you describe your project in a few sentences?",advance:false,data:{}};let d=p.data,u=d.conversationalMessage??l.text?.slice(0,500)??"Thanks for the details.",y=d.needsClarification===true,m=[];if(Array.isArray(d.questions))for(let L of d.questions){let j=wt.safeParse(L);j.success&&m.push(j.data);}let J=null;if(d.projectBrief&&!y){let L=_e.safeParse(d.projectBrief);L.success&&(J=L.data);}return r?.debug("Discovery stage complete",{advance:!y&&J!==null,hasProjectBrief:!!J,questionsCount:m.length}),{message:u,questions:m.length?m:void 0,advance:!y&&J!==null,data:{...J&&{projectBrief:J},pendingQuestions:m}}}async function Es(t,e,o){if(t.invokeObject)return (await t.invokeObject(e,xt,{temperature:.4,maxOutputTokens:4096})).data;let r=await t.invoke(e,{temperature:.4,maxOutputTokens:4096}),n=W(V(r.text));if(!n.success)throw new Error(`Actors: ${n.error}`);let a=xt.safeParse(n.data);if(!a.success)throw new Error(`Actors schema: ${a.error.message}`);return a.data}async function Ms(t,e,o,r){if(t.invokeObject)return (await t.invokeObject(e,Tt,{temperature:.4,maxOutputTokens:8192})).data;let n=await t.invoke(e,{temperature:.4,maxOutputTokens:8192}),a=W(V(n.text));if(!a.success)throw new Error(`Flows: ${a.error}`);let s=Tt.safeParse(a.data);if(!s.success)throw new Error(`Flows schema: ${s.error.message}`);return s.data}async function Os(t,e,o,r,n){if(t.invokeObject)return (await t.invokeObject(e,Pt,{temperature:.4,maxOutputTokens:16384})).data;let a=await t.invoke(e,{temperature:.4,maxOutputTokens:16384}),s=W(V(a.text));if(!s.success)throw new Error(`Stories: ${s.error}`);let i=Pt.safeParse(s.data);if(!i.success)throw new Error(`Stories schema: ${i.error.message}`);return i.data}async function Cs(t,e,o,r,n,a){if(t.invokeObject)return (await t.invokeObject(e,Rt,{temperature:.4,maxOutputTokens:16384})).data;let s=await t.invoke(e,{temperature:.4,maxOutputTokens:16384}),i=W(V(s.text));if(!i.success)throw new Error(`Modules: ${i.error}`);let l=Rt.safeParse(i.data);if(!l.success)throw new Error(`Modules schema: ${l.error.message}`);return l.data}async function Mt(t,e,o,r){r?.debug("Requirements stage started");let n=e.projectBrief;if(!n)return {message:"Project brief is missing. Complete discovery first.",advance:false,data:{}};let a=n.name,s=n.goal,i=n.features.join(". "),l=[{role:"system",content:he}];try{l.push({role:"user",content:ir(a,s,i)});let p=(await Es(o,l,r)).actors;r?.debug("Requirements: actors",{count:p.length}),l.push({role:"assistant",content:`[Extracted ${p.length} actors]`}),l.push({role:"user",content:lr(a,s,i,JSON.stringify(p))});let u=(await Ms(o,l,p,r)).flows;r?.debug("Requirements: flows",{count:u.length}),l.push({role:"assistant",content:`[Generated ${u.length} flows]`}),l.push({role:"user",content:cr(a,s,i,JSON.stringify(p),JSON.stringify(u))});let m=(await Os(o,l,p,u,r)).stories;r?.debug("Requirements: stories",{count:m.length}),l.push({role:"assistant",content:`[Generated ${m.length} stories]`}),l.push({role:"user",content:pr(a,s,i,JSON.stringify(p),JSON.stringify(u),JSON.stringify(m))});let L=(await Cs(o,l,p,u,m,r)).modules;return r?.debug("Requirements stage complete",{actors:p.length,flows:u.length,stories:m.length,modules:L.length}),{message:`I've identified ${p.length} actors, ${u.length} flows, ${m.length} stories, and ${L.length} modules. Proceeding to technical design.`,advance:!0,data:{actors:p,flows:u,stories:m,modules:L,pendingQuestions:[]}}}catch(c){let p=c instanceof Error?c.message:String(c);return r?.warn("Requirements stage failed",{error:p}),{message:`Requirements step failed: ${p}. Please try again.`,advance:false,data:{}}}}async function Ot(t,e,o,r){let n=e.projectBrief;if(!n)return {message:"Project brief is missing.",advance:false,data:{}};if(!e.modules.length||!e.stories.length)return {message:"Requirements (modules and stories) are missing. Run requirements stage first.",advance:false,data:{}};r?.info("Design stage: database design",{modules:e.modules.length,stories:e.stories.length});let a=JSON.stringify(n),s=vs(e.modules),i=As(e.stories),l=ur(a,s,i),c=[{role:"system",content:dr},{role:"user",content:l}],p=await o.invoke(c,{temperature:.3,maxOutputTokens:8192}),d=V(p.text),u=W(d);if(!u.success)return r?.warn("Database design response was not valid JSON",{error:u.error}),{message:"Failed to parse database design response. Please try again.",advance:false,data:{}};let y=fe.safeParse(u.data);if(!y.success){let J=y.error;return r?.warn("Database design schema validation failed",{error:zod.z.treeifyError(J)}),{message:"Failed to produce database design. Please try again.",advance:false,data:{}}}let m=y.data;return {message:`Database design complete: ${m.type}. API design will be handled by the api-designer module.`,advance:true,data:{database:m,pendingQuestions:[]}}}async function Ct(t,e,o,r){r?.debug("Synthesis stage started");let n=e.projectBrief;if(!n||!e.database)return {message:"Missing project brief or database design. Complete earlier stages first.",advance:false,data:{}};let a=gr(JSON.stringify(n),JSON.stringify(e.actors),JSON.stringify(e.flows),JSON.stringify(e.stories),JSON.stringify(e.modules),JSON.stringify(e.database)),i=[{role:"system",content:`${he}
|
|
841
647
|
|
|
842
|
-
|
|
648
|
+
${mr}`},{role:"user",content:a}],l=await o.invoke(i,{temperature:.3,maxOutputTokens:16384}),c=V(l.text),p=W(c);if(!p.success)return r?.warn("Synthesis response was not valid JSON",{error:p.error}),{message:"Failed to compile final requirement document. Please try again.",advance:false,data:{}};let d=nr.safeParse(p.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 u=d.data;return r?.info("Synthesis stage complete",{overview:u.summary?.overview}),{message:`Requirement document ready. ${u.summary.overview}`,advance:true,data:{finalRequirement:u}}}var Nt=class{stageName="discovery";async process(e,o){return Et(o.userMessage,e,o.model,o.logger)}canAdvance(e){return e.advance}getNextStageName(){return "requirements"}};var Dt=class{stageName="requirements";async process(e,o){return Mt(o.userMessage,e,o.model,o.logger)}canAdvance(e){return e.advance}getNextStageName(){return "design"}};var _t=class{stageName="design";async process(e,o){return Ot(o.userMessage,e,o.model,o.logger)}canAdvance(e){return e.advance}getNextStageName(){return "complete"}};var kt=class{stageName="complete";async process(e,o){return Ct(o.userMessage,e,o.model,o.logger)}canAdvance(e){return e.advance}getNextStageName(){return null}};var el={discovery:new Nt,requirements:new Dt,design:new _t,complete:new kt};function yr(t){return el[t]}async function Ns(t,e,o,r,n){n?.debug("Stage processor invoked",{stage:t});let s=await yr(t).process(o,{userMessage:e,model:r,logger:n}),i=hr(o,s),l="finalRequirement"in s.data?s.data.finalRequirement:void 0;n?.debug("Stage result",{stage:t,advance:s.advance,hasFinalRequirement:!!l});let c={...i,pendingQuestions:s.questions??i.pendingQuestions};return {message:s.message,questions:s.questions??i.pendingQuestions,advance:s.advance,data:c,finalRequirement:l}}var Sr=["discovery","requirements","design","complete"];async function It(t,e,o){let{logger:r}=o,n=o.model??{provider:"openai",model:"gpt-4o-mini"},a=v(n),s=e??fr();s=Fe(s,"user",t),r?.info("Chat turn",{stage:s.stage,messageLength:t.length});let i="",l=[],c=null,p=async y=>{let m=await Ns(y,t,s,a,r);return i=m.message,l=m.questions,s=m.data,m.finalRequirement&&(c=m.finalRequirement),{advance:m.advance,finalReq:m.finalRequirement}},d=s.stage;r?.info("Stage",{stage:d});let u=await p(d);for(s={...s,pendingQuestions:l};u.advance&&!c;){let y=Sr.indexOf(d),m=y>=0&&y<Sr.length-1?Sr[y+1]:void 0;if(m===void 0)break;r?.info("Stage transition",{from:d,to:m}),d=m,s=At(s),s={...s,stage:d},r?.info("Stage",{stage:d}),u=await p(d),s={...s,pendingQuestions:l};}return s=Fe(s,"assistant",i),r?.info("Chat turn done",{stage:d,hasFinalRequirement:!!c}),{message:i,context:s,questions:l,finalRequirement:c}}var Ds=10;async function br(t){let{input:e,model:o,onStep:r,logger:n}=t;n?.info("Starting requirement gatherer agent",{maxTurns:Ds});let a=null,s=await It(e,a,{model:o,logger:n});a=s.context;let i=1;for(;!s.finalRequirement&&i<Ds;)n?.debug("Requirement gatherer turn",{turn:i}),s=await It("continue",a,{model:o,logger:n}),a=s.context,i++;let l=s.finalRequirement?JSON.stringify(s.finalRequirement,null,2):s.message,c=a.history.map(p=>({role:p.role,content:p.content}));return n?.info("Requirement gatherer agent completed",{turns:i,hasFinalRequirement:!!s.finalRequirement}),{output:l,steps:[],totalUsage:void 0,messages:c}}var ol="discovery",jt=class{data={};withStage(e){return this.data.stage=e,this}withProjectBrief(e){return this.data.projectBrief=e,this}withActors(e){return this.data.actors=e,this}withFlows(e){return this.data.flows=e,this}withStories(e){return this.data.stories=e,this}withModules(e){return this.data.modules=e,this}withDatabase(e){return this.data.database=e,this}withHistory(e){return this.data.history=e,this}withPendingQuestions(e){return this.data.pendingQuestions=e,this}reset(){return this.data={},this}build(){return {stage:this.data.stage??ol,projectBrief:this.data.projectBrief??null,actors:this.data.actors??[],flows:this.data.flows??[],stories:this.data.stories??[],modules:this.data.modules??[],database:this.data.database??null,history:this.data.history??[],pendingQuestions:this.data.pendingQuestions??[]}}};function rl(){return new jt}var xr=zod.z.object({name:zod.z.string(),type:zod.z.string(),required:zod.z.coerce.boolean().default(false),unique:zod.z.coerce.boolean().default(false),description:zod.z.string().default(""),default:zod.z.string().optional()}),_s=zod.z.object({name:zod.z.string().default(""),fields:zod.z.array(zod.z.string()).default([]),unique:zod.z.coerce.boolean().default(false)}),nl=zod.z.string().transform(t=>{let e=t.toLowerCase().replace(/[\s_-]+/g,"");return ["1:1","onetoone"].includes(e)?"1:1":["1:n","1:m","n:1","onetomany","manytoone"].includes(e)?"1:N":["m:n","n:m","manytomany"].includes(e)?"M:N":t}).pipe(zod.z.enum(["1:1","1:N","M:N"])),ks=zod.z.object({field:zod.z.string(),references:zod.z.string(),type:nl,description:zod.z.string().default("")}),Tr=zod.z.object({name:zod.z.string(),description:zod.z.string().default(""),fields:zod.z.union([zod.z.array(xr),zod.z.record(zod.z.string(),zod.z.unknown())]).transform((t,e)=>{if(Array.isArray(t))return t;let o=[];for(let[r,n]of Object.entries(t)){let a=typeof n=="object"&&n!==null?{...n}:{};a.name||(a.name=r);let s=xr.safeParse(a);if(s.success)o.push(s.data);else for(let i of s.error.issues)e.addIssue({...i,path:[r,...i.path]});}return o}),indexes:zod.z.array(_s).default([]),relations:zod.z.array(ks).default([])}),sl=zod.z.string().transform(t=>t.toLowerCase().trim()).pipe(zod.z.enum(["mongodb","postgresql"])),oe=zod.z.object({type:sl,reasoning:zod.z.string().default(""),entities:zod.z.array(Tr).default([])});var ke=zod.z.object({fieldName:zod.z.string().describe("fieldName must be in camelCase"),fieldType:zod.z.string().default("string").transform(t=>{let e=t.toLowerCase().trim();return ["string","text","varchar"].includes(e)?"string":["number","int","integer","float","double","decimal"].includes(e)?"number":["boolean","bool"].includes(e)?"boolean":["types.objectid","objectid","ref","reference"].includes(e)?"Types.ObjectId":["date","datetime","timestamp"].includes(e)?"Date":["object","json","mixed"].includes(e)?"object":["email"].includes(e)?"email":["password","hash"].includes(e)?"password":["enum","select"].includes(e)?"enum":("string")}).pipe(zod.z.enum(["string","number","boolean","Types.ObjectId","Date","object","email","password","enum"])),isArray:zod.z.coerce.boolean().default(false),isRequired:zod.z.coerce.boolean().default(true),isUnique:zod.z.coerce.boolean().default(false),values:zod.z.array(zod.z.string()).default([]).describe("Enum values if fieldType is enum, else empty array"),defaultVal:zod.z.union([zod.z.string(),zod.z.boolean(),zod.z.number(),zod.z.null()]).optional(),relationTo:zod.z.string().optional().describe("Module name for relations"),relationType:zod.z.string().transform(t=>{let e=t.toLowerCase().replace(/[\s_]+/g,"-");return ["one-to-one","1:1","1-to-1"].includes(e)?"one-to-one":["many-to-one","n:1","n-to-1","many-to-1","*:1"].includes(e)?"many-to-one":""}).pipe(zod.z.enum(["one-to-one","many-to-one",""])).optional(),isPrivate:zod.z.coerce.boolean().default(false).describe("True if password field, else false")});var Ie=zod.z.object({moduleName:zod.z.string().describe("camelCase, single word, never auth/authentication"),isUserModule:zod.z.coerce.boolean().default(false),authMethod:zod.z.string().transform(t=>{let e=t.toUpperCase().replace(/[\s-]+/g,"_");return ["EMAIL_AND_PASSWORD","EMAIL_PASSWORD","EMAIL"].includes(e)?"EMAIL_AND_PASSWORD":["PHONE_AND_OTP","PHONE_OTP","PHONE","SMS"].includes(e)?"PHONE_AND_OTP":""}).pipe(zod.z.enum(["EMAIL_AND_PASSWORD","PHONE_AND_OTP",""])).optional(),emailField:zod.z.string().optional(),passwordField:zod.z.string().optional(),phoneField:zod.z.string().optional(),roleField:zod.z.string().optional(),permissions:zod.z.record(zod.z.string(),zod.z.array(zod.z.enum(["CREATE","READ","UPDATE","DELETE"]))).optional().describe("Permissions per role"),fields:zod.z.union([zod.z.array(ke),zod.z.record(zod.z.string(),zod.z.unknown())]).transform((t,e)=>{if(Array.isArray(t))return t;let o=[];for(let[r,n]of Object.entries(t)){let a=typeof n=="object"&&n!==null?{...n}:{};a.fieldName||(a.fieldName=r);let s=ke.safeParse(a);if(s.success)o.push(s.data);else for(let i of s.error.issues)e.addIssue({...i,path:[r,...i.path]});}return o})});var X=zod.z.object({projectName:zod.z.string().default("project").describe("projectName must be in kebab-case"),projectDescription:zod.z.string().default(""),modules:zod.z.union([zod.z.array(Ie),zod.z.record(zod.z.string(),zod.z.unknown())]).transform((t,e)=>{if(Array.isArray(t))return t;let o=[];for(let[r,n]of Object.entries(t)){let a=typeof n=="object"&&n!==null?{...n}:{};a.moduleName||(a.moduleName=r);let s=Ie.safeParse(a);if(s.success)o.push(s.data);else for(let i of s.error.issues)e.addIssue({...i,path:[r,...i.path]});}return o}),author:zod.z.string().default("sijeeshmiziha")});var qt=`You are a senior database architect specializing in both MongoDB and PostgreSQL schema design.
|
|
843
649
|
|
|
844
650
|
You analyze requirements and produce enterprise-quality data models with:
|
|
845
651
|
- Properly typed fields (MongoDB: ObjectId, string, number, date, array; PostgreSQL: uuid, varchar, text, integer, timestamp, jsonb)
|
|
@@ -848,7 +654,7 @@ You analyze requirements and produce enterprise-quality data models with:
|
|
|
848
654
|
- Validation constraints and default values
|
|
849
655
|
- Security considerations (hashed passwords, encrypted fields)
|
|
850
656
|
|
|
851
|
-
Output only valid JSON unless instructed otherwise.`;var
|
|
657
|
+
Output only valid JSON unless instructed otherwise.`;var Is=`## Requirements:
|
|
852
658
|
{requirement}
|
|
853
659
|
|
|
854
660
|
Design the database schema. Determine the best database type (mongodb or postgresql) based on the requirements, or use the one specified.
|
|
@@ -871,13 +677,13 @@ Return ONLY valid JSON:
|
|
|
871
677
|
"relations": [ { "field": "refField", "references": "OtherEntity", "type": "1:N", "description": "..." } ]
|
|
872
678
|
}
|
|
873
679
|
]
|
|
874
|
-
}`,
|
|
680
|
+
}`,js=`## Current Schema (JSON):
|
|
875
681
|
{existingSchema}
|
|
876
682
|
|
|
877
683
|
## Feedback:
|
|
878
684
|
{feedback}
|
|
879
685
|
|
|
880
|
-
Update the schema based on the feedback. Return the complete updated schema as valid JSON in the same format.`;function
|
|
686
|
+
Update the schema based on the feedback. Return the complete updated schema as valid JSON in the same format.`;function Pr(t){return Is.replace("{requirement}",t)}function Rr(t,e){return js.replace("{existingSchema}",t).replace("{feedback}",e)}var qs=`## Project: {projectName}
|
|
881
687
|
## Goal: {projectGoal}
|
|
882
688
|
## Database: {databaseType}
|
|
883
689
|
|
|
@@ -907,7 +713,7 @@ Apply the 5-phase enterprise data modeling process:
|
|
|
907
713
|
- Verify every entity referenced in relations exists.
|
|
908
714
|
- Verify no orphan fields or missing indexes.
|
|
909
715
|
|
|
910
|
-
Return ONLY valid JSON in the DataModelDesign format.`;function
|
|
716
|
+
Return ONLY valid JSON in the DataModelDesign format.`;function wr(t,e,o,r){return qs.replace("{projectName}",t).replace("{projectGoal}",e).replace("{databaseType}",o).replace("{context}",r)}var K=`You are an expert MongoDB database architect with deep expertise in schema design, performance optimization, scalability, and domain-driven design. You analyze requirements systematically using a multi-phase approach to create production-ready database schemas.
|
|
911
717
|
|
|
912
718
|
## ANALYSIS FRAMEWORK
|
|
913
719
|
|
|
@@ -957,19 +763,19 @@ Synthesize all analyses into the final schema:
|
|
|
957
763
|
2. **Relationships**: One-to-One: reference in BOTH collections; Many-to-One: reference in "many" side; One-to-Many: FORBIDDEN - invert to many-to-one
|
|
958
764
|
3. **Data Types**: NO arrays of ObjectIds; Timestamps: createdAt, updatedAt in EVERY collection; Enums: fieldType: 'enum' with values array
|
|
959
765
|
4. **Security**: NO separate "Auth" collection; NO token storage; Password fields: isPrivate: true
|
|
960
|
-
5. **Authorization (RBAC)**: Define permissions per role on user modules`;function
|
|
766
|
+
5. **Authorization (RBAC)**: Define permissions per role on user modules`;function vr(t){return !t||t.length===0?'No specific user types defined. Assume a general "User" role.':t.map((e,o)=>{let r=e.goals.filter(n=>n.trim()).join(`
|
|
961
767
|
- `);return `### ${o+1}. ${e.name}
|
|
962
768
|
**Description:** ${e.description}
|
|
963
769
|
**Goals:**
|
|
964
770
|
- ${r||"No specific goals defined"}`}).join(`
|
|
965
771
|
|
|
966
|
-
`)}function
|
|
772
|
+
`)}function Ar(t,e){return !t||t.length===0?"No specific user flows defined.":t.map((o,r)=>{let n=e.find(a=>a.id===o.actorId);return `### ${r+1}. ${o.name}
|
|
967
773
|
**Actor:** ${n?.name||"User"}
|
|
968
774
|
**Description:** ${o.description}
|
|
969
775
|
**Trigger:** ${o.trigger||"User initiates action"}
|
|
970
776
|
**Outcome:** ${o.outcome||"Action completed"}`}).join(`
|
|
971
777
|
|
|
972
|
-
`)}function
|
|
778
|
+
`)}function Er(t,e){if(!t||t.length===0)return "No specific user stories defined.";let o=new Map;for(let a of t){let s=o.get(a.flowId)||[];s.push(a),o.set(a.flowId,s);}let r=[];for(let a of e){let s=o.get(a.id)||[];if(s.length!==0){r.push(`### Flow: ${a.name}
|
|
973
779
|
`);for(let i of s){let l=i.preconditions.filter(u=>u.trim()),c=i.postconditions.filter(u=>u.trim()),p=i.dataInvolved.filter(u=>u.trim()),d=`**As a** ${i.actor}, **I want to** ${i.action}, **so that** ${i.benefit}
|
|
974
780
|
`;l.length&&(d+=`
|
|
975
781
|
**Preconditions:**
|
|
@@ -988,8 +794,8 @@ ${p.map(u=>`- ${u}`).join(`
|
|
|
988
794
|
`;s.length&&(i+=`
|
|
989
795
|
**Data Involved:** ${s.join(", ")}
|
|
990
796
|
`),r.push(i);}}return r.join(`
|
|
991
|
-
`)}function
|
|
992
|
-
`)}function
|
|
797
|
+
`)}function Mr(t){if(!t)return "No specific technical requirements. Use defaults.";let e=[`**Authentication:** ${t.authentication||"none"}`];return t.authorization?(e.push("**Authorization (RBAC):** Enabled"),t.roles?.length&&e.push(`**Defined Roles:** ${t.roles.join(", ")}`)):e.push("**Authorization:** Disabled"),t.realtime&&e.push("**Realtime Features:** Required"),t.fileUpload&&e.push("**File Upload:** Required"),t.search&&e.push("**Search Functionality:** Required"),t.integrations?.length&&e.push(`**Integrations:** ${t.integrations.join(", ")}`),e.join(`
|
|
798
|
+
`)}function Ft(t){let e=new Set;for(let o of t)for(let r of o.dataInvolved)r.trim()&&e.add(r.trim());return Array.from(e)}function Ut(t){return t.map(e=>e.name.toLowerCase().replaceAll(/\s+/g,"_"))}function Lt(t){return {projectName:t.projectName,projectGoal:t.projectGoal,projectDescription:t.projectDescription||t.projectGoal,userTypes:vr(t.actors),userFlows:Ar(t.flows,t.actors),userStories:Er(t.stories,t.flows),technicalRequirements:Mr(t.technicalRequirements)}}function Ue(t){return `${K}
|
|
993
799
|
|
|
994
800
|
Design a robust and efficient MongoDB database schema based on the following requirements:
|
|
995
801
|
|
|
@@ -1002,7 +808,7 @@ ${t}
|
|
|
1002
808
|
3. Define proper relationships between modules
|
|
1003
809
|
4. Set appropriate permissions for user modules
|
|
1004
810
|
|
|
1005
|
-
Return ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`}function
|
|
811
|
+
Return ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`}function Le(t){let e=Lt(t);return `${K}
|
|
1006
812
|
|
|
1007
813
|
---
|
|
1008
814
|
|
|
@@ -1062,7 +868,7 @@ Follow the 5-phase analysis framework:
|
|
|
1062
868
|
### Step 5: Schema Construction
|
|
1063
869
|
Generate the final schema with complete module definitions, fields, relationships, RBAC permissions, and timestamps.
|
|
1064
870
|
|
|
1065
|
-
Return ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`}function
|
|
871
|
+
Return ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`}function Ge(t,e){return `${K}
|
|
1066
872
|
|
|
1067
873
|
Update the existing MongoDB schema based on user feedback.
|
|
1068
874
|
|
|
@@ -1078,7 +884,7 @@ ${t}
|
|
|
1078
884
|
${e}
|
|
1079
885
|
|
|
1080
886
|
Return the updated schema as a valid JSON object matching the original schema format.
|
|
1081
|
-
IMPORTANT: Return ONLY the JSON object, no markdown code blocks, no explanations.`}var
|
|
887
|
+
IMPORTANT: Return ONLY the JSON object, no markdown code blocks, no explanations.`}var Gt=q("validate_data_model",oe,"Validates a data model JSON string against the DataModelDesign schema. Returns valid: true or valid: false with errors.","schema");function Bt(t){return h({name:"design_schema",description:"Generate a database schema (MongoDB or PostgreSQL) from plain text requirements. Returns the full data model as JSON.",input:zod.z.object({requirement:zod.z.string().describe("Plain text description of the data modeling requirements")}),handler:async({requirement:e})=>{let o=Pr(e),r=[{role:"system",content:"You are a database schema expert. Return only valid JSON."},{role:"user",content:o}],n=await t.invoke(r,{temperature:.3,maxOutputTokens:8192});return M(n.text,oe)}})}function Jt(t){return h({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:zod.z.object({projectName:zod.z.string().describe("Project name"),projectGoal:zod.z.string().describe("Project goal / purpose"),databaseType:zod.z.enum(["mongodb","postgresql"]).describe("Target database type"),context:zod.z.string().describe("Full project context: features, actors, flows, stories")}),handler:async({projectName:e,projectGoal:o,databaseType:r,context:n})=>{let a=wr(e,o,r,n),s=[{role:"system",content:"You are a database schema expert. Return only valid JSON."},{role:"user",content:a}],i=await t.invoke(s,{temperature:.2,maxOutputTokens:16384});return M(i.text,oe)}})}function Yt(t){return h({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:zod.z.object({existingSchema:zod.z.string().describe("Current data model schema as JSON string"),feedback:zod.z.string().describe("Feedback describing desired changes")}),handler:async({existingSchema:e,feedback:o})=>{let r=Rr(e,o),n=[{role:"system",content:"You are a database schema expert. Return only valid JSON."},{role:"user",content:r}],a=await t.invoke(n,{temperature:.3,maxOutputTokens:8192});return M(a.text,oe)}})}var zt=q("validate_schema",X,"Validates a MongoDB project schema JSON string against the expected schema. Returns valid: true or valid: false with errors.","schema");function $t(t){return h({name:"design_database",description:"Generate a MongoDB database schema from plain text requirements. Returns the full project schema as JSON.",input:zod.z.object({requirement:zod.z.string().describe("Plain text description of the database requirements")}),handler:async({requirement:e})=>{let o=Ue(e),r=[{role:"system",content:"You are a MongoDB schema expert. Return only valid JSON."},{role:"user",content:o}],n=await t.invoke(r,{temperature:.3,maxOutputTokens:8192});return M(n.text,X)}})}var al=zod.z.object({projectName:zod.z.string(),projectGoal:zod.z.string(),projectDescription:zod.z.string().optional(),actors:zod.z.array(zod.z.object({id:zod.z.string(),name:zod.z.string(),description:zod.z.string(),goals:zod.z.array(zod.z.string())})),flows:zod.z.array(zod.z.object({id:zod.z.string(),actorId:zod.z.string(),name:zod.z.string(),description:zod.z.string(),trigger:zod.z.string(),outcome:zod.z.string()})),stories:zod.z.array(zod.z.object({id:zod.z.string(),flowId:zod.z.string(),actor:zod.z.string(),action:zod.z.string(),benefit:zod.z.string(),preconditions:zod.z.array(zod.z.string()),postconditions:zod.z.array(zod.z.string()),dataInvolved:zod.z.array(zod.z.string())})),technicalRequirements:zod.z.object({authentication:zod.z.string().transform(t=>{let e=t.toLowerCase().replace(/[\s_-]+/g,"");return ["none","no",""].includes(e)?"none":["email","emailpassword","emailandpassword"].includes(e)?"email":["oauth","oauth2","social"].includes(e)?"oauth":["phone","phoneotp","sms"].includes(e)?"phone":["emailandphone","emailphone","both"].includes(e)?"email_and_phone":"email"}).pipe(zod.z.enum(["none","email","oauth","phone","email_and_phone"])),authorization:zod.z.coerce.boolean().default(false),roles:zod.z.array(zod.z.string()).optional(),integrations:zod.z.array(zod.z.string()).optional(),realtime:zod.z.boolean().optional(),fileUpload:zod.z.boolean().optional(),search:zod.z.boolean().optional()}).optional()});function Ht(t){return h({name:"design_database_pro",description:"Generate a MongoDB schema from structured requirements (actors, flows, stories, technical requirements). Returns dbDesign and metadata.",input:al,handler:async e=>{let o=Le(e),r=[{role:"system",content:"You are a MongoDB schema expert. Return only valid JSON."},{role:"user",content:o}],n=await t.invoke(r,{temperature:.2,maxOutputTokens:16384}),a=M(n.text,X),s={entitiesDetected:Ft(e.stories),rolesExtracted:Ut(e.actors)};return {dbDesign:a,metadata:s}}})}function Qt(t){return h({name:"redesign_database",description:"Update an existing MongoDB project schema based on user feedback. Provide the current schema JSON string and the feedback.",input:zod.z.object({existingSchema:zod.z.string().describe("Current project schema as JSON string"),feedback:zod.z.string().describe("User feedback describing desired changes")}),handler:async({existingSchema:e,feedback:o})=>{let r=Ge(e,o),n=[{role:"system",content:"You are a MongoDB schema expert. Return only valid JSON."},{role:"user",content:r}],a=await t.invoke(n,{temperature:.3,maxOutputTokens:8192});return M(a.text,X)}})}function Nr(t){return {validate_data_model:Gt,design_schema:Bt(t),design_schema_pro:Jt(t),refine_schema:Yt(t)}}function Dr(t){return {validate_schema:zt,design_database:$t(t),design_database_pro:Ht(t),redesign_database:Qt(t)}}var il=`${qt}
|
|
1082
888
|
|
|
1083
889
|
You are the data modeling orchestrator. When the user asks for a data model:
|
|
1084
890
|
|
|
@@ -1088,7 +894,7 @@ You are the data modeling orchestrator. When the user asks for a data model:
|
|
|
1088
894
|
4. **Refine (optional)**: Use subagent_schema-refiner to validate and suggest improvements to the generated schema.
|
|
1089
895
|
5. **Validate**: Use validate_data_model to check the final schema JSON before returning.
|
|
1090
896
|
|
|
1091
|
-
Respond with the final data model schema as JSON.`;async function
|
|
897
|
+
Respond with the final data model schema as JSON.`;async function _r(t){let{input:e,model:o,maxIterations:r=15,onStep:n,logger:a}=t,s=v(o??{provider:"openai",model:"gpt-4o-mini"}),i=Nr(s),l=me(),c=I([ne,mt,l],{parentModel:s}),p={...i,...c};return C({model:s,tools:p,systemPrompt:il,input:e,maxIterations:r,onStep:n,logger:a})}var ll=`${K}
|
|
1092
898
|
|
|
1093
899
|
You are the MongoDB database design orchestrator. When the user asks for a database design:
|
|
1094
900
|
|
|
@@ -1098,7 +904,7 @@ You are the MongoDB database design orchestrator. When the user asks for a datab
|
|
|
1098
904
|
4. **Validate**: Use validate_schema to check the final schema JSON.
|
|
1099
905
|
5. **Redesign**: If changes are requested, use redesign_database with existing schema and feedback.
|
|
1100
906
|
|
|
1101
|
-
Respond with the final schema as JSON.`;async function
|
|
907
|
+
Respond with the final schema as JSON.`;async function cl(t){let{input:e,model:o,maxIterations:r=15,onStep:n,logger:a}=t,s=v(o??{provider:"openai",model:"gpt-4o-mini"}),i=Dr(s),l=me(),c=I([ne,l],{parentModel:s}),p={...i,...c};return C({model:s,tools:p,systemPrompt:ll,input:e,maxIterations:r,onStep:n,logger:a})}var pl=zod.z.union([zod.z.enum(["GET","POST","PUT","PATCH","DELETE"]),zod.z.string()]).transform(t=>typeof t=="string"?t.toUpperCase():t).pipe(zod.z.enum(["GET","POST","PUT","PATCH","DELETE"])),kr=zod.z.record(zod.z.string(),zod.z.unknown()).optional().default({}).transform(t=>Object.fromEntries(Object.entries(t??{}).map(([e,o])=>[e,typeof o=="string"?o:String(o)]))),Ls=zod.z.array(zod.z.unknown()).default([]).transform(t=>t.map(e=>typeof e=="string"?e:JSON.stringify(e))),Ir=zod.z.object({id:zod.z.string(),resource:zod.z.string(),method:pl,path:zod.z.string(),description:zod.z.string(),auth:zod.z.coerce.boolean(),roles:zod.z.array(zod.z.string()).default([]),requestBody:kr,responseBody:kr,queryParams:kr,validation:Ls,errorResponses:Ls}),jr=zod.z.object({name:zod.z.string(),type:zod.z.enum(["query","mutation","subscription"]),description:zod.z.string(),auth:zod.z.coerce.boolean(),roles:zod.z.array(zod.z.string()).default([]),args:zod.z.array(zod.z.object({name:zod.z.string(),type:zod.z.string(),required:zod.z.coerce.boolean()})),returnType:zod.z.string()}),dl=zod.z.unknown().transform(t=>(typeof t=="string"?t.toLowerCase().trim():"rest").includes("graphql")?"graphql":"rest"),pe=zod.z.object({style:dl,baseUrl:zod.z.string().default("/api/v1"),endpoints:zod.z.array(Ir).default([]),graphqlOperations:zod.z.array(jr).default([])});var Vt=`You are a senior API architect specializing in REST and GraphQL API design.
|
|
1102
908
|
|
|
1103
909
|
You analyze data models and requirements to produce enterprise-quality API designs with:
|
|
1104
910
|
- RESTful endpoints grouped by resource with proper HTTP methods
|
|
@@ -1108,7 +914,7 @@ You analyze data models and requirements to produce enterprise-quality API desig
|
|
|
1108
914
|
- Authentication and authorization annotations per endpoint
|
|
1109
915
|
- GraphQL types, queries, mutations, and subscriptions when applicable
|
|
1110
916
|
|
|
1111
|
-
Output only valid JSON unless instructed otherwise.`;var
|
|
917
|
+
Output only valid JSON unless instructed otherwise.`;var Gs=`## Requirements:
|
|
1112
918
|
{requirement}
|
|
1113
919
|
|
|
1114
920
|
Design the API. Determine the best API style (rest or graphql) based on the requirements, or use the one specified.
|
|
@@ -1124,7 +930,7 @@ Return ONLY valid JSON:
|
|
|
1124
930
|
{ "id": "ep-1", "resource": "users", "method": "POST", "path": "/api/v1/users", "description": "Create user", "auth": false, "roles": [], "requestBody": {}, "responseBody": {}, "queryParams": {}, "validation": [], "errorResponses": [] }
|
|
1125
931
|
],
|
|
1126
932
|
"graphqlOperations": []
|
|
1127
|
-
}`,
|
|
933
|
+
}`,Bs=`## Project: {projectName}
|
|
1128
934
|
## API Style: {apiStyle}
|
|
1129
935
|
## Data Model:
|
|
1130
936
|
{dataModel}
|
|
@@ -1135,139 +941,53 @@ Design a comprehensive API surface from the data model and requirements. For eac
|
|
|
1135
941
|
|
|
1136
942
|
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.
|
|
1137
943
|
|
|
1138
|
-
Return ONLY valid JSON in the ApiDesign format.`;function
|
|
944
|
+
Return ONLY valid JSON in the ApiDesign format.`;function qr(t){return Gs.replace("{requirement}",t)}function Fr(t,e,o,r){return Bs.replace("{projectName}",t).replace("{apiStyle}",e).replace("{dataModel}",o).replace("{context}",r)}var Wt=q("validate_api",pe,"Validates an API design JSON string against the ApiDesign schema. Returns valid: true or valid: false with errors.","design");function Xt(t){return h({name:"design_api",description:"Generate an API design (REST or GraphQL) from plain text requirements. Returns the full API design as JSON.",input:zod.z.object({requirement:zod.z.string().describe("Plain text description of the API requirements")}),handler:async({requirement:e})=>{let o=qr(e),r=[{role:"system",content:"You are an API architect. Return only valid JSON."},{role:"user",content:o}],n=await t.invoke(r,{temperature:.3,maxOutputTokens:8192});return M(n.text,pe)}})}function Kt(t){return h({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:zod.z.object({projectName:zod.z.string().describe("Project name"),apiStyle:zod.z.enum(["rest","graphql"]).describe("Target API style"),dataModel:zod.z.string().describe("Data model JSON or description"),context:zod.z.string().describe("Project context: features, actors, stories")}),handler:async({projectName:e,apiStyle:o,dataModel:r,context:n})=>{let a=Fr(e,o,r,n),s=[{role:"system",content:"You are an API architect. Return only valid JSON."},{role:"user",content:a}],i=await t.invoke(s,{temperature:.2,maxOutputTokens:16384});return M(i.text,pe)}})}function Ur(t){return {validate_api:Wt,design_api:Xt(t),design_api_pro:Kt(t)}}var ul=`${Vt}
|
|
1139
945
|
|
|
1140
946
|
You are the API design orchestrator. When the user asks for an API design:
|
|
1141
947
|
|
|
1142
|
-
1. **Analyze endpoints**: Use subagent_endpoint-analyzer to derive endpoints from the data model and requirements.
|
|
1143
|
-
2. **Design contracts**: Use subagent_contract-designer to design request/response contracts, validation rules, and error responses.
|
|
1144
|
-
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.
|
|
1145
|
-
4. **Validate**: Use validate_api to check the final API design JSON before returning.
|
|
1146
|
-
|
|
1147
|
-
Respond with the final API design as JSON.`;async function cl(t){let{input:e,model:o,maxIterations:r=15,onStep:n,logger:a}=t,s=v(o??{provider:"openai",model:"gpt-4o-mini"}),i=Yr(s),l=I([Ce,Ne],{parentModel:s}),c={...i,...l};return C({model:s,tools:c,systemPrompt:ll,input:e,maxIterations:r,onStep:n,logger:a})}var js=zod.z.object({order:zod.z.number(),side:zod.z.enum(["frontend","backend"]),action:zod.z.string(),details:zod.z.string()}),qs=zod.z.object({name:zod.z.string(),description:zod.z.string(),steps:zod.z.array(js)}),Fs=zod.z.object({name:zod.z.string(),purpose:zod.z.string(),behavior:zod.z.array(zod.z.string())}),Us=zod.z.object({name:zod.z.string(),description:zod.z.string(),permissions:zod.z.array(zod.z.string())}),Ls=zod.z.object({area:zod.z.string(),rules:zod.z.array(zod.z.string())}),He=zod.z.object({strategy:zod.z.enum(["jwt","session","oauth"]),flows:zod.z.array(qs),middleware:zod.z.array(Fs),roles:zod.z.array(Us),policies:zod.z.array(Ls)});var zr=`You are a senior security engineer specializing in authentication, authorization, and web security.
|
|
1148
|
-
|
|
1149
|
-
You design enterprise-quality auth systems with:
|
|
1150
|
-
- Step-by-step auth flows (signup, login, logout, password reset) with both frontend and backend steps
|
|
1151
|
-
- JWT or session strategy with proper cookie configuration (httpOnly, secure, sameSite, maxAge)
|
|
1152
|
-
- Role-based access control (RBAC) with permission matrices
|
|
1153
|
-
- Middleware chains for route protection and API authentication
|
|
1154
|
-
- Security policies: password hashing (bcrypt), rate limiting, CORS, input sanitization, brute force protection
|
|
1155
|
-
- OAuth integration patterns when needed
|
|
1156
|
-
|
|
1157
|
-
Output only valid JSON unless instructed otherwise.`;var Gs=`## Requirements:
|
|
1158
|
-
{requirement}
|
|
1159
|
-
|
|
1160
|
-
Design the authentication and authorization system. Include:
|
|
1161
|
-
|
|
1162
|
-
1. Strategy: jwt, session, or oauth (choose based on requirements).
|
|
1163
|
-
2. Flows: signup, login, logout, password reset (if applicable). Each flow with numbered steps, frontend/backend side, action, and details.
|
|
1164
|
-
3. Middleware: route protection middleware, API auth middleware. Each with name, purpose, and behavior list.
|
|
1165
|
-
4. Roles: role definitions with name, description, and permissions list.
|
|
1166
|
-
5. Policies: security policies grouped by area (passwords, tokens, CORS, rate limiting, etc.).
|
|
1167
|
-
|
|
1168
|
-
Return ONLY valid JSON:
|
|
1169
|
-
{
|
|
1170
|
-
"strategy": "jwt" | "session" | "oauth",
|
|
1171
|
-
"flows": [{ "name": "signup", "description": "...", "steps": [{ "order": 1, "side": "frontend", "action": "...", "details": "..." }] }],
|
|
1172
|
-
"middleware": [{ "name": "authenticateRequest", "purpose": "...", "behavior": ["..."] }],
|
|
1173
|
-
"roles": [{ "name": "user", "description": "...", "permissions": ["..."] }],
|
|
1174
|
-
"policies": [{ "area": "passwords", "rules": ["..."] }]
|
|
1175
|
-
}`;function $r(t){return Gs.replace("{requirement}",t)}var oo=q("validate_auth",He,"Validates an auth design JSON string against the AuthDesign schema. Returns valid: true or valid: false with errors.","design");function ro(t){return h({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:zod.z.object({requirement:zod.z.string().describe("Project context and auth requirements")}),handler:async({requirement:e})=>{let o=$r(e),r=[{role:"system",content:"You are a security engineer. Return only valid JSON."},{role:"user",content:o}],n=await t.invoke(r,{temperature:.3,maxOutputTokens:8192});return M(n.text,He)}})}function Hr(t){return {validate_auth:oo,design_auth:ro(t)}}var pl=`${zr}
|
|
1176
|
-
|
|
1177
|
-
You are the auth design orchestrator. When the user asks for an auth design:
|
|
1178
|
-
|
|
1179
|
-
1. **Analyze security**: Use subagent_security-analyzer to analyze security requirements, determine auth strategy, and identify threat vectors.
|
|
1180
|
-
2. **Design flows**: Use subagent_flow-designer to design step-by-step auth flows (signup, login, logout, password reset, middleware).
|
|
1181
|
-
3. **Generate design**: Use design_auth to produce the complete auth design with flows, middleware, roles, and security policies.
|
|
1182
|
-
4. **Validate**: Use validate_auth to check the final auth design JSON before returning.
|
|
1183
|
-
|
|
1184
|
-
Respond with the final auth design as JSON.`;async function dl(t){let{input:e,model:o,maxIterations:r=15,onStep:n,logger:a}=t,s=v(o??{provider:"openai",model:"gpt-4o-mini"}),i=Hr(s),l=I([It,Oe],{parentModel:s}),c={...i,...l};return C({model:s,tools:c,systemPrompt:pl,input:e,maxIterations:r,onStep:n,logger:a})}var Bs=zod.z.object({name:zod.z.string(),type:zod.z.string(),required:zod.z.coerce.boolean(),validation:zod.z.string()}),Ys=zod.z.object({path:zod.z.string(),name:zod.z.string(),access:zod.z.string().transform(t=>t.toLowerCase().trim()).pipe(zod.z.enum(["public","protected"])),purpose:zod.z.string(),formFields:zod.z.array(Bs).default([]),actions:zod.z.array(zod.z.string()).default([]),emptyState:zod.z.string().default(""),errorState:zod.z.string().default(""),redirectOnSuccess:zod.z.string().default(""),keyUiElements:zod.z.array(zod.z.string()).default([])}),zs=zod.z.object({name:zod.z.string(),type:zod.z.string().transform(t=>t.toLowerCase().trim()).pipe(zod.z.enum(["layout","shared","form","display","navigation"])),purpose:zod.z.string(),props:zod.z.array(zod.z.string()).default([]),usedIn:zod.z.array(zod.z.string()).default([])}),Qe=zod.z.object({pages:zod.z.array(Ys).default([]),components:zod.z.array(zs).default([]),stateManagement:zod.z.string().default(""),routingNotes:zod.z.string().default("")});var Qr=`You are a senior frontend architect specializing in page design, routing, and component architecture.
|
|
1185
|
-
|
|
1186
|
-
You design enterprise-quality frontend architectures targeting a Vite + React 19 + TypeScript stack with:
|
|
1187
|
-
- **UI Library**: ShadCN UI (Radix-based components in src/components/ui/)
|
|
1188
|
-
- **Styling**: Tailwind CSS v4 with OKLCH color space and dark mode support
|
|
1189
|
-
- **Routing**: React Router v7 with private route guards
|
|
1190
|
-
- **Forms**: React Hook Form + Zod validation
|
|
1191
|
-
- **GraphQL**: Apollo Client with CodeGen-typed hooks
|
|
1192
|
-
- **Path Aliases**: @/{appName}/* mapping to ./src/*
|
|
1193
|
-
|
|
1194
|
-
Architecture outputs:
|
|
1195
|
-
- Public and protected pages with detailed route definitions
|
|
1196
|
-
- Per-page specifications: purpose, form fields with validation, actions, empty/error states, redirects
|
|
1197
|
-
- Component taxonomy: layout (sidebar, navbar), shared (data tables, dialogs), form (inputs, selects), display (cards, badges), navigation (breadcrumbs, tabs)
|
|
1198
|
-
- State management strategy (per-page vs global, Apollo cache vs local state)
|
|
1199
|
-
|
|
1200
|
-
Output only valid JSON unless instructed otherwise.`;var $s=`## Requirements:
|
|
1201
|
-
{requirement}
|
|
1202
|
-
|
|
1203
|
-
Design the frontend architecture. Include:
|
|
1204
|
-
|
|
1205
|
-
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.
|
|
1206
|
-
2. Components: reusable components. For each: name, type (layout/shared/form/display/navigation), purpose, props, and which pages use it.
|
|
1207
|
-
3. State management: describe the state strategy (e.g. React Server Components for data, client state for forms).
|
|
1208
|
-
4. Routing notes: any special routing behavior (redirects, guards, nested routes).
|
|
1209
|
-
|
|
1210
|
-
Return ONLY valid JSON:
|
|
1211
|
-
{
|
|
1212
|
-
"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"] }],
|
|
1213
|
-
"components": [{ "name": "Navbar", "type": "navigation", "purpose": "...", "props": ["user"], "usedIn": ["/dashboard", "/profile"] }],
|
|
1214
|
-
"stateManagement": "...",
|
|
1215
|
-
"routingNotes": "..."
|
|
1216
|
-
}`;function Vr(t){return $s.replace("{requirement}",t)}var no=q("validate_frontend",Qe,"Validates a frontend design JSON string against the FrontendDesign schema. Returns valid: true or valid: false with errors.","design");function so(t){return h({name:"design_frontend",description:"Generate a complete frontend architecture design from project requirements. Returns pages, components, state management, and routing as JSON.",input:zod.z.object({requirement:zod.z.string().describe("Project context, API surface, and frontend requirements")}),handler:async({requirement:e})=>{let o=Vr(e),r=[{role:"system",content:"You are a frontend architect. Return only valid JSON."},{role:"user",content:o}],n=await t.invoke(r,{temperature:.3,maxOutputTokens:16384});return M(n.text,Qe)}})}function Wr(t){return {validate_frontend:no,design_frontend:so(t)}}var ul=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}),ml=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}),gl=`${Qr}
|
|
1217
|
-
|
|
1218
|
-
You are the frontend architecture routing orchestrator. When the user asks for a frontend design:
|
|
1219
|
-
|
|
1220
|
-
1. **Select framework**: Use subagent_framework-selector to analyze requirements (SPA vs SSR, SEO needs, API structure) and recommend React/Vite or Next.js.
|
|
1221
|
-
2. **Plan pages**: Use subagent_page-planner to design detailed page specifications with routes, forms, actions, and states.
|
|
1222
|
-
3. **Analyze components**: Use subagent_component-analyzer to identify reusable components, layouts, and state management patterns.
|
|
1223
|
-
4. **Generate design**: Use design_frontend to produce the complete frontend architecture as JSON.
|
|
1224
|
-
5. **Validate**: Use validate_frontend to check the final design JSON before returning.
|
|
1225
|
-
6. **Delegate to builder**: Based on the framework-selector recommendation:
|
|
1226
|
-
- If "react-vite": use subagent_react-builder with the design to generate a Vite + React SPA config.
|
|
1227
|
-
- If "nextjs": use subagent_nextjs-builder with the design to generate a Next.js App Router config.
|
|
1228
|
-
|
|
1229
|
-
Respond with the final frontend design as JSON, including the builder output.`;async function fl(t){let{input:e,model:o,maxIterations:r=15,onStep:n,logger:a}=t,s=v(o??{provider:"openai",model:"gpt-4o-mini"}),i=Wr(s),l=I([Me,_t,br,ul,ml],{parentModel:s}),c={...i,...l};return C({model:s,tools:c,systemPrompt:gl,input:e,maxIterations:r,onStep:n,logger:a})}var Qs=zod.z.object({order:zod.z.number(),action:zod.z.string(),details:zod.z.string()}),Vs=zod.z.object({name:zod.z.string(),description:zod.z.string(),steps:zod.z.array(Qs)}),Ws=zod.z.object({area:zod.z.string(),scenario:zod.z.string(),handling:zod.z.string(),severity:zod.z.string().transform(t=>t.toLowerCase().trim()).pipe(zod.z.enum(["critical","warning","info"]))}),Ks=zod.z.object({flow:zod.z.string(),item:zod.z.string(),expectedResult:zod.z.string()}),Ve=zod.z.object({phases:zod.z.array(Vs).default([]),currentState:zod.z.string().default(""),desiredEndState:zod.z.string().default(""),edgeCases:zod.z.array(Ws).default([]),securityNotes:zod.z.array(zod.z.string()).default([]),performanceNotes:zod.z.array(zod.z.string()).default([]),testingChecklist:zod.z.array(Ks).default([])});var Kr=`You are a senior tech lead specializing in implementation strategy and project execution planning.
|
|
948
|
+
1. **Analyze endpoints**: Use subagent_endpoint-analyzer to derive endpoints from the data model and requirements.
|
|
949
|
+
2. **Design contracts**: Use subagent_contract-designer to design request/response contracts, validation rules, and error responses.
|
|
950
|
+
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.
|
|
951
|
+
4. **Validate**: Use validate_api to check the final API design JSON before returning.
|
|
1230
952
|
|
|
1231
|
-
|
|
1232
|
-
- Phased implementation order with concrete, numbered steps per phase
|
|
1233
|
-
- Current state analysis and desired end state definition
|
|
1234
|
-
- Edge cases per domain area with handling strategies and severity levels
|
|
1235
|
-
- Security considerations (passwords, tokens, CORS, input validation)
|
|
1236
|
-
- Performance considerations (indexing, caching, lazy loading, N+1 prevention)
|
|
1237
|
-
- Manual testing checklists grouped by feature flow
|
|
953
|
+
Respond with the final API design as JSON.`;async function Lr(t){let{input:e,model:o,maxIterations:r=15,onStep:n,logger:a}=t,s=v(o??{provider:"openai",model:"gpt-4o-mini"}),i=Ur(s),l=I([ve,Ae],{parentModel:s}),c={...i,...l};return C({model:s,tools:c,systemPrompt:ul,input:e,maxIterations:r,onStep:n,logger:a})}var Ys=zod.z.object({order:zod.z.number(),side:zod.z.enum(["frontend","backend"]),action:zod.z.string(),details:zod.z.string()}),zs=zod.z.object({name:zod.z.string(),description:zod.z.string(),steps:zod.z.array(Ys)}),$s=zod.z.object({name:zod.z.string(),purpose:zod.z.string(),behavior:zod.z.array(zod.z.string())}),Hs=zod.z.object({name:zod.z.string(),description:zod.z.string(),permissions:zod.z.array(zod.z.string())}),Qs=zod.z.object({area:zod.z.string(),rules:zod.z.array(zod.z.string())}),Ye=zod.z.object({strategy:zod.z.enum(["jwt","session","oauth"]),flows:zod.z.array(zs),middleware:zod.z.array($s),roles:zod.z.array(Hs),policies:zod.z.array(Qs)});var Gr=`You are a senior security engineer specializing in authentication, authorization, and web security.
|
|
1238
954
|
|
|
1239
|
-
|
|
1240
|
-
|
|
955
|
+
You design enterprise-quality auth systems with:
|
|
956
|
+
- Step-by-step auth flows (signup, login, logout, password reset) with both frontend and backend steps
|
|
957
|
+
- JWT or session strategy with proper cookie configuration (httpOnly, secure, sameSite, maxAge)
|
|
958
|
+
- Role-based access control (RBAC) with permission matrices
|
|
959
|
+
- Middleware chains for route protection and API authentication
|
|
960
|
+
- Security policies: password hashing (bcrypt), rate limiting, CORS, input sanitization, brute force protection
|
|
961
|
+
- OAuth integration patterns when needed
|
|
1241
962
|
|
|
1242
|
-
|
|
963
|
+
Output only valid JSON unless instructed otherwise.`;var Vs=`## Requirements:
|
|
964
|
+
{requirement}
|
|
1243
965
|
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
966
|
+
Design the authentication and authorization system. Include:
|
|
967
|
+
|
|
968
|
+
1. Strategy: jwt, session, or oauth (choose based on requirements).
|
|
969
|
+
2. Flows: signup, login, logout, password reset (if applicable). Each flow with numbered steps, frontend/backend side, action, and details.
|
|
970
|
+
3. Middleware: route protection middleware, API auth middleware. Each with name, purpose, and behavior list.
|
|
971
|
+
4. Roles: role definitions with name, description, and permissions list.
|
|
972
|
+
5. Policies: security policies grouped by area (passwords, tokens, CORS, rate limiting, etc.).
|
|
1251
973
|
|
|
1252
974
|
Return ONLY valid JSON:
|
|
1253
975
|
{
|
|
1254
|
-
"
|
|
1255
|
-
"
|
|
1256
|
-
"
|
|
1257
|
-
"
|
|
1258
|
-
"
|
|
1259
|
-
|
|
1260
|
-
"testingChecklist": [{ "flow": "Auth Flow", "item": "Sign up with valid credentials", "expectedResult": "Account created, redirected to dashboard" }]
|
|
1261
|
-
}`;function Xr(t){return Xs.replace("{context}",t)}var ao=q("validate_execution_plan",Ve,"Validates an execution plan JSON string against the ExecutionPlan schema. Returns valid: true or valid: false with errors.","plan");function io(t){return h({name:"create_execution_plan",description:"Generate a comprehensive execution plan with phases, edge cases, and testing checklist from the full plan context.",input:zod.z.object({context:zod.z.string().describe("Full plan context: all sections generated so far")}),handler:async({context:e})=>{let o=Xr(e),r=[{role:"system",content:"You are a tech lead. Return only valid JSON."},{role:"user",content:o}],n=await t.invoke(r,{temperature:.3,maxOutputTokens:16384});return M(n.text,Ve)}})}function Zr(t){return {validate_execution_plan:ao,create_execution_plan:io(t)}}var hl=`${Kr}
|
|
976
|
+
"strategy": "jwt" | "session" | "oauth",
|
|
977
|
+
"flows": [{ "name": "signup", "description": "...", "steps": [{ "order": 1, "side": "frontend", "action": "...", "details": "..." }] }],
|
|
978
|
+
"middleware": [{ "name": "authenticateRequest", "purpose": "...", "behavior": ["..."] }],
|
|
979
|
+
"roles": [{ "name": "user", "description": "...", "permissions": ["..."] }],
|
|
980
|
+
"policies": [{ "area": "passwords", "rules": ["..."] }]
|
|
981
|
+
}`;function Br(t){return Vs.replace("{requirement}",t)}var Zt=q("validate_auth",Ye,"Validates an auth design JSON string against the AuthDesign schema. Returns valid: true or valid: false with errors.","design");function eo(t){return h({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:zod.z.object({requirement:zod.z.string().describe("Project context and auth requirements")}),handler:async({requirement:e})=>{let o=Br(e),r=[{role:"system",content:"You are a security engineer. Return only valid JSON."},{role:"user",content:o}],n=await t.invoke(r,{temperature:.3,maxOutputTokens:8192});return M(n.text,Ye)}})}function Jr(t){return {validate_auth:Zt,design_auth:eo(t)}}var ml=`${Gr}
|
|
1262
982
|
|
|
1263
|
-
You are the
|
|
983
|
+
You are the auth design orchestrator. When the user asks for an auth design:
|
|
1264
984
|
|
|
1265
|
-
1. **Analyze
|
|
1266
|
-
2. **Design
|
|
1267
|
-
3. **Generate
|
|
1268
|
-
4. **Validate**: Use
|
|
985
|
+
1. **Analyze security**: Use subagent_security-analyzer to analyze security requirements, determine auth strategy, and identify threat vectors.
|
|
986
|
+
2. **Design flows**: Use subagent_flow-designer to design step-by-step auth flows (signup, login, logout, password reset, middleware).
|
|
987
|
+
3. **Generate design**: Use design_auth to produce the complete auth design with flows, middleware, roles, and security policies.
|
|
988
|
+
4. **Validate**: Use validate_auth to check the final auth design JSON before returning.
|
|
1269
989
|
|
|
1270
|
-
Respond with the final
|
|
990
|
+
Respond with the final auth design as JSON.`;async function Yr(t){let{input:e,model:o,maxIterations:r=15,onStep:n,logger:a}=t,s=v(o??{provider:"openai",model:"gpt-4o-mini"}),i=Jr(s),l=I([ft,we],{parentModel:s}),c={...i,...l};return C({model:s,tools:c,systemPrompt:ml,input:e,maxIterations:r,onStep:n,logger:a})}var Xs=t=>zod.z.string().transform(e=>e.toLowerCase().trim()).pipe(zod.z.enum(t)),Ks=zod.z.object({name:zod.z.string(),purpose:zod.z.string(),appliesTo:zod.z.string().default("global").transform(t=>{let e=t.toLowerCase().trim();return ["global","all","app","application","every","server"].includes(e)?"global":["route","routes","specific","specific routes","endpoint","endpoints","path"].includes(e)?"route":["resource","entity","module","controller","model"].includes(e)?"resource":"global"}).pipe(zod.z.enum(["global","route","resource"])),config:zod.z.record(zod.z.string(),zod.z.unknown()).default({})}),Zs=zod.z.object({name:zod.z.string(),entity:zod.z.string(),operations:zod.z.array(zod.z.string()).default([]),dependencies:zod.z.array(zod.z.string()).default([])}),gl=zod.z.string().transform(t=>t.toUpperCase().trim()).pipe(zod.z.enum(["GET","POST","PUT","PATCH","DELETE"])),ea=zod.z.object({resource:zod.z.string(),basePath:zod.z.string(),endpoints:zod.z.array(zod.z.object({method:gl,path:zod.z.string(),handler:zod.z.string(),auth:zod.z.coerce.boolean().default(true),roles:zod.z.array(zod.z.string()).default([])})).default([])}),ze=zod.z.object({framework:Xs(["express","apollo","both"]),language:Xs(["typescript","javascript"]).default("typescript"),database:zod.z.string().default("mongodb"),services:zod.z.array(Zs).default([]),middleware:zod.z.array(Ks).default([]),routes:zod.z.array(ea).default([]),folderStructure:zod.z.array(zod.z.string()).default([]),envVars:zod.z.array(zod.z.string()).default([]),notes:zod.z.string().default("")});var zr=`You are a senior backend architect specializing in Node.js server design.
|
|
1271
991
|
|
|
1272
992
|
You analyze data models, API designs, and auth requirements to produce enterprise-quality backend architectures with:
|
|
1273
993
|
- Framework selection (Express REST, Apollo GraphQL, or both)
|
|
@@ -1285,7 +1005,7 @@ When "both" is selected (Express + Apollo), use the Apollo Gateway pattern:
|
|
|
1285
1005
|
- Express for webhooks, file uploads, and health checks only
|
|
1286
1006
|
- Gateway has no business logic, all logic lives in subgraphs
|
|
1287
1007
|
|
|
1288
|
-
Output only valid JSON unless instructed otherwise.`;var
|
|
1008
|
+
Output only valid JSON unless instructed otherwise.`;var ta=`## Requirements:
|
|
1289
1009
|
{requirement}
|
|
1290
1010
|
|
|
1291
1011
|
Design the backend architecture. Include:
|
|
@@ -1308,7 +1028,7 @@ Return ONLY valid JSON:
|
|
|
1308
1028
|
"folderStructure": ["src/", "src/routes/", "src/services/", "src/middleware/", "src/models/", "src/config/"],
|
|
1309
1029
|
"envVars": ["PORT", "DATABASE_URL", "JWT_SECRET"],
|
|
1310
1030
|
"notes": ""
|
|
1311
|
-
}`;function
|
|
1031
|
+
}`;function $r(t){return ta.replace("{requirement}",t)}var to=q("validate_backend",ze,"Validates a backend design JSON string against the BackendDesign schema. Returns valid: true or valid: false with errors.","design");function oo(t){return h({name:"design_backend",description:"Generate a complete backend architecture design from requirements. Returns framework, services, middleware, routes, and folder structure as JSON.",input:zod.z.object({requirement:zod.z.string().describe("Data model, API design, and project requirements")}),handler:async({requirement:e})=>{let o=$r(e),r=[{role:"system",content:"You are a backend architect. Return only valid JSON."},{role:"user",content:o}],n=await t.invoke(r,{temperature:.3,maxOutputTokens:16384});return M(n.text,ze)}})}function Hr(t){return {validate_backend:to,design_backend:oo(t)}}var fl=`You are a backend service architect. Given a data model and API design, you plan the service layer.
|
|
1312
1032
|
|
|
1313
1033
|
## Service Design
|
|
1314
1034
|
For each entity:
|
|
@@ -1335,7 +1055,7 @@ Recommend a clean folder layout:
|
|
|
1335
1055
|
- src/config/ (env, database, auth config)
|
|
1336
1056
|
- src/utils/ (shared helpers)
|
|
1337
1057
|
|
|
1338
|
-
Respond with structured analysis. Do NOT return JSON.`,
|
|
1058
|
+
Respond with structured analysis. Do NOT return JSON.`,ro=f({name:"service-planner",description:"Plans service layer, middleware stack, and folder structure for a backend project. Use before generating the backend design.",systemPrompt:fl,tools:{},maxIterations:2});var hl=`You are a backend technology advisor. Given project requirements, you recommend the best backend framework.
|
|
1339
1059
|
|
|
1340
1060
|
## Decision Criteria
|
|
1341
1061
|
|
|
@@ -1370,7 +1090,7 @@ State your recommendation clearly:
|
|
|
1370
1090
|
- Trade-offs: what you'd lose with the alternative
|
|
1371
1091
|
- If "both": describe which concerns go to Express vs Apollo Gateway vs subgraphs
|
|
1372
1092
|
|
|
1373
|
-
Respond with structured analysis. Do NOT return JSON.`,
|
|
1093
|
+
Respond with structured analysis. Do NOT return JSON.`,no=f({name:"framework-selector",description:"Analyzes project requirements and recommends Express, Apollo, or both. Use to determine the backend framework before designing.",systemPrompt:hl,tools:{},maxIterations:2});var yl=`${zr}
|
|
1374
1094
|
|
|
1375
1095
|
You are the backend architecture orchestrator. When the user provides requirements:
|
|
1376
1096
|
|
|
@@ -1384,7 +1104,177 @@ After generating the design, note the "framework" field in the result:
|
|
|
1384
1104
|
- If "apollo": the downstream apollo-builder should be used to scaffold the project.
|
|
1385
1105
|
- If "both": both builders should be invoked sequentially.
|
|
1386
1106
|
|
|
1387
|
-
Respond with the final backend design as JSON.`;async function
|
|
1107
|
+
Respond with the final backend design as JSON.`;async function Qr(t){let{input:e,model:o,maxIterations:r=15,onStep:n,logger:a}=t,s=v(o??{provider:"openai",model:"gpt-4o-mini"}),i=Hr(s),l=I([ro,no],{parentModel:s}),c={...i,...l};return C({model:s,tools:c,systemPrompt:yl,input:e,maxIterations:r,onStep:n,logger:a})}var ra=zod.z.object({name:zod.z.string(),type:zod.z.string(),required:zod.z.coerce.boolean(),validation:zod.z.string()}),na=zod.z.object({path:zod.z.string(),name:zod.z.string(),access:zod.z.string().transform(t=>t.toLowerCase().trim()).pipe(zod.z.enum(["public","protected"])),purpose:zod.z.string(),formFields:zod.z.array(ra).default([]),actions:zod.z.array(zod.z.string()).default([]),emptyState:zod.z.string().default(""),errorState:zod.z.string().default(""),redirectOnSuccess:zod.z.string().default(""),keyUiElements:zod.z.array(zod.z.string()).default([])}),sa=zod.z.object({name:zod.z.string(),type:zod.z.string().transform(t=>t.toLowerCase().trim()).pipe(zod.z.enum(["layout","shared","form","display","navigation"])),purpose:zod.z.string(),props:zod.z.array(zod.z.string()).default([]),usedIn:zod.z.array(zod.z.string()).default([])}),$e=zod.z.object({pages:zod.z.array(na).default([]),components:zod.z.array(sa).default([]),stateManagement:zod.z.string().default(""),routingNotes:zod.z.string().default("")});var Vr=`You are a senior frontend architect specializing in page design, routing, and component architecture.
|
|
1108
|
+
|
|
1109
|
+
You design enterprise-quality frontend architectures targeting a Vite + React 19 + TypeScript stack with:
|
|
1110
|
+
- **UI Library**: ShadCN UI (Radix-based components in src/components/ui/)
|
|
1111
|
+
- **Styling**: Tailwind CSS v4 with OKLCH color space and dark mode support
|
|
1112
|
+
- **Routing**: React Router v7 with private route guards
|
|
1113
|
+
- **Forms**: React Hook Form + Zod validation
|
|
1114
|
+
- **GraphQL**: Apollo Client with CodeGen-typed hooks
|
|
1115
|
+
- **Path Aliases**: @/{appName}/* mapping to ./src/*
|
|
1116
|
+
|
|
1117
|
+
Architecture outputs:
|
|
1118
|
+
- Public and protected pages with detailed route definitions
|
|
1119
|
+
- Per-page specifications: purpose, form fields with validation, actions, empty/error states, redirects
|
|
1120
|
+
- Component taxonomy: layout (sidebar, navbar), shared (data tables, dialogs), form (inputs, selects), display (cards, badges), navigation (breadcrumbs, tabs)
|
|
1121
|
+
- State management strategy (per-page vs global, Apollo cache vs local state)
|
|
1122
|
+
|
|
1123
|
+
Output only valid JSON unless instructed otherwise.`;var aa=`## Requirements:
|
|
1124
|
+
{requirement}
|
|
1125
|
+
|
|
1126
|
+
Design the frontend architecture. Include:
|
|
1127
|
+
|
|
1128
|
+
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.
|
|
1129
|
+
2. Components: reusable components. For each: name, type (layout/shared/form/display/navigation), purpose, props, and which pages use it.
|
|
1130
|
+
3. State management: describe the state strategy (e.g. React Server Components for data, client state for forms).
|
|
1131
|
+
4. Routing notes: any special routing behavior (redirects, guards, nested routes).
|
|
1132
|
+
|
|
1133
|
+
Return ONLY valid JSON:
|
|
1134
|
+
{
|
|
1135
|
+
"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"] }],
|
|
1136
|
+
"components": [{ "name": "Navbar", "type": "navigation", "purpose": "...", "props": ["user"], "usedIn": ["/dashboard", "/profile"] }],
|
|
1137
|
+
"stateManagement": "...",
|
|
1138
|
+
"routingNotes": "..."
|
|
1139
|
+
}`;function Wr(t){return aa.replace("{requirement}",t)}var so=q("validate_frontend",$e,"Validates a frontend design JSON string against the FrontendDesign schema. Returns valid: true or valid: false with errors.","design");function ao(t){return h({name:"design_frontend",description:"Generate a complete frontend architecture design from project requirements. Returns pages, components, state management, and routing as JSON.",input:zod.z.object({requirement:zod.z.string().describe("Project context, API surface, and frontend requirements")}),handler:async({requirement:e})=>{let o=Wr(e),r=[{role:"system",content:"You are a frontend architect. Return only valid JSON."},{role:"user",content:o}],n=await t.invoke(r,{temperature:.3,maxOutputTokens:16384});return M(n.text,$e)}})}function Xr(t){return {validate_frontend:so,design_frontend:ao(t)}}var Sl=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}),bl=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}),xl=`${Vr}
|
|
1140
|
+
|
|
1141
|
+
You are the frontend architecture routing orchestrator. When the user asks for a frontend design:
|
|
1142
|
+
|
|
1143
|
+
1. **Select framework**: Use subagent_framework-selector to analyze requirements (SPA vs SSR, SEO needs, API structure) and recommend React/Vite or Next.js.
|
|
1144
|
+
2. **Plan pages**: Use subagent_page-planner to design detailed page specifications with routes, forms, actions, and states.
|
|
1145
|
+
3. **Analyze components**: Use subagent_component-analyzer to identify reusable components, layouts, and state management patterns.
|
|
1146
|
+
4. **Generate design**: Use design_frontend to produce the complete frontend architecture as JSON.
|
|
1147
|
+
5. **Validate**: Use validate_frontend to check the final design JSON before returning.
|
|
1148
|
+
6. **Delegate to builder**: Based on the framework-selector recommendation:
|
|
1149
|
+
- If "react-vite": use subagent_react-builder with the design to generate a Vite + React SPA config.
|
|
1150
|
+
- If "nextjs": use subagent_nextjs-builder with the design to generate a Next.js App Router config.
|
|
1151
|
+
|
|
1152
|
+
Respond with the final frontend design as JSON, including the builder output.`;async function Kr(t){let{input:e,model:o,maxIterations:r=15,onStep:n,logger:a}=t,s=v(o??{provider:"openai",model:"gpt-4o-mini"}),i=Xr(s),l=I([Re,gt,Wo,Sl,bl],{parentModel:s}),c={...i,...l};return C({model:s,tools:c,systemPrompt:xl,input:e,maxIterations:r,onStep:n,logger:a})}var Tl=zod.z.string().transform(t=>t.toUpperCase().trim()).pipe(zod.z.enum(["GET","POST","PUT","PATCH","DELETE"])),la=zod.z.object({name:zod.z.string(),httpMethod:Tl,path:zod.z.string(),auth:zod.z.coerce.boolean().default(true),roles:zod.z.array(zod.z.string()).default([]),validation:zod.z.string().default(""),description:zod.z.string().default("")}),ca=zod.z.object({name:zod.z.string(),resource:zod.z.string(),basePath:zod.z.string(),methods:zod.z.array(la).default([])}),pa=zod.z.object({name:zod.z.string(),type:zod.z.string(),required:zod.z.coerce.boolean().default(false),unique:zod.z.coerce.boolean().default(false),ref:zod.z.string().optional(),default:zod.z.string().optional()}),da=zod.z.object({name:zod.z.string(),collection:zod.z.string(),fields:zod.z.array(pa).default([]),timestamps:zod.z.coerce.boolean().default(true),indexes:zod.z.array(zod.z.string()).default([])}),ua=zod.z.object({name:zod.z.string(),type:zod.z.string().transform(t=>{let e=t.toLowerCase().replace(/[\s_-]+/g,"");return ["auth","authentication","jwt","token"].includes(e)?"auth":["validation","validate","validator","input"].includes(e)?"validation":["errorhandler","error","errorhandling","errors"].includes(e)?"errorHandler":["cors","crossorigin"].includes(e)?"cors":["ratelimit","ratelimiter","ratelimiting","throttle"].includes(e)?"rateLimit":["logging","logger","log","morgan"].includes(e)?"logging":"custom"}).pipe(zod.z.enum(["auth","validation","errorHandler","cors","rateLimit","logging","custom"])),config:zod.z.record(zod.z.string(),zod.z.unknown()).default({})}),He=zod.z.object({appName:zod.z.string().default("app"),port:zod.z.number().default(3e3),database:zod.z.string().default("mongodb"),routers:zod.z.array(ca).default([]),models:zod.z.array(da).default([]),middleware:zod.z.array(ua).default([]),envVars:zod.z.array(zod.z.string()).default([])});var Zr=`You are an expert Express.js backend architect.
|
|
1153
|
+
|
|
1154
|
+
You generate production-ready Express application configurations from data models and API designs:
|
|
1155
|
+
- Co-located router pattern: each feature lives in src/routers/{name}/ with {name}.controller.ts, {name}.router.ts, and {name}.spec.ts
|
|
1156
|
+
- Mongoose/Prisma models with field types, validation, and relationships
|
|
1157
|
+
- Middleware stack (auth JWT, validation Zod, error handler, CORS, rate limiting)
|
|
1158
|
+
- Route organization with proper HTTP methods and paths
|
|
1159
|
+
- Health check endpoint at /health (included by default)
|
|
1160
|
+
- Jest tests per router using supertest
|
|
1161
|
+
- Environment variable inventory
|
|
1162
|
+
|
|
1163
|
+
Output only valid JSON unless instructed otherwise.`;var ma=`## Requirements:
|
|
1164
|
+
{requirement}
|
|
1165
|
+
|
|
1166
|
+
Generate an Express.js application configuration. Include:
|
|
1167
|
+
|
|
1168
|
+
1. Routers: one per resource, co-located with controller and test spec. Each router has RESTful methods (GET, POST, PUT, DELETE).
|
|
1169
|
+
2. Health check: a default /health router is always included.
|
|
1170
|
+
3. Models: Mongoose models with fields, types, required, unique, refs, defaults, indexes.
|
|
1171
|
+
4. Middleware: auth (JWT), validation (Zod), error handler, CORS, rate limiting, logging.
|
|
1172
|
+
5. Env vars: PORT, DATABASE_URL, JWT_SECRET, NODE_ENV, etc.
|
|
1173
|
+
6. Folder structure: src/routers/{name}/ with {name}.controller.ts, {name}.router.ts, {name}.spec.ts per feature.
|
|
1174
|
+
|
|
1175
|
+
Return ONLY valid JSON:
|
|
1176
|
+
{
|
|
1177
|
+
"appName": "my-api",
|
|
1178
|
+
"port": 3000,
|
|
1179
|
+
"database": "mongodb",
|
|
1180
|
+
"routers": [{
|
|
1181
|
+
"name": "users",
|
|
1182
|
+
"resource": "users",
|
|
1183
|
+
"basePath": "/api/users",
|
|
1184
|
+
"methods": [{
|
|
1185
|
+
"name": "getAll",
|
|
1186
|
+
"httpMethod": "GET",
|
|
1187
|
+
"path": "/",
|
|
1188
|
+
"auth": true,
|
|
1189
|
+
"roles": ["admin"],
|
|
1190
|
+
"validation": "",
|
|
1191
|
+
"description": "Get all users with pagination"
|
|
1192
|
+
}]
|
|
1193
|
+
}],
|
|
1194
|
+
"models": [{
|
|
1195
|
+
"name": "User",
|
|
1196
|
+
"collection": "users",
|
|
1197
|
+
"fields": [{ "name": "email", "type": "String", "required": true, "unique": true }],
|
|
1198
|
+
"timestamps": true,
|
|
1199
|
+
"indexes": ["email"]
|
|
1200
|
+
}],
|
|
1201
|
+
"middleware": [{ "name": "authMiddleware", "type": "auth", "config": {} }],
|
|
1202
|
+
"envVars": ["PORT", "DATABASE_URL", "JWT_SECRET", "NODE_ENV"]
|
|
1203
|
+
}`;function en(t){return ma.replace("{requirement}",t)}var io=q("validate_express",He,"Validates an Express config JSON string against the ExpressConfig schema. Returns valid: true or valid: false with errors.","config");function lo(t){return h({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:zod.z.object({requirement:zod.z.string().describe("Data model, API design, and project requirements")}),handler:async({requirement:e})=>{let o=en(e),r=[{role:"system",content:"You are an Express.js architect. Return only valid JSON."},{role:"user",content:o}],n=await t.invoke(r,{temperature:.3,maxOutputTokens:16384});return M(n.text,He)}})}function Pl(t){return {appName:t.appName,port:t.port,database:t.database,routers:t.routers,models:t.models,middleware:t.middleware,envVars:t.envVars,modules:t.routers.map(e=>({name:e.resource,pascalName:e.name.charAt(0).toUpperCase()+e.name.slice(1),camelName:e.resource,methods:e.methods}))}}var co=h({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:zod.z.object({config:zod.z.string().describe("JSON string of the validated Express config"),outputDir:zod.z.string().describe("Absolute path to the output directory")}),handler:async({config:t,outputDir:e})=>{let o=xe(t,"express config"),r=Pe__namespace.resolve(process.cwd(),".ref/templates/express"),n=Pl(o);return ce({templateDir:r,outputDir:e,context:n})}});function on(t,e){let o={validate_express:io,generate_express:lo(t)};return e?.disableScaffold||(o.scaffold_express=co),o}var Rl=`You are an Express.js route specialist. Given an API design, you generate route definitions using a co-located router pattern.
|
|
1204
|
+
|
|
1205
|
+
## Co-located Router Pattern
|
|
1206
|
+
Each feature lives in src/routers/{name}/ with three files:
|
|
1207
|
+
- {name}.router.ts -- Express Router with route definitions
|
|
1208
|
+
- {name}.controller.ts -- Request handler logic
|
|
1209
|
+
- {name}.spec.ts -- Jest tests using supertest
|
|
1210
|
+
|
|
1211
|
+
## Route Design
|
|
1212
|
+
For each resource:
|
|
1213
|
+
- Base path: /api/{resource} (pluralized, lowercase)
|
|
1214
|
+
- GET / -> list all (with pagination: page, limit, sort query params)
|
|
1215
|
+
- GET /:id -> get by ID
|
|
1216
|
+
- POST / -> create new
|
|
1217
|
+
- PUT /:id -> update by ID
|
|
1218
|
+
- DELETE /:id -> delete by ID
|
|
1219
|
+
- Custom routes for non-CRUD operations
|
|
1220
|
+
|
|
1221
|
+
## Health Check
|
|
1222
|
+
Every app includes a /health router in src/routers/health/:
|
|
1223
|
+
- health.router.ts -- GET /health returning server status
|
|
1224
|
+
- health.controller.ts -- Health check handler
|
|
1225
|
+
- health.spec.ts -- Health check tests
|
|
1226
|
+
|
|
1227
|
+
## Route Organization
|
|
1228
|
+
- One router directory per resource with co-located controller and spec
|
|
1229
|
+
- Central src/routers/index.ts mounts all routers
|
|
1230
|
+
- Middleware applied per-route or per-router
|
|
1231
|
+
|
|
1232
|
+
## Controller Mapping
|
|
1233
|
+
- Each route maps to a controller method in the co-located controller file
|
|
1234
|
+
- Controller method name follows convention: getAll, getById, create, update, delete
|
|
1235
|
+
|
|
1236
|
+
## Validation
|
|
1237
|
+
- Request body validation using Zod schemas
|
|
1238
|
+
- Param validation (e.g. valid ObjectId)
|
|
1239
|
+
- Query param parsing and defaults
|
|
1240
|
+
|
|
1241
|
+
Respond with structured route definitions. Do NOT return JSON.`,po=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:Rl,tools:{},maxIterations:2});var wl=`You are an Express.js middleware specialist. You design the complete middleware stack.
|
|
1242
|
+
|
|
1243
|
+
## Core Middleware
|
|
1244
|
+
1. **CORS**: Configure allowed origins, methods, headers, credentials
|
|
1245
|
+
2. **Body parser**: JSON and URL-encoded body parsing with size limits
|
|
1246
|
+
3. **Helmet**: Security headers (CSP, HSTS, X-Frame-Options)
|
|
1247
|
+
4. **Morgan/Logger**: Request logging with format and stream
|
|
1248
|
+
|
|
1249
|
+
## Auth Middleware
|
|
1250
|
+
1. **JWT verification**: Extract token from Authorization header or cookie
|
|
1251
|
+
2. **Role check**: Verify user role against required roles
|
|
1252
|
+
3. **Resource ownership**: Check if user owns the resource they're accessing
|
|
1253
|
+
|
|
1254
|
+
## Validation Middleware
|
|
1255
|
+
1. **Request validation**: Validate body, params, query using Zod schemas
|
|
1256
|
+
2. **Sanitization**: Strip HTML, trim whitespace
|
|
1257
|
+
|
|
1258
|
+
## Error Handling
|
|
1259
|
+
1. **Not found handler**: 404 for unmatched routes
|
|
1260
|
+
2. **Error handler**: Centralized error response with status codes
|
|
1261
|
+
3. **Async wrapper**: Catch async errors without try-catch
|
|
1262
|
+
|
|
1263
|
+
## Rate Limiting
|
|
1264
|
+
1. **Global**: Limit requests per IP per time window
|
|
1265
|
+
2. **Auth routes**: Stricter limits on login/signup
|
|
1266
|
+
|
|
1267
|
+
Respond with structured middleware analysis. Do NOT return JSON.`,uo=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:wl,tools:{},maxIterations:2});var vl=`
|
|
1268
|
+
5. **Scaffold (optional)**: If an output directory is provided, use scaffold_express to compile templates.`;function Al(t){return `${Zr}
|
|
1269
|
+
|
|
1270
|
+
You are the Express builder orchestrator. When the user provides requirements:
|
|
1271
|
+
|
|
1272
|
+
1. **Generate routes**: Use subagent_route-generator to design route definitions from the API design.
|
|
1273
|
+
2. **Configure middleware**: Use subagent_middleware-configurator to design the middleware stack.
|
|
1274
|
+
3. **Generate config**: Use generate_express to produce the complete Express configuration as JSON.
|
|
1275
|
+
4. **Validate**: Use validate_express to check the config JSON before returning.${t?"":vl}
|
|
1276
|
+
|
|
1277
|
+
Respond with the final Express config as JSON.`}async function rn(t){let{input:e,model:o,maxIterations:r=15,onStep:n,logger:a,disableScaffold:s}=t,i=v(o??{provider:"openai",model:"gpt-4o-mini"}),l=on(i,{disableScaffold:s}),c=I([po,uo],{parentModel:i}),p={...l,...c};return C({model:i,tools:p,systemPrompt:Al(s),input:e,maxIterations:r,onStep:n,logger:a})}var ha=t=>zod.z.string().transform(e=>e.toLowerCase().trim()).pipe(zod.z.enum(t)),nn=zod.z.object({name:zod.z.string(),type:zod.z.string(),nullable:zod.z.coerce.boolean().default(false),isList:zod.z.coerce.boolean().default(false),description:zod.z.string().default("")}),sn=zod.z.object({name:zod.z.string(),kind:ha(["type","input","enum","interface","union"]),fields:zod.z.array(nn).default([]),values:zod.z.array(zod.z.string()).default([]),description:zod.z.string().default(""),isEntity:zod.z.coerce.boolean().default(false),keyFields:zod.z.array(zod.z.string()).default([])}),ya=zod.z.object({name:zod.z.string(),type:ha(["query","mutation","subscription"]),args:zod.z.array(nn).default([]),returnType:zod.z.string(),auth:zod.z.coerce.boolean().default(true),roles:zod.z.array(zod.z.string()).default([]),description:zod.z.string().default("")}),Sa=zod.z.object({name:zod.z.string(),entity:zod.z.string(),types:zod.z.array(sn).default([]),operations:zod.z.array(ya).default([]),datasource:zod.z.string().default(""),loader:zod.z.string().default("")}),Qe=zod.z.object({appName:zod.z.string().default("app"),port:zod.z.number().default(4e3),database:zod.z.string().default("mongodb"),modules:zod.z.array(Sa).default([]),sharedTypes:zod.z.array(sn).default([]),authDirective:zod.z.coerce.boolean().default(true),cacheDirective:zod.z.coerce.boolean().default(false),envVars:zod.z.array(zod.z.string()).default([])});var an=`You are an expert Apollo GraphQL subgraph architect using Apollo Federation v2.
|
|
1388
1278
|
|
|
1389
1279
|
You generate production-ready Apollo subgraph configurations from data models and API designs:
|
|
1390
1280
|
- 4-file module pattern per entity: {module}.graphql, {module}.resolver.ts, {module}.datasource.ts, {module}.loader.ts
|
|
@@ -1401,7 +1291,7 @@ You generate production-ready Apollo subgraph configurations from data models an
|
|
|
1401
1291
|
- GraphQL CodeGen for TypeScript types (generates base-types.ts)
|
|
1402
1292
|
- Module-based organization (one module per entity/domain)
|
|
1403
1293
|
|
|
1404
|
-
Output only valid JSON unless instructed otherwise.`;var
|
|
1294
|
+
Output only valid JSON unless instructed otherwise.`;var ba=`## Requirements:
|
|
1405
1295
|
{requirement}
|
|
1406
1296
|
|
|
1407
1297
|
Generate an Apollo GraphQL subgraph configuration (Federation v2). Include:
|
|
@@ -1432,7 +1322,7 @@ Return ONLY valid JSON:
|
|
|
1432
1322
|
"authDirective": true,
|
|
1433
1323
|
"cacheDirective": false,
|
|
1434
1324
|
"envVars": ["PORT", "DATABASE_URL", "JWT_SECRET", "REDIS_URL"]
|
|
1435
|
-
}`;function
|
|
1325
|
+
}`;function ln(t){return ba.replace("{requirement}",t)}var mo=q("validate_subgraph",Qe,"Validates a subgraph config JSON string against the SubgraphConfig schema. Returns valid: true or valid: false with errors.","config");function go(t){return h({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:zod.z.object({requirement:zod.z.string().describe("Data model, API design, and project requirements")}),handler:async({requirement:e})=>{let o=ln(e),r=[{role:"system",content:"You are an Apollo GraphQL architect. Return only valid JSON."},{role:"user",content:o}],n=await t.invoke(r,{temperature:.3,maxOutputTokens:16384});return M(n.text,Qe)}})}function El(t){return {appName:t.appName,port:t.port,database:t.database,modules:t.modules.map(e=>({name:e.name,pascalName:e.name.charAt(0).toUpperCase()+e.name.slice(1),camelName:e.name.charAt(0).toLowerCase()+e.name.slice(1),entity:e.entity,datasource:e.datasource,types:e.types,operations:e.operations})),authDirective:t.authDirective,envVars:t.envVars,sharedTypes:t.sharedTypes}}var fo=h({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:zod.z.object({config:zod.z.string().describe("JSON string of the validated subgraph config"),outputDir:zod.z.string().describe("Absolute path to the output directory")}),handler:async({config:t,outputDir:e})=>{let o=xe(t,"subgraph config"),r=Pe__namespace.resolve(process.cwd(),".ref/templates/subgraph"),n=El(o);return ce({templateDir:r,outputDir:e,context:n})}});function pn(t,e){let o={validate_subgraph:mo,generate_subgraph:go(t)};return e?.disableScaffold||(o.scaffold_subgraph=fo),o}var Ml=`You are a GraphQL schema specialist for Apollo Federation v2 subgraphs. Given a data model, you generate GraphQL type definitions using buildSubgraphSchema.
|
|
1436
1326
|
|
|
1437
1327
|
## Type Generation
|
|
1438
1328
|
For each entity in the data model:
|
|
@@ -1463,7 +1353,7 @@ For each entity in the data model:
|
|
|
1463
1353
|
- Inputs: PascalCase + Input suffix (CreateUserInput, UpdateUserInput)
|
|
1464
1354
|
- Enums: SCREAMING_SNAKE_CASE values (ADMIN, ACTIVE)
|
|
1465
1355
|
|
|
1466
|
-
Respond with the full GraphQL SDL. Do NOT return JSON.`,ho=f({name:"schema-generator",description:"Generates GraphQL type definitions, input types, and enums from a data model. Use before generating the subgraph config.",systemPrompt:
|
|
1356
|
+
Respond with the full GraphQL SDL. Do NOT return JSON.`,ho=f({name:"schema-generator",description:"Generates GraphQL type definitions, input types, and enums from a data model. Use before generating the subgraph config.",systemPrompt:Ml,tools:{},maxIterations:2});var Ol=`You are a GraphQL resolver architect for Apollo Federation v2 subgraphs. Given types and operations, you plan resolver implementations.
|
|
1467
1357
|
|
|
1468
1358
|
## 4-File Module Pattern
|
|
1469
1359
|
Each module has four files:
|
|
@@ -1510,142 +1400,211 @@ Each module has a loader file that creates DataLoader instances:
|
|
|
1510
1400
|
- Verify role permissions per operation
|
|
1511
1401
|
- Resource ownership checks for user-specific data
|
|
1512
1402
|
|
|
1513
|
-
Respond with structured analysis per module. Do NOT return JSON.`,yo=f({name:"resolver-planner",description:"Plans resolver implementations, datasource methods, and auth integration per GraphQL module. Use after schema generation.",systemPrompt:
|
|
1403
|
+
Respond with structured analysis per module. Do NOT return JSON.`,yo=f({name:"resolver-planner",description:"Plans resolver implementations, datasource methods, and auth integration per GraphQL module. Use after schema generation.",systemPrompt:Ol,tools:{},maxIterations:2});var Cl=`
|
|
1404
|
+
5. **Scaffold (optional)**: If an output directory is provided, use scaffold_subgraph to compile templates.`;function Nl(t){return `${an}
|
|
1514
1405
|
|
|
1515
1406
|
You are the Apollo subgraph builder orchestrator. When the user provides requirements:
|
|
1516
1407
|
|
|
1517
1408
|
1. **Generate schema**: Use subagent_schema-generator to create GraphQL type definitions from the data model.
|
|
1518
1409
|
2. **Plan resolvers**: Use subagent_resolver-planner to design resolver implementations per module.
|
|
1519
1410
|
3. **Generate config**: Use generate_subgraph to produce the complete subgraph configuration as JSON.
|
|
1520
|
-
4. **Validate**: Use validate_subgraph to check the config JSON before returning
|
|
1521
|
-
5. **Scaffold (optional)**: If an output directory is provided, use scaffold_subgraph to compile templates.
|
|
1411
|
+
4. **Validate**: Use validate_subgraph to check the config JSON before returning.${t?"":Cl}
|
|
1522
1412
|
|
|
1523
|
-
Respond with the final subgraph config as JSON.`;async function Al(t){let{input:e,model:o,maxIterations:r=15,onStep:n,logger:a}=t,s=v(o??{provider:"openai",model:"gpt-4o-mini"}),i=cn(s),l=I([ho,yo],{parentModel:s}),c={...i,...l};return C({model:s,tools:c,systemPrompt:El,input:e,maxIterations:r,onStep:n,logger:a})}var Ml=zod.z.string().transform(t=>t.toUpperCase().trim()).pipe(zod.z.enum(["GET","POST","PUT","PATCH","DELETE"])),ua=zod.z.object({name:zod.z.string(),httpMethod:Ml,path:zod.z.string(),auth:zod.z.coerce.boolean().default(true),roles:zod.z.array(zod.z.string()).default([]),validation:zod.z.string().default(""),description:zod.z.string().default("")}),ma=zod.z.object({name:zod.z.string(),resource:zod.z.string(),basePath:zod.z.string(),methods:zod.z.array(ua).default([])}),ga=zod.z.object({name:zod.z.string(),type:zod.z.string(),required:zod.z.coerce.boolean().default(false),unique:zod.z.coerce.boolean().default(false),ref:zod.z.string().optional(),default:zod.z.string().optional()}),fa=zod.z.object({name:zod.z.string(),collection:zod.z.string(),fields:zod.z.array(ga).default([]),timestamps:zod.z.coerce.boolean().default(true),indexes:zod.z.array(zod.z.string()).default([])}),ha=zod.z.object({name:zod.z.string(),type:zod.z.string().transform(t=>{let e=t.toLowerCase().replace(/[\s_-]+/g,"");return ["auth","authentication","jwt","token"].includes(e)?"auth":["validation","validate","validator","input"].includes(e)?"validation":["errorhandler","error","errorhandling","errors"].includes(e)?"errorHandler":["cors","crossorigin"].includes(e)?"cors":["ratelimit","ratelimiter","ratelimiting","throttle"].includes(e)?"rateLimit":["logging","logger","log","morgan"].includes(e)?"logging":"custom"}).pipe(zod.z.enum(["auth","validation","errorHandler","cors","rateLimit","logging","custom"])),config:zod.z.record(zod.z.string(),zod.z.unknown()).default({})}),Xe=zod.z.object({appName:zod.z.string().default("app"),port:zod.z.number().default(3e3),database:zod.z.string().default("mongodb"),routers:zod.z.array(ma).default([]),models:zod.z.array(fa).default([]),middleware:zod.z.array(ha).default([]),envVars:zod.z.array(zod.z.string()).default([])});var pn=`You are an expert Express.js backend architect.
|
|
1413
|
+
Respond with the final subgraph config as JSON.`}async function dn(t){let{input:e,model:o,maxIterations:r=15,onStep:n,logger:a,disableScaffold:s}=t,i=v(o??{provider:"openai",model:"gpt-4o-mini"}),l=pn(i,{disableScaffold:s}),c=I([ho,yo],{parentModel:i}),p={...l,...c};return C({model:i,tools:p,systemPrompt:Nl(s),input:e,maxIterations:r,onStep:n,logger:a})}var un=zod.z.object({brandName:zod.z.string().describe("The brand's display name"),primaryColor:zod.z.string().describe("The brand's primary color code (e.g., #FFFFFF)"),secondaryColor:zod.z.string().describe("The brand's secondary color code (e.g., #000000)"),logo:zod.z.url().describe("URL pointing to the brand's logo")});var mn=zod.z.object({name:zod.z.string().describe("Application name"),description:zod.z.string().describe("Brief description of the application"),author:zod.z.string().describe("Author or owner of the application").default("sijeeshmiziha (HubSpire)"),branding:un.describe("Branding information for the application"),apiEndpoint:zod.z.url().describe("URL endpoint for the app's API calls")});var Pa=zod.z.object({minLength:zod.z.number().optional().describe("Minimum length requirement"),zodString:zod.z.string().describe("Raw Zod string validation (e.g. regex)")}),Ra=zod.z.object({hookName:zod.z.string().optional().describe("Name of the hook for dynamic field options"),queryString:zod.z.string().optional().describe("Optional query string for fetching field options"),labelKey:zod.z.string().optional().describe("Key used as label when displaying options"),valueKey:zod.z.string().optional().describe("Key used as value for a field when selecting options"),values:zod.z.array(zod.z.string()).optional().describe("Static list of possible field values")}),So=zod.z.object({name:zod.z.string().describe("The field's key or identifier"),type:zod.z.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:zod.z.boolean().optional().describe("Whether this field must be filled"),validation:Pa.optional().describe("Optional field validation requirements"),defaultValue:zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean()]).optional().describe("Default value can be string, number, or boolean"),options:Ra.optional().describe("Additional dynamic or static options for this field")}),gn=zod.z.object({field:zod.z.string().describe("Key or name of the data field in the table"),label:zod.z.string().describe("User-friendly label to show on the table header")});var hn=zod.z.object({type:zod.z.string().describe("Indicates the response type (e.g., 'object')"),properties:zod.z.record(zod.z.string(),zod.z.object({type:zod.z.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"),wa=zod.z.object({type:zod.z.enum(["list","create","update","delete","getById"]).describe("Type of API call for CRUD operations"),graphqlHook:zod.z.string().describe("Name of the GraphQL hook (e.g. useGetAllUserQuery, useCreateUserMutation)"),queryString:zod.z.string().describe("Actual GraphQL query string"),responseType:hn.describe("Optional schema describing shape of the API response")}),va=zod.z.object({type:zod.z.enum(["login","currentUser","forgotPassword","resetPassword"]).describe("Type of API call"),graphqlHook:zod.z.string().describe("Name of the GraphQL hook (e.g. useLoginMutation)"),queryString:zod.z.string().describe("Actual GraphQL query string"),responseType:hn.describe("Optional schema describing shape of the API response")}),fn=zod.z.object({title:zod.z.string().describe("Title displayed on the drawer"),graphqlHook:zod.z.string().describe("Name of the GraphQL hook (e.g. useCreateUserMutation, useDeleteOneUserMutation)"),fields:zod.z.array(So).describe("List of fields displayed within the drawer")}),Aa=zod.z.object({name:zod.z.enum(["LoginPage","ForgotPasswordPage","ResetPasswordPage"]).describe("Internal name of the auth page"),type:zod.z.enum(["EmailPassword","ForgotPassword","ResetPassword"]).describe("Type of authentication page"),route:zod.z.string().describe("URL route for this page (e.g., '/login')"),isPrivate:zod.z.boolean().describe("Whether this page requires an authenticated session"),api:zod.z.array(va).describe("List of API calls involved in this page"),fields:zod.z.array(So).optional().describe("Optional form fields needed on this auth page")}),Ea=zod.z.object({type:zod.z.literal("Listing").describe("Indicates that this page is a listing-type page"),name:zod.z.string().describe("Internal name of the listing page"),route:zod.z.string().describe("URL route for this listing page"),isPrivate:zod.z.boolean().describe("Whether this page is private (requires auth)"),api:zod.z.array(wa).describe("List of API calls that power this listing page"),columns:zod.z.array(gn).describe("Table columns displayed on the listing page"),actions:zod.z.array(zod.z.string()).describe("List of possible actions on each row (e.g., create, edit, delete, view)"),drawerCreate:fn.describe("Drawer configuration for creating new records"),drawerUpdate:fn.describe("Drawer configuration for editing existing records")}),yn=zod.z.discriminatedUnion("type",[Aa,Ea]);var Ma=zod.z.object({name:zod.z.string().describe("Name of the module"),pages:zod.z.array(yn).describe("Pages included within this module")}),Ke=zod.z.object({app:mn.describe("Overall application configuration"),modules:zod.z.array(Ma).describe("List of modules that make up the application. Ensure all modules use every available CRUD GraphQL query and mutation from the schema.")});var Dl=zod.z.object({email:zod.z.email().describe("User's email address, must be valid format"),password:zod.z.string().min(8).describe("User's password, minimum length of 8")}),Oa=zod.z.object({_id:zod.z.string().describe("Unique identifier of the specialization, type: string"),title:zod.z.string().describe("Display title for the specialization, type: string")}),_l=zod.z.object({_id:zod.z.string().describe("Unique ID of the user, type: string"),firstName:zod.z.string().min(2).max(30).describe("First name, 2-30 characters, type: string"),lastName:zod.z.string().min(2).max(30).describe("Last name, 2-30 characters, type: string"),email:zod.z.email().describe("Email address in valid format, type: string"),phoneNumber:zod.z.string().min(10).describe("User's phone number, at least 10 digits, type: string"),profileImage:zod.z.string().optional().describe("Optional URL to user's profile image, type: string, optional"),role:zod.z.enum(["ADMIN","TRAINER","CLIENT"]).describe("User's role in the system (ADMIN, TRAINER, CLIENT)"),rate:zod.z.number().min(1).optional().describe("User's rate (e.g., hourly, etc.), type: number, optional"),specializations:zod.z.array(Oa).optional().describe("Array of specialization objects, optional"),languages:zod.z.array(zod.z.string()).optional().describe("Array of languages the user speaks, type: string[], optional"),about:zod.z.string().min(20).max(500).optional().describe("Brief bio or description (20-500 chars), type: string, optional"),gender:zod.z.string().optional().describe("User's gender, type: string, optional"),timezone:zod.z.string().optional().describe("User's timezone, type: string, optional"),averageRating:zod.z.number().optional().describe("Average rating for this user, type: number, optional")}),kl=zod.z.object({firstName:zod.z.string().min(2).max(30).describe("First name, 2-30 characters, type: string"),lastName:zod.z.string().min(2).max(30).describe("Last name, 2-30 characters, type: string"),email:zod.z.email().describe("Valid email for the new user, type: string"),phoneNumber:zod.z.string().min(10).describe("Phone number (at least 10 digits), type: string"),password:zod.z.string().min(8).describe("Password with min length 8, type: string"),role:zod.z.enum(["ADMIN","TRAINER","CLIENT"]).describe("Role of the new user (ADMIN, TRAINER, CLIENT)"),rate:zod.z.number().min(1).optional().describe("Rate for the new user, type: number, optional"),specializationIds:zod.z.array(zod.z.string()).min(1).optional().describe("Array of specialization IDs, optional"),languages:zod.z.array(zod.z.string()).min(1).optional().describe("List of languages user speaks, optional"),about:zod.z.string().min(20).max(500).optional().describe("User's about/bio field, 20-500 chars, optional")}),Il=zod.z.object({_id:zod.z.string().describe("ID of the user to be updated, type: string"),firstName:zod.z.string().min(2).max(30).optional().describe("Updated first name, type: string, optional"),lastName:zod.z.string().min(2).max(30).optional().describe("Updated last name, type: string, optional"),email:zod.z.email().optional().describe("Updated email, type: string, optional"),phoneNumber:zod.z.string().min(10).optional().describe("Updated phone number, at least 10 digits, optional"),rate:zod.z.number().min(1).optional().describe("Updated rate, type: number, optional"),specializationIds:zod.z.array(zod.z.string()).min(1).optional().describe("Updated array of specialization IDs, optional"),languages:zod.z.array(zod.z.string()).min(1).optional().describe("Updated list of languages, optional"),about:zod.z.string().min(20).max(500).optional().describe("Updated about/bio (20-500 chars), optional")}),jl=zod.z.object({email:zod.z.email().describe("Email to initiate the password reset process, type: string")}),ql=zod.z.object({type:zod.z.enum(["EMAIL","SMS"]).describe("How the reset code was sent (EMAIL or SMS)"),resetTicket:zod.z.string().describe("Token/ticket to validate the reset request, type: string"),newPassword:zod.z.string().min(8).describe("The new password, min length 8, type: string")});var Ze=`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.
|
|
1524
1414
|
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
-
|
|
1528
|
-
-
|
|
1529
|
-
-
|
|
1530
|
-
-
|
|
1531
|
-
-
|
|
1532
|
-
-
|
|
1415
|
+
## Target Tech Stack
|
|
1416
|
+
The generated configuration will be consumed by a Vite + React 19 + TypeScript template with:
|
|
1417
|
+
- **UI Components**: ShadCN UI (Radix-based) from src/components/ui/
|
|
1418
|
+
- **Styling**: Tailwind CSS v4 with OKLCH color space
|
|
1419
|
+
- **Routing**: React Router v7 with private route support
|
|
1420
|
+
- **Forms**: React Hook Form + Zod validation (zodResolver)
|
|
1421
|
+
- **GraphQL Client**: Apollo Client with typed hooks from CodeGen
|
|
1422
|
+
- **Path Aliases**: @/{appName}/* maps to ./src/*
|
|
1423
|
+
|
|
1424
|
+
**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).
|
|
1425
|
+
|
|
1426
|
+
Strict guidelines:
|
|
1427
|
+
- Use every available CRUD GraphQL query and mutation from the project schema.
|
|
1428
|
+
- Map GraphQL types to frontend modules and pages.
|
|
1429
|
+
- EmailAddress \u2192 "type": "email" with validation; DateTime \u2192 "type": "date"; enums \u2192 select with options.values.
|
|
1430
|
+
- Relationships \u2192 multiSelect with query-based options where appropriate.
|
|
1431
|
+
- Add isPrivate: true for authenticated operations (route guarded by React Router).
|
|
1432
|
+
- Form fields should map to React Hook Form + Zod validation schemas.
|
|
1433
|
+
- Maintain camelCase. Ensure valid JSON syntax.`;var bo=`
|
|
1434
|
+
Act as an expert GraphQL-to-frontend configuration converter. Transform the provided schema into a structured JSON configuration for rapid app development.
|
|
1435
|
+
|
|
1436
|
+
**Conversion Process**
|
|
1437
|
+
|
|
1438
|
+
1. Schema Analysis:
|
|
1439
|
+
- Identify all modules using 100% of available CRUD operations
|
|
1440
|
+
- Catalog all Query/Mutation operations with arguments
|
|
1441
|
+
- Map GraphQL types to frontend modules
|
|
1442
|
+
- Detect @auth directives and role requirements
|
|
1443
|
+
- Analyze relationships through nested types
|
|
1444
|
+
|
|
1445
|
+
2. Field Mapping:
|
|
1446
|
+
- EmailAddress \u2192 "type": "email" with Zod email validation
|
|
1447
|
+
- DateTime \u2192 "type": "date"
|
|
1448
|
+
- Enums \u2192 dropdowns with options.values
|
|
1449
|
+
- Relationships \u2192 multiSelect with query-based options
|
|
1533
1450
|
|
|
1534
|
-
|
|
1535
|
-
|
|
1451
|
+
3. API Operations:
|
|
1452
|
+
- For each Query/Mutation: determine CRUD type, generate query string with variables, map to React Hook, define response type shape
|
|
1536
1453
|
|
|
1537
|
-
|
|
1454
|
+
4. Validation:
|
|
1455
|
+
- Generate Zod schemas from @required directives, scalar types (Password \u2192 min 8 chars), custom directives
|
|
1456
|
+
- Include validation error messages
|
|
1538
1457
|
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
4. Middleware: auth (JWT), validation (Zod), error handler, CORS, rate limiting, logging.
|
|
1543
|
-
5. Env vars: PORT, DATABASE_URL, JWT_SECRET, NODE_ENV, etc.
|
|
1544
|
-
6. Folder structure: src/routers/{name}/ with {name}.controller.ts, {name}.router.ts, {name}.spec.ts per feature.
|
|
1458
|
+
5. Security:
|
|
1459
|
+
- Add isPrivate: true for authenticated operations
|
|
1460
|
+
- Implement role checks from @auth directives
|
|
1545
1461
|
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
"
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1462
|
+
6. Output:
|
|
1463
|
+
- Generate complete CRUD pages with table column mappings, validated Create/Update forms, API hooks
|
|
1464
|
+
- Include Zod validation strings, maintain camelCase, valid JSON only
|
|
1465
|
+
`.trim();function Sn(){return bo}var Ca=`
|
|
1466
|
+
type Query {
|
|
1467
|
+
getCurrentUser: User
|
|
1468
|
+
getAllUser(limit: Int, offset: Int): [User]!
|
|
1469
|
+
}
|
|
1470
|
+
type Mutation {
|
|
1471
|
+
login(data: LoginInput!): Login!
|
|
1472
|
+
createUser(data: CreateUserInput!): User!
|
|
1473
|
+
}
|
|
1474
|
+
type User {
|
|
1475
|
+
_id: ID!
|
|
1476
|
+
firstName: String!
|
|
1477
|
+
lastName: String!
|
|
1478
|
+
email: String!
|
|
1479
|
+
role: Role!
|
|
1480
|
+
}
|
|
1481
|
+
enum Role { ADMIN TRAINER CLIENT }
|
|
1482
|
+
input LoginInput { email: String! password: String! }
|
|
1483
|
+
input CreateUserInput { firstName: String! lastName: String! email: String! role: Role! }
|
|
1484
|
+
`.trim(),Na=`{
|
|
1485
|
+
"app": {
|
|
1486
|
+
"name": "my-app",
|
|
1487
|
+
"description": "App description",
|
|
1488
|
+
"author": "Author",
|
|
1489
|
+
"branding": {
|
|
1490
|
+
"brandName": "MyBrand",
|
|
1491
|
+
"primaryColor": "#333",
|
|
1492
|
+
"secondaryColor": "#fff",
|
|
1493
|
+
"logo": "https://example.com/logo.png"
|
|
1494
|
+
},
|
|
1495
|
+
"apiEndpoint": "http://localhost:4000/graphql"
|
|
1496
|
+
},
|
|
1497
|
+
"modules": [
|
|
1498
|
+
{
|
|
1499
|
+
"name": "auth",
|
|
1500
|
+
"pages": [
|
|
1501
|
+
{
|
|
1502
|
+
"name": "LoginPage",
|
|
1503
|
+
"type": "EmailPassword",
|
|
1504
|
+
"route": "/login",
|
|
1505
|
+
"isPrivate": false,
|
|
1506
|
+
"api": [
|
|
1507
|
+
{ "type": "login", "graphqlHook": "useLoginMutation", "queryString": "mutation Login($data: LoginInput!) { login(data: $data) { accessToken } }" }
|
|
1508
|
+
]
|
|
1509
|
+
}
|
|
1510
|
+
]
|
|
1511
|
+
},
|
|
1512
|
+
{
|
|
1513
|
+
"name": "user",
|
|
1514
|
+
"pages": [
|
|
1515
|
+
{
|
|
1516
|
+
"type": "Listing",
|
|
1517
|
+
"name": "UserListPage",
|
|
1518
|
+
"route": "/users",
|
|
1519
|
+
"isPrivate": true,
|
|
1520
|
+
"api": [
|
|
1521
|
+
{ "type": "list", "graphqlHook": "useGetAllUserQuery", "queryString": "query GetAllUser { getAllUser { _id firstName email } }" },
|
|
1522
|
+
{ "type": "create", "graphqlHook": "useCreateUserMutation", "queryString": "mutation CreateUser($data: CreateUserInput!) { createUser(data: $data) { _id } }" }
|
|
1523
|
+
],
|
|
1524
|
+
"columns": [{ "field": "firstName", "label": "First Name" }, { "field": "email", "label": "Email" }],
|
|
1525
|
+
"actions": ["create", "edit", "delete"],
|
|
1526
|
+
"drawerCreate": { "title": "Create User", "graphqlHook": "useCreateUserMutation", "fields": [{ "name": "firstName", "type": "text", "required": true }, { "name": "email", "type": "email", "required": true }] },
|
|
1527
|
+
"drawerUpdate": { "title": "Edit User", "graphqlHook": "useUpdateUserMutation", "fields": [{ "name": "firstName", "type": "text" }, { "name": "email", "type": "email" }] }
|
|
1528
|
+
}
|
|
1529
|
+
]
|
|
1530
|
+
}
|
|
1531
|
+
]
|
|
1532
|
+
}`;function bn(){return `
|
|
1533
|
+
**Reference Conversion Example**
|
|
1575
1534
|
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
- {name}.spec.ts -- Jest tests using supertest
|
|
1535
|
+
EXAMPLE GRAPHQL INPUT:
|
|
1536
|
+
\`\`\`graphql
|
|
1537
|
+
${Ca}
|
|
1538
|
+
\`\`\`
|
|
1581
1539
|
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
- PUT /:id -> update by ID
|
|
1589
|
-
- DELETE /:id -> delete by ID
|
|
1590
|
-
- Custom routes for non-CRUD operations
|
|
1540
|
+
EXPECTED JSON OUTPUT:
|
|
1541
|
+
\`\`\`json
|
|
1542
|
+
${Na}
|
|
1543
|
+
\`\`\`
|
|
1544
|
+
`.trim()}function Fl(t,e){return `
|
|
1545
|
+
Review the user feedback carefully to understand the required updates.
|
|
1591
1546
|
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
- health.spec.ts -- Health check tests
|
|
1547
|
+
The user feedback for updating the generated Frontend Config JSON is provided below:
|
|
1548
|
+
"""
|
|
1549
|
+
${t}
|
|
1550
|
+
"""
|
|
1597
1551
|
|
|
1598
|
-
|
|
1599
|
-
- One router directory per resource with co-located controller and spec
|
|
1600
|
-
- Central src/routers/index.ts mounts all routers
|
|
1601
|
-
- Middleware applied per-route or per-router
|
|
1552
|
+
Now, generate the Frontend Config JSON for this project based on the provided feedback.
|
|
1602
1553
|
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1554
|
+
**Project GRAPHQL SCHEMA INPUT:**
|
|
1555
|
+
\`\`\`graphql
|
|
1556
|
+
${e}
|
|
1557
|
+
\`\`\`
|
|
1606
1558
|
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
-
|
|
1559
|
+
Update the Frontend Config JSON to incorporate the requested changes. Return ONLY valid JSON, no markdown code blocks.
|
|
1560
|
+
`.trim()}var je=q("validate_frontend_config",Ke,"Validates a frontend configuration JSON string against the ApplicationSchema. Returns valid: true or valid: false with errors array.","config");function Ul(t,e){let o=Sn(),r=bn(),n=e?`
|
|
1561
|
+
**Project context:**
|
|
1562
|
+
- name: ${e.projectName??"project"}
|
|
1563
|
+
- description: ${e.projectDescription??""}
|
|
1564
|
+
- modules: ${e.modules??""}
|
|
1565
|
+
- apiEndpoint: ${e.apiEndpoint??"http://localhost:4000/graphql"}
|
|
1566
|
+
`:"";return `${o}
|
|
1611
1567
|
|
|
1612
|
-
|
|
1568
|
+
${r}
|
|
1569
|
+
${n}
|
|
1613
1570
|
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
4. **Morgan/Logger**: Request logging with format and stream
|
|
1571
|
+
**Current Project GraphQL Schema:**
|
|
1572
|
+
\`\`\`graphql
|
|
1573
|
+
${t}
|
|
1574
|
+
\`\`\`
|
|
1619
1575
|
|
|
1620
|
-
|
|
1621
|
-
1. **JWT verification**: Extract token from Authorization header or cookie
|
|
1622
|
-
2. **Role check**: Verify user role against required roles
|
|
1623
|
-
3. **Resource ownership**: Check if user owns the resource they're accessing
|
|
1576
|
+
Generate the Frontend Config JSON. Use every available CRUD GraphQL query and mutation. Return ONLY valid JSON.`}function xo(t){return h({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:zod.z.object({graphqlSchema:zod.z.string().describe("The GraphQL schema string to convert"),appInfo:zod.z.object({projectName:zod.z.string().optional(),projectDescription:zod.z.string().optional(),modules:zod.z.string().optional(),apiEndpoint:zod.z.string().optional()}).optional().describe("Optional project/app context")}),handler:async({graphqlSchema:e,appInfo:o})=>{let r=Ul(e,o),n=[{role:"system",content:Ze},{role:"user",content:r}],a=await t.invoke(n,{temperature:.2,maxOutputTokens:16384});return M(a.text,Ke)}})}function To(t){return h({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:zod.z.object({graphqlSchema:zod.z.string().describe("The GraphQL schema string to analyze")}),handler:async({graphqlSchema:e})=>{let o=`${bo}
|
|
1624
1577
|
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1578
|
+
**Schema to analyze:**
|
|
1579
|
+
\`\`\`graphql
|
|
1580
|
+
${e}
|
|
1581
|
+
\`\`\`
|
|
1628
1582
|
|
|
1629
|
-
|
|
1630
|
-
1. **Not found handler**: 404 for unmatched routes
|
|
1631
|
-
2. **Error handler**: Centralized error response with status codes
|
|
1632
|
-
3. **Async wrapper**: Catch async errors without try-catch
|
|
1583
|
+
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 t.invoke(r,{temperature:.3,maxOutputTokens:4096})).text,modules:[],operations:[],suggestedPages:[]}}})}function Ll(t){return {appName:t.app.name,description:t.app.description,apiEndpoint:t.app.apiEndpoint,branding:{brandName:t.app.branding.brandName,primaryColor:t.app.branding.primaryColor,secondaryColor:t.app.branding.secondaryColor,logo:t.app.branding.logo},modules:t.modules.map(e=>({name:e.name,pascalName:e.name.charAt(0).toUpperCase()+e.name.slice(1),camelName:e.name.charAt(0).toLowerCase()+e.name.slice(1)})),author:t.app.author,pages:t.modules.flatMap(e=>e.pages)}}var Tn=h({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:zod.z.object({config:zod.z.string().describe("JSON string of the validated ApplicationSchema config"),outputDir:zod.z.string().describe("Absolute path to the output directory")}),handler:async({config:t,outputDir:e})=>{let o=xe(t,"application schema config"),r=Pe__namespace.resolve(process.cwd(),".ref/templates/vite"),n=Ll(o);return ce({templateDir:r,outputDir:e,context:n})}});function Pn(t,e){let o={validate_frontend_config:je,generate_frontend:xo(t),generate_feature_breakdown:To(t)};return e?.disableScaffold||(o.scaffold_vite=Tn),o}var Gl=`You are an expert at analyzing GraphQL schemas. Your job is to:
|
|
1633
1584
|
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1585
|
+
1. **Types**: List all object types, enums, scalars, and input types.
|
|
1586
|
+
2. **Queries**: List every Query field with arguments and return type.
|
|
1587
|
+
3. **Mutations**: List every Mutation field with arguments and return type.
|
|
1588
|
+
4. **Relationships**: Identify types that reference other types (e.g. User has role: Role, or Order has customer: User).
|
|
1589
|
+
5. **Auth/directives**: Note any @auth, @directive usage that affects access control.
|
|
1637
1590
|
|
|
1638
|
-
Respond with structured
|
|
1591
|
+
Respond with a clear, structured analysis (headings and bullet points). The user will use this to generate a frontend configuration.`,Po=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:Gl,tools:{},maxIterations:2});var Bl=`You are a frontend configuration validator. Your job is to:
|
|
1639
1592
|
|
|
1640
|
-
|
|
1593
|
+
1. Validate the provided frontend config JSON using the validate_frontend_config tool.
|
|
1594
|
+
2. Compare the config against the GraphQL schema (if provided) and check that all CRUD operations are covered.
|
|
1595
|
+
3. Report any missing modules, pages, or API hooks.
|
|
1641
1596
|
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1597
|
+
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:Bl,tools:{validate_frontend_config:je},maxIterations:5})}var Jl=`${Ze}
|
|
1598
|
+
|
|
1599
|
+
You are the React frontend builder orchestrator. When the user provides a GraphQL schema and asks for a frontend configuration:
|
|
1600
|
+
|
|
1601
|
+
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.
|
|
1602
|
+
2. **Generate**: Use generate_frontend with the GraphQL schema (and optional appInfo) to produce the frontend config JSON.
|
|
1603
|
+
3. **Validate (optional)**: Use subagent_config-validator with the generated config (and schema) to check structure and completeness.
|
|
1604
|
+
4. **Validate directly**: You can use validate_frontend_config to check any config JSON.
|
|
1605
|
+
5. **Feature breakdown**: Use generate_feature_breakdown to get a module/operation breakdown before generating.
|
|
1647
1606
|
|
|
1648
|
-
Respond with the final
|
|
1607
|
+
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 Rn(t){let{input:e,model:o,maxIterations:r=15,onStep:n,logger:a,disableScaffold:s}=t,i=v(o??{provider:"openai",model:"gpt-4o-mini"}),l=Pn(i,{disableScaffold:s}),c=Ro(),p=I([Po,c],{parentModel:i}),d={...l,...p};return C({model:i,tools:d,systemPrompt:Jl,input:e,maxIterations:r,onStep:n,logger:a})}var ka=t=>zod.z.string().transform(e=>e.toLowerCase().trim()).pipe(zod.z.enum(t)),Yl=zod.z.string().transform(t=>t.toUpperCase().trim()).pipe(zod.z.enum(["GET","POST","PUT","PATCH","DELETE"])),Ia=zod.z.object({path:zod.z.string(),name:zod.z.string(),access:ka(["public","protected"]),routeGroup:zod.z.string().default(""),purpose:zod.z.string(),hasForm:zod.z.coerce.boolean().default(false),formFields:zod.z.array(zod.z.string()).default([]),dataFetching:ka(["server","client","hybrid"]).default("server"),actions:zod.z.array(zod.z.string()).default([])}),ja=zod.z.object({name:zod.z.string(),path:zod.z.string(),routeGroup:zod.z.string().default(""),components:zod.z.array(zod.z.string()).default([]),purpose:zod.z.string()}),qa=zod.z.object({path:zod.z.string(),methods:zod.z.array(Yl).default([]),auth:zod.z.coerce.boolean().default(true),description:zod.z.string()}),Fa=zod.z.object({name:zod.z.string(),module:zod.z.string(),description:zod.z.string(),revalidates:zod.z.array(zod.z.string()).default([])}),et=zod.z.object({appName:zod.z.string().default("app"),pages:zod.z.array(Ia).default([]),layouts:zod.z.array(ja).default([]),apiRoutes:zod.z.array(qa).default([]),serverActions:zod.z.array(Fa).default([]),middleware:zod.z.array(zod.z.string()).default([]),envVars:zod.z.array(zod.z.string()).default([]),packages:zod.z.array(zod.z.string()).default([])});var wn=`You are an expert Next.js application architect using the App Router.
|
|
1649
1608
|
|
|
1650
1609
|
You generate production-ready Next.js configurations from frontend designs and API designs:
|
|
1651
1610
|
- App Router file structure with route groups, layouts, pages, loading, and error boundaries
|
|
@@ -1656,7 +1615,7 @@ You generate production-ready Next.js configurations from frontend designs and A
|
|
|
1656
1615
|
- Data fetching strategy (server vs client vs hybrid per page)
|
|
1657
1616
|
- Package recommendations (next-auth, prisma, tailwindcss, shadcn/ui)
|
|
1658
1617
|
|
|
1659
|
-
Output only valid JSON unless instructed otherwise.`;var
|
|
1618
|
+
Output only valid JSON unless instructed otherwise.`;var Ua=`## Requirements:
|
|
1660
1619
|
{requirement}
|
|
1661
1620
|
|
|
1662
1621
|
Generate a Next.js App Router application configuration. Include:
|
|
@@ -1705,7 +1664,7 @@ Return ONLY valid JSON:
|
|
|
1705
1664
|
"middleware": ["Redirect unauthenticated users to /login"],
|
|
1706
1665
|
"envVars": ["DATABASE_URL", "NEXTAUTH_SECRET"],
|
|
1707
1666
|
"packages": ["next-auth", "prisma", "@prisma/client", "tailwindcss"]
|
|
1708
|
-
}`;function
|
|
1667
|
+
}`;function vn(t){return Ua.replace("{requirement}",t)}var wo=q("validate_nextjs",et,"Validates a Next.js config JSON string against the NextjsConfig schema. Returns valid: true or valid: false with errors.","config");function vo(t){return h({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:zod.z.object({requirement:zod.z.string().describe("Frontend design, API design, and project requirements")}),handler:async({requirement:e})=>{let o=vn(e),r=[{role:"system",content:"You are a Next.js architect. Return only valid JSON."},{role:"user",content:o}],n=await t.invoke(r,{temperature:.3,maxOutputTokens:16384});return M(n.text,et)}})}function An(t){return {validate_nextjs:wo,generate_nextjs:vo(t)}}var zl=`You are a Next.js App Router specialist. Given page specs, you plan the file structure.
|
|
1709
1668
|
|
|
1710
1669
|
## Route Groups
|
|
1711
1670
|
- (auth) for public auth pages: login, signup, forgot-password
|
|
@@ -1731,7 +1690,7 @@ Return ONLY valid JSON:
|
|
|
1731
1690
|
- Parallel routes: @modal, @sidebar
|
|
1732
1691
|
- Intercepting routes: (.)photo, (..)details
|
|
1733
1692
|
|
|
1734
|
-
Respond with the full file tree and route structure. Do NOT return JSON.`,
|
|
1693
|
+
Respond with the full file tree and route structure. Do NOT return JSON.`,Ao=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:zl,tools:{},maxIterations:2});var $l=`You are a Next.js API specialist. Given an API design, you plan route handlers and server actions.
|
|
1735
1694
|
|
|
1736
1695
|
## API Route Handlers (app/api/)
|
|
1737
1696
|
For external integrations, webhooks, and file uploads:
|
|
@@ -1756,7 +1715,7 @@ For form submissions and data writes:
|
|
|
1756
1715
|
- Server Actions: check session at the start of each action
|
|
1757
1716
|
- Middleware: protect route groups with matcher patterns
|
|
1758
1717
|
|
|
1759
|
-
Respond with structured analysis per module. Do NOT return JSON.`,Eo=f({name:"api-route-generator",description:"Generates Next.js API route handlers and server actions from API design. Use after route planning.",systemPrompt
|
|
1718
|
+
Respond with structured analysis per module. Do NOT return JSON.`,Eo=f({name:"api-route-generator",description:"Generates Next.js API route handlers and server actions from API design. Use after route planning.",systemPrompt:$l,tools:{},maxIterations:2});var Hl=`${wn}
|
|
1760
1719
|
|
|
1761
1720
|
You are the Next.js builder orchestrator. When the user provides requirements:
|
|
1762
1721
|
|
|
@@ -1765,5 +1724,47 @@ You are the Next.js builder orchestrator. When the user provides requirements:
|
|
|
1765
1724
|
3. **Generate config**: Use generate_nextjs to produce the complete Next.js configuration as JSON.
|
|
1766
1725
|
4. **Validate**: Use validate_nextjs to check the config JSON before returning.
|
|
1767
1726
|
|
|
1768
|
-
Respond with the final Next.js config as JSON.`;async function
|
|
1727
|
+
Respond with the final Next.js config as JSON.`;async function En(t){let{input:e,model:o,maxIterations:r=15,onStep:n,logger:a}=t,s=v(o??{provider:"openai",model:"gpt-4o-mini"}),i=An(s),l=I([Ao,Eo],{parentModel:s}),c={...i,...l};return C({model:s,tools:c,systemPrompt:Hl,input:e,maxIterations:r,onStep:n,logger:a})}var Ga=zod.z.object({order:zod.z.number(),action:zod.z.string(),details:zod.z.string()}),Ba=zod.z.object({name:zod.z.string(),description:zod.z.string(),steps:zod.z.array(Ga)}),Ja=zod.z.object({area:zod.z.string(),scenario:zod.z.string(),handling:zod.z.string(),severity:zod.z.string().transform(t=>t.toLowerCase().trim()).pipe(zod.z.enum(["critical","warning","info"]))}),Ya=zod.z.object({flow:zod.z.string(),item:zod.z.string(),expectedResult:zod.z.string()}),tt=zod.z.object({phases:zod.z.array(Ba).default([]),currentState:zod.z.string().default(""),desiredEndState:zod.z.string().default(""),edgeCases:zod.z.array(Ja).default([]),securityNotes:zod.z.array(zod.z.string()).default([]),performanceNotes:zod.z.array(zod.z.string()).default([]),testingChecklist:zod.z.array(Ya).default([])});var Mn=`You are a senior tech lead specializing in implementation strategy and project execution planning.
|
|
1728
|
+
|
|
1729
|
+
You create enterprise-quality execution plans with:
|
|
1730
|
+
- Phased implementation order with concrete, numbered steps per phase
|
|
1731
|
+
- Current state analysis and desired end state definition
|
|
1732
|
+
- Edge cases per domain area with handling strategies and severity levels
|
|
1733
|
+
- Security considerations (passwords, tokens, CORS, input validation)
|
|
1734
|
+
- Performance considerations (indexing, caching, lazy loading, N+1 prevention)
|
|
1735
|
+
- Manual testing checklists grouped by feature flow
|
|
1736
|
+
|
|
1737
|
+
Output only valid JSON unless instructed otherwise.`;var za=`## Full Plan Context:
|
|
1738
|
+
{context}
|
|
1739
|
+
|
|
1740
|
+
Create a comprehensive execution plan. Include:
|
|
1741
|
+
|
|
1742
|
+
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").
|
|
1743
|
+
2. **currentState**: What the project starts with (e.g. "vanilla Next.js, no DB, no auth").
|
|
1744
|
+
3. **desiredEndState**: What must work when done (user capabilities + technical verification).
|
|
1745
|
+
4. **edgeCases**: Edge cases per area with scenario, handling strategy, and severity (critical/warning/info).
|
|
1746
|
+
5. **securityNotes**: Security considerations (password hashing, JWT config, rate limiting, etc.).
|
|
1747
|
+
6. **performanceNotes**: Performance considerations (indexing, caching, lazy loading, etc.).
|
|
1748
|
+
7. **testingChecklist**: Manual testing items per flow with expected results.
|
|
1749
|
+
|
|
1750
|
+
Return ONLY valid JSON:
|
|
1751
|
+
{
|
|
1752
|
+
"phases": [{ "name": "Phase 1: Foundation", "description": "...", "steps": [{ "order": 1, "action": "Install dependencies", "details": "npm install mongoose bcryptjs jsonwebtoken" }] }],
|
|
1753
|
+
"currentState": "...",
|
|
1754
|
+
"desiredEndState": "...",
|
|
1755
|
+
"edgeCases": [{ "area": "Authentication", "scenario": "Email already exists", "handling": "Return 400 with clear message", "severity": "critical" }],
|
|
1756
|
+
"securityNotes": ["..."],
|
|
1757
|
+
"performanceNotes": ["..."],
|
|
1758
|
+
"testingChecklist": [{ "flow": "Auth Flow", "item": "Sign up with valid credentials", "expectedResult": "Account created, redirected to dashboard" }]
|
|
1759
|
+
}`;function On(t){return za.replace("{context}",t)}var Mo=q("validate_execution_plan",tt,"Validates an execution plan JSON string against the ExecutionPlan schema. Returns valid: true or valid: false with errors.","plan");function Oo(t){return h({name:"create_execution_plan",description:"Generate a comprehensive execution plan with phases, edge cases, and testing checklist from the full plan context.",input:zod.z.object({context:zod.z.string().describe("Full plan context: all sections generated so far")}),handler:async({context:e})=>{let o=On(e),r=[{role:"system",content:"You are a tech lead. Return only valid JSON."},{role:"user",content:o}],n=await t.invoke(r,{temperature:.3,maxOutputTokens:16384});return M(n.text,tt)}})}function Cn(t){return {validate_execution_plan:Mo,create_execution_plan:Oo(t)}}var Ql=`${Mn}
|
|
1760
|
+
|
|
1761
|
+
You are the execution planning orchestrator. When the user provides plan sections:
|
|
1762
|
+
|
|
1763
|
+
1. **Analyze edge cases**: Use subagent_edge-case-analyzer to identify edge cases per domain area with handling strategies.
|
|
1764
|
+
2. **Design testing**: Use subagent_testing-strategist to design manual testing checklists grouped by feature flow.
|
|
1765
|
+
3. **Generate plan**: Use create_execution_plan to produce the complete execution plan with phases, edge cases, and testing checklist.
|
|
1766
|
+
4. **Validate**: Use validate_execution_plan to check the final plan JSON before returning.
|
|
1767
|
+
|
|
1768
|
+
Respond with the final execution plan as JSON.`;async function Nn(t){let{input:e,model:o,maxIterations:r=15,onStep:n,logger:a}=t,s=v(o??{provider:"openai",model:"gpt-4o-mini"}),i=Cn(s),l=I([Ee,Me],{parentModel:s}),c={...i,...l};return C({model:s,tools:c,systemPrompt:Ql,input:e,maxIterations:r,onStep:n,logger:a})}var Dn=h({name:"hello_world",description:"Returns a greeting message for the given name",input:zod.z.object({name:zod.z.string().describe("Name to greet")}),handler:async({name:t})=>({greeting:`Hello, ${t}! Welcome to sweagent.`})});var Vl="You are a friendly greeter. Use the hello_world tool to greet users.";async function _n(t){let{input:e,model:o,systemPrompt:r=Vl,maxIterations:n=3,onStep:a,logger:s}=t,i=v(o??{provider:"openai",model:"gpt-4o-mini"});return C({model:i,tools:{hello_world:Dn},systemPrompt:r,input:e,maxIterations:n,onStep:a,logger:s})}function $(t,e,o){return {name:t,description:e,handler:(r,n,a)=>o({input:r,model:n,onStep:a})}}var qe=[$("plan","Generate a full software plan (discovery, requirements, design, synthesis) from a project description.",rr),$("gather_requirements","Extract structured requirements (actors, flows, stories, modules) from a project description.",br),$("design_data_model","Design a database schema (MongoDB or PostgreSQL) with entities, relations, and indexes.",_r),$("design_api","Design REST or GraphQL API contracts (endpoints, request/response schemas) from requirements.",Lr),$("design_auth","Design authentication and authorization strategy (providers, roles, permissions, flows).",Yr),$("architect_backend","Design backend architecture (folder structure, services, middleware, deployment) from requirements.",Qr),$("architect_frontend","Design frontend architecture (components, state management, routing, styling) from requirements.",Kr),$("build_express","Generate Express.js REST API configuration and boilerplate from an API design.",t=>rn({...t,disableScaffold:true})),$("build_apollo","Generate Apollo GraphQL subgraph configuration and resolvers from an API design.",t=>dn({...t,disableScaffold:true})),$("build_react","Generate React + Vite application configuration and components from a GraphQL schema.",t=>Rn({...t,disableScaffold:true})),$("build_nextjs","Generate Next.js App Router configuration and pages from requirements.",En),$("plan_execution","Create a phased execution plan with edge-case analysis and testing strategy.",Nn),$("hello_world","Test agent that greets users. Use to verify the MCP server is working.",_n)];function kn(t){return qe.find(e=>e.name===t)}var In={input:zod.z.string().describe("Natural language description of what to build or design"),provider:zod.z.enum(["openai","anthropic","google"]).optional().describe("LLM provider (defaults to openai)"),model:zod.z.string().optional().describe("Model name, e.g. gpt-4o-mini, claude-3-5-sonnet-20241022"),temperature:zod.z.number().min(0).max(1).optional().describe("Sampling temperature (0-1)")};function jn(t){if(!(!t.provider&&!t.model))return {provider:t.provider??"openai",model:t.model??"gpt-4o-mini",temperature:t.temperature}}var Xl="sweagent",Kl="0.0.3",ot=t=>{process.stderr.write(`[sweagent] ${t}
|
|
1769
|
+
`);},Qa=200;function Zl(t){return e=>{let o=`${t} \u2014 step ${e.iteration+1}`;if(e.content){let r=e.content.length>Qa?e.content.slice(0,Qa)+"\u2026":e.content;ot(`${o}: ${r}`);}else {let r=e.toolCalls?.map(n=>n.toolName).join(", ");ot(`${o}${r?` (tools: ${r})`:""}`);}}}function qn(){let t=new mcp_js.McpServer({name:Xl,version:Kl},{capabilities:{tools:{}}});for(let e of qe)t.registerTool(e.name,{description:e.description,inputSchema:In},async o=>{ot(`${e.name} \u2014 started`);try{let r=jn(o),n=Zl(e.name),a=await e.handler(o.input,r,n);return ot(`${e.name} \u2014 completed`),{content:[{type:"text",text:a.output}]}}catch(r){let n=r instanceof Error?r.message:String(r);return ot(`${e.name} \u2014 error: ${n}`),{content:[{type:"text",text:n}],isError:true}}});return t}Object.defineProperty(exports,"jsonSchema",{enumerable:true,get:function(){return ai.jsonSchema}});Object.defineProperty(exports,"tool",{enumerable:true,get:function(){return ai.tool}});exports.API_DESIGNER_SYSTEM_PROMPT=Vt;exports.APOLLO_BUILDER_SYSTEM_PROMPT=an;exports.AUTH_DESIGNER_SYSTEM_PROMPT=Gr;exports.AgentError=rt;exports.ApiResponseTypeSchema=hn;exports.AppConfigSchema=mn;exports.ApplicationSchema=Ke;exports.AuthPageApiSchema=va;exports.AuthPageSchema=Aa;exports.BACKEND_ARCHITECT_SYSTEM_PROMPT=zr;exports.BaseMcpClient=lt;exports.BrandingSchema=un;exports.CREATE_EXECUTION_PLAN_PROMPT=za;exports.ColumnSchema=gn;exports.CreateUserInputSchema=kl;exports.DATA_MODELER_SYSTEM_PROMPT=qt;exports.DB_DESIGN_SYSTEM_PROMPT=K;exports.DESIGN_AUTH_PROMPT=Vs;exports.DESIGN_BACKEND_PROMPT=ta;exports.DESIGN_DATABASE_SYSTEM_PROMPT=dr;exports.DESIGN_EXPRESS_PROMPT=ma;exports.DESIGN_FRONTEND_PROMPT=aa;exports.DESIGN_NEXTJS_PROMPT=Ua;exports.DESIGN_SUBGRAPH_PROMPT=ba;exports.DISCOVERY_SYSTEM_FRAGMENT=sr;exports.DISCOVERY_USER_PROMPT=bs;exports.DrawerSchema=fn;exports.EXAMPLE_GRAPHQL_SCHEMA=Ca;exports.EXAMPLE_JSON_OUTPUT=Na;exports.EXECUTION_PLANNER_SYSTEM_PROMPT=Mn;exports.EXPRESS_BUILDER_SYSTEM_PROMPT=Zr;exports.EXTRACT_ACTORS_PROMPT=xs;exports.EXTRACT_MODULES_PROMPT=Rs;exports.FRONTEND_ARCHITECT_SYSTEM_PROMPT=Vr;exports.FieldOptionsSchema=Ra;exports.ForgotPasswordSchema=jl;exports.FormFieldSchema=So;exports.GENERATE_FLOWS_PROMPT=Ts;exports.GENERATE_STORIES_PROMPT=Ps;exports.LibraryError=ue;exports.ListingPageApiSchema=wa;exports.ListingPageSchema=Ea;exports.LoginInputSchema=Dl;exports.MONGODB_SYSTEM_PROMPT=K;exports.ModelError=ie;exports.ModuleSchema=Ma;exports.NEXTJS_BUILDER_SYSTEM_PROMPT=wn;exports.PLANNING_SYSTEM_PROMPT=ee;exports.PageSchema=yn;exports.PlanningContextBuilder=bt;exports.REACT_BUILDER_INSTRUCTION=bo;exports.REACT_BUILDER_SYSTEM_PROMPT=Ze;exports.REQUIREMENT_GATHERER_SYSTEM_PROMPT=he;exports.RequirementContextBuilder=jt;exports.ResetPasswordSchema=ql;exports.SYNTHESIS_SYSTEM_FRAGMENT=mr;exports.SYNTHESIS_USER_PROMPT=ws;exports.SpecializationSchema=Oa;exports.SubagentError=be;exports.TOOL_REGISTRY=qe;exports.ToolError=H;exports.UpdateUserInputSchema=Il;exports.UserSchema=_l;exports.ValidationError=Fn;exports.ValidationSchema=Pa;exports.actorSchema=Oe;exports.actorsResultSchema=xt;exports.adApiDesignSchema=pe;exports.adGraphqlOperationSchema=jr;exports.adRestEndpointSchema=Ir;exports.addChatEntry=Fe;exports.advanceStage=At;exports.apiRouteGeneratorSubagent=Eo;exports.assemblePlan=Zo;exports.authDesignSchema=Ye;exports.authFlowSchema=zs;exports.authFlowStepSchema=Ys;exports.authMiddlewareSchema=$s;exports.backendDesignSchema=ze;exports.buildCreateExecutionPlanPrompt=On;exports.buildDesignAuthPrompt=Br;exports.buildDesignBackendPrompt=$r;exports.buildDesignDatabasePrompt=ur;exports.buildDesignExpressPrompt=en;exports.buildDesignFrontendPrompt=Wr;exports.buildDesignNextjsPrompt=vn;exports.buildDesignSubgraphPrompt=ln;exports.buildDiscoveryPrompt=ar;exports.buildExampleShotPrompt=bn;exports.buildExtractActorsPrompt=ir;exports.buildExtractModulesPrompt=pr;exports.buildFeedbackPrompt=Fl;exports.buildGenerateFlowsPrompt=lr;exports.buildGenerateStoriesPrompt=cr;exports.buildInstructionPrompt=Sn;exports.buildPromptVariables=Lt;exports.buildSynthesisPrompt=gr;exports.chatEntrySchema=ys;exports.compileTemplate=qo;exports.componentAnalyzerSubagent=gt;exports.componentDesignSchema=sa;exports.contractDesignerSubagent=Ae;exports.convertRequirementToContext=ps;exports.createAnthropicModel=at;exports.createApiDesignerTools=Ur;exports.createApolloBuilderTools=pn;exports.createAuthDesignerTools=Jr;exports.createBackendArchitectTools=Hr;exports.createConfigValidatorSubagent=Ro;exports.createDataModelerTools=Nr;exports.createDbDesignPrompt=Ue;exports.createDbDesignerTools=Dr;exports.createDesignApiProTool=Kt;exports.createDesignApiTool=Xt;exports.createDesignAuthTool=eo;exports.createDesignBackendTool=oo;exports.createDesignDatabaseProTool=Ht;exports.createDesignDatabaseTool=$t;exports.createDesignFrontendTool=ao;exports.createDesignSchemaProTool=Jt;exports.createDesignSchemaTool=Bt;exports.createExecutionPlanTool=Oo;exports.createExecutionPlannerTools=Cn;exports.createExpressBuilderTools=on;exports.createFrontendArchitectTools=Xr;exports.createGenerateExpressTool=lo;exports.createGenerateFeatureBreakdownTool=To;exports.createGenerateFrontendTool=xo;exports.createGenerateNextjsTool=vo;exports.createGenerateSubgraphTool=go;exports.createGoogleModel=it;exports.createInitialContext=fr;exports.createLogger=rc;exports.createModel=v;exports.createMongoDesignPrompt=Ue;exports.createMongoProDesignPrompt=Le;exports.createMongoRedesignPrompt=Ge;exports.createNextjsBuilderTools=An;exports.createOpenAIModel=st;exports.createPlanningContextBuilder=Wi;exports.createProDbDesignPrompt=Le;exports.createReactBuilderTools=Pn;exports.createRedesignDatabaseTool=Qt;exports.createRedesignPrompt=Ge;exports.createRefineSchemaTools=Yt;exports.createRequirementContextBuilder=rl;exports.createSchemaRefinerSubagent=me;exports.createSubagentTool=jo;exports.createSubagentToolSet=I;exports.createSweagentServer=qn;exports.createToolSet=k;exports.crudApiSchema=us;exports.databaseDesignSchema=fe;exports.databaseEntitySchema=hs;exports.defineSubagent=f;exports.defineTool=h;exports.dmCreateSchemaRefinerSubagent=me;exports.dmDataEntitySchema=Tr;exports.dmDataModelDesignSchema=oe;exports.dmEntityAnalyzerSubagent=ne;exports.dmValidateSchemaTool=Gt;exports.edgeCaseAnalyzerSubagent=Ee;exports.edgeCaseSchema=Ja;exports.editPlan=Li;exports.endpointAnalyzerSubagent=ve;exports.entityAnalyzerSubagent=ne;exports.entityFieldSchema=ms;exports.entityIndexSchema=gs;exports.entityRelationSchema=fs;exports.executeTool=_o;exports.executeToolByName=nt;exports.executionPlanSchema=tt;exports.expressConfigSchema=He;exports.extractDataEntities=Ft;exports.extractJson=Wa;exports.extractRoles=Ut;exports.extractedModuleSchema=De;exports.fieldSchema=ke;exports.finalRequirementSchema=nr;exports.findTool=kn;exports.flowDesignerSubagent=we;exports.flowSchema=Ce;exports.flowsResultSchema=Tt;exports.formFieldSchema=ra;exports.formatTechnicalRequirements=Mr;exports.formatUserFlows=Ar;exports.formatUserStories=Er;exports.formatUserTypes=vr;exports.frameworkSelectorSubagent=no;exports.frontendDesignSchema=$e;exports.getTool=Bn;exports.getTools=Gn;exports.graphqlAnalyzerSubagent=Po;exports.graphqlFieldSchema=nn;exports.graphqlTypeSchema=sn;exports.helloWorldTool=Dn;exports.implementationPhaseSchema=Ba;exports.loggerConfigFromEnv=nc;exports.mergeStageResult=hr;exports.middlewareConfigSchema=ua;exports.middlewareConfiguratorSubagent=uo;exports.middlewareSchema=Ks;exports.modelFieldSchema=pa;exports.modelSchema=da;exports.moduleSchema=Ie;exports.modulesResultSchema=Rt;exports.mongoFieldSchema=ke;exports.mongoModuleSchema=Ie;exports.mongoProjectSchema=X;exports.nextjsApiRouteSchema=qa;exports.nextjsConfigSchema=et;exports.nextjsLayoutSchema=ja;exports.nextjsPageSchema=Ia;exports.pageDesignSchema=na;exports.pagePlannerSubagent=Re;exports.parseModelJsonResponse=M;exports.phaseStepSchema=Ga;exports.processPlanningChat=ge;exports.processRequirementChat=It;exports.projectBriefSchema=_e;exports.projectSchema=X;exports.questionSchema=wt;exports.registerHelpers=Fo;exports.relationshipMapperSubagent=mt;exports.requirementContextSchema=Xi;exports.requirementSummarySchema=Ss;exports.resolverOperationSchema=ya;exports.resolverPlannerSubagent=yo;exports.roleDefinitionSchema=Hs;exports.routeGeneratorSubagent=po;exports.routeGroupSchema=ea;exports.routePlannerSubagent=Ao;exports.routerMethodSchema=la;exports.routerSchema=ca;exports.runAgent=C;exports.runApiDesignerAgent=Lr;exports.runApolloBuilderAgent=dn;exports.runAuthDesignerAgent=Yr;exports.runBackendArchitectAgent=Qr;exports.runDataModelerAgent=_r;exports.runDbDesignerAgent=cl;exports.runExecutionPlannerAgent=Nn;exports.runExpressBuilderAgent=rn;exports.runFrontendArchitectAgent=Kr;exports.runHelloWorldAgent=_n;exports.runNextjsBuilderAgent=En;exports.runPlanningAgent=rr;exports.runPlanningFromRequirements=Qi;exports.runReactBuilderAgent=Rn;exports.runRequirementGathererAgent=br;exports.runSubagent=z;exports.safeJsonParse=xe;exports.scaffoldExpressTool=co;exports.scaffoldProject=ce;exports.scaffoldSubgraphTool=fo;exports.schemaGeneratorSubagent=ho;exports.securityAnalyzerSubagent=ft;exports.securityPolicySchema=Qs;exports.serverActionSchema=Fa;exports.servicePlannerSubagent=ro;exports.serviceSchema=Zs;exports.storiesResultSchema=Pt;exports.storySchema=Ne;exports.subgraphConfigSchema=Qe;exports.subgraphModuleSchema=Sa;exports.sumTokenUsage=Do;exports.testChecklistItemSchema=Ya;exports.testingStrategistSubagent=Me;exports.validateApiTool=Wt;exports.validateAuthTool=Zt;exports.validateBackendTool=to;exports.validateExecutionPlanTool=Mo;exports.validateExpressTool=io;exports.validateFrontendConfigTool=je;exports.validateFrontendTool=so;exports.validateNextjsTool=wo;exports.validateSchemaTool=zt;exports.validateSubgraphTool=mo;exports.writePlanToFile=ki;//# sourceMappingURL=index.cjs.map
|
|
1769
1770
|
//# sourceMappingURL=index.cjs.map
|