sweagent 0.0.1 → 0.0.2

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/dist/index.js CHANGED
@@ -1,5 +1,7 @@
1
- import {z}from'zod';import {tool,generateText}from'ai';export{jsonSchema,tool}from'ai';import {createOpenAI}from'@ai-sdk/openai';import {createAnthropic}from'@ai-sdk/anthropic';import {createGoogleGenerativeAI}from'@ai-sdk/google';import {Client}from'@modelcontextprotocol/sdk/client';import {createRequire}from'module';import k from'path';import {pathToFileURL}from'url';var M=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}`);}},C=class extends M{constructor(o,r,n){super(o,n);this.provider=r;this.name="ModelError";}},x=class extends M{constructor(o,r,n){super(o,n);this.toolName=r;this.name="ToolError";}},Ne=class extends M{constructor(o,r){super(o);this.errors=r;this.name="ValidationError";}},Y=class extends M{constructor(o,r,n){super(o,n);this.iteration=r;this.name="AgentError";}},D=class extends M{constructor(o,r,n){super(o,n);this.subagentName=r;this.name="SubagentError";}};var Ue={debug:0,info:1,warn:2,error:3};function Ht(t={}){let{prefix:e="",level:o="info",timestamps:r=false}=t,n=Ue[o];function i(a,p){let m=[];return r&&m.push(`[${new Date().toISOString()}]`),m.push(`[${a.toUpperCase()}]`),e&&m.push(`[${e}]`),m.push(p),m.join(" ")}function s(a){return Ue[a]>=n}return {debug(a,p){s("debug")&&console.debug(i("debug",a),p??"");},info(a,p){s("info")&&console.info(i("info",a),p??"");},warn(a,p){s("warn")&&console.warn(i("warn",a),p??"");},error(a,p){s("error")&&console.error(i("error",a),p??"");}}}var pt={noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},dt={textTokens:void 0,reasoningTokens:void 0};function ke(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:pt,outputTokenDetails:dt}}function h(t){let{name:e,description:o,input:r,handler:n}=t;return tool({description:o,inputSchema:r,execute:async i=>{let s=r.safeParse(i);if(!s.success)throw new x(`Invalid input: ${s.error.message}`,e,s.error);try{return await n(s.data,void 0)}catch(a){throw a instanceof x?a:new x(`Tool "${e}" failed: ${a instanceof Error?a.message:String(a)}`,e,a instanceof Error?a:void 0)}}})}function I(t){return t}function _e(t){return Object.values(t)}function je(t,e){return t[e]}async function ce(t,e,o){if(!t.execute)return {success:false,error:"Tool has no execute function"};try{return {success:!0,output:await t.execute(e,{toolCallId:o?.toolCallId??"",messages:[],abortSignal:o?.abortSignal})}}catch(r){return {success:false,error:r instanceof Error?r.message:String(r)}}}async function H(t,e,o,r){let n=t[e];if(!n)throw new x(`Tool not found: ${e}`);return ce(n,o,r)}async function w(t){let{model:e,tools:o,systemPrompt:r,input:n,maxIterations:i=10,onStep:s}=t,a=[{role:"system",content:r},{role:"user",content:n}],p=[];for(let m=0;m<i;m++){let u=await e.invoke(a,{tools:o}),g={iteration:m,content:u.text,toolCalls:u.toolCalls,usage:u.usage};if(!u.toolCalls?.length)return p.push(g),s?.(g),{output:u.text,steps:p,totalUsage:ke(p.map(S=>S.usage)),messages:a};let y=[...u.text?[{type:"text",text:u.text}]:[],...u.toolCalls.map(S=>({type:"tool-call",toolCallId:S.toolCallId,toolName:S.toolName,input:S.input}))];a.push({role:"assistant",content:y});let G=[];for(let S of u.toolCalls){let J=await H(o,S.toolName,S.input,{toolCallId:S.toolCallId}),O={toolCallId:S.toolCallId,toolName:S.toolName,output:J.success?J.output:J.error,isError:!J.success};G.push(O);let ct=O.isError?{type:"error-text",value:String(O.output)}:{type:"text",value:typeof O.output=="string"?O.output:JSON.stringify(O.output)};a.push({role:"tool",content:[{type:"tool-result",toolCallId:S.toolCallId,toolName:S.toolName,output:ct}]});}g.toolResults=G,p.push(g),s?.(g);}throw new Y(`Agent reached maximum iterations (${i}) without completing`,i-1)}function N(t){let{provider:e,modelName:o,getModel:r}=t;return {provider:e,modelName:o,async invoke(n,i){try{let s=await r(),a=i?.tools?Object.fromEntries(Object.entries(i.tools).map(([u,g])=>{let{execute:y,...G}=g;return [u,G]})):void 0,p=await generateText({model:s,messages:n,tools:a,maxOutputTokens:i?.maxOutputTokens,temperature:i?.temperature,stopSequences:i?.stop}),m=p.toolCalls.map(u=>({toolCallId:u.toolCallId,toolName:u.toolName,input:u.input}));return {text:p.text,toolCalls:m,usage:p.usage,finishReason:p.finishReason}}catch(s){let a=s instanceof Error?s:new Error(String(s));throw new C(`Failed to invoke ${e} model`,e,a)}},async generateVision(n,i,s){try{let a=await r(),p=[];for(let g of i)p.push({type:"image",image:`data:${g.mimeType};base64,${g.base64}`,mimeType:g.mimeType});p.push({type:"text",text:n});let m=[];s?.systemPrompt&&m.push({role:"system",content:s.systemPrompt}),m.push({role:"user",content:p});let u=await generateText({model:a,messages:m,maxOutputTokens:s?.maxOutputTokens,temperature:s?.temperature});return {text:u.text,toolCalls:[],usage:u.usage,finishReason:u.finishReason}}catch(a){let p=a instanceof Error?a:new Error(String(a));throw new C("Failed to generate vision response",e,p)}}}}function Q(t){let{model:e,apiKey:o,baseUrl:r}=t,n=createOpenAI({apiKey:o??process.env.OPENAI_API_KEY,baseURL:r});return N({provider:"openai",modelName:e,getModel:()=>n.chat(e)})}function V(t){let{model:e,apiKey:o}=t,r=createAnthropic({apiKey:o??process.env.ANTHROPIC_API_KEY});return N({provider:"anthropic",modelName:e,getModel:()=>r(e)})}function W(t){let{model:e,apiKey:o}=t,r=createGoogleGenerativeAI({apiKey:o??process.env.GOOGLE_GENERATIVE_AI_API_KEY});return N({provider:"google",modelName:e,getModel:()=>r(e)})}function R(t){let{provider:e}=t;switch(e){case "openai":return Q(t);case "anthropic":return V(t);case "google":return W(t);default:throw new C(`Unsupported provider: ${e}. Supported providers: openai, anthropic, google`)}}var bt=/^[a-z0-9]+(-[a-z0-9]+)*$/;function v(t){if(!t.name.trim())throw new D("Subagent name is required",void 0);if(!bt.test(t.name))throw new D(`Subagent name must be kebab-case (lowercase letters, numbers, hyphens): ${t.name}`,t.name);return {...t}}function St(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[i,s]of Object.entries(o))i.startsWith("subagent_")||r.has(i)||(n[i]=s);return n}async function pe(t,e,o){let{parentTools:r,parentModel:n}=o??{},i=St(t,r),s=t.model==null?n:R(t.model);if(!s)throw new D("Subagent has no model: set definition.model or pass parentModel in options",t.name);return {...await w({model:s,tools:i,systemPrompt:t.systemPrompt,input:e,maxIterations:t.maxIterations??10,onStep:t.onStep}),subagentName:t.name}}function de(t,e){let o=`subagent_${t.name}`;return h({name:o,description:t.description,input:z.object({prompt:z.string().describe("The task or question to delegate to this subagent")}),handler:async({prompt:r})=>(await pe(t,r,{parentTools:e?.parentTools,parentModel:e?.parentModel})).output})}function U(t,e){let o={};for(let r of t){let n=de(r,e);o[`subagent_${r.name}`]=n;}return o}function xt(){let e=createRequire(import.meta.url).resolve("@modelcontextprotocol/sdk/client");return k.dirname(k.dirname(k.dirname(k.dirname(e))))}var Fe=xt();function $e(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 Be(t,e){let o=k.join(Fe,"dist","esm","client","streamableHttp.js"),r=await import(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 Ge(t,e){let o=k.join(Fe,"dist","esm","client","stdio.js"),r=await import(pathToFileURL(o).href);return new r.StdioClientTransport({command:t,args:e})}var K=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:i}=o,s=e?.url??process.env[`${r}_URL`],a=process.env[`${r}_API_KEY`],p=e?.command??process.env[`${r}_COMMAND`],m=process.env[`${r}_ARGS`],u=e?.args??(m?m.split(",").map(y=>y.trim()):void 0),g=e?.headers?{...e.headers}:void 0;if(a){let y=i??"Authorization";g=g??{},g[y]=y==="Authorization"?`Bearer ${a}`:a;}if(s)return {url:s,headers:g};if(p)return {command:p,args:u?.length?u:[]};throw new x(`${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 x("MCP connection failed.","mcp_client");return this.client}if(this.connectPromise=this.doConnect(),await this.connectPromise,this.connectPromise=null,!this.client)throw new x("MCP connection failed.","mcp_client");return this.client}async doConnect(){let e=new Client({name:this.info.name,version:this.info.version},{capabilities:{}});if(this.config.url)this.transport=await Be(this.config.url,this.config.headers);else if(this.config.command)this.transport=await Ge(this.config.command,this.config.args??[]);else throw new x("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?$e(n):n}async close(){this.transport&&(await this.transport.close(),this.transport=null),this.client=null,this.connectPromise=null;}};var me=h({name:"hello_world",description:"Returns a greeting message for the given name",input:z.object({name:z.string().describe("Name to greet")}),handler:async({name:t})=>({greeting:`Hello, ${t}! Welcome to sweagent.`})});var Rt="You are a friendly greeter. Use the hello_world tool to greet users.";async function vt(t){let{input:e,model:o,systemPrompt:r=Rt,maxIterations:n=3,onStep:i}=t,s=R(o??{provider:"openai",model:"gpt-4o-mini"});return w({model:s,tools:{hello_world:me},systemPrompt:r,input:e,maxIterations:n,onStep:i})}var ue=z.object({fieldName:z.string().describe("fieldName must be in camelCase"),fieldType:z.enum(["string","number","boolean","Types.ObjectId","Date","object","email","password","enum"]),isArray:z.boolean(),isRequired:z.boolean(),isUnique:z.boolean(),values:z.array(z.string()).describe("Enum values if fieldType is enum, else empty array"),defaultVal:z.union([z.string(),z.boolean(),z.number(),z.null()]).optional(),relationTo:z.string().optional().describe("Module name for relations"),relationType:z.enum(["one-to-one","many-to-one",""]).optional(),isPrivate:z.boolean().describe("True if password field, else false")});var ge=z.object({moduleName:z.string().describe("camelCase, single word, never auth/authentication"),isUserModule:z.boolean(),authMethod:z.enum(["EMAIL_AND_PASSWORD","PHONE_AND_OTP",""]).optional(),emailField:z.string().optional(),passwordField:z.string().optional(),phoneField:z.string().optional(),roleField:z.string().optional(),permissions:z.record(z.string(),z.array(z.enum(["CREATE","READ","UPDATE","DELETE"]))).optional().describe("Permissions per role"),fields:z.array(ue)});var A=z.object({projectName:z.string().describe("projectName must be in kebab-case"),projectDescription:z.string(),modules:z.array(ge),author:z.string().default("sijeeshmiziha")});var P=`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.
1
+ import Er from'pino';import {z}from'zod';import {tool,zodSchema,generateObject,generateText}from'ai';export{jsonSchema,tool}from'ai';import {createOpenAI}from'@ai-sdk/openai';import {createAnthropic}from'@ai-sdk/anthropic';import {createGoogleGenerativeAI}from'@ai-sdk/google';import*as W from'fs';import*as xe from'path';import xe__default from'path';import te from'handlebars';import {Client}from'@modelcontextprotocol/sdk/client';import {createRequire}from'module';import {pathToFileURL}from'url';import {writeFile}from'fs/promises';var de=class extends Error{constructor(e,r){super(e,r===void 0?void 0:{cause:r}),this.name="LibraryError",r?.stack&&(this.stack=`${this.stack}
2
+ Caused by: ${r.stack}`);}},ae=class extends de{constructor(r,o,n){super(r,n);this.provider=o;this.name="ModelError";}},Q=class extends de{constructor(r,o,n){super(r,n);this.toolName=o;this.name="ToolError";}},In=class extends de{constructor(r,o){super(r);this.errors=o;this.name="ValidationError";}},Ke=class extends de{constructor(r,o,n){super(r,n);this.iteration=o;this.name="AgentError";}},ye=class extends de{constructor(r,o,n){super(r,n);this.subagentName=o;this.name="SubagentError";}};function Xa(t){let e=t.trim(),r=/```(?:json)?\s*([\s\S]*?)```/.exec(e);return r?.[1]?r[1].trim():e}function M(t,e){let r=Xa(t),o;try{o=JSON.parse(r);}catch(a){let s=r.length>300?r.slice(0,300)+"...":r;throw new Error(`Failed to parse model response as JSON: ${a instanceof Error?a.message:String(a)}. Preview: ${s}`)}let n=e.safeParse(o);if(!n.success){let a=n.error.issues.slice(0,5).map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
3
+ `);throw new Error(`Model JSON does not match expected schema:
4
+ ${a}`)}return n.data}function Se(t,e){try{return JSON.parse(t)}catch(r){let o=t.length>200?t.slice(0,200)+"...":t;throw new Error(`Invalid JSON${e?` for ${e}`:""}: ${r instanceof Error?r.message:String(r)}. Preview: ${o}`)}}var kn={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},child:()=>kn};function dc(t={}){if(t.enabled===false)return kn;let{name:e,level:r="info",pretty:o=false,file:n,stream:a,destination:s}=t,i=a==="stderr"?2:a==="stdout"?1:o?2:1,l;if(s)l=Er({name:e,level:r},s);else {let p=[];o?p.push({target:"pino-pretty",options:{colorize:true,destination:i,singleLine:true,ignore:"time,pid,hostname",translateTime:false},level:r}):p.push({target:"pino/file",options:{destination:i},level:r}),n&&p.push({target:"pino/file",options:{destination:n,mkdir:true},level:r});let c=Er.transport({targets:p});l=Er({name:e,level:r},c);}return _n(l)}function uc(t={}){let e=process.env,r=(e.SWE_LOG_ENABLED??"true").trim().toLowerCase(),o=r!=="0"&&r!=="false"&&r!=="no"&&r!=="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",p=s==="stdout"?"stdout":s==="stderr"||l?"stderr":"stdout",c=e.SWE_LOG_FILE?.trim()||void 0,d=e.SWE_LOG_NAME?.trim()||void 0;return {enabled:o,level:a,stream:p,pretty:l,...c&&{file:c},...d&&{name:d},...t}}function _n(t){return {debug:(e,r)=>{t.debug(r??{},e);},info:(e,r)=>{t.info(r??{},e);},warn:(e,r)=>{t.warn(r??{},e);},error:(e,r)=>{r instanceof Error?t.error({err:r},e):t.error(r??{},e);},child:e=>_n(t.child(e))}}var Za={noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},ei={textTokens:void 0,reasoningTokens:void 0};function Ar(t){let e=0,r=0,o=0;for(let n of t)n&&(e+=n.inputTokens??0,r+=n.outputTokens??0,o+=n.totalTokens??0);return {inputTokens:e,outputTokens:r,totalTokens:o,inputTokenDetails:Za,outputTokenDetails:ei}}function u(t){let{name:e,description:r,input:o,handler:n}=t;return tool({description:r,inputSchema:o,execute:async a=>{let s=o.safeParse(a);if(!s.success)throw new Q(`Invalid input: ${s.error.message}`,e,s.error);try{return await n(s.data,void 0)}catch(i){throw i instanceof Q?i:new Q(`Tool "${e}" failed: ${i instanceof Error?i.message:String(i)}`,e,i instanceof Error?i:void 0)}}})}function j(t){return t}function jn(t){return Object.values(t)}function qn(t,e){return t[e]}async function Or(t,e,r){let{logger:o}=r??{},n=r?.toolName??("name"in t&&typeof t.name=="string"?t.name:"unknown");if(!t.execute)return o?.error("Tool has no execute function",{toolName:n}),{success:false,error:"Tool has no execute function"};o?.debug("Executing tool",{toolName:n,toolCallId:r?.toolCallId});try{let a=await t.execute(e,{toolCallId:r?.toolCallId??"",messages:[],abortSignal:r?.abortSignal});return o?.info("Tool completed",{toolName:n,toolCallId:r?.toolCallId}),{success:!0,output:a}}catch(a){let s=a instanceof Error?a.message:String(a);return o?.error("Tool failed",{toolName:n,toolCallId:r?.toolCallId,error:s}),{success:false,error:s}}}async function Xe(t,e,r,o){let n=t[e];if(!n)throw o?.logger?.error("Tool not found",{name:e,availableTools:Object.keys(t)}),new Q(`Tool not found: ${e}`);return Or(n,r,{...o,toolName:e})}function Mr(t,e){t?.forEach(r=>r.onStep?.(e));}function Un(t,e,r){t?.forEach(o=>o.onToolExecution?.(e,r));}function Ln(t,e){t?.forEach(r=>r.onError?.(e));}async function D(t){let{model:e,tools:r,systemPrompt:o,input:n,maxIterations:a=10,onStep:s,observers:i,logger:l}=t;l?.info("Starting agent",{maxIterations:a});let p=[{role:"system",content:o},{role:"user",content:n}],c=[];for(let m=0;m<a;m++){m>0&&m>=a-2&&l?.warn("Approaching max iterations",{iteration:m,maxIterations:a}),l?.debug("Agent iteration",{iteration:m});let S=await e.invoke(p,{tools:r}),g={iteration:m,content:S.text,toolCalls:S.toolCalls,usage:S.usage};if(S.text&&l?.debug("Model response",{iteration:m,textLength:S.text.length}),!S.toolCalls?.length)return c.push(g),s?.(g),Mr(i,g),l?.info("Agent completed",{steps:c.length,totalUsage:Ar(c.map(_=>_.usage))}),{output:S.text,steps:c,totalUsage:Ar(c.map(_=>_.usage)),messages:p};l?.debug("Tool calls",{iteration:m,toolCalls:S.toolCalls.map(_=>({name:_.toolName,toolCallId:_.toolCallId}))});let G=[...S.text?[{type:"text",text:S.text}]:[],...S.toolCalls.map(_=>({type:"tool-call",toolCallId:_.toolCallId,toolName:_.toolName,input:_.input}))];p.push({role:"assistant",content:G});let U=[];for(let _ of S.toolCalls){let se=await Xe(r,_.toolName,_.input,{toolCallId:_.toolCallId,logger:l}),ee={toolCallId:_.toolCallId,toolName:_.toolName,output:se.success?se.output:se.error,isError:!se.success};U.push(ee),Un(i,_.toolName,ee.output);let _e=ee.isError?{type:"error-text",value:String(ee.output)}:{type:"text",value:typeof ee.output=="string"?ee.output:JSON.stringify(ee.output)};p.push({role:"tool",content:[{type:"tool-result",toolCallId:_.toolCallId,toolName:_.toolName,output:_e}]});}g.toolResults=U,c.push(g),s?.(g),Mr(i,g);}let d=new Ke(`Agent reached maximum iterations (${a}) without completing`,a-1);throw Ln(i,d),l?.error("Agent failed: max iterations reached",{maxIterations:a,error:d}),d}function be(t){let{provider:e,modelName:r,getModel:o}=t;return {provider:e,modelName:r,async invoke(n,a){try{let s=await o(),i=a?.tools?Object.fromEntries(Object.entries(a.tools).map(([c,d])=>{let{execute:m,...S}=d;return [c,S]})):void 0,l=await generateText({model:s,messages:n,tools:i,maxOutputTokens:a?.maxOutputTokens,temperature:a?.temperature,stopSequences:a?.stop}),p=l.toolCalls.map(c=>({toolCallId:c.toolCallId,toolName:c.toolName,input:c.input}));return {text:l.text,toolCalls:p,usage:l.usage,finishReason:l.finishReason}}catch(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 o(),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 p=[];s?.systemPrompt&&p.push({role:"system",content:s.systemPrompt}),p.push({role:"user",content:l});let c=await generateText({model:i,messages:p,maxOutputTokens:s?.maxOutputTokens,temperature:s?.temperature});return {text:c.text,toolCalls:[],usage:c.usage,finishReason:c.finishReason}}catch(i){let l=i instanceof Error?i:new Error(String(i));throw new ae("Failed to generate vision response",e,l)}},async invokeObject(n,a,s){try{let i=await o(),l=zodSchema(a),p=await generateObject({model:i,messages:n,schema:l,temperature:s?.temperature,maxOutputTokens:s?.maxOutputTokens});return {data:p.object,usage:p.usage}}catch(i){let l=i instanceof Error?i:new Error(String(i));throw new ae(`Failed to invokeObject ${e} model`,e,l)}}}}function Ze(t){let{model:e,apiKey:r,baseUrl:o}=t,n=createOpenAI({apiKey:r??process.env.OPENAI_API_KEY,baseURL:o});return be({provider:"openai",modelName:e,getModel:()=>n.chat(e)})}function et(t){let{model:e,apiKey:r}=t,o=createAnthropic({apiKey:r??process.env.ANTHROPIC_API_KEY});return be({provider:"anthropic",modelName:e,getModel:()=>o(e)})}function tt(t){let{model:e,apiKey:r}=t,o=createGoogleGenerativeAI({apiKey:r??process.env.GOOGLE_GENERATIVE_AI_API_KEY});return be({provider:"google",modelName:e,getModel:()=>o(e)})}function E(t){let{provider:e}=t;switch(e){case "openai":return Ze(t);case "anthropic":return et(t);case "google":return tt(t);default:throw new ae(`Unsupported provider: ${e}. Supported providers: openai, anthropic, google`)}}var ci=/^[a-z0-9]+(-[a-z0-9]+)*$/;function f(t){if(!t.name.trim())throw new ye("Subagent name is required",void 0);if(!ci.test(t.name))throw new ye(`Subagent name must be kebab-case (lowercase letters, numbers, hyphens): ${t.name}`,t.name);return {...t}}function pi(t,e){if(t.tools!=null&&Object.keys(t.tools).length>0)return t.tools;let r=e??{},o=new Set(t.disallowedTools??[]),n={};for(let[a,s]of Object.entries(r))a.startsWith("subagent_")||o.has(a)||(n[a]=s);return n}async function Y(t,e,r){let{parentTools:o,parentModel:n}=r??{},a=pi(t,o),s=t.model==null?n:E(t.model);if(!s)throw new ye("Subagent has no model: set definition.model or pass parentModel in options",t.name);return {...await D({model:s,tools:a,systemPrompt:t.systemPrompt,input:e,maxIterations:t.maxIterations??10,onStep:t.onStep}),subagentName:t.name}}function Cr(t,e){let r=`subagent_${t.name}`;return u({name:r,description:t.description,input:z.object({prompt:z.string().describe("The task or question to delegate to this subagent")}),handler:async({prompt:o})=>(await Y(t,o,{parentTools:e?.parentTools,parentModel:e?.parentModel})).output})}function q(t,e){let r={};for(let o of t){let n=Cr(o,e);r[`subagent_${o.name}`]=n;}return r}function Dr(t,e){return te.compile(t,{noEscape:true})(e)}function Jn(t,e=t){let r=[];if(!W.existsSync(t))return r;let o=W.readdirSync(t,{withFileTypes:true});for(let n of o){let a=xe.join(t,n.name);n.isDirectory()?r.push(...Jn(a,e)):n.name.endsWith(".hbs")&&r.push(xe.relative(e,a));}return r}function di(t){return t.replace(/\.hbs$/,"")}function ui(t,e){for(let r of e)if(new RegExp("^"+r.replace(/\./g,"\\.").replace(/\*\*/g,"<<GLOBSTAR>>").replace(/\*/g,"[^/]*").replace(/<<GLOBSTAR>>/g,".*")+"$").test(t))return true;return false}async function le(t){let{templateDir:e,outputDir:r,context:o,skipPatterns:n=[]}=t,a=Jn(e),s=[],i=[];for(let l of a){if(ui(l,n))continue;let p=di(l),c=xe.join(e,l),d=xe.join(r,p);try{let m=W.readFileSync(c,"utf-8"),S=Dr(m,o);W.mkdirSync(xe.dirname(d),{recursive:!0}),W.writeFileSync(d,S,"utf-8"),s.push(p);}catch(m){i.push({file:l,message:m instanceof Error?m.message:String(m)});}}return {fileCount:s.length,files:s,errors:i}}function Nr(){te.registerHelper("eq",(t,e)=>t===e),te.registerHelper("neq",(t,e)=>t!==e),te.registerHelper("json",t=>JSON.stringify(t,null,2)),te.registerHelper("uppercase",t=>typeof t=="string"?t.toUpperCase():""),te.registerHelper("lowercase",t=>typeof t=="string"?t.toLowerCase():""),te.registerHelper("capitalize",t=>typeof t=="string"?t.charAt(0).toUpperCase()+t.slice(1):""),te.registerHelper("camelCase",t=>typeof t!="string"?"":t.replace(/[-_\s]+(.)?/g,(e,r)=>r?r.toUpperCase():"").replace(/^(.)/,e=>e.toLowerCase())),te.registerHelper("pascalCase",t=>typeof t!="string"?"":t.replace(/[-_\s]+(.)?/g,(e,r)=>r?r.toUpperCase():"").replace(/^(.)/,e=>e.toUpperCase()));}Nr();function gi(){let e=createRequire(import.meta.url).resolve("@modelcontextprotocol/sdk/client");return xe__default.dirname(xe__default.dirname(xe__default.dirname(xe__default.dirname(e))))}var zn=gi();function Yn(t){let e=t.content;if(!e?.length)return {};let r=e[0];if(r?.type==="text"&&typeof r.text=="string"){let o=r.text.trim();if(o.startsWith("{")||o.startsWith("["))try{return JSON.parse(o)}catch{return {raw:o}}return {text:o}}return t}async function $n(t,e){let r=xe__default.join(zn,"dist","esm","client","streamableHttp.js"),o=await import(pathToFileURL(r).href),n=e?{headers:new Headers(e)}:void 0;return new o.StreamableHTTPClientTransport(new URL(t),n?{requestInit:n}:void 0)}async function Hn(t,e){let r=xe__default.join(zn,"dist","esm","client","stdio.js"),o=await import(pathToFileURL(r).href);return new o.StdioClientTransport({command:t,args:e})}var rt=class{info;config;client=null;transport=null;connectPromise=null;constructor(e,r){this.info=e,this.config=r;}static resolveConfig(e,r={envPrefix:"MCP"}){let{envPrefix:o,serverLabel:n,apiKeyHeader:a}=r,s=e?.url??process.env[`${o}_URL`],i=process.env[`${o}_API_KEY`],l=e?.command??process.env[`${o}_COMMAND`],p=process.env[`${o}_ARGS`],c=e?.args??(p?p.split(",").map(m=>m.trim()):void 0),d=e?.headers?{...e.headers}:void 0;if(i){let m=a??"Authorization";d=d??{},d[m]=m==="Authorization"?`Bearer ${i}`:i;}if(s)return {url:s,headers:d};if(l)return {command:l,args:c?.length?c:[]};throw new Q(`${n??o} uses MCP only. Set ${o}_URL or ${o}_COMMAND (and optionally ${o}_ARGS).`,"mcp_client")}async ensureConnected(){if(this.client)return this.client;if(this.connectPromise){if(await this.connectPromise,!this.client)throw new Q("MCP connection failed.","mcp_client");return this.client}if(this.connectPromise=this.doConnect(),await this.connectPromise,this.connectPromise=null,!this.client)throw new Q("MCP connection failed.","mcp_client");return this.client}async doConnect(){let e=new Client({name:this.info.name,version:this.info.version},{capabilities:{}});if(this.config.url)this.transport=await $n(this.config.url,this.config.headers);else if(this.config.command)this.transport=await Hn(this.config.command,this.config.args??[]);else throw new Q("MCP config missing: provide url or command.","mcp_client");await e.connect(this.transport),this.client=e;}async callTool(e,r={}){let n=await(await this.ensureConnected()).callTool({name:e,arguments:r});return n&&typeof n=="object"&&"content"in n?Yn(n):n}async close(){this.transport&&(await this.transport.close(),this.transport=null),this.client=null,this.connectPromise=null;}};var Ir=u({name:"hello_world",description:"Returns a greeting message for the given name",input:z.object({name:z.string().describe("Name to greet")}),handler:async({name:t})=>({greeting:`Hello, ${t}! Welcome to sweagent.`})});var hi="You are a friendly greeter. Use the hello_world tool to greet users.";async function yi(t){let{input:e,model:r,systemPrompt:o=hi,maxIterations:n=3,onStep:a,logger:s}=t,i=E(r??{provider:"openai",model:"gpt-4o-mini"});return D({model:i,tools:{hello_world:Ir},systemPrompt:o,input:e,maxIterations:n,onStep:a,logger:s})}var ot=z.object({fieldName:z.string().describe("fieldName must be in camelCase"),fieldType: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(z.enum(["string","number","boolean","Types.ObjectId","Date","object","email","password","enum"])),isArray:z.coerce.boolean().default(false),isRequired:z.coerce.boolean().default(true),isUnique:z.coerce.boolean().default(false),values:z.array(z.string()).default([]).describe("Enum values if fieldType is enum, else empty array"),defaultVal:z.union([z.string(),z.boolean(),z.number(),z.null()]).optional(),relationTo:z.string().optional().describe("Module name for relations"),relationType: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(z.enum(["one-to-one","many-to-one",""])).optional(),isPrivate:z.coerce.boolean().default(false).describe("True if password field, else false")});var nt=z.object({moduleName:z.string().describe("camelCase, single word, never auth/authentication"),isUserModule:z.coerce.boolean().default(false),authMethod: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(z.enum(["EMAIL_AND_PASSWORD","PHONE_AND_OTP",""])).optional(),emailField:z.string().optional(),passwordField:z.string().optional(),phoneField:z.string().optional(),roleField:z.string().optional(),permissions:z.record(z.string(),z.array(z.enum(["CREATE","READ","UPDATE","DELETE"]))).optional().describe("Permissions per role"),fields:z.union([z.array(ot),z.record(z.string(),z.unknown())]).transform((t,e)=>{if(Array.isArray(t))return t;let r=[];for(let[o,n]of Object.entries(t)){let a=typeof n=="object"&&n!==null?{...n}:{};a.fieldName||(a.fieldName=o);let s=ot.safeParse(a);if(s.success)r.push(s.data);else for(let i of s.error.issues)e.addIssue({...i,path:[o,...i.path]});}return r})});var oe=z.object({projectName:z.string().default("project").describe("projectName must be in kebab-case"),projectDescription:z.string().default(""),modules:z.union([z.array(nt),z.record(z.string(),z.unknown())]).transform((t,e)=>{if(Array.isArray(t))return t;let r=[];for(let[o,n]of Object.entries(t)){let a=typeof n=="object"&&n!==null?{...n}:{};a.moduleName||(a.moduleName=o);let s=nt.safeParse(a);if(s.success)r.push(s.data);else for(let i of s.error.issues)e.addIssue({...i,path:[o,...i.path]});}return r}),author:z.string().default("sijeeshmiziha")});var ce=`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.
3
5
 
4
6
  ## ANALYSIS FRAMEWORK
5
7
 
@@ -126,7 +128,7 @@ Synthesize all analyses into the final schema:
126
128
 
127
129
  5. **Authorization (RBAC)**:
128
130
  - Define permissions per role on user modules
129
- - Format: {{ "roleName": ["CREATE", "READ", "UPDATE", "DELETE"] }}`;function fe(t){return `${P}
131
+ - Format: {{ "roleName": ["CREATE", "READ", "UPDATE", "DELETE"] }}`;function kr(t){return `${ce}
130
132
 
131
133
  Design a robust and efficient MongoDB database schema based on the following requirements:
132
134
 
@@ -139,39 +141,39 @@ ${t}
139
141
  3. Define proper relationships between modules
140
142
  4. Set appropriate permissions for user modules
141
143
 
142
- Return ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`}function Ye(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(`
143
- - `);return `### ${o+1}. ${e.name}
144
+ Return ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`}function Vn(t){return !t||t.length===0?'No specific user types defined. Assume a general "User" role.':t.map((e,r)=>{let o=e.goals.filter(n=>n.trim()).join(`
145
+ - `);return `### ${r+1}. ${e.name}
144
146
  **Description:** ${e.description}
145
147
  **Goals:**
146
- - ${r||"No specific goals defined"}`}).join(`
148
+ - ${o||"No specific goals defined"}`}).join(`
147
149
 
148
- `)}function He(t,e){return !t||t.length===0?"No specific user flows defined.":t.map((o,r)=>{let i=e.find(s=>s.id===o.actorId)?.name||"User";return `### ${r+1}. ${o.name}
149
- **Actor:** ${i}
150
- **Description:** ${o.description}
151
- **Trigger:** ${o.trigger||"User initiates action"}
152
- **Outcome:** ${o.outcome||"Action completed"}`}).join(`
150
+ `)}function Wn(t,e){return !t||t.length===0?"No specific user flows defined.":t.map((r,o)=>{let a=e.find(s=>s.id===r.actorId)?.name||"User";return `### ${o+1}. ${r.name}
151
+ **Actor:** ${a}
152
+ **Description:** ${r.description}
153
+ **Trigger:** ${r.trigger||"User initiates action"}
154
+ **Outcome:** ${r.outcome||"Action completed"}`}).join(`
153
155
 
154
- `)}function Qe(t,e){if(!t||t.length===0)return "No specific user stories defined.";let o=new Map;for(let i of t){let s=o.get(i.flowId)||[];s.push(i),o.set(i.flowId,s);}let r=[];for(let i of e){let s=o.get(i.id)||[];if(s.length!==0){r.push(`### Flow: ${i.name}
155
- `);for(let a of s){let p=a.preconditions.filter(y=>y.trim()),m=a.postconditions.filter(y=>y.trim()),u=a.dataInvolved.filter(y=>y.trim()),g=`**As a** ${a.actor}, **I want to** ${a.action}, **so that** ${a.benefit}
156
- `;p.length>0&&(g+=`
156
+ `)}function Kn(t,e){if(!t||t.length===0)return "No specific user stories defined.";let r=new Map;for(let a of t){let s=r.get(a.flowId)||[];s.push(a),r.set(a.flowId,s);}let o=[];for(let a of e){let s=r.get(a.id)||[];if(s.length!==0){o.push(`### Flow: ${a.name}
157
+ `);for(let i of s){let l=i.preconditions.filter(m=>m.trim()),p=i.postconditions.filter(m=>m.trim()),c=i.dataInvolved.filter(m=>m.trim()),d=`**As a** ${i.actor}, **I want to** ${i.action}, **so that** ${i.benefit}
158
+ `;l.length>0&&(d+=`
157
159
  **Preconditions:**
158
- ${p.map(y=>`- ${y}`).join(`
160
+ ${l.map(m=>`- ${m}`).join(`
159
161
  `)}
160
- `),m.length>0&&(g+=`
162
+ `),p.length>0&&(d+=`
161
163
  **Postconditions:**
162
- ${m.map(y=>`- ${y}`).join(`
164
+ ${p.map(m=>`- ${m}`).join(`
163
165
  `)}
164
- `),u.length>0&&(g+=`
166
+ `),c.length>0&&(d+=`
165
167
  **Data Involved (IMPORTANT - these indicate entities/fields):**
166
- ${u.map(y=>`- ${y}`).join(`
168
+ ${c.map(m=>`- ${m}`).join(`
167
169
  `)}
168
- `),r.push(g);}}}let n=t.filter(i=>!e.some(s=>s.id===i.flowId));if(n.length>0){r.push(`### Other Stories
169
- `);for(let i of n){let s=i.dataInvolved.filter(p=>p.trim()),a=`**As a** ${i.actor}, **I want to** ${i.action}, **so that** ${i.benefit}
170
- `;s.length>0&&(a+=`
170
+ `),o.push(d);}}}let n=t.filter(a=>!e.some(s=>s.id===a.flowId));if(n.length>0){o.push(`### Other Stories
171
+ `);for(let a of n){let s=a.dataInvolved.filter(l=>l.trim()),i=`**As a** ${a.actor}, **I want to** ${a.action}, **so that** ${a.benefit}
172
+ `;s.length>0&&(i+=`
171
173
  **Data Involved:** ${s.join(", ")}
172
- `),r.push(a);}}return r.join(`
173
- `)}function Ve(t){if(!t)return "No specific technical requirements. Use defaults.";let e=[];return e.push(`**Authentication:** ${t.authentication||"none"}`),t.authorization?(e.push("**Authorization (RBAC):** Enabled"),t.roles&&t.roles.length>0&&e.push(`**Defined Roles:** ${t.roles.join(", ")}`)):e.push("**Authorization:** Disabled"),t.realtime&&e.push("**Realtime Features:** Required (consider subscription patterns)"),t.fileUpload&&e.push("**File Upload:** Required (consider file/document collection)"),t.search&&e.push("**Search Functionality:** Required (consider text indexes)"),t.integrations&&t.integrations.length>0&&e.push(`**Integrations:** ${t.integrations.join(", ")}`),e.join(`
174
- `)}function he(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 ye(t){return t.map(e=>e.name.toLowerCase().replaceAll(/\s+/g,"_"))}function We(t){return {projectName:t.projectName,projectGoal:t.projectGoal,projectDescription:t.projectDescription||t.projectGoal,userTypes:Ye(t.actors),userFlows:He(t.flows,t.actors),userStories:Qe(t.stories,t.flows),technicalRequirements:Ve(t.technicalRequirements)}}function be(t){let e=We(t);return `${P}
174
+ `),o.push(i);}}return o.join(`
175
+ `)}function Xn(t){if(!t)return "No specific technical requirements. Use defaults.";let e=[];return e.push(`**Authentication:** ${t.authentication||"none"}`),t.authorization?(e.push("**Authorization (RBAC):** Enabled"),t.roles&&t.roles.length>0&&e.push(`**Defined Roles:** ${t.roles.join(", ")}`)):e.push("**Authorization:** Disabled"),t.realtime&&e.push("**Realtime Features:** Required (consider subscription patterns)"),t.fileUpload&&e.push("**File Upload:** Required (consider file/document collection)"),t.search&&e.push("**Search Functionality:** Required (consider text indexes)"),t.integrations&&t.integrations.length>0&&e.push(`**Integrations:** ${t.integrations.join(", ")}`),e.join(`
176
+ `)}function _r(t){let e=new Set;for(let r of t)for(let o of r.dataInvolved)o.trim()&&e.add(o.trim());return Array.from(e)}function jr(t){return t.map(e=>e.name.toLowerCase().replaceAll(/\s+/g,"_"))}function Zn(t){return {projectName:t.projectName,projectGoal:t.projectGoal,projectDescription:t.projectDescription||t.projectGoal,userTypes:Vn(t.actors),userFlows:Wn(t.flows,t.actors),userStories:Kn(t.stories,t.flows),technicalRequirements:Xn(t.technicalRequirements)}}function qr(t){let e=Zn(t);return `${ce}
175
177
 
176
178
  ---
177
179
 
@@ -249,7 +251,7 @@ Generate the final schema with:
249
251
  - RBAC permissions on user modules
250
252
  - Timestamps on every module
251
253
 
252
- Return ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`}function Se(t,e){return `${P}
254
+ Return ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`}function Ur(t,e){return `${ce}
253
255
 
254
256
  Update the existing MongoDB schema based on user feedback.
255
257
 
@@ -265,7 +267,7 @@ ${t}
265
267
  ${e}
266
268
 
267
269
  Return the updated schema as a valid JSON object matching the original schema format.
268
- IMPORTANT: Return ONLY the JSON object, no markdown code blocks, no explanations.`}var _=h({name:"validate_schema",description:"Validates a MongoDB project schema JSON string against the expected schema. Returns valid: true or valid: false with errors array.",input:z.object({schema:z.string().describe("JSON string of the database project schema to validate")}),handler:async({schema:t})=>{try{let e=JSON.parse(t);return A.parse(e),{valid:!0}}catch(e){return e instanceof z.ZodError?{valid:false,errors:e.issues.map(o=>`${o.path.join(".")}: ${o.message}`)}:e instanceof SyntaxError?{valid:false,errors:[`Invalid JSON: ${e.message}`]}:{valid:false,errors:[String(e)]}}}});function At(t){let e=t.trim(),o=/```(?:json)?\s*([\s\S]*?)```/.exec(e);return o?.[1]?o[1].trim():e}function Z(t){return h({name:"design_database",description:"Generate a MongoDB database schema from plain text requirements. Use for ad-hoc or legacy requirements. Returns the full project schema as JSON.",input:z.object({requirement:z.string().describe("Plain text description of the database requirements")}),handler:async({requirement:e})=>{let o=fe(e),r=[{role:"system",content:"You are a MongoDB schema expert. Return only valid JSON."},{role:"user",content:o}],i=(await t.invoke(r,{temperature:.3,maxOutputTokens:8192})).text,s=At(i),a=JSON.parse(s);return A.parse(a)}})}function Pt(t){let e=t.trim(),o=/```(?:json)?\s*([\s\S]*?)```/.exec(e);return o?.[1]?o[1].trim():e}var Mt=z.object({projectName:z.string(),projectGoal:z.string(),projectDescription:z.string().optional(),actors:z.array(z.object({id:z.string(),name:z.string(),description:z.string(),goals:z.array(z.string())})),flows:z.array(z.object({id:z.string(),actorId:z.string(),name:z.string(),description:z.string(),trigger:z.string(),outcome:z.string()})),stories:z.array(z.object({id:z.string(),flowId:z.string(),actor:z.string(),action:z.string(),benefit:z.string(),preconditions:z.array(z.string()),postconditions:z.array(z.string()),dataInvolved:z.array(z.string())})),technicalRequirements:z.object({authentication:z.enum(["none","email","oauth","phone","email_and_phone"]),authorization:z.boolean(),roles:z.array(z.string()).optional(),integrations:z.array(z.string()).optional(),realtime:z.boolean().optional(),fileUpload:z.boolean().optional(),search:z.boolean().optional()}).optional()});function X(t){return h({name:"design_database_pro",description:"Generate a MongoDB schema from structured requirements (project name, goal, actors, flows, user stories with dataInvolved, technical requirements). Use for pro-level 5-phase analysis. Returns dbDesign and metadata (entitiesDetected, rolesExtracted).",input:Mt,handler:async e=>{let o=be(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}),i=Pt(n.text),s=JSON.parse(i),a=A.parse(s),p={entitiesDetected:he(e.stories),rolesExtracted:ye(e.actors)};return {dbDesign:a,metadata:p}}})}function Ct(t){let e=t.trim(),o=/```(?:json)?\s*([\s\S]*?)```/.exec(e);return o?.[1]?o[1].trim():e}function ee(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. Returns the updated schema as JSON.",input:z.object({existingSchema:z.string().describe("Current project schema as JSON string"),feedback:z.string().describe("User feedback describing desired changes")}),handler:async({existingSchema:e,feedback:o})=>{let r=Se(e,o),n=[{role:"system",content:"You are a MongoDB schema expert. Return only valid JSON."},{role:"user",content:r}],i=await t.invoke(n,{temperature:.3,maxOutputTokens:8192}),s=Ct(i.text),a=JSON.parse(s);return A.parse(a)}})}function we(t){return {validate_schema:_,design_database:Z(t),design_database_pro:X(t),redesign_database:ee(t)}}var It=`You are an expert at analyzing software requirements to extract database design signals.
270
+ IMPORTANT: Return ONLY the JSON object, no markdown code blocks, no explanations.`}var Te=u({name:"validate_schema",description:"Validates a MongoDB project schema JSON string against the expected schema. Returns valid: true or valid: false with errors array.",input:z.object({schema:z.string().describe("JSON string of the database project schema to validate")}),handler:async({schema:t})=>{try{let e=JSON.parse(t);return oe.parse(e),{valid:!0}}catch(e){return e instanceof z.ZodError?{valid:false,errors:e.issues.map(r=>`${r.path.join(".")}: ${r.message}`)}:e instanceof SyntaxError?{valid:false,errors:[`Invalid JSON: ${e.message}`]}:{valid:false,errors:[String(e)]}}}});function st(t){return u({name:"design_database",description:"Generate a MongoDB database schema from plain text requirements. Use for ad-hoc or legacy requirements. Returns the full project schema as JSON.",input:z.object({requirement:z.string().describe("Plain text description of the database requirements")}),handler:async({requirement:e})=>{let r=kr(e),o=[{role:"system",content:"You are a MongoDB schema expert. Return only valid JSON."},{role:"user",content:r}],n=await t.invoke(o,{temperature:.3,maxOutputTokens:8192});return M(n.text,oe)}})}var Si=z.object({projectName:z.string(),projectGoal:z.string(),projectDescription:z.string().optional(),actors:z.array(z.object({id:z.string(),name:z.string(),description:z.string(),goals:z.array(z.string())})),flows:z.array(z.object({id:z.string(),actorId:z.string(),name:z.string(),description:z.string(),trigger:z.string(),outcome:z.string()})),stories:z.array(z.object({id:z.string(),flowId:z.string(),actor:z.string(),action:z.string(),benefit:z.string(),preconditions:z.array(z.string()),postconditions:z.array(z.string()),dataInvolved:z.array(z.string())})),technicalRequirements:z.object({authentication: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(z.enum(["none","email","oauth","phone","email_and_phone"])),authorization:z.coerce.boolean().default(false),roles:z.array(z.string()).optional(),integrations:z.array(z.string()).optional(),realtime:z.boolean().optional(),fileUpload:z.boolean().optional(),search:z.boolean().optional()}).optional()});function at(t){return u({name:"design_database_pro",description:"Generate a MongoDB schema from structured requirements (project name, goal, actors, flows, user stories with dataInvolved, technical requirements). Use for pro-level 5-phase analysis. Returns dbDesign and metadata (entitiesDetected, rolesExtracted).",input:Si,handler:async e=>{let r=qr(e),o=[{role:"system",content:"You are a MongoDB schema expert. Return only valid JSON."},{role:"user",content:r}],n=await t.invoke(o,{temperature:.2,maxOutputTokens:16384}),a=M(n.text,oe),s={entitiesDetected:_r(e.stories),rolesExtracted:jr(e.actors)};return {dbDesign:a,metadata:s}}})}function it(t){return u({name:"redesign_database",description:"Update an existing MongoDB project schema based on user feedback. Provide the current schema JSON string and the feedback. Returns the updated schema as JSON.",input:z.object({existingSchema:z.string().describe("Current project schema as JSON string"),feedback:z.string().describe("User feedback describing desired changes")}),handler:async({existingSchema:e,feedback:r})=>{let o=Ur(e,r),n=[{role:"system",content:"You are a MongoDB schema expert. Return only valid JSON."},{role:"user",content:o}],a=await t.invoke(n,{temperature:.3,maxOutputTokens:8192});return M(a.text,oe)}})}function Gr(t){return {validate_schema:Te,design_database:st(t),design_database_pro:at(t),redesign_database:it(t)}}var bi=`You are an expert at analyzing software requirements to extract database design signals.
269
271
 
270
272
  Focus on PHASES 1-3 of the analysis framework:
271
273
 
@@ -283,13 +285,13 @@ Focus on PHASES 1-3 of the analysis framework:
283
285
  - Map each actor type to a role name.
284
286
  - From user story actions, infer CRUD permissions per role per entity.
285
287
 
286
- Respond with a clear, structured analysis (you can use headings and bullet points). The user will use this to generate or refine a MongoDB schema.`,te=v({name:"entity-analyzer",description:"Analyzes raw requirements text to extract entities, relationships, and roles. Use when you need to understand what data and actors the system has before designing the schema. Returns structured analysis (no JSON).",systemPrompt:It,tools:{},maxIterations:2});var Et=`You are an expert MongoDB schema reviewer. Your job is to:
288
+ Respond with a clear, structured analysis (you can use headings and bullet points). The user will use this to generate or refine a MongoDB schema.`,lt=f({name:"entity-analyzer",description:"Analyzes raw requirements text to extract entities, relationships, and roles. Use when you need to understand what data and actors the system has before designing the schema. Returns structured analysis (no JSON).",systemPrompt:bi,tools:{},maxIterations:2});var xi=`You are an expert MongoDB schema reviewer. Your job is to:
287
289
 
288
290
  1. Validate the provided schema using the validate_schema tool.
289
291
  2. Compare the schema against the original requirements and identify gaps (missing fields, wrong relationships, missing permissions).
290
292
  3. Suggest concrete improvements or return a corrected schema description.
291
293
 
292
- When the user gives you a schema (as JSON string) and optionally the original requirements, first call validate_schema to check structure. Then analyze completeness and correctness. Respond with either refinement suggestions or a summary of issues.`;function oe(){return v({name:"schema-refiner",description:"Validates a MongoDB project schema and suggests refinements based on requirements. Use when you have a draft schema and want to check it or improve it. Has access to validate_schema tool.",systemPrompt:Et,tools:{validate_schema:_},maxIterations:5})}var Ot=`${P}
294
+ When the user gives you a schema (as JSON string) and optionally the original requirements, first call validate_schema to check structure. Then analyze completeness and correctness. Respond with either refinement suggestions or a summary of issues.`;function ct(){return f({name:"schema-refiner",description:"Validates a MongoDB project schema and suggests refinements based on requirements. Use when you have a draft schema and want to check it or improve it. Has access to validate_schema tool.",systemPrompt:xi,tools:{validate_schema:Te},maxIterations:5})}var Ti=`${ce}
293
295
 
294
296
  You are the database design orchestrator. When the user asks for a database design:
295
297
 
@@ -299,7 +301,16 @@ You are the database design orchestrator. When the user asks for a database desi
299
301
  4. **Validate**: You can use validate_schema to check any schema JSON before returning.
300
302
  5. **Redesign**: If the user asks for changes to an existing schema, use redesign_database with the existing schema string and their feedback.
301
303
 
302
- Respond with the final schema (as JSON) or a clear summary and the schema.`;async function Dt(t){let{input:e,model:o,maxIterations:r=15,onStep:n}=t,i=R(o??{provider:"openai",model:"gpt-4o-mini"}),s=we(i),a=oe(),p=U([te,a],{parentModel:i}),m={...s,...p};return w({model:i,tools:m,systemPrompt:Ot,input:e,maxIterations:r,onStep:n})}var Re=z.object({brandName:z.string().describe("The brand's display name"),primaryColor:z.string().describe("The brand's primary color code (e.g., #FFFFFF)"),secondaryColor:z.string().describe("The brand's secondary color code (e.g., #000000)"),logo:z.url().describe("URL pointing to the brand's logo")});var ve=z.object({name:z.string().describe("Application name"),description:z.string().describe("Brief description of the application"),author:z.string().describe("Author or owner of the application").default("sijeeshmiziha (HubSpire)"),branding:Re.describe("Branding information for the application"),apiEndpoint:z.url().describe("URL endpoint for the app's API calls")});var Ze=z.object({minLength:z.number().optional().describe("Minimum length requirement"),zodString:z.string().describe("Raw Zod string validation (e.g. regex)")}),Xe=z.object({hookName:z.string().optional().describe("Name of the hook for dynamic field options"),queryString:z.string().optional().describe("Optional query string for fetching field options"),labelKey:z.string().optional().describe("Key used as label when displaying options"),valueKey:z.string().optional().describe("Key used as value for a field when selecting options"),values:z.array(z.string()).optional().describe("Static list of possible field values")}),re=z.object({name:z.string().describe("The field's key or identifier"),type: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:z.boolean().optional().describe("Whether this field must be filled"),validation:Ze.optional().describe("Optional field validation requirements"),defaultValue:z.union([z.string(),z.number(),z.boolean()]).optional().describe("Default value can be string, number, or boolean"),options:Xe.optional().describe("Additional dynamic or static options for this field")}),Ae=z.object({field:z.string().describe("Key or name of the data field in the table"),label:z.string().describe("User-friendly label to show on the table header")});var Me=z.object({type:z.string().describe("Indicates the response type (e.g., 'object')"),properties:z.record(z.string(),z.object({type: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"),et=z.object({type:z.enum(["list","create","update","delete","getById"]).describe("Type of API call for CRUD operations"),graphqlHook:z.string().describe("Name of the GraphQL hook (e.g. useGetAllUserQuery, useCreateUserMutation)"),queryString:z.string().describe("Actual GraphQL query string"),responseType:Me.describe("Optional schema describing shape of the API response")}),tt=z.object({type:z.enum(["login","currentUser","forgotPassword","resetPassword"]).describe("Type of API call"),graphqlHook:z.string().describe("Name of the GraphQL hook (e.g. useLoginMutation)"),queryString:z.string().describe("Actual GraphQL query string"),responseType:Me.describe("Optional schema describing shape of the API response")}),Pe=z.object({title:z.string().describe("Title displayed on the drawer"),graphqlHook:z.string().describe("Name of the GraphQL hook (e.g. useCreateUserMutation, useDeleteOneUserMutation)"),fields:z.array(re).describe("List of fields displayed within the drawer")}),ot=z.object({name:z.enum(["LoginPage","ForgotPasswordPage","ResetPasswordPage"]).describe("Internal name of the auth page"),type:z.enum(["EmailPassword","ForgotPassword","ResetPassword"]).describe("Type of authentication page"),route:z.string().describe("URL route for this page (e.g., '/login')"),isPrivate:z.boolean().describe("Whether this page requires an authenticated session"),api:z.array(tt).describe("List of API calls involved in this page"),fields:z.array(re).optional().describe("Optional form fields needed on this auth page")}),rt=z.object({type:z.literal("Listing").describe("Indicates that this page is a listing-type page"),name:z.string().describe("Internal name of the listing page"),route:z.string().describe("URL route for this listing page"),isPrivate:z.boolean().describe("Whether this page is private (requires auth)"),api:z.array(et).describe("List of API calls that power this listing page"),columns:z.array(Ae).describe("Table columns displayed on the listing page"),actions:z.array(z.string()).describe("List of possible actions on each row (e.g., create, edit, delete, view)"),drawerCreate:Pe.describe("Drawer configuration for creating new records"),drawerUpdate:Pe.describe("Drawer configuration for editing existing records")}),Ce=z.discriminatedUnion("type",[ot,rt]);var nt=z.object({name:z.string().describe("Name of the module"),pages:z.array(Ce).describe("Pages included within this module")}),$=z.object({app:ve.describe("Overall application configuration"),modules:z.array(nt).describe("List of modules that make up the application. Ensure all modules use every available CRUD GraphQL query and mutation from the schema.")});var Nt=z.object({email:z.email().describe("User's email address, must be valid format"),password:z.string().min(8).describe("User's password, minimum length of 8")}),at=z.object({_id:z.string().describe("Unique identifier of the specialization, type: string"),title:z.string().describe("Display title for the specialization, type: string")}),Ut=z.object({_id:z.string().describe("Unique ID of the user, type: string"),firstName:z.string().min(2).max(30).describe("First name, 2-30 characters, type: string"),lastName:z.string().min(2).max(30).describe("Last name, 2-30 characters, type: string"),email:z.email().describe("Email address in valid format, type: string"),phoneNumber:z.string().min(10).describe("User's phone number, at least 10 digits, type: string"),profileImage:z.string().optional().describe("Optional URL to user's profile image, type: string, optional"),role:z.enum(["ADMIN","TRAINER","CLIENT"]).describe("User's role in the system (ADMIN, TRAINER, CLIENT)"),rate:z.number().min(1).optional().describe("User's rate (e.g., hourly, etc.), type: number, optional"),specializations:z.array(at).optional().describe("Array of specialization objects, optional"),languages:z.array(z.string()).optional().describe("Array of languages the user speaks, type: string[], optional"),about:z.string().min(20).max(500).optional().describe("Brief bio or description (20-500 chars), type: string, optional"),gender:z.string().optional().describe("User's gender, type: string, optional"),timezone:z.string().optional().describe("User's timezone, type: string, optional"),averageRating:z.number().optional().describe("Average rating for this user, type: number, optional")}),kt=z.object({firstName:z.string().min(2).max(30).describe("First name, 2-30 characters, type: string"),lastName:z.string().min(2).max(30).describe("Last name, 2-30 characters, type: string"),email:z.email().describe("Valid email for the new user, type: string"),phoneNumber:z.string().min(10).describe("Phone number (at least 10 digits), type: string"),password:z.string().min(8).describe("Password with min length 8, type: string"),role:z.enum(["ADMIN","TRAINER","CLIENT"]).describe("Role of the new user (ADMIN, TRAINER, CLIENT)"),rate:z.number().min(1).optional().describe("Rate for the new user, type: number, optional"),specializationIds:z.array(z.string()).min(1).optional().describe("Array of specialization IDs, optional"),languages:z.array(z.string()).min(1).optional().describe("List of languages user speaks, optional"),about:z.string().min(20).max(500).optional().describe("User's about/bio field, 20-500 chars, optional")}),_t=z.object({_id:z.string().describe("ID of the user to be updated, type: string"),firstName:z.string().min(2).max(30).optional().describe("Updated first name, type: string, optional"),lastName:z.string().min(2).max(30).optional().describe("Updated last name, type: string, optional"),email:z.email().optional().describe("Updated email, type: string, optional"),phoneNumber:z.string().min(10).optional().describe("Updated phone number, at least 10 digits, optional"),rate:z.number().min(1).optional().describe("Updated rate, type: number, optional"),specializationIds:z.array(z.string()).min(1).optional().describe("Updated array of specialization IDs, optional"),languages:z.array(z.string()).min(1).optional().describe("Updated list of languages, optional"),about:z.string().min(20).max(500).optional().describe("Updated about/bio (20-500 chars), optional")}),jt=z.object({email:z.email().describe("Email to initiate the password reset process, type: string")}),Lt=z.object({type:z.enum(["EMAIL","SMS"]).describe("How the reset code was sent (EMAIL or SMS)"),resetTicket:z.string().describe("Token/ticket to validate the reset request, type: string"),newPassword:z.string().min(8).describe("The new password, min length 8, type: string")});var B=`You are an expert GraphQL-to-frontend configuration converter. Transform the provided GraphQL schema into a structured JSON configuration for rapid app development.
304
+ Respond with the final schema (as JSON) or a clear summary and the schema.`;async function Pi(t){let{input:e,model:r,maxIterations:o=15,onStep:n,logger:a}=t,s=E(r??{provider:"openai",model:"gpt-4o-mini"}),i=Gr(s),l=ct(),p=q([lt,l],{parentModel:s}),c={...i,...p};return D({model:s,tools:c,systemPrompt:Ti,input:e,maxIterations:o,onStep:n,logger:a})}var Jr=z.object({brandName:z.string().describe("The brand's display name"),primaryColor:z.string().describe("The brand's primary color code (e.g., #FFFFFF)"),secondaryColor:z.string().describe("The brand's secondary color code (e.g., #000000)"),logo:z.url().describe("URL pointing to the brand's logo")});var Br=z.object({name:z.string().describe("Application name"),description:z.string().describe("Brief description of the application"),author:z.string().describe("Author or owner of the application").default("sijeeshmiziha (HubSpire)"),branding:Jr.describe("Branding information for the application"),apiEndpoint:z.url().describe("URL endpoint for the app's API calls")});var ts=z.object({minLength:z.number().optional().describe("Minimum length requirement"),zodString:z.string().describe("Raw Zod string validation (e.g. regex)")}),rs=z.object({hookName:z.string().optional().describe("Name of the hook for dynamic field options"),queryString:z.string().optional().describe("Optional query string for fetching field options"),labelKey:z.string().optional().describe("Key used as label when displaying options"),valueKey:z.string().optional().describe("Key used as value for a field when selecting options"),values:z.array(z.string()).optional().describe("Static list of possible field values")}),pt=z.object({name:z.string().describe("The field's key or identifier"),type: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:z.boolean().optional().describe("Whether this field must be filled"),validation:ts.optional().describe("Optional field validation requirements"),defaultValue:z.union([z.string(),z.number(),z.boolean()]).optional().describe("Default value can be string, number, or boolean"),options:rs.optional().describe("Additional dynamic or static options for this field")}),zr=z.object({field:z.string().describe("Key or name of the data field in the table"),label:z.string().describe("User-friendly label to show on the table header")});var $r=z.object({type:z.string().describe("Indicates the response type (e.g., 'object')"),properties:z.record(z.string(),z.object({type: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"),os=z.object({type:z.enum(["list","create","update","delete","getById"]).describe("Type of API call for CRUD operations"),graphqlHook:z.string().describe("Name of the GraphQL hook (e.g. useGetAllUserQuery, useCreateUserMutation)"),queryString:z.string().describe("Actual GraphQL query string"),responseType:$r.describe("Optional schema describing shape of the API response")}),ns=z.object({type:z.enum(["login","currentUser","forgotPassword","resetPassword"]).describe("Type of API call"),graphqlHook:z.string().describe("Name of the GraphQL hook (e.g. useLoginMutation)"),queryString:z.string().describe("Actual GraphQL query string"),responseType:$r.describe("Optional schema describing shape of the API response")}),Yr=z.object({title:z.string().describe("Title displayed on the drawer"),graphqlHook:z.string().describe("Name of the GraphQL hook (e.g. useCreateUserMutation, useDeleteOneUserMutation)"),fields:z.array(pt).describe("List of fields displayed within the drawer")}),ss=z.object({name:z.enum(["LoginPage","ForgotPasswordPage","ResetPasswordPage"]).describe("Internal name of the auth page"),type:z.enum(["EmailPassword","ForgotPassword","ResetPassword"]).describe("Type of authentication page"),route:z.string().describe("URL route for this page (e.g., '/login')"),isPrivate:z.boolean().describe("Whether this page requires an authenticated session"),api:z.array(ns).describe("List of API calls involved in this page"),fields:z.array(pt).optional().describe("Optional form fields needed on this auth page")}),as=z.object({type:z.literal("Listing").describe("Indicates that this page is a listing-type page"),name:z.string().describe("Internal name of the listing page"),route:z.string().describe("URL route for this listing page"),isPrivate:z.boolean().describe("Whether this page is private (requires auth)"),api:z.array(os).describe("List of API calls that power this listing page"),columns:z.array(zr).describe("Table columns displayed on the listing page"),actions:z.array(z.string()).describe("List of possible actions on each row (e.g., create, edit, delete, view)"),drawerCreate:Yr.describe("Drawer configuration for creating new records"),drawerUpdate:Yr.describe("Drawer configuration for editing existing records")}),Hr=z.discriminatedUnion("type",[ss,as]);var is=z.object({name:z.string().describe("Name of the module"),pages:z.array(Hr).describe("Pages included within this module")}),Le=z.object({app:Br.describe("Overall application configuration"),modules:z.array(is).describe("List of modules that make up the application. Ensure all modules use every available CRUD GraphQL query and mutation from the schema.")});var Ri=z.object({email:z.email().describe("User's email address, must be valid format"),password:z.string().min(8).describe("User's password, minimum length of 8")}),ls=z.object({_id:z.string().describe("Unique identifier of the specialization, type: string"),title:z.string().describe("Display title for the specialization, type: string")}),wi=z.object({_id:z.string().describe("Unique ID of the user, type: string"),firstName:z.string().min(2).max(30).describe("First name, 2-30 characters, type: string"),lastName:z.string().min(2).max(30).describe("Last name, 2-30 characters, type: string"),email:z.email().describe("Email address in valid format, type: string"),phoneNumber:z.string().min(10).describe("User's phone number, at least 10 digits, type: string"),profileImage:z.string().optional().describe("Optional URL to user's profile image, type: string, optional"),role:z.enum(["ADMIN","TRAINER","CLIENT"]).describe("User's role in the system (ADMIN, TRAINER, CLIENT)"),rate:z.number().min(1).optional().describe("User's rate (e.g., hourly, etc.), type: number, optional"),specializations:z.array(ls).optional().describe("Array of specialization objects, optional"),languages:z.array(z.string()).optional().describe("Array of languages the user speaks, type: string[], optional"),about:z.string().min(20).max(500).optional().describe("Brief bio or description (20-500 chars), type: string, optional"),gender:z.string().optional().describe("User's gender, type: string, optional"),timezone:z.string().optional().describe("User's timezone, type: string, optional"),averageRating:z.number().optional().describe("Average rating for this user, type: number, optional")}),vi=z.object({firstName:z.string().min(2).max(30).describe("First name, 2-30 characters, type: string"),lastName:z.string().min(2).max(30).describe("Last name, 2-30 characters, type: string"),email:z.email().describe("Valid email for the new user, type: string"),phoneNumber:z.string().min(10).describe("Phone number (at least 10 digits), type: string"),password:z.string().min(8).describe("Password with min length 8, type: string"),role:z.enum(["ADMIN","TRAINER","CLIENT"]).describe("Role of the new user (ADMIN, TRAINER, CLIENT)"),rate:z.number().min(1).optional().describe("Rate for the new user, type: number, optional"),specializationIds:z.array(z.string()).min(1).optional().describe("Array of specialization IDs, optional"),languages:z.array(z.string()).min(1).optional().describe("List of languages user speaks, optional"),about:z.string().min(20).max(500).optional().describe("User's about/bio field, 20-500 chars, optional")}),Ei=z.object({_id:z.string().describe("ID of the user to be updated, type: string"),firstName:z.string().min(2).max(30).optional().describe("Updated first name, type: string, optional"),lastName:z.string().min(2).max(30).optional().describe("Updated last name, type: string, optional"),email:z.email().optional().describe("Updated email, type: string, optional"),phoneNumber:z.string().min(10).optional().describe("Updated phone number, at least 10 digits, optional"),rate:z.number().min(1).optional().describe("Updated rate, type: number, optional"),specializationIds:z.array(z.string()).min(1).optional().describe("Updated array of specialization IDs, optional"),languages:z.array(z.string()).min(1).optional().describe("Updated list of languages, optional"),about:z.string().min(20).max(500).optional().describe("Updated about/bio (20-500 chars), optional")}),Ai=z.object({email:z.email().describe("Email to initiate the password reset process, type: string")}),Oi=z.object({type:z.enum(["EMAIL","SMS"]).describe("How the reset code was sent (EMAIL or SMS)"),resetTicket:z.string().describe("Token/ticket to validate the reset request, type: string"),newPassword:z.string().min(8).describe("The new password, min length 8, type: string")});var Fe=`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.
305
+
306
+ ## Target Tech Stack
307
+ The generated configuration will be consumed by a Vite + React 19 + TypeScript template with:
308
+ - **UI Components**: ShadCN UI (Radix-based) from src/components/ui/
309
+ - **Styling**: Tailwind CSS v4 with OKLCH color space
310
+ - **Routing**: React Router v7 with private route support
311
+ - **Forms**: React Hook Form + Zod validation (zodResolver)
312
+ - **GraphQL Client**: Apollo Client with typed hooks from CodeGen
313
+ - **Path Aliases**: @/{appName}/* maps to ./src/*
303
314
 
304
315
  **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).
305
316
 
@@ -308,8 +319,9 @@ Strict guidelines:
308
319
  - Map GraphQL types to frontend modules and pages.
309
320
  - EmailAddress \u2192 "type": "email" with validation; DateTime \u2192 "type": "date"; enums \u2192 select with options.values.
310
321
  - Relationships \u2192 multiSelect with query-based options where appropriate.
311
- - Add isPrivate: true for authenticated operations.
312
- - Maintain camelCase. Ensure valid JSON syntax.`;var ne=`
322
+ - Add isPrivate: true for authenticated operations (route guarded by React Router).
323
+ - Form fields should map to React Hook Form + Zod validation schemas.
324
+ - Maintain camelCase. Ensure valid JSON syntax.`;var dt=`
313
325
  Act as an expert GraphQL-to-frontend configuration converter. Transform the provided schema into a structured JSON configuration for rapid app development.
314
326
 
315
327
  **Conversion Process**
@@ -341,7 +353,7 @@ Act as an expert GraphQL-to-frontend configuration converter. Transform the prov
341
353
  6. Output:
342
354
  - Generate complete CRUD pages with table column mappings, validated Create/Update forms, API hooks
343
355
  - Include Zod validation strings, maintain camelCase, valid JSON only
344
- `.trim();function Ie(){return ne}var it=`
356
+ `.trim();function Qr(){return dt}var cs=`
345
357
  type Query {
346
358
  getCurrentUser: User
347
359
  getAllUser(limit: Int, offset: Int): [User]!
@@ -360,7 +372,7 @@ type User {
360
372
  enum Role { ADMIN TRAINER CLIENT }
361
373
  input LoginInput { email: String! password: String! }
362
374
  input CreateUserInput { firstName: String! lastName: String! email: String! role: Role! }
363
- `.trim(),st=`{
375
+ `.trim(),ps=`{
364
376
  "app": {
365
377
  "name": "my-app",
366
378
  "description": "App description",
@@ -408,19 +420,19 @@ input CreateUserInput { firstName: String! lastName: String! email: String! role
408
420
  ]
409
421
  }
410
422
  ]
411
- }`;function Ee(){return `
423
+ }`;function Vr(){return `
412
424
  **Reference Conversion Example**
413
425
 
414
426
  EXAMPLE GRAPHQL INPUT:
415
427
  \`\`\`graphql
416
- ${it}
428
+ ${cs}
417
429
  \`\`\`
418
430
 
419
431
  EXPECTED JSON OUTPUT:
420
432
  \`\`\`json
421
- ${st}
433
+ ${ps}
422
434
  \`\`\`
423
- `.trim()}function qt(t,e){return `
435
+ `.trim()}function Mi(t,e){return `
424
436
  Review the user feedback carefully to understand the required updates.
425
437
 
426
438
  The user feedback for updating the generated Frontend Config JSON is provided below:
@@ -436,15 +448,15 @@ ${e}
436
448
  \`\`\`
437
449
 
438
450
  Update the Frontend Config JSON to incorporate the requested changes. Return ONLY valid JSON, no markdown code blocks.
439
- `.trim()}var j=h({name:"validate_frontend_config",description:"Validates a frontend configuration JSON string against the ApplicationSchema. Returns valid: true or valid: false with errors array.",input:z.object({config:z.string().describe("JSON string of the frontend application config to validate")}),handler:async({config:t})=>{try{let e=JSON.parse(t);return $.parse(e),{valid:!0}}catch(e){return e instanceof z.ZodError?{valid:false,errors:e.issues.map(o=>`${o.path.join(".")}: ${o.message}`)}:e instanceof SyntaxError?{valid:false,errors:[`Invalid JSON: ${e.message}`]}:{valid:false,errors:[String(e)]}}}});function zt(t){let e=t.trim(),o=/```(?:json)?\s*([\s\S]*?)```/.exec(e);return o?.[1]?o[1].trim():e}function Ft(t,e){let o=Ie(),r=Ee(),n=e?`
451
+ `.trim()}var Pe=u({name:"validate_frontend_config",description:"Validates a frontend configuration JSON string against the ApplicationSchema. Returns valid: true or valid: false with errors array.",input:z.object({config:z.string().describe("JSON string of the frontend application config to validate")}),handler:async({config:t})=>{try{let e=JSON.parse(t);return Le.parse(e),{valid:!0}}catch(e){return e instanceof z.ZodError?{valid:false,errors:e.issues.map(r=>`${r.path.join(".")}: ${r.message}`)}:e instanceof SyntaxError?{valid:false,errors:[`Invalid JSON: ${e.message}`]}:{valid:false,errors:[String(e)]}}}});function Ci(t,e){let r=Qr(),o=Vr(),n=e?`
440
452
  **Project context:**
441
453
  - name: ${e.projectName??"project"}
442
454
  - description: ${e.projectDescription??""}
443
455
  - modules: ${e.modules??""}
444
456
  - apiEndpoint: ${e.apiEndpoint??"http://localhost:4000/graphql"}
445
- `:"";return `${o}
457
+ `:"";return `${r}
446
458
 
447
- ${r}
459
+ ${o}
448
460
  ${n}
449
461
 
450
462
  **Current Project GraphQL Schema:**
@@ -452,14 +464,14 @@ ${n}
452
464
  ${t}
453
465
  \`\`\`
454
466
 
455
- Generate the Frontend Config JSON. Use every available CRUD GraphQL query and mutation. Return ONLY valid JSON.`}function ae(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:z.object({graphqlSchema:z.string().describe("The GraphQL schema string to convert"),appInfo:z.object({projectName:z.string().optional(),projectDescription:z.string().optional(),modules:z.string().optional(),apiEndpoint:z.string().optional()}).optional().describe("Optional project/app context")}),handler:async({graphqlSchema:e,appInfo:o})=>{let r=Ft(e,o),n=[{role:"system",content:B},{role:"user",content:r}],i=await t.invoke(n,{temperature:.2,maxOutputTokens:16384}),s=zt(i.text),a=JSON.parse(s);return $.parse(a)}})}function ie(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:z.object({graphqlSchema:z.string().describe("The GraphQL schema string to analyze")}),handler:async({graphqlSchema:e})=>{let o=`${ne}
467
+ Generate the Frontend Config JSON. Use every available CRUD GraphQL query and mutation. Return ONLY valid JSON.`}function ut(t){return u({name:"generate_frontend",description:"Convert a GraphQL schema into a frontend configuration JSON (app, modules, pages, fields, API hooks). Optionally provide app info (project name, description, apiEndpoint). Returns the full application config as JSON.",input:z.object({graphqlSchema:z.string().describe("The GraphQL schema string to convert"),appInfo:z.object({projectName:z.string().optional(),projectDescription:z.string().optional(),modules:z.string().optional(),apiEndpoint:z.string().optional()}).optional().describe("Optional project/app context")}),handler:async({graphqlSchema:e,appInfo:r})=>{let o=Ci(e,r),n=[{role:"system",content:Fe},{role:"user",content:o}],a=await t.invoke(n,{temperature:.2,maxOutputTokens:16384});return M(a.text,Le)}})}function mt(t){return u({name:"generate_feature_breakdown",description:"Analyze a GraphQL schema and produce a feature/component breakdown: list of modules, CRUD operations, and suggested pages. Returns a structured summary (not the full frontend JSON).",input:z.object({graphqlSchema:z.string().describe("The GraphQL schema string to analyze")}),handler:async({graphqlSchema:e})=>{let r=`${dt}
456
468
 
457
469
  **Schema to analyze:**
458
470
  \`\`\`graphql
459
471
  ${e}
460
472
  \`\`\`
461
473
 
462
- 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 De(t){return {validate_frontend_config:j,generate_frontend:ae(t),generate_feature_breakdown:ie(t)}}var $t=`You are an expert at analyzing GraphQL schemas. Your job is to:
474
+ 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.`,o=[{role:"system",content:"You are a GraphQL schema analyst. Return a clear, structured text breakdown."},{role:"user",content:r}];return {summary:(await t.invoke(o,{temperature:.3,maxOutputTokens:4096})).text,modules:[],operations:[],suggestedPages:[]}}})}function Di(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 Xr=u({name:"scaffold_vite",description:"Scaffold a Vite + React project from a validated ApplicationSchema config. Compiles Handlebars templates from .ref/templates/vite/ and writes the project to the output directory.",input:z.object({config:z.string().describe("JSON string of the validated ApplicationSchema config"),outputDir:z.string().describe("Absolute path to the output directory")}),handler:async({config:t,outputDir:e})=>{let r=Se(t,"application schema config"),o=xe.resolve(process.cwd(),".ref/templates/vite"),n=Di(r);return le({templateDir:o,outputDir:e,context:n})}});function Zr(t){return {validate_frontend_config:Pe,generate_frontend:ut(t),generate_feature_breakdown:mt(t),scaffold_vite:Xr}}var Ni=`You are an expert at analyzing GraphQL schemas. Your job is to:
463
475
 
464
476
  1. **Types**: List all object types, enums, scalars, and input types.
465
477
  2. **Queries**: List every Query field with arguments and return type.
@@ -467,13 +479,13 @@ Respond with a structured breakdown only (no full JSON config): list modules, li
467
479
  4. **Relationships**: Identify types that reference other types (e.g. User has role: Role, or Order has customer: User).
468
480
  5. **Auth/directives**: Note any @auth, @directive usage that affects access control.
469
481
 
470
- Respond with a clear, structured analysis (headings and bullet points). The user will use this to generate a frontend configuration.`,se=v({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:$t,tools:{},maxIterations:2});var Bt=`You are a frontend configuration validator. Your job is to:
482
+ Respond with a clear, structured analysis (headings and bullet points). The user will use this to generate a frontend configuration.`,gt=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:Ni,tools:{},maxIterations:2});var Ii=`You are a frontend configuration validator. Your job is to:
471
483
 
472
484
  1. Validate the provided frontend config JSON using the validate_frontend_config tool.
473
485
  2. Compare the config against the GraphQL schema (if provided) and check that all CRUD operations are covered.
474
486
  3. Report any missing modules, pages, or API hooks.
475
487
 
476
- 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 le(){return v({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:Bt,tools:{validate_frontend_config:j},maxIterations:5})}var Gt=`${B}
488
+ 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 ft(){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:Ii,tools:{validate_frontend_config:Pe},maxIterations:5})}var ki=`${Fe}
477
489
 
478
490
  You are the React frontend builder orchestrator. When the user provides a GraphQL schema and asks for a frontend configuration:
479
491
 
@@ -483,5 +495,1383 @@ You are the React frontend builder orchestrator. When the user provides a GraphQ
483
495
  4. **Validate directly**: You can use validate_frontend_config to check any config JSON.
484
496
  5. **Feature breakdown**: Use generate_feature_breakdown to get a module/operation breakdown before generating.
485
497
 
486
- 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 Jt(t){let{input:e,model:o,maxIterations:r=15,onStep:n}=t,i=R(o??{provider:"openai",model:"gpt-4o-mini"}),s=De(i),a=le(),p=U([se,a],{parentModel:i}),m={...s,...p};return w({model:i,tools:m,systemPrompt:Gt,input:e,maxIterations:r,onStep:n})}export{Y as AgentError,Me as ApiResponseTypeSchema,ve as AppConfigSchema,$ as ApplicationSchema,tt as AuthPageApiSchema,ot as AuthPageSchema,K as BaseMcpClient,Re as BrandingSchema,Ae as ColumnSchema,kt as CreateUserInputSchema,P as DB_DESIGN_SYSTEM_PROMPT,Pe as DrawerSchema,it as EXAMPLE_GRAPHQL_SCHEMA,st as EXAMPLE_JSON_OUTPUT,Xe as FieldOptionsSchema,jt as ForgotPasswordSchema,re as FormFieldSchema,M as LibraryError,et as ListingPageApiSchema,rt as ListingPageSchema,Nt as LoginInputSchema,C as ModelError,nt as ModuleSchema,Ce as PageSchema,ne as REACT_BUILDER_INSTRUCTION,B as REACT_BUILDER_SYSTEM_PROMPT,Lt as ResetPasswordSchema,at as SpecializationSchema,D as SubagentError,x as ToolError,_t as UpdateUserInputSchema,Ut as UserSchema,Ne as ValidationError,Ze as ValidationSchema,Ee as buildExampleShotPrompt,qt as buildFeedbackPrompt,Ie as buildInstructionPrompt,We as buildPromptVariables,V as createAnthropicModel,le as createConfigValidatorSubagent,fe as createDbDesignPrompt,we as createDbDesignerTools,X as createDesignDatabaseProTool,Z as createDesignDatabaseTool,ie as createGenerateFeatureBreakdownTool,ae as createGenerateFrontendTool,W as createGoogleModel,Ht as createLogger,R as createModel,Q as createOpenAIModel,be as createProDbDesignPrompt,De as createReactBuilderTools,ee as createRedesignDatabaseTool,Se as createRedesignPrompt,oe as createSchemaRefinerSubagent,de as createSubagentTool,U as createSubagentToolSet,I as createToolSet,v as defineSubagent,h as defineTool,te as entityAnalyzerSubagent,ce as executeTool,H as executeToolByName,he as extractDataEntities,ye as extractRoles,ue as fieldSchema,Ve as formatTechnicalRequirements,He as formatUserFlows,Qe as formatUserStories,Ye as formatUserTypes,je as getTool,_e as getTools,se as graphqlAnalyzerSubagent,me as helloWorldTool,ge as moduleSchema,A as projectSchema,w as runAgent,Dt as runDbDesignerAgent,vt as runHelloWorldAgent,Jt as runReactBuilderAgent,pe as runSubagent,ke as sumTokenUsage,j as validateFrontendConfigTool,_ as validateSchemaTool};//# sourceMappingURL=index.js.map
498
+ 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 _i(t){let{input:e,model:r,maxIterations:o=15,onStep:n,logger:a}=t,s=E(r??{provider:"openai",model:"gpt-4o-mini"}),i=Zr(s),l=ft(),p=q([gt,l],{parentModel:s}),c={...i,...p};return D({model:s,tools:c,systemPrompt:ki,input:e,maxIterations:o,onStep:n,logger:a})}var Re=z.object({id:z.string(),name:z.string(),description:z.string(),goals:z.array(z.string())}),ht=z.object({actors:z.array(Re),message:z.string()});var we=z.object({id:z.string(),actorId:z.string(),name:z.string(),description:z.string(),trigger:z.string(),outcome:z.string()}),yt=z.object({flows:z.array(we),message:z.string()});var ve=z.object({id:z.string(),flowId:z.string(),actor:z.string(),action:z.string(),benefit:z.string(),preconditions:z.array(z.string()),postconditions:z.array(z.string()),dataInvolved:z.array(z.string())}),St=z.object({stories:z.array(ve),message:z.string()});var ms=z.object({id:z.string(),name:z.string(),operation:z.enum(["create","read","readAll","update","delete"]),description:z.string(),inputs:z.array(z.string()),outputs:z.array(z.string())}),Ee=z.object({id:z.string(),name:z.string(),description:z.string(),entity:z.string(),apis:z.array(ms)}),bt=z.object({modules:z.array(Ee),summary:z.object({totalModules:z.number(),totalApis:z.number()}),message:z.string()});var gs=z.object({name:z.string(),type:z.string(),required:z.boolean(),unique:z.boolean(),description:z.string(),default:z.string().optional()}),fs=z.object({name:z.string(),fields:z.array(z.string()),unique:z.boolean()}),hs=z.object({field:z.string(),references:z.string(),description:z.string()}),ys=z.object({name:z.string(),description:z.string(),fields:z.array(gs),indexes:z.array(fs),relations:z.array(hs)}),me=z.object({type:z.enum(["mongodb","postgresql"]),reasoning:z.string(),entities:z.array(ys)});var ji=z.union([z.enum(["GET","POST","PUT","PATCH","DELETE"]),z.string()]).transform(t=>typeof t=="string"?t.toUpperCase():t).pipe(z.enum(["GET","POST","PUT","PATCH","DELETE"])),eo=z.record(z.string(),z.unknown()).optional().default({}).transform(t=>Object.fromEntries(Object.entries(t??{}).map(([e,r])=>[e,typeof r=="string"?r:String(r)]))),Ss=z.object({id:z.string(),moduleId:z.string(),method:ji,path:z.string(),description:z.string(),auth:z.coerce.boolean(),roles:z.array(z.string()).default([]),requestBody:eo,responseBody:eo,queryParams:eo}),bs=z.object({baseUrl:z.string().default("/api/v1"),endpoints:z.array(Ss).default([])}),qi=z.object({name:z.string(),type:z.string(),description:z.string()}),Ui=z.union([z.enum(["type","input","enum"]),z.string()]).transform(t=>typeof t=="string"?t.toLowerCase():t).pipe(z.enum(["type","input","enum"])),xs=z.object({name:z.string(),kind:Ui,fields:z.array(qi)}),Li=z.object({name:z.string(),type:z.string(),required:z.coerce.boolean()}),to=z.object({name:z.string(),moduleId:z.string(),description:z.string(),auth:z.coerce.boolean(),roles:z.array(z.string()).default([]),args:z.array(Li),returnType:z.string()}),Ts=z.object({types:z.array(xs).default([]),queries:z.array(to).default([]),mutations:z.array(to).default([])}),Fi=z.union([z.enum(["rest","graphql"]),z.string()]).transform(t=>typeof t=="string"?t.toLowerCase():t).pipe(z.enum(["rest","graphql"])),ge=z.object({style:Fi,rest:bs.optional(),graphql:Ts.optional()});var Ae=z.object({name:z.string(),goal:z.string(),features:z.array(z.string()),domain:z.string(),database:z.enum(["mongodb","postgresql"]),backendRuntime:z.literal("nodejs"),apiStyle:z.enum(["rest","graphql"])}),xt=z.object({id:z.string(),question:z.string(),context:z.string(),suggestions:z.array(z.string()),multiSelect:z.boolean(),required:z.boolean()}),Ps=z.object({role:z.enum(["user","assistant"]),content:z.string()}),Gi=z.object({stage:z.enum(["discovery","requirements","design","complete"]),projectBrief:Ae.nullable(),actors:z.array(Re),flows:z.array(we),stories:z.array(ve),modules:z.array(Ee),database:me.nullable(),apiDesign:ge.nullable(),history:z.array(Ps),pendingQuestions:z.array(xt)});var Rs=z.object({totalActors:z.number(),totalFlows:z.number(),totalStories:z.number(),totalModules:z.number(),totalEntities:z.number(),totalEndpoints:z.number(),overview:z.string()}),ro=z.object({project:Ae,actors:z.array(Re),flows:z.array(we),stories:z.array(ve),modules:z.array(Ee),database:me,apiDesign:ge,summary:Rs});var fe=`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.
499
+
500
+ You work in stages: discovery (understand the project and tech preferences), requirements (actors, flows, stories, modules), design (database + APIs), and complete (final document).
501
+
502
+ 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.
503
+
504
+ Guidelines:
505
+ - For tech choices (API style: REST vs GraphQL; database: MongoDB vs PostgreSQL), offer predefined options and ask what the user is comfortable with.
506
+ - For everything else, ask open-ended, context-specific questions based on what the user described. Leave suggestions empty for those.
507
+ - Never repeat a question already answered in the conversation history.
508
+ - When the user says "continue", "yes", "looks good", or similar, treat it as confirmation and advance.
509
+ - Return valid JSON only when the prompt asks for JSON (no markdown code fences unless specified).
510
+ - Backend is Node.js only; database is MongoDB or PostgreSQL per user preference.`;var oo=`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.
511
+
512
+ Determine from the user's words:
513
+ - Project name and goal
514
+ - Key features (array of strings)
515
+ - Domain (e.g. e-commerce, healthcare, saas)
516
+ - API style: "rest" | "graphql" \u2014 infer from context or ask with predefined options
517
+ - Database: "mongodb" | "postgresql" \u2014 ask which they are comfortable with, with predefined options
518
+ - Backend is always "nodejs"
519
+
520
+ Question rules:
521
+ - Tech stack (API style, database): Always provide "suggestions" with predefined options (e.g. ["REST", "GraphQL"], ["MongoDB", "PostgreSQL"]). Frame as "which are you comfortable with?"
522
+ - 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).
523
+ - Never ask: scale, "how many users?", "what's the complexity?", or generic intake-form questions.
524
+ - Before asking, check conversation history \u2014 never repeat something already answered.
525
+ - 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.`,ws=`## Current user message:
526
+ {userMessage}
527
+
528
+ ## Prior conversation (if any):
529
+ {history}
530
+
531
+ 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.
532
+
533
+ Return ONLY valid JSON (no markdown, no explanation) in this shape:
534
+ {
535
+ "needsClarification": boolean,
536
+ "questions": [
537
+ {
538
+ "id": "q1",
539
+ "question": "Question text",
540
+ "context": "Why this helps",
541
+ "suggestions": [],
542
+ "multiSelect": false,
543
+ "required": true
544
+ }
545
+ ],
546
+ "conversationalMessage": "Brief friendly message to the user",
547
+ "projectBrief": {
548
+ "name": "string",
549
+ "goal": "string",
550
+ "features": ["string"],
551
+ "domain": "string",
552
+ "database": "mongodb" | "postgresql",
553
+ "backendRuntime": "nodejs",
554
+ "apiStyle": "rest" | "graphql"
555
+ }
556
+ }
557
+
558
+ For tech choices (API style, database), populate "suggestions" with the predefined options. For all other questions, use "suggestions": [].
559
+ If needsClarification is true, projectBrief can have empty/default values. If false, projectBrief must be complete.`;function no(t,e){return ws.replace("{userMessage}",t).replace("{history}",e||"(No prior messages)")}var Tt=`## Project:
560
+ - **Name**: {projectName}
561
+ - **Goal**: {projectGoal}
562
+ - **Features**: {projectFeatures}`,vs=`${Tt}
563
+
564
+ Identify ALL distinct user types (actors) who will use this system. 2-5 actors. Include unauthenticated and admin roles if applicable.
565
+
566
+ Return ONLY valid JSON:
567
+ {
568
+ "actors": [
569
+ { "id": "actor-1", "name": "Name", "description": "Who they are", "goals": ["goal1", "goal2"] }
570
+ ],
571
+ "message": "Brief explanation"
572
+ }`,Es=`${Tt}
573
+
574
+ ## Actors (JSON):
575
+ {actors}
576
+
577
+ For EACH actor, identify 2-5 key user journeys (flows). Each flow: id, actorId, name, description, trigger, outcome.
578
+
579
+ Return ONLY valid JSON:
580
+ {
581
+ "flows": [
582
+ { "id": "flow-1", "actorId": "actor-1", "name": "Flow Name", "description": "...", "trigger": "...", "outcome": "..." }
583
+ ],
584
+ "message": "Brief explanation"
585
+ }`,As=`${Tt}
586
+
587
+ ## Actors: {actors}
588
+
589
+ ## Flows (JSON):
590
+ {flows}
591
+
592
+ For EACH flow, generate 2-5 user stories. Each story MUST include dataInvolved (entity.field names) for DB design. Include preconditions, postconditions.
593
+
594
+ Return ONLY valid JSON:
595
+ {
596
+ "stories": [
597
+ { "id": "story-1", "flowId": "flow-1", "actor": "ActorName", "action": "...", "benefit": "...", "preconditions": [], "postconditions": [], "dataInvolved": ["User.email", "Order.total"] }
598
+ ],
599
+ "message": "Brief explanation"
600
+ }`,Os=`${Tt}
601
+
602
+ ## Actors: {actors}
603
+ ## Flows: {flows}
604
+ ## Stories (JSON):
605
+ {stories}
606
+
607
+ 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.
608
+
609
+ Return ONLY valid JSON:
610
+ {
611
+ "modules": [
612
+ { "id": "module-1", "name": "User", "description": "...", "entity": "User", "apis": [ { "id": "api-1-1", "name": "createUser", "operation": "create", "description": "...", "inputs": [], "outputs": [] } ] }
613
+ ],
614
+ "summary": { "totalModules": 0, "totalApis": 0 },
615
+ "message": "Brief explanation"
616
+ }`;function so(t,e,r){return vs.replace("{projectName}",t).replace("{projectGoal}",e).replace("{projectFeatures}",r)}function ao(t,e,r,o){return Es.replace("{projectName}",t).replace("{projectGoal}",e).replace("{projectFeatures}",r).replace("{actors}",o)}function io(t,e,r,o,n){return As.replace("{projectName}",t).replace("{projectGoal}",e).replace("{projectFeatures}",r).replace("{actors}",o).replace("{flows}",n)}function lo(t,e,r,o,n,a){return Os.replace("{projectName}",t).replace("{projectGoal}",e).replace("{projectFeatures}",r).replace("{actors}",o).replace("{flows}",n).replace("{stories}",a)}var Ji=`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.
617
+
618
+ ## Project brief (includes database: "mongodb" | "postgresql"):
619
+ {projectBrief}
620
+
621
+ ## Modules (entities and CRUD):
622
+ {modules}
623
+
624
+ ## User stories (data involved):
625
+ {stories}
626
+
627
+ 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.
628
+
629
+ Return ONLY valid JSON (no markdown) in this exact shape. Set "type" to the database from the project brief.
630
+ {
631
+ "type": "mongodb" | "postgresql",
632
+ "reasoning": "2-4 sentences on how the schema fits the project",
633
+ "entities": [
634
+ {
635
+ "name": "EntityName",
636
+ "description": "Brief description",
637
+ "fields": [
638
+ { "name": "fieldName", "type": "DB-native type", "required": true, "unique": false, "description": "..." }
639
+ ],
640
+ "indexes": [ { "name": "index_name", "fields": ["field1"], "unique": false } ],
641
+ "relations": [ { "field": "refField", "references": "OtherEntity", "description": "..." } ]
642
+ }
643
+ ]
644
+ }`,Bi=`You are an API architect for Node.js backends. Design the API according to apiStyle in the project brief.
645
+
646
+ ## Project brief (includes apiStyle: "rest" | "graphql"):
647
+ {projectBrief}
648
+
649
+ ## Modules:
650
+ {modules}
651
+
652
+ ## Actors:
653
+ {actors}
654
+
655
+ ## Stories:
656
+ {stories}
657
+
658
+ ## Database design (entities and fields):
659
+ {database}
660
+
661
+ Produce an API design:
662
+ - If apiStyle is "rest": include "rest" with baseUrl (e.g. "/api/v1") and endpoints array. Each endpoint: id, moduleId, method (exactly one of GET, POST, PUT, PATCH, DELETE), path, description, auth (boolean), roles (array of strings), requestBody/responseBody/queryParams (flat object of string keys to string values, or {}). responseBody must always be a flat object, never an array\u2014even for list endpoints use a single object describing the shape (e.g. for GET /users use "responseBody": { "items": "array of user objects", "total": "number" }).
663
+ - If apiStyle is "graphql": include "graphql" with types (kind: "type" | "input" | "enum", fields array), queries, mutations. Each operation: name, moduleId, description, auth (boolean), roles (array), args (name, type, required boolean), returnType.
664
+
665
+ Return ONLY valid JSON (no markdown, no code fences). Required shape:
666
+ {
667
+ "style": "rest" or "graphql",
668
+ "rest": { "baseUrl": "/api/v1", "endpoints": [ { "id": "ep-1", "moduleId": "module-1", "method": "GET", "path": "/users", "description": "List users", "auth": true, "roles": [], "requestBody": {}, "responseBody": { "items": "array of user objects", "total": "number" }, "queryParams": {} } ] },
669
+ "graphql": { "types": [], "queries": [], "mutations": [] }
670
+ }
671
+ - Use lowercase "rest" or "graphql" for style. Omit the branch not used (omit "graphql" when style is "rest", omit "rest" when style is "graphql").`,co="You output only valid JSON. No markdown, no explanation.",po="You output only valid JSON. No markdown, no explanation.";function uo(t,e,r){return Ji.replace("{projectBrief}",t).replace("{modules}",e).replace("{stories}",r)}function mo(t,e,r,o,n){return Bi.replace("{projectBrief}",t).replace("{modules}",e).replace("{actors}",r).replace("{stories}",o).replace("{database}",n)}var go="You are in the complete stage. You have the full context: project brief, actors, flows, stories, modules, database design, and API 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, totalEndpoints, and a short overview paragraph.",Ms=`## Project brief (JSON):
672
+ {projectBrief}
673
+
674
+ ## Actors (JSON):
675
+ {actors}
676
+
677
+ ## Flows (JSON):
678
+ {flows}
679
+
680
+ ## Stories (JSON):
681
+ {stories}
682
+
683
+ ## Modules (JSON):
684
+ {modules}
685
+
686
+ ## Database design (JSON):
687
+ {database}
688
+
689
+ ## API design (JSON):
690
+ {apiDesign}
691
+
692
+ Compile the above into one FinalRequirement JSON. Include a "summary" object with: totalActors, totalFlows, totalStories, totalModules, totalEntities (from database.entities.length), totalEndpoints (count of REST endpoints or GraphQL queries+mutations as appropriate), and "overview" (2-4 sentence paragraph summarizing the project and tech choices).
693
+
694
+ Return ONLY valid JSON in this shape (no markdown, no extra text):
695
+ {
696
+ "project": { ... },
697
+ "actors": [ ... ],
698
+ "flows": [ ... ],
699
+ "stories": [ ... ],
700
+ "modules": [ ... ],
701
+ "database": { ... },
702
+ "apiDesign": { ... },
703
+ "summary": {
704
+ "totalActors": 0,
705
+ "totalFlows": 0,
706
+ "totalStories": 0,
707
+ "totalModules": 0,
708
+ "totalEntities": 0,
709
+ "totalEndpoints": 0,
710
+ "overview": "string"
711
+ }
712
+ }`;function fo(t,e,r,o,n,a,s){return Ms.replace("{projectBrief}",t).replace("{actors}",e).replace("{flows}",r).replace("{stories}",o).replace("{modules}",n).replace("{database}",a).replace("{apiDesign}",s)}function ho(){return {stage:"discovery",projectBrief:null,actors:[],flows:[],stories:[],modules:[],database:null,apiDesign:null,history:[],pendingQuestions:[]}}function yo(t,e){let r=e.data;return {...t,...r.stage!==void 0&&{stage:r.stage},...r.projectBrief!==void 0&&{projectBrief:r.projectBrief},...r.actors!==void 0&&{actors:r.actors},...r.flows!==void 0&&{flows:r.flows},...r.stories!==void 0&&{stories:r.stories},...r.modules!==void 0&&{modules:r.modules},...r.database!==void 0&&{database:r.database},...r.apiDesign!==void 0&&{apiDesign:r.apiDesign},...r.pendingQuestions!==void 0&&{pendingQuestions:r.pendingQuestions}}}function Ge(t,e,r){let o={role:e,content:r};return {...t,history:[...t.history,o]}}function Pt(t){let e=["discovery","requirements","design","complete"],r=e.indexOf(t.stage),n=(r>=0&&r<e.length-1?e[r+1]:void 0)??t.stage;return {...t,stage:n}}function Cs(t){return t.map(e=>`${e.name}: ${e.entity} (${e.apis.length} APIs)`).join(`
713
+ `)}function Ds(t){return t.map(e=>`- ${e.actor}: ${e.action}`).join(`
714
+ `)}function H(t){let e=t.trim(),r=/```(?:json)?\s*([\s\S]*?)```/.exec(e);return r?.[1]?r[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 Rt(t,e,r,o){o?.debug("Discovery stage started",{historyLength:e.history.length});let n=e.history.map(U=>`${U.role}: ${U.content}`).slice(-10).join(`
715
+ `),a=no(t,n),i=[{role:"system",content:`${fe}
716
+
717
+ ${oo}`},{role:"user",content:a}],l=await r.invoke(i,{temperature:.4,maxOutputTokens:4096}),p=H(l.text),c=V(p);if(!c.success)return o?.warn("Discovery response was not valid JSON",{error:c.error}),{message:"I couldn't parse that. Could you describe your project in a few sentences?",advance:false,data:{}};let d=c.data,m=d.conversationalMessage??l.text?.slice(0,500)??"Thanks for the details.",S=d.needsClarification===true,g=[];if(Array.isArray(d.questions))for(let U of d.questions){let _=xt.safeParse(U);_.success&&g.push(_.data);}let G=null;if(d.projectBrief&&!S){let U=Ae.safeParse(d.projectBrief);U.success&&(G=U.data);}return o?.debug("Discovery stage complete",{advance:!S&&G!==null,hasProjectBrief:!!G,questionsCount:g.length}),{message:m,questions:g.length?g:void 0,advance:!S&&G!==null,data:{...G&&{projectBrief:G},pendingQuestions:g}}}async function Ns(t,e,r){if(t.invokeObject)return (await t.invokeObject(e,ht,{temperature:.4,maxOutputTokens:4096})).data;let o=await t.invoke(e,{temperature:.4,maxOutputTokens:4096}),n=V(H(o.text));if(!n.success)throw new Error(`Actors: ${n.error}`);let a=ht.safeParse(n.data);if(!a.success)throw new Error(`Actors schema: ${a.error.message}`);return a.data}async function Is(t,e,r,o){if(t.invokeObject)return (await t.invokeObject(e,yt,{temperature:.4,maxOutputTokens:8192})).data;let n=await t.invoke(e,{temperature:.4,maxOutputTokens:8192}),a=V(H(n.text));if(!a.success)throw new Error(`Flows: ${a.error}`);let s=yt.safeParse(a.data);if(!s.success)throw new Error(`Flows schema: ${s.error.message}`);return s.data}async function ks(t,e,r,o,n){if(t.invokeObject)return (await t.invokeObject(e,St,{temperature:.4,maxOutputTokens:16384})).data;let a=await t.invoke(e,{temperature:.4,maxOutputTokens:16384}),s=V(H(a.text));if(!s.success)throw new Error(`Stories: ${s.error}`);let i=St.safeParse(s.data);if(!i.success)throw new Error(`Stories schema: ${i.error.message}`);return i.data}async function _s(t,e,r,o,n,a){if(t.invokeObject)return (await t.invokeObject(e,bt,{temperature:.4,maxOutputTokens:16384})).data;let s=await t.invoke(e,{temperature:.4,maxOutputTokens:16384}),i=V(H(s.text));if(!i.success)throw new Error(`Modules: ${i.error}`);let l=bt.safeParse(i.data);if(!l.success)throw new Error(`Modules schema: ${l.error.message}`);return l.data}async function wt(t,e,r,o){o?.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:fe}];try{l.push({role:"user",content:so(a,s,i)});let c=(await Ns(r,l,o)).actors;o?.debug("Requirements: actors",{count:c.length}),l.push({role:"assistant",content:`[Extracted ${c.length} actors]`}),l.push({role:"user",content:ao(a,s,i,JSON.stringify(c))});let m=(await Is(r,l,c,o)).flows;o?.debug("Requirements: flows",{count:m.length}),l.push({role:"assistant",content:`[Generated ${m.length} flows]`}),l.push({role:"user",content:io(a,s,i,JSON.stringify(c),JSON.stringify(m))});let g=(await ks(r,l,c,m,o)).stories;o?.debug("Requirements: stories",{count:g.length}),l.push({role:"assistant",content:`[Generated ${g.length} stories]`}),l.push({role:"user",content:lo(a,s,i,JSON.stringify(c),JSON.stringify(m),JSON.stringify(g))});let U=(await _s(r,l,c,m,g,o)).modules;return o?.debug("Requirements stage complete",{actors:c.length,flows:m.length,stories:g.length,modules:U.length}),{message:`I've identified ${c.length} actors, ${m.length} flows, ${g.length} stories, and ${U.length} modules. Proceeding to technical design.`,advance:!0,data:{actors:c,flows:m,stories:g,modules:U,pendingQuestions:[]}}}catch(p){let c=p instanceof Error?p.message:String(p);return o?.warn("Requirements stage failed",{error:c}),{message:`Requirements step failed: ${c}. Please try again.`,advance:false,data:{}}}}async function vt(t,e,r,o){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:{}};o?.info("Design stage: database and API design",{modules:e.modules.length,stories:e.stories.length});let a=JSON.stringify(n),s=Cs(e.modules),i=Ds(e.stories),l=e.actors.map(he=>`${he.name}: ${he.description}`).join(`
718
+ `),p=uo(a,s,i),c=[{role:"system",content:co},{role:"user",content:p}],d=await r.invoke(c,{temperature:.3,maxOutputTokens:8192}),m=H(d.text),S=V(m);if(!S.success)return o?.warn("Database design response was not valid JSON",{error:S.error}),{message:"Failed to parse database design response. Please try again.",advance:false,data:{}};let g=me.safeParse(S.data);if(!g.success){let he=g.error;return o?.warn("Database design schema validation failed",{error:z.treeifyError(he)}),{message:"Failed to produce database design. Please try again.",advance:false,data:{}}}let G=g.data,U=mo(a,s,l,i,JSON.stringify(G)),_=[{role:"system",content:po},{role:"user",content:U}],se=await r.invoke(_,{temperature:.3,maxOutputTokens:16384}),ee=H(se.text),_e=V(ee);if(!_e.success)return o?.warn("API design response was not valid JSON",{error:_e.error}),{message:"Failed to parse API design response. Please try again.",advance:false,data:{database:G}};let vr=ge.safeParse(_e.data);if(!vr.success){let he=vr.error;return o?.warn("API design schema validation failed",{error:z.treeifyError(he)}),{message:"Failed to produce API design. Please try again.",advance:false,data:{database:G}}}let Nn=vr.data;return {message:`Database: ${G.type}. API: ${Nn.style}.`,advance:true,data:{database:G,apiDesign:Nn,pendingQuestions:[]}}}async function Et(t,e,r,o){o?.debug("Synthesis stage started");let n=e.projectBrief;if(!n||!e.database||!e.apiDesign)return {message:"Missing project brief, database design, or API design. Complete earlier stages first.",advance:false,data:{}};let a=fo(JSON.stringify(n),JSON.stringify(e.actors),JSON.stringify(e.flows),JSON.stringify(e.stories),JSON.stringify(e.modules),JSON.stringify(e.database),JSON.stringify(e.apiDesign)),i=[{role:"system",content:`${fe}
719
+
720
+ ${go}`},{role:"user",content:a}],l=await r.invoke(i,{temperature:.3,maxOutputTokens:16384}),p=H(l.text),c=V(p);if(!c.success)return o?.warn("Synthesis response was not valid JSON",{error:c.error}),{message:"Failed to compile final requirement document. Please try again.",advance:false,data:{}};let d=ro.safeParse(c.data);if(!d.success)return o?.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 m=d.data;return o?.info("Synthesis stage complete",{overview:m.summary?.overview}),{message:`Requirement document ready. ${m.summary.overview}`,advance:true,data:{finalRequirement:m}}}var At=class{stageName="discovery";async process(e,r){return Rt(r.userMessage,e,r.model,r.logger)}canAdvance(e){return e.advance}getNextStageName(){return "requirements"}};var Ot=class{stageName="requirements";async process(e,r){return wt(r.userMessage,e,r.model,r.logger)}canAdvance(e){return e.advance}getNextStageName(){return "design"}};var Mt=class{stageName="design";async process(e,r){return vt(r.userMessage,e,r.model,r.logger)}canAdvance(e){return e.advance}getNextStageName(){return "complete"}};var Ct=class{stageName="complete";async process(e,r){return Et(r.userMessage,e,r.model,r.logger)}canAdvance(e){return e.advance}getNextStageName(){return null}};var zi={discovery:new At,requirements:new Ot,design:new Mt,complete:new Ct};function So(t){return zi[t]}async function qs(t,e,r,o,n){n?.debug("Stage processor invoked",{stage:t});let s=await So(t).process(r,{userMessage:e,model:o,logger:n}),i=yo(r,s),l="finalRequirement"in s.data?s.data.finalRequirement:void 0;n?.debug("Stage result",{stage:t,advance:s.advance,hasFinalRequirement:!!l});let p={...i,pendingQuestions:s.questions??i.pendingQuestions};return {message:s.message,questions:s.questions??i.pendingQuestions,advance:s.advance,data:p,finalRequirement:l}}var bo=["discovery","requirements","design","complete"];async function Dt(t,e,r){let{logger:o}=r,n=r.model??{provider:"openai",model:"gpt-4o-mini"},a=E(n),s=e??ho();s=Ge(s,"user",t),o?.info("Chat turn",{stage:s.stage,messageLength:t.length});let i="",l=[],p=null,c=async S=>{let g=await qs(S,t,s,a,o);return i=g.message,l=g.questions,s=g.data,g.finalRequirement&&(p=g.finalRequirement),{advance:g.advance,finalReq:g.finalRequirement}},d=s.stage;o?.info("Stage",{stage:d});let m=await c(d);for(s={...s,pendingQuestions:l};m.advance&&!p;){let S=bo.indexOf(d),g=S>=0&&S<bo.length-1?bo[S+1]:void 0;if(g===void 0)break;o?.info("Stage transition",{from:d,to:g}),d=g,s=Pt(s),s={...s,stage:d},o?.info("Stage",{stage:d}),m=await c(d),s={...s,pendingQuestions:l};}return s=Ge(s,"assistant",i),o?.info("Chat turn done",{stage:d,hasFinalRequirement:!!p}),{message:i,context:s,questions:l,finalRequirement:p}}var Us=10;async function $i(t){let{input:e,model:r,onStep:o,logger:n}=t;n?.info("Starting requirement gatherer agent",{maxTurns:Us});let a=null,s=await Dt(e,a,{model:r,logger:n});a=s.context;let i=1;for(;!s.finalRequirement&&i<Us;)n?.debug("Requirement gatherer turn",{turn:i}),s=await Dt("continue",a,{model:r,logger:n}),a=s.context,i++;let l=s.finalRequirement?JSON.stringify(s.finalRequirement,null,2):s.message,p=a.history.map(c=>({role:c.role,content:c.content}));return n?.info("Requirement gatherer agent completed",{turns:i,hasFinalRequirement:!!s.finalRequirement}),{output:l,steps:[],totalUsage:void 0,messages:p}}var Hi="discovery",Nt=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}withApiDesign(e){return this.data.apiDesign=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??Hi,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,apiDesign:this.data.apiDesign??null,history:this.data.history??[],pendingQuestions:this.data.pendingQuestions??[]}}};function Qi(){return new Nt}var Vi={overview:null,techStack:null,featureDecisions:null,dataModels:null,pagesAndRoutes:null,authFlow:null,apiRoutes:null,implementation:null,executionPlan:null,edgeCases:null,testingChecklist:null};function Ls(){return {stage:"discovery",projectDescription:null,sections:{...Vi},history:[],pendingQuestions:[]}}function Fs(t,e){let{sections:r,projectDescription:o,pendingQuestions:n}=e,a={...t.sections};if(r)for(let s of Object.keys(r)){let i=r[s];i!=null&&(a[s]=i);}return {...t,...o!==void 0&&{projectDescription:o},sections:a,...n!==void 0&&{pendingQuestions:n}}}function It(t,e,r){let o={role:e,content:r};return {...t,history:[...t.history,o]}}function xo(t){let e=["discovery","requirements","design","complete"],r=e.indexOf(t.stage),n=(r>=0&&r<e.length-1?e[r+1]:void 0)??t.stage;return {...t,stage:n}}function kt(t){let e=t.trim().toLowerCase();return ["continue","yes","yeah","yep","looks good","good","ok","okay","next","proceed","sure"].some(o=>e===o||e.startsWith(o+" "))}var X=`You are a senior software architect creating a single, implementation-ready plan that a developer can follow without ambiguity.
721
+
722
+ CRITICAL RULES:
723
+ - 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.
724
+ - 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**).
725
+ - 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 To=`You are in the discovery stage. Your goal is to understand what the user wants to build.
726
+
727
+ Respond in natural language only. Do NOT output JSON.
728
+
729
+ - If you need more information: ask 1-3 short, specific questions. Focus on tech choices (REST vs GraphQL, MongoDB vs PostgreSQL) and any gaps that block design.
730
+ - When you have enough to proceed: output the project overview in this exact pro format so it matches the rest of the plan:
731
+ - **## Overview** \u2014 One paragraph (2\u20134 sentences) summarizing the project and its purpose.
732
+ - **## Core Features** \u2014 Numbered list: 1. **Feature Name** - Short description. (one line per feature)
733
+ - **## Tech Stack** \u2014 Bullet list with category labels: - **Frontend**: ... (versions if known), - **Database**: ..., - **Authentication**: ..., - **API**: ..., - **Backend**: ... Include versions and key libraries where relevant.
734
+
735
+ 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.`,Gs=`## Current user message:
736
+ {userMessage}
737
+
738
+ ## Prior conversation (if any):
739
+ {history}
740
+
741
+ 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 Po(t,e){return Gs.replace("{userMessage}",t).replace("{history}",e||"(No prior messages)")}var _t=`## Project description / context:
742
+ {context}`,Js=`${_t}
743
+
744
+ Using the project description above, write two markdown sections in this exact format:
745
+
746
+ 1. **## Overview** \u2014 One paragraph only (2\u20134 sentences) summarizing the project and its purpose.
747
+ 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.
748
+
749
+ Output only these two sections in markdown. Do NOT output JSON.`,Bs=`${_t}
750
+
751
+ ## Already written (Overview + Tech Stack):
752
+ {overviewAndTechStack}
753
+
754
+ Write the next two markdown sections in this exact format:
755
+
756
+ 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).
757
+ 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.
758
+
759
+ Output only markdown. Do NOT output JSON.`;function Ro(t){return Js.replace("{context}",t)}function wo(t,e){return Bs.replace("{context}",t).replace("{overviewAndTechStack}",e)}var zs=`## Project context (all sections so far):
760
+ {priorSections}`,Ys=`${zs}
761
+
762
+ ## API Routes (already written):
763
+ {apiRoutes}
764
+
765
+ Write the next markdown section in this exact format:
766
+
767
+ **## Implementation Details**
768
+ - **### File Structure** \u2014 Full directory tree in a **code block** (e.g. src/app/(auth)/login/page.tsx, src/app/api/auth/signup/route.ts, src/components/..., src/lib/, src/models/). Show the real layout a developer would create.
769
+ - **### Environment Variables** \u2014 List with comments (e.g. MONGODB_URI=... # connection string, JWT_SECRET=... # change in production).
770
+ - **### Dependencies to Install** \u2014 npm install line and short explanation per dependency (e.g. mongoose: MongoDB ODM; bcryptjs: password hashing; jsonwebtoken: JWT; cookie: cookie parsing).
771
+ - **### 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).
772
+ - 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).
773
+
774
+ Output only markdown. Do NOT output JSON.`;function vo(t,e){return Ys.replace("{priorSections}",t).replace("{apiRoutes}",e)}var Zi=`## Full plan so far (all sections):
775
+ {priorSections}`,Eo="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.",$s=`${Zi}
776
+
777
+ Write the following sections in this exact order. Output only markdown. Do NOT output JSON.
778
+
779
+ **Block 1 \u2014 Implementation Order, Current State, Desired End State**
780
+
781
+ 1. **## Implementation Order** \u2014 Phased: ### Phase 1: Foundation, ### Phase 2: Authentication, etc. Under each phase, numbered steps (e.g. "1. Install dependencies", "2. Create User model", "3. Implement POST /api/auth/signup", "4. Create login page"). Be concrete so a developer can follow step-by-step.
782
+
783
+ 2. **## Current State Analysis** \u2014 What the project starts with (e.g. vanilla Next.js, no DB, no auth). Then a short bullet list: "What needs to be built from scratch" (all auth, models, API routes, pages, etc.).
784
+
785
+ 3. **## Desired End State** \u2014 Short subsections or bullets: (1) For users: what they can do when the app is done; (2) Technical verification: what must work (DB connected, auth working, endpoints returning correct data, etc.); (3) Testing approach: manual flows, API checks, DB checks.
786
+
787
+ **Block 2 \u2014 Edge Cases, Security, Performance, Future Enhancements**
788
+
789
+ 4. **## Edge Cases and Considerations** \u2014 ### per area (e.g. ### Authentication, ### Workouts, ### Nutrition, ### Goals, ### Profile, ### General). Under each, bullets for edge cases and how to handle them (e.g. "Email already exists: return 400 with clear message"; "External API down: show error, allow manual entry").
790
+
791
+ 5. **## Security Considerations** \u2014 Numbered list: passwords (bcrypt, min length); JWT (HTTP-only cookie, secure flag, strong secret, expiry); API (verify JWT on protected routes, check resource ownership); env (never commit secrets, different values in production).
792
+
793
+ 6. **## Performance Considerations** \u2014 Numbered list: DB (index user id and date fields, lean queries, avoid N+1); API (debounce search, cache external API if applicable); frontend (RSC where possible, lazy load heavy components); optional future caching.
794
+
795
+ 7. **## Future Enhancements (Not in Current Scope)** \u2014 Short grouped list (e.g. Social, Analytics, Integrations, Mobile, Premium) so scope is clear. One line per group is enough.
796
+
797
+ **Block 3 \u2014 Manual Testing Checklist**
798
+
799
+ 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").
800
+
801
+ Output all eight sections in the order above. Do NOT output JSON.`;function Ao(t){return $s.replace("{priorSections}",t)}var Oo=`You are a senior software architect revising an existing implementation plan.
802
+
803
+ CRITICAL RULES:
804
+ - You will receive the FULL existing plan and the user's feedback or edit instructions.
805
+ - Output ONLY the complete revised plan in markdown. Do NOT output partial plans, explanations, or commentary.
806
+ - Preserve the same section structure (## headings) as the original plan.
807
+ - Only modify sections that are affected by the feedback. Leave unrelated sections intact.
808
+ - Use code blocks ONLY for: request/response JSON examples, file/directory trees, and env or config snippets.
809
+ - Be concrete and actionable: include validation rules, HTTP status codes, redirects, field-level data model descriptions, and step-by-step auth flows.
810
+ - 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 Mo(t,e){return `## Existing Plan
811
+
812
+ ${t}
813
+
814
+ ---
815
+
816
+ ## Edit Instructions
817
+
818
+ ${e}`}function el(t){let e=t.trim();if(e.length<100)return false;if(e.includes("## Overview")||e.includes("## Core Features"))return true;let r=e.toLowerCase();return !!((r.includes("overview")||r.includes("core features"))&&(r.includes("tech stack")||r.includes("technology")))}async function Co(t,e,r,o){o?.debug("Discovery stage started",{historyLength:e.history.length});let a=e.history.slice(0,-1).map(U=>`${U.role}: ${U.content}`).slice(-10).join(`
819
+ `),s=Po(t,a),l=[{role:"system",content:`${X}
820
+
821
+ ${To}`},{role:"user",content:s}],c=(await r.invoke(l,{temperature:.4,maxOutputTokens:4096})).text?.trim()??"",d=el(c),m=kt(t),S=m&&e.history.length>=7&&c.length>50,g=d&&(e.projectDescription==null||m)||m&&e.projectDescription!=null||S,G=d||S&&c.length>50;return o?.debug("Discovery stage complete",{advance:g,hasOverview:d,userConfirmed:m,forceAdvance:S}),{message:c,advance:g,sections:{},...G&&{projectDescription:c}}}var jt=class{stageName="discovery";async process(e,r){return Co(r.userMessage,e,r.model,r.logger)}canAdvance(e){return e.advance}getNextStageName(){return "requirements"}};var tl=`You are an expert database entity analyst. Your job is to extract data model signals from requirements.
822
+
823
+ Perform these analyses:
824
+
825
+ ## Entity Discovery
826
+ - List every entity implied by the requirements (users, domain objects, settings, logs).
827
+ - For each entity: name, purpose, key fields (with types), and which user type owns it.
828
+ - Identify status enums from flow transitions (e.g. pending -> active -> completed).
829
+
830
+ ## Field Analysis
831
+ - For each entity, list fields with: name, likely type, required/optional, unique constraints.
832
+ - Identify computed vs stored fields.
833
+ - Note fields that need indexing (lookups, sorting, filtering).
834
+
835
+ ## Relationship Signals
836
+ - List entity pairs that reference each other.
837
+ - Note ownership direction (which entity "belongs to" which).
838
+ - Identify potential M:N relationships that may need join tables.
839
+
840
+ Respond with a clear, structured analysis using headings and bullet points. Do NOT return JSON.`,Oe=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:tl,tools:{},maxIterations:2});var rl=`You are a database relationship specialist. Given a list of entities and their fields, you determine:
841
+
842
+ ## Cardinality Analysis
843
+ - For every entity pair that references each other, classify: 1:1, 1:N, or M:N.
844
+ - Explain the reasoning (e.g. "A User has many Orders, but an Order belongs to one User -> 1:N").
845
+
846
+ ## Foreign Key / Reference Strategy
847
+ - For MongoDB: recommend ObjectId references vs embedding. Embed when: data is small, always read together, rarely updated independently.
848
+ - For PostgreSQL: define foreign key columns, ON DELETE behavior (CASCADE, SET NULL, RESTRICT).
849
+
850
+ ## Join Table Design (M:N)
851
+ - When M:N is detected, design the join table with: both foreign keys, any extra fields (e.g. role in a membership), indexes.
852
+
853
+ ## Index Recommendations
854
+ - Suggest compound indexes for common query patterns.
855
+ - Suggest unique indexes for natural keys (email, slug, etc.).
856
+ - Note partial indexes where applicable (e.g. only active records).
857
+
858
+ Respond with structured analysis. Do NOT return JSON.`,qt=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:rl,tools:{},maxIterations:2});var ol=`You are an expert database schema reviewer. Your job is to:
859
+
860
+ 1. Validate the schema structure: every entity has fields, indexes, and relations properly defined.
861
+ 2. Check completeness: all entities from requirements are present, all relationships are bidirectional where needed.
862
+ 3. Check normalization: no redundant data, proper use of references vs embedding.
863
+ 4. Check performance: indexes cover common query patterns, no missing indexes on foreign keys.
864
+ 5. Check security: passwords are marked as hashed, sensitive fields noted, no plaintext secrets.
865
+ 6. Check conventions: consistent naming (camelCase or snake_case), timestamps on all entities.
866
+
867
+ If you have access to the validate_schema tool, use it first. Then provide a detailed review with:
868
+ - Issues found (with severity: critical, warning, suggestion)
869
+ - Specific fixes for each issue
870
+ - Overall assessment (ready / needs work)
871
+
872
+ Respond with structured analysis. Do NOT return JSON.`;function Ut(){return f({name:"schema-refiner",description:"Reviews a data model schema for completeness, normalization, performance, and security. Has access to validate_schema tool.",systemPrompt:ol,tools:{},maxIterations:3})}var nl=`You are a UX-focused frontend architect. You design detailed page specifications.
873
+
874
+ ## Page Planning
875
+ For each page in the application:
876
+
877
+ ### Route Definition
878
+ - Path (e.g. /login, /dashboard, /workouts/:id)
879
+ - Access level: public (no auth) or protected (requires auth)
880
+ - Page name and purpose (one sentence)
881
+
882
+ ### Page Detail
883
+ - **Form fields**: name, type (text, email, password, number, select, textarea, date, checkbox), required flag, validation rule.
884
+ - **Actions**: buttons and what they do (e.g. "Submit form", "Delete item", "Export CSV").
885
+ - **Empty state**: what to show when there's no data (e.g. "No workouts yet. Click + to add one.").
886
+ - **Error state**: how to handle errors (e.g. "Show inline validation errors", "Toast notification").
887
+ - **Redirect on success**: where to go after successful action (e.g. "/dashboard").
888
+ - **Key UI elements**: cards, tables, charts, sidebar, modals, tabs.
889
+
890
+ ### Page Grouping
891
+ - Group by access: public pages first, then protected.
892
+ - Order by user flow: signup -> login -> dashboard -> feature pages -> settings -> admin.
893
+
894
+ Respond with structured page specs. Do NOT return JSON.`,Me=f({name:"page-planner",description:"Designs detailed page specifications with routes, form fields, actions, states, and UI elements. Use for frontend page design.",systemPrompt:nl,tools:{},maxIterations:2});var sl=`You are a component design specialist. Given page specifications, you identify reusable components and shared patterns.
895
+
896
+ ## Component Identification
897
+ - **Layout components**: main layout (with nav, sidebar, content area), auth layout (centered form), admin layout.
898
+ - **Navigation components**: navbar, sidebar, breadcrumbs, mobile menu.
899
+ - **Form components**: reusable form inputs, form wrappers, validation display.
900
+ - **Display components**: cards, tables, lists, stat widgets, charts, badges.
901
+ - **Shared components**: modals, toasts, loading spinners, empty state illustrations, error boundaries.
902
+
903
+ ## Component Analysis
904
+ For each component:
905
+ - Name (PascalCase)
906
+ - Type: layout, shared, form, display, navigation
907
+ - Purpose (one sentence)
908
+ - Props it accepts (e.g. "user", "items", "onSubmit", "isLoading")
909
+ - Which pages use it
910
+
911
+ ## State Management
912
+ - Identify which state is per-page (form state, UI state) vs global (auth state, user preferences).
913
+ - Recommend server vs client state strategy.
914
+ - Identify data fetching patterns (on mount, on action, real-time).
915
+
916
+ Respond with structured analysis. Do NOT return JSON.`,Lt=f({name:"component-analyzer",description:"Identifies reusable components, shared layouts, and state management patterns from page specifications. Use after page planning.",systemPrompt:sl,tools:{},maxIterations:2});var al=`You are a frontend technology advisor. Given project requirements, you recommend the best frontend framework.
917
+
918
+ ## Decision Criteria
919
+
920
+ ### Choose "react-vite" (Vite + React SPA) when:
921
+ - The app is a single-page application (SPA) behind authentication
922
+ - No SEO requirements (admin dashboards, internal tools, B2B apps)
923
+ - Backend is a separate API (GraphQL or REST) already built
924
+ - Simple routing with client-side navigation
925
+ - Team prefers traditional React patterns (hooks, context)
926
+
927
+ ### Choose "nextjs" (Next.js App Router) when:
928
+ - SEO is important (marketing pages, blogs, e-commerce storefronts)
929
+ - Need server-side rendering (SSR) or static site generation (SSG)
930
+ - Want unified frontend + API in one project (server actions, API routes)
931
+ - Need streaming and progressive rendering
932
+ - Complex data fetching with caching requirements
933
+ - Mix of public and authenticated pages
934
+
935
+ ## Output Format
936
+ State your recommendation clearly:
937
+ - Framework: react-vite | nextjs
938
+ - Reasoning: 2-3 sentences explaining why
939
+ - Trade-offs: what you would lose with the alternative
940
+
941
+ Respond with structured analysis. Do NOT return JSON.`,Do=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:al,tools:{},maxIterations:2});var il=`You are a web security specialist. You analyze project requirements for security concerns and design security policies.
942
+
943
+ ## Authentication Analysis
944
+ - Determine the best auth strategy (JWT, session, OAuth) based on requirements.
945
+ - JWT: token expiry, refresh strategy, cookie vs header, httpOnly/secure/sameSite flags.
946
+ - Session: session store (memory, Redis, DB), cookie config, session expiry.
947
+ - OAuth: which providers, callback flow, token exchange, account linking.
948
+
949
+ ## Password Security
950
+ - Hashing algorithm (bcrypt recommended), cost factor (10+ rounds).
951
+ - Password requirements: minimum length, complexity rules.
952
+ - Password reset flow: token generation, expiry, one-time use.
953
+
954
+ ## Authorization Analysis
955
+ - Identify role hierarchy (e.g. admin > moderator > user).
956
+ - Map roles to permissions per resource (CRUD matrix).
957
+ - Resource ownership checks (users can only modify their own data).
958
+
959
+ ## Threat Analysis
960
+ - Rate limiting: login attempts, API calls, password reset requests.
961
+ - CORS: allowed origins, methods, headers.
962
+ - Input sanitization: XSS prevention, SQL injection prevention.
963
+ - Brute force protection: account lockout, exponential backoff.
964
+
965
+ 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:il,tools:{},maxIterations:2});var ll=`You are an authentication flow architect. You design detailed, numbered step-by-step auth flows.
966
+
967
+ For each flow (signup, login, logout, password reset, protected route middleware, API auth middleware):
968
+
969
+ ## Flow Design Pattern
970
+ 1. Number each step sequentially.
971
+ 2. Mark each step as "frontend" or "backend".
972
+ 3. Describe the action clearly (e.g. "Frontend sends POST to /api/auth/signup with { name, email, password }").
973
+ 4. Include implementation details (e.g. "Backend hashes password with bcrypt (10 rounds)").
974
+
975
+ ## Signup Flow
976
+ - Frontend: form validation, submit request.
977
+ - Backend: validate input, check existing user, hash password, create user + profile, generate token, set cookie.
978
+ - Frontend: redirect to dashboard.
979
+
980
+ ## Login Flow
981
+ - Frontend: form validation, submit credentials.
982
+ - Backend: find user, compare password hash, generate token, set cookie.
983
+ - Frontend: redirect to dashboard.
984
+
985
+ ## Password Reset Flow
986
+ - Frontend: request reset (email).
987
+ - Backend: generate reset token, send email.
988
+ - Frontend: enter new password with token.
989
+ - Backend: validate token, hash new password, update user, invalidate token.
990
+
991
+ ## Middleware Flows
992
+ - Protected route: check cookie/header, verify token, attach user to request, reject if invalid.
993
+ - API auth: same as above but for API routes, return 401 JSON.
994
+
995
+ Respond with structured numbered flows. Do NOT return JSON.`,Ce=f({name:"flow-designer",description:"Designs detailed step-by-step authentication flows (signup, login, logout, password reset, middleware). Use after security analysis.",systemPrompt:ll,tools:{},maxIterations:2});function Hs(t,e,r){let o=[{role:"system",content:e},{role:"user",content:r}];return t.invoke(o,{temperature:.3,maxOutputTokens:8192}).then(n=>n.text?.trim()??"")}function cl(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 pl(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 No(t,e,r,o){o?.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=`${X}
996
+
997
+ Output only markdown. Do NOT output JSON.`,s=await Hs(r,a,Ro(n)),{overview:i,techStack:l}=cl(s),p=await Hs(r,a,wo(n,s)),{featureDecisions:c}=pl(p);o?.info("Delegating to data-modeler specialist");let m=(await Y(Oe,`Analyze the data model for this project:
998
+
999
+ ${n}
1000
+
1001
+ Features:
1002
+ ${c}`,{parentModel:r})).output;o?.info("Delegating to frontend-architect specialist");let S=[s,c,m].join(`
1003
+
1004
+ ---
1005
+
1006
+ `),G=(await Y(Me,`Design the pages and routes for this project:
1007
+
1008
+ ${n}
1009
+
1010
+ Context:
1011
+ ${S}`,{parentModel:r})).output;o?.info("Delegating to auth-designer specialist");let U=[S,G].join(`
1012
+
1013
+ ---
1014
+
1015
+ `),se=(await Y(Ce,`Design the authentication flows for this project:
1016
+
1017
+ ${n}
1018
+
1019
+ Context:
1020
+ ${U}`,{parentModel:r})).output;return o?.info("Requirements stage complete (specialist agents)"),{message:"Requirements generated via specialist agents (Data Modeler, Frontend Architect, Auth Designer).",advance:true,sections:{overview:i,techStack:l,featureDecisions:c,dataModels:m,pagesAndRoutes:G,authFlow:se}}}var Gt=class{stageName="requirements";async process(e,r){return No(r.userMessage,e,r.model,r.logger)}canAdvance(e){return e.advance}getNextStageName(){return "design"}};var dl=`You are an API endpoint analyst. Given a data model and requirements, you derive the complete API surface.
1021
+
1022
+ ## Endpoint Discovery
1023
+ - For each entity in the data model, determine CRUD operations: create, read (by ID), list (with filters/pagination), update, delete.
1024
+ - From user stories/flows, identify custom operations beyond CRUD (e.g. searchUsers, bulkImport, exportCsv, toggleStatus).
1025
+ - Group endpoints by resource name (pluralized entity name).
1026
+
1027
+ ## Route Design
1028
+ - Design RESTful routes: POST /resource, GET /resource/:id, GET /resource, PUT /resource/:id, DELETE /resource/:id.
1029
+ - For nested resources: GET /users/:userId/orders, POST /users/:userId/orders.
1030
+ - For custom operations: POST /resource/:id/actions/activate, GET /resource/search.
1031
+
1032
+ ## Auth Annotations
1033
+ - Mark which endpoints require authentication.
1034
+ - Mark which endpoints require specific roles (admin, owner).
1035
+ - Identify resource-ownership checks (user can only access their own data).
1036
+
1037
+ Respond with structured analysis using headings and bullet points. Do NOT return JSON.`,De=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:dl,tools:{},maxIterations:2});var ul=`You are an API contract specialist. Given endpoints and a data model, you design detailed request/response contracts.
1038
+
1039
+ ## Request Design
1040
+ - For each endpoint, define: required fields, optional fields, field types, validation rules.
1041
+ - Validation rules: required, min/max length, email format, enum values, numeric ranges.
1042
+ - For list endpoints: pagination (page, limit, offset), sorting (sortBy, order), filtering (query params).
1043
+
1044
+ ## Response Design
1045
+ - Success responses: HTTP status (200, 201, 204), response body shape.
1046
+ - For list endpoints: { items: T[], total: number, page: number, limit: number }.
1047
+ - For single item: the entity shape with all fields.
1048
+
1049
+ ## Error Responses
1050
+ - 400: validation errors with field-level messages.
1051
+ - 401: unauthenticated (missing or invalid token).
1052
+ - 403: forbidden (insufficient role or not resource owner).
1053
+ - 404: resource not found.
1054
+ - 409: conflict (duplicate unique field).
1055
+ - 500: internal server error.
1056
+
1057
+ ## Naming Conventions
1058
+ - Use consistent field naming (camelCase for JSON, snake_case for query params if preferred).
1059
+ - Use ISO 8601 for dates in responses.
1060
+
1061
+ Respond with structured analysis. Do NOT return JSON.`,Ne=f({name:"contract-designer",description:"Designs detailed request/response contracts, validation rules, and error responses per API endpoint. Use after endpoint analysis.",systemPrompt:ul,tools:{},maxIterations:2});function ml(t){let e=[];t.projectDescription&&e.push(t.projectDescription);let r=t.sections;return r.overview&&e.push(r.overview),r.techStack&&e.push(r.techStack),r.featureDecisions&&e.push(r.featureDecisions),r.dataModels&&e.push(r.dataModels),r.pagesAndRoutes&&e.push(r.pagesAndRoutes),r.authFlow&&e.push(r.authFlow),e.join(`
1062
+
1063
+ ---
1064
+
1065
+ `)}async function Io(t,e,r,o){o?.debug("Design stage started (specialist agents)");let n=ml(e);if(!n)return {message:"No prior sections. Complete discovery and requirements first.",advance:false,sections:{}};o?.info("Delegating to api-designer endpoint-analyzer specialist");let s=(await Y(De,`Design the API routes for this project:
1066
+
1067
+ ${n}`,{parentModel:r})).output;o?.info("Delegating to api-designer contract-designer specialist");let i=await Y(Ne,`Design detailed request/response contracts for these API endpoints:
1068
+
1069
+ ${s}
1070
+
1071
+ Project context:
1072
+ ${n}`,{parentModel:r}),l=`${X}
1073
+
1074
+ Output only markdown. Do NOT output JSON.`,p=await r.invoke([{role:"system",content:l},{role:"user",content:vo(n,s+`
1075
+
1076
+ `+i.output)}],{temperature:.3,maxOutputTokens:8192}).then(c=>c.text?.trim()??"");return o?.info("Design stage complete (specialist agents)"),{message:"Design generated via specialist agents (Endpoint Analyzer, Contract Designer).",advance:true,sections:{apiRoutes:s,implementation:p}}}var Jt=class{stageName="design";async process(e,r){return Io(r.userMessage,e,r.model,r.logger)}canAdvance(e){return e.advance}getNextStageName(){return "complete"}};function ko(t,e){return [`# ${t} Implementation Plan
1077
+ `,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(`
1078
+
1079
+ `)}async function fl(t,e){await writeFile(e,t,"utf-8");}var hl=`You are a QA-minded tech lead. You identify edge cases that developers often miss.
1080
+
1081
+ For each domain area (Authentication, Data, API, Frontend, Integrations):
1082
+
1083
+ ## Edge Case Analysis
1084
+ - **Scenario**: Describe the edge case concretely (e.g. "User submits signup form with email that already exists").
1085
+ - **Handling**: How to handle it (e.g. "Return 400 with message 'Email already in use'").
1086
+ - **Severity**: critical (must handle or app breaks), warning (should handle for good UX), info (nice to have).
1087
+
1088
+ ## Common Areas to Check
1089
+ - **Authentication**: duplicate email, invalid credentials, expired token, concurrent sessions, password reset with invalid token.
1090
+ - **Data**: empty collections, max field lengths, special characters in input, date timezone issues, null references.
1091
+ - **API**: missing required fields, invalid field types, unauthorized access, rate limiting, pagination edge (page 0, negative page).
1092
+ - **Frontend**: empty states, loading states, network errors, form resubmission, back button behavior.
1093
+ - **Integrations**: external API down, timeout, rate limited, invalid response format.
1094
+
1095
+ Respond with structured edge cases grouped by area. Do NOT return JSON.`,Ie=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:hl,tools:{},maxIterations:2});var yl=`You are a testing strategy specialist. You design comprehensive manual testing checklists.
1096
+
1097
+ ## Testing Checklist Design
1098
+ Group test items by flow (Authentication, CRUD operations, Edge cases, etc.).
1099
+
1100
+ For each test item:
1101
+ - **Flow name**: which feature flow this tests (e.g. "Authentication Flow", "Workout CRUD Flow").
1102
+ - **Test item**: what to verify (e.g. "Sign up with valid credentials creates account").
1103
+ - **Expected result**: what should happen (e.g. "User created in DB, JWT cookie set, redirected to /dashboard").
1104
+
1105
+ ## Coverage Areas
1106
+ - **Happy paths**: normal user flows work end-to-end.
1107
+ - **Validation**: invalid inputs are rejected with clear messages.
1108
+ - **Authorization**: users can only access what they should.
1109
+ - **Error handling**: errors are caught and displayed properly.
1110
+ - **Data integrity**: data is saved correctly, relationships maintained.
1111
+ - **UI states**: loading, empty, error, success states display correctly.
1112
+
1113
+ ## Checklist Format
1114
+ Present as grouped checklist items using markdown checkboxes:
1115
+ ### Flow Name
1116
+ - [ ] Test item description -> Expected result
1117
+
1118
+ Respond with structured checklist. Do NOT return JSON.`,ke=f({name:"testing-strategist",description:"Designs comprehensive manual testing checklists grouped by feature flow. Use for testing strategy and QA planning.",systemPrompt:yl,tools:{},maxIterations:2});function Sl(t){let e=[];t.projectDescription&&e.push(t.projectDescription);let r=t.sections;return [r.overview,r.techStack,r.featureDecisions,r.dataModels,r.pagesAndRoutes,r.authFlow,r.apiRoutes,r.implementation].forEach(o=>{o&&e.push(o);}),e.join(`
1119
+
1120
+ ---
1121
+
1122
+ `)}function bl(t){let r=(t.sections.overview??t.projectDescription??"").split(`
1123
+ `)[0]?.trim()??"",n=/^#+\s*(.+?)(?:\s+Implementation Plan)?$/i.exec(r);return n?.[1]?n[1].trim():r.length>0&&r.length<80?r.replace(/^#+\s*/,"").trim():"Project Implementation Plan"}async function _o(t,e,r,o){o?.debug("Synthesis stage started (specialist agents)");let n=Sl(e);if(!n)return {message:"No prior sections. Complete earlier stages first.",advance:false,sections:{}};let a=`${X}
1124
+
1125
+ ${Eo}
1126
+
1127
+ Output only markdown. Do NOT output JSON.`,s=await r.invoke([{role:"system",content:a},{role:"user",content:Ao(n)}],{temperature:.3,maxOutputTokens:8192}).then(g=>g.text?.trim()??"");o?.info("Delegating to execution-planner edge-case-analyzer specialist");let l=(await Y(Ie,`Identify edge cases for this project:
1128
+
1129
+ ${n}`,{parentModel:r})).output;o?.info("Delegating to execution-planner testing-strategist specialist");let c=(await Y(ke,`Design the manual testing checklist for this project:
1130
+
1131
+ ${n}`,{parentModel:r})).output,d=bl(e),m={...e.sections,executionPlan:s||null,edgeCases:l||null,testingChecklist:c||null},S=ko(d,m);return o?.info("Synthesis stage complete (specialist agents)",{projectName:d}),{message:`Plan complete: ${d}. Generated via specialist agents.`,advance:true,sections:{executionPlan:s,edgeCases:l,testingChecklist:c},planMarkdown:S}}var Bt=class{stageName="complete";async process(e,r){return _o(r.userMessage,e,r.model,r.logger)}canAdvance(e){return e.advance}getNextStageName(){return null}};var xl={discovery:new jt,requirements:new Gt,design:new Jt,complete:new Bt};function jo(t){return xl[t]}async function Qs(t,e,r,o,n){n?.debug("Stage processor invoked",{stage:t});let s=await jo(t).process(r,{userMessage:e,model:o,logger:n}),i=Fs(r,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 qo=["discovery","requirements","design","complete"];async function zt(t,e,r){let{logger:o}=r,n=r.model??{provider:"openai",model:"gpt-4o-mini"},a=E(n),s=e??Ls();s=It(s,"user",t),o?.info("Planning chat turn",{stage:s.stage,messageLength:t.length});let i="",l=[],p=null,c=async S=>{let g=await Qs(S,t,s,a,o);return i=g.message,l=g.pendingQuestions,s=g.data,g.planMarkdown&&(p=g.planMarkdown),{advance:g.advance,planMarkdown:g.planMarkdown}},d=s.stage;o?.info("Stage",{stage:d});let m=await c(d);for(;m.advance&&!p;){let S=qo.indexOf(d),g=S>=0&&S<qo.length-1?qo[S+1]:void 0;if(g===void 0)break;o?.info("Stage transition",{from:d,to:g}),d=g,s=xo(s),s={...s,stage:d},o?.info("Stage",{stage:d}),m=await c(d);}return s=It(s,"assistant",i),o?.info("Planning chat turn done",{stage:d,hasPlanMarkdown:!!p}),{message:i,context:s,pendingQuestions:l,planMarkdown:p}}var Vs=10;async function Tl(t){let{input:e,model:r,onStep:o,logger:n}=t;n?.info("Starting planning agent",{maxTurns:Vs});let a=null,s=await zt(e,a,{model:r,logger:n});a=s.context;let i=1;for(;!s.planMarkdown&&i<Vs;){n?.debug("Planning agent turn",{turn:i});let c=`continue - proceed with the project: "${e}". Make reasonable assumptions for any unresolved details and produce the required output format.`;s=await zt(c,a,{model:r,logger:n}),a=s.context,i++;}let l=s.planMarkdown??s.message,p=a.history.map(c=>({role:c.role,content:c.content}));return n?.info("Planning agent completed",{turns:i,hasPlanMarkdown:!!s.planMarkdown}),{output:l,steps:[],totalUsage:void 0,messages:p}}async function Pl(t){let{existingPlan:e,feedback:r,logger:o}=t;if(o?.info("Editing plan",{feedbackLength:r.length}),!e||e.trim().length<50)throw new Error("existingPlan is too short or empty. Provide a valid plan to edit.");if(!r||r.trim().length===0)throw new Error("feedback is empty. Provide edit instructions.");let n=t.model??{provider:"openai",model:"gpt-4o-mini"},i=(await E(n).invoke([{role:"system",content:Oo},{role:"user",content:Mo(e,r)}],{temperature:.3,maxOutputTokens:16384})).text?.trim()??"";if(!i)throw new Error("Model returned empty response when editing plan.");return o?.info("Plan edited successfully",{outputLength:i.length}),i}var Rl="discovery",Ws={overview:null,techStack:null,featureDecisions:null,dataModels:null,pagesAndRoutes:null,authFlow:null,apiRoutes:null,implementation:null,executionPlan:null,edgeCases:null,testingChecklist:null},Yt=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??Ws,...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??Rl,projectDescription:this.data.projectDescription??null,sections:this.data.sections??{...Ws},history:this.data.history??[],pendingQuestions:this.data.pendingQuestions??[]}}};function wl(){return new Yt}var Uo=z.object({name:z.string(),type:z.string(),required:z.coerce.boolean().default(false),unique:z.coerce.boolean().default(false),description:z.string().default(""),default:z.string().optional()}),Ks=z.object({name:z.string().default(""),fields:z.array(z.string()).default([]),unique:z.coerce.boolean().default(false)}),vl=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(z.enum(["1:1","1:N","M:N"])),Xs=z.object({field:z.string(),references:z.string(),type:vl,description:z.string().default("")}),Lo=z.object({name:z.string(),description:z.string().default(""),fields:z.union([z.array(Uo),z.record(z.string(),z.unknown())]).transform((t,e)=>{if(Array.isArray(t))return t;let r=[];for(let[o,n]of Object.entries(t)){let a=typeof n=="object"&&n!==null?{...n}:{};a.name||(a.name=o);let s=Uo.safeParse(a);if(s.success)r.push(s.data);else for(let i of s.error.issues)e.addIssue({...i,path:[o,...i.path]});}return r}),indexes:z.array(Ks).default([]),relations:z.array(Xs).default([])}),El=z.string().transform(t=>t.toLowerCase().trim()).pipe(z.enum(["mongodb","postgresql"])),Z=z.object({type:El,reasoning:z.string().default(""),entities:z.array(Lo).default([])});var $t=`You are a senior database architect specializing in both MongoDB and PostgreSQL schema design.
1132
+
1133
+ You analyze requirements and produce enterprise-quality data models with:
1134
+ - Properly typed fields (MongoDB: ObjectId, string, number, date, array; PostgreSQL: uuid, varchar, text, integer, timestamp, jsonb)
1135
+ - Indexes optimized for query patterns
1136
+ - Relationships with correct cardinality (1:1, 1:N, M:N)
1137
+ - Validation constraints and default values
1138
+ - Security considerations (hashed passwords, encrypted fields)
1139
+
1140
+ Output only valid JSON unless instructed otherwise.`;var Zs=`## Requirements:
1141
+ {requirement}
1142
+
1143
+ Design the database schema. Determine the best database type (mongodb or postgresql) based on the requirements, or use the one specified.
1144
+
1145
+ For MongoDB use types: ObjectId, string, number, boolean, date, array, mixed.
1146
+ For PostgreSQL use types: uuid, varchar(n), text, integer, bigint, boolean, timestamp, jsonb, and proper foreign key relations.
1147
+
1148
+ Return ONLY valid JSON:
1149
+ {
1150
+ "type": "mongodb" | "postgresql",
1151
+ "reasoning": "2-4 sentences explaining the choice and design approach",
1152
+ "entities": [
1153
+ {
1154
+ "name": "EntityName",
1155
+ "description": "Brief description",
1156
+ "fields": [
1157
+ { "name": "fieldName", "type": "DB-native type", "required": true, "unique": false, "description": "..." }
1158
+ ],
1159
+ "indexes": [ { "name": "idx_name", "fields": ["field1"], "unique": false } ],
1160
+ "relations": [ { "field": "refField", "references": "OtherEntity", "type": "1:N", "description": "..." } ]
1161
+ }
1162
+ ]
1163
+ }`,ea=`## Current Schema (JSON):
1164
+ {existingSchema}
1165
+
1166
+ ## Feedback:
1167
+ {feedback}
1168
+
1169
+ Update the schema based on the feedback. Return the complete updated schema as valid JSON in the same format.`;function Fo(t){return Zs.replace("{requirement}",t)}function Go(t,e){return ea.replace("{existingSchema}",t).replace("{feedback}",e)}var ta=`## Project: {projectName}
1170
+ ## Goal: {projectGoal}
1171
+ ## Database: {databaseType}
1172
+
1173
+ ## Context:
1174
+ {context}
1175
+
1176
+ Apply the 5-phase enterprise data modeling process:
1177
+
1178
+ ### Phase 1: Entity Discovery
1179
+ - Extract every entity from the context (user types, domain objects, settings, logs).
1180
+ - Identify status enums from flow transitions.
1181
+
1182
+ ### Phase 2: Relationship Mapping
1183
+ - For each entity pair, determine ownership and cardinality (1:1, 1:N, M:N).
1184
+ - Note bidirectional references and join tables (PostgreSQL) or embedded arrays (MongoDB).
1185
+
1186
+ ### Phase 3: Permission Derivation
1187
+ - Map actor types to role names.
1188
+ - From actions, derive which role can CRUD which entity.
1189
+
1190
+ ### Phase 4: Schema Generation
1191
+ - Generate fields with DB-native types, required/unique flags, defaults.
1192
+ - Add indexes for common queries (user lookups, date ranges, foreign keys).
1193
+ - Include timestamps (createdAt, updatedAt) on all entities.
1194
+
1195
+ ### Phase 5: Validation
1196
+ - Verify every entity referenced in relations exists.
1197
+ - Verify no orphan fields or missing indexes.
1198
+
1199
+ Return ONLY valid JSON in the DataModelDesign format.`;function Jo(t,e,r,o){return ta.replace("{projectName}",t).replace("{projectGoal}",e).replace("{databaseType}",r).replace("{context}",o)}var Ht=u({name:"validate_data_model",description:"Validates a data model JSON string against the DataModelDesign schema. Returns valid: true or valid: false with errors.",input:z.object({schema:z.string().describe("JSON string of the data model to validate")}),handler:async({schema:t})=>{try{let e=JSON.parse(t);return Z.parse(e),{valid:!0}}catch(e){return e instanceof z.ZodError?{valid:false,errors:e.issues.map(r=>`${r.path.join(".")}: ${r.message}`)}:e instanceof SyntaxError?{valid:false,errors:[`Invalid JSON: ${e.message}`]}:{valid:false,errors:[String(e)]}}}});function Qt(t){return u({name:"design_schema",description:"Generate a database schema (MongoDB or PostgreSQL) from plain text requirements. Returns the full data model as JSON.",input:z.object({requirement:z.string().describe("Plain text description of the data modeling requirements")}),handler:async({requirement:e})=>{let r=Fo(e),o=[{role:"system",content:"You are a database schema expert. Return only valid JSON."},{role:"user",content:r}],n=await t.invoke(o,{temperature:.3,maxOutputTokens:8192});return M(n.text,Z)}})}function Vt(t){return u({name:"design_schema_pro",description:"Generate an enterprise-quality database schema using 5-phase analysis (Entity Discovery, Relationship Mapping, Permission Derivation, Schema Generation, Validation). Use when structured context is available.",input:z.object({projectName:z.string().describe("Project name"),projectGoal:z.string().describe("Project goal / purpose"),databaseType:z.enum(["mongodb","postgresql"]).describe("Target database type"),context:z.string().describe("Full project context: features, actors, flows, stories")}),handler:async({projectName:e,projectGoal:r,databaseType:o,context:n})=>{let a=Jo(e,r,o,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,Z)}})}function Wt(t){return u({name:"refine_schema",description:"Update an existing data model schema based on user feedback. Provide the current schema JSON and feedback describing desired changes.",input:z.object({existingSchema:z.string().describe("Current data model schema as JSON string"),feedback:z.string().describe("Feedback describing desired changes")}),handler:async({existingSchema:e,feedback:r})=>{let o=Go(e,r),n=[{role:"system",content:"You are a database schema expert. Return only valid JSON."},{role:"user",content:o}],a=await t.invoke(n,{temperature:.3,maxOutputTokens:8192});return M(a.text,Z)}})}function Yo(t){return {validate_data_model:Ht,design_schema:Qt(t),design_schema_pro:Vt(t),refine_schema:Wt(t)}}var Al=`${$t}
1200
+
1201
+ You are the data modeling orchestrator. When the user asks for a data model:
1202
+
1203
+ 1. **Analyze first**: Use subagent_entity-analyzer to extract entities, fields, and relationships from the requirements.
1204
+ 2. **Map relationships**: Use subagent_relationship-mapper with the entity analysis to determine cardinality, foreign keys, and indexes.
1205
+ 3. **Generate schema**: Use design_schema (plain text) or design_schema_pro (when structured context is available) to produce the data model.
1206
+ 4. **Refine (optional)**: Use subagent_schema-refiner to validate and suggest improvements to the generated schema.
1207
+ 5. **Validate**: Use validate_data_model to check the final schema JSON before returning.
1208
+
1209
+ Respond with the final data model schema as JSON.`;async function Ol(t){let{input:e,model:r,maxIterations:o=15,onStep:n,logger:a}=t,s=E(r??{provider:"openai",model:"gpt-4o-mini"}),i=Yo(s),l=Ut(),p=q([Oe,qt,l],{parentModel:s}),c={...i,...p};return D({model:s,tools:c,systemPrompt:Al,input:e,maxIterations:o,onStep:n,logger:a})}var Ml=z.union([z.enum(["GET","POST","PUT","PATCH","DELETE"]),z.string()]).transform(t=>typeof t=="string"?t.toUpperCase():t).pipe(z.enum(["GET","POST","PUT","PATCH","DELETE"])),$o=z.record(z.string(),z.unknown()).optional().default({}).transform(t=>Object.fromEntries(Object.entries(t??{}).map(([e,r])=>[e,typeof r=="string"?r:String(r)]))),oa=z.array(z.unknown()).default([]).transform(t=>t.map(e=>typeof e=="string"?e:JSON.stringify(e))),Ho=z.object({id:z.string(),resource:z.string(),method:Ml,path:z.string(),description:z.string(),auth:z.coerce.boolean(),roles:z.array(z.string()).default([]),requestBody:$o,responseBody:$o,queryParams:$o,validation:oa,errorResponses:oa}),Qo=z.object({name:z.string(),type:z.enum(["query","mutation","subscription"]),description:z.string(),auth:z.coerce.boolean(),roles:z.array(z.string()).default([]),args:z.array(z.object({name:z.string(),type:z.string(),required:z.coerce.boolean()})),returnType:z.string()}),Cl=z.unknown().transform(t=>(typeof t=="string"?t.toLowerCase().trim():"rest").includes("graphql")?"graphql":"rest"),pe=z.object({style:Cl,baseUrl:z.string().default("/api/v1"),endpoints:z.array(Ho).default([]),graphqlOperations:z.array(Qo).default([])});var Kt=`You are a senior API architect specializing in REST and GraphQL API design.
1210
+
1211
+ You analyze data models and requirements to produce enterprise-quality API designs with:
1212
+ - RESTful endpoints grouped by resource with proper HTTP methods
1213
+ - Request/response contracts with field types and validation rules
1214
+ - Error responses with appropriate HTTP status codes (400, 401, 403, 404, 500)
1215
+ - Pagination, filtering, and sorting patterns
1216
+ - Authentication and authorization annotations per endpoint
1217
+ - GraphQL types, queries, mutations, and subscriptions when applicable
1218
+
1219
+ Output only valid JSON unless instructed otherwise.`;var na=`## Requirements:
1220
+ {requirement}
1221
+
1222
+ Design the API. Determine the best API style (rest or graphql) based on the requirements, or use the one specified.
1223
+
1224
+ For REST: group endpoints by resource. Each endpoint needs method, path, description, auth flag, roles, requestBody, responseBody, queryParams, validation rules, and error responses.
1225
+ For GraphQL: define operations (queries, mutations, subscriptions) with args and return types.
1226
+
1227
+ Return ONLY valid JSON:
1228
+ {
1229
+ "style": "rest" | "graphql",
1230
+ "baseUrl": "/api/v1",
1231
+ "endpoints": [
1232
+ { "id": "ep-1", "resource": "users", "method": "POST", "path": "/api/v1/users", "description": "Create user", "auth": false, "roles": [], "requestBody": {}, "responseBody": {}, "queryParams": {}, "validation": [], "errorResponses": [] }
1233
+ ],
1234
+ "graphqlOperations": []
1235
+ }`,sa=`## Project: {projectName}
1236
+ ## API Style: {apiStyle}
1237
+ ## Data Model:
1238
+ {dataModel}
1239
+ ## Requirements:
1240
+ {context}
1241
+
1242
+ Design a comprehensive API surface from the data model and requirements. For each entity in the data model, generate CRUD endpoints plus any custom operations implied by the requirements.
1243
+
1244
+ 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.
1245
+
1246
+ Return ONLY valid JSON in the ApiDesign format.`;function Vo(t){return na.replace("{requirement}",t)}function Wo(t,e,r,o){return sa.replace("{projectName}",t).replace("{apiStyle}",e).replace("{dataModel}",r).replace("{context}",o)}var Xt=u({name:"validate_api",description:"Validates an API design JSON string against the ApiDesign schema. Returns valid: true or valid: false with errors.",input:z.object({design:z.string().describe("JSON string of the API design to validate")}),handler:async({design:t})=>{try{let e=JSON.parse(t);return pe.parse(e),{valid:!0}}catch(e){return e instanceof z.ZodError?{valid:false,errors:e.issues.map(r=>`${r.path.join(".")}: ${r.message}`)}:e instanceof SyntaxError?{valid:false,errors:[`Invalid JSON: ${e.message}`]}:{valid:false,errors:[String(e)]}}}});function Zt(t){return u({name:"design_api",description:"Generate an API design (REST or GraphQL) from plain text requirements. Returns the full API design as JSON.",input:z.object({requirement:z.string().describe("Plain text description of the API requirements")}),handler:async({requirement:e})=>{let r=Vo(e),o=[{role:"system",content:"You are an API architect. Return only valid JSON."},{role:"user",content:r}],n=await t.invoke(o,{temperature:.3,maxOutputTokens:8192});return M(n.text,pe)}})}function er(t){return u({name:"design_api_pro",description:"Generate a comprehensive API design from a data model and project context. Produces detailed endpoints with validation, error responses, and auth annotations.",input:z.object({projectName:z.string().describe("Project name"),apiStyle:z.enum(["rest","graphql"]).describe("Target API style"),dataModel:z.string().describe("Data model JSON or description"),context:z.string().describe("Project context: features, actors, stories")}),handler:async({projectName:e,apiStyle:r,dataModel:o,context:n})=>{let a=Wo(e,r,o,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 Xo(t){return {validate_api:Xt,design_api:Zt(t),design_api_pro:er(t)}}var Dl=`${Kt}
1247
+
1248
+ You are the API design orchestrator. When the user asks for an API design:
1249
+
1250
+ 1. **Analyze endpoints**: Use subagent_endpoint-analyzer to derive endpoints from the data model and requirements.
1251
+ 2. **Design contracts**: Use subagent_contract-designer to design request/response contracts, validation rules, and error responses.
1252
+ 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.
1253
+ 4. **Validate**: Use validate_api to check the final API design JSON before returning.
1254
+
1255
+ Respond with the final API design as JSON.`;async function Nl(t){let{input:e,model:r,maxIterations:o=15,onStep:n,logger:a}=t,s=E(r??{provider:"openai",model:"gpt-4o-mini"}),i=Xo(s),l=q([De,Ne],{parentModel:s}),p={...i,...l};return D({model:s,tools:p,systemPrompt:Dl,input:e,maxIterations:o,onStep:n,logger:a})}var ia=z.object({order:z.number(),side:z.enum(["frontend","backend"]),action:z.string(),details:z.string()}),la=z.object({name:z.string(),description:z.string(),steps:z.array(ia)}),ca=z.object({name:z.string(),purpose:z.string(),behavior:z.array(z.string())}),pa=z.object({name:z.string(),description:z.string(),permissions:z.array(z.string())}),da=z.object({area:z.string(),rules:z.array(z.string())}),ze=z.object({strategy:z.enum(["jwt","session","oauth"]),flows:z.array(la),middleware:z.array(ca),roles:z.array(pa),policies:z.array(da)});var Zo=`You are a senior security engineer specializing in authentication, authorization, and web security.
1256
+
1257
+ You design enterprise-quality auth systems with:
1258
+ - Step-by-step auth flows (signup, login, logout, password reset) with both frontend and backend steps
1259
+ - JWT or session strategy with proper cookie configuration (httpOnly, secure, sameSite, maxAge)
1260
+ - Role-based access control (RBAC) with permission matrices
1261
+ - Middleware chains for route protection and API authentication
1262
+ - Security policies: password hashing (bcrypt), rate limiting, CORS, input sanitization, brute force protection
1263
+ - OAuth integration patterns when needed
1264
+
1265
+ Output only valid JSON unless instructed otherwise.`;var ua=`## Requirements:
1266
+ {requirement}
1267
+
1268
+ Design the authentication and authorization system. Include:
1269
+
1270
+ 1. Strategy: jwt, session, or oauth (choose based on requirements).
1271
+ 2. Flows: signup, login, logout, password reset (if applicable). Each flow with numbered steps, frontend/backend side, action, and details.
1272
+ 3. Middleware: route protection middleware, API auth middleware. Each with name, purpose, and behavior list.
1273
+ 4. Roles: role definitions with name, description, and permissions list.
1274
+ 5. Policies: security policies grouped by area (passwords, tokens, CORS, rate limiting, etc.).
1275
+
1276
+ Return ONLY valid JSON:
1277
+ {
1278
+ "strategy": "jwt" | "session" | "oauth",
1279
+ "flows": [{ "name": "signup", "description": "...", "steps": [{ "order": 1, "side": "frontend", "action": "...", "details": "..." }] }],
1280
+ "middleware": [{ "name": "authenticateRequest", "purpose": "...", "behavior": ["..."] }],
1281
+ "roles": [{ "name": "user", "description": "...", "permissions": ["..."] }],
1282
+ "policies": [{ "area": "passwords", "rules": ["..."] }]
1283
+ }`;function en(t){return ua.replace("{requirement}",t)}var tr=u({name:"validate_auth",description:"Validates an auth design JSON string against the AuthDesign schema. Returns valid: true or valid: false with errors.",input:z.object({design:z.string().describe("JSON string of the auth design to validate")}),handler:async({design:t})=>{try{let e=JSON.parse(t);return ze.parse(e),{valid:!0}}catch(e){return e instanceof z.ZodError?{valid:false,errors:e.issues.map(r=>`${r.path.join(".")}: ${r.message}`)}:e instanceof SyntaxError?{valid:false,errors:[`Invalid JSON: ${e.message}`]}:{valid:false,errors:[String(e)]}}}});function rr(t){return u({name:"design_auth",description:"Generate a complete authentication and authorization design from project requirements. Returns auth flows, middleware, roles, and security policies as JSON.",input:z.object({requirement:z.string().describe("Project context and auth requirements")}),handler:async({requirement:e})=>{let r=en(e),o=[{role:"system",content:"You are a security engineer. Return only valid JSON."},{role:"user",content:r}],n=await t.invoke(o,{temperature:.3,maxOutputTokens:8192});return M(n.text,ze)}})}function rn(t){return {validate_auth:tr,design_auth:rr(t)}}var Il=`${Zo}
1284
+
1285
+ You are the auth design orchestrator. When the user asks for an auth design:
1286
+
1287
+ 1. **Analyze security**: Use subagent_security-analyzer to analyze security requirements, determine auth strategy, and identify threat vectors.
1288
+ 2. **Design flows**: Use subagent_flow-designer to design step-by-step auth flows (signup, login, logout, password reset, middleware).
1289
+ 3. **Generate design**: Use design_auth to produce the complete auth design with flows, middleware, roles, and security policies.
1290
+ 4. **Validate**: Use validate_auth to check the final auth design JSON before returning.
1291
+
1292
+ Respond with the final auth design as JSON.`;async function kl(t){let{input:e,model:r,maxIterations:o=15,onStep:n,logger:a}=t,s=E(r??{provider:"openai",model:"gpt-4o-mini"}),i=rn(s),l=q([Ft,Ce],{parentModel:s}),p={...i,...l};return D({model:s,tools:p,systemPrompt:Il,input:e,maxIterations:o,onStep:n,logger:a})}var ga=z.object({name:z.string(),type:z.string(),required:z.coerce.boolean(),validation:z.string()}),fa=z.object({path:z.string(),name:z.string(),access:z.string().transform(t=>t.toLowerCase().trim()).pipe(z.enum(["public","protected"])),purpose:z.string(),formFields:z.array(ga).default([]),actions:z.array(z.string()).default([]),emptyState:z.string().default(""),errorState:z.string().default(""),redirectOnSuccess:z.string().default(""),keyUiElements:z.array(z.string()).default([])}),ha=z.object({name:z.string(),type:z.string().transform(t=>t.toLowerCase().trim()).pipe(z.enum(["layout","shared","form","display","navigation"])),purpose:z.string(),props:z.array(z.string()).default([]),usedIn:z.array(z.string()).default([])}),Ye=z.object({pages:z.array(fa).default([]),components:z.array(ha).default([]),stateManagement:z.string().default(""),routingNotes:z.string().default("")});var on=`You are a senior frontend architect specializing in page design, routing, and component architecture.
1293
+
1294
+ You design enterprise-quality frontend architectures targeting a Vite + React 19 + TypeScript stack with:
1295
+ - **UI Library**: ShadCN UI (Radix-based components in src/components/ui/)
1296
+ - **Styling**: Tailwind CSS v4 with OKLCH color space and dark mode support
1297
+ - **Routing**: React Router v7 with private route guards
1298
+ - **Forms**: React Hook Form + Zod validation
1299
+ - **GraphQL**: Apollo Client with CodeGen-typed hooks
1300
+ - **Path Aliases**: @/{appName}/* mapping to ./src/*
1301
+
1302
+ Architecture outputs:
1303
+ - Public and protected pages with detailed route definitions
1304
+ - Per-page specifications: purpose, form fields with validation, actions, empty/error states, redirects
1305
+ - Component taxonomy: layout (sidebar, navbar), shared (data tables, dialogs), form (inputs, selects), display (cards, badges), navigation (breadcrumbs, tabs)
1306
+ - State management strategy (per-page vs global, Apollo cache vs local state)
1307
+
1308
+ Output only valid JSON unless instructed otherwise.`;var ya=`## Requirements:
1309
+ {requirement}
1310
+
1311
+ Design the frontend architecture. Include:
1312
+
1313
+ 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.
1314
+ 2. Components: reusable components. For each: name, type (layout/shared/form/display/navigation), purpose, props, and which pages use it.
1315
+ 3. State management: describe the state strategy (e.g. React Server Components for data, client state for forms).
1316
+ 4. Routing notes: any special routing behavior (redirects, guards, nested routes).
1317
+
1318
+ Return ONLY valid JSON:
1319
+ {
1320
+ "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"] }],
1321
+ "components": [{ "name": "Navbar", "type": "navigation", "purpose": "...", "props": ["user"], "usedIn": ["/dashboard", "/profile"] }],
1322
+ "stateManagement": "...",
1323
+ "routingNotes": "..."
1324
+ }`;function nn(t){return ya.replace("{requirement}",t)}var or=u({name:"validate_frontend",description:"Validates a frontend design JSON string against the FrontendDesign schema. Returns valid: true or valid: false with errors.",input:z.object({design:z.string().describe("JSON string of the frontend design to validate")}),handler:async({design:t})=>{try{let e=JSON.parse(t);return Ye.parse(e),{valid:!0}}catch(e){return e instanceof z.ZodError?{valid:false,errors:e.issues.map(r=>`${r.path.join(".")}: ${r.message}`)}:e instanceof SyntaxError?{valid:false,errors:[`Invalid JSON: ${e.message}`]}:{valid:false,errors:[String(e)]}}}});function nr(t){return u({name:"design_frontend",description:"Generate a complete frontend architecture design from project requirements. Returns pages, components, state management, and routing as JSON.",input:z.object({requirement:z.string().describe("Project context, API surface, and frontend requirements")}),handler:async({requirement:e})=>{let r=nn(e),o=[{role:"system",content:"You are a frontend architect. Return only valid JSON."},{role:"user",content:r}],n=await t.invoke(o,{temperature:.3,maxOutputTokens:16384});return M(n.text,Ye)}})}function an(t){return {validate_frontend:or,design_frontend:nr(t)}}var _l=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}),jl=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}),ql=`${on}
1325
+
1326
+ You are the frontend architecture routing orchestrator. When the user asks for a frontend design:
1327
+
1328
+ 1. **Select framework**: Use subagent_framework-selector to analyze requirements (SPA vs SSR, SEO needs, API structure) and recommend React/Vite or Next.js.
1329
+ 2. **Plan pages**: Use subagent_page-planner to design detailed page specifications with routes, forms, actions, and states.
1330
+ 3. **Analyze components**: Use subagent_component-analyzer to identify reusable components, layouts, and state management patterns.
1331
+ 4. **Generate design**: Use design_frontend to produce the complete frontend architecture as JSON.
1332
+ 5. **Validate**: Use validate_frontend to check the final design JSON before returning.
1333
+ 6. **Delegate to builder**: Based on the framework-selector recommendation:
1334
+ - If "react-vite": use subagent_react-builder with the design to generate a Vite + React SPA config.
1335
+ - If "nextjs": use subagent_nextjs-builder with the design to generate a Next.js App Router config.
1336
+
1337
+ Respond with the final frontend design as JSON, including the builder output.`;async function Ul(t){let{input:e,model:r,maxIterations:o=15,onStep:n,logger:a}=t,s=E(r??{provider:"openai",model:"gpt-4o-mini"}),i=an(s),l=q([Me,Lt,Do,_l,jl],{parentModel:s}),p={...i,...l};return D({model:s,tools:p,systemPrompt:ql,input:e,maxIterations:o,onStep:n,logger:a})}var ba=z.object({order:z.number(),action:z.string(),details:z.string()}),xa=z.object({name:z.string(),description:z.string(),steps:z.array(ba)}),Ta=z.object({area:z.string(),scenario:z.string(),handling:z.string(),severity:z.string().transform(t=>t.toLowerCase().trim()).pipe(z.enum(["critical","warning","info"]))}),Pa=z.object({flow:z.string(),item:z.string(),expectedResult:z.string()}),$e=z.object({phases:z.array(xa).default([]),currentState:z.string().default(""),desiredEndState:z.string().default(""),edgeCases:z.array(Ta).default([]),securityNotes:z.array(z.string()).default([]),performanceNotes:z.array(z.string()).default([]),testingChecklist:z.array(Pa).default([])});var ln=`You are a senior tech lead specializing in implementation strategy and project execution planning.
1338
+
1339
+ You create enterprise-quality execution plans with:
1340
+ - Phased implementation order with concrete, numbered steps per phase
1341
+ - Current state analysis and desired end state definition
1342
+ - Edge cases per domain area with handling strategies and severity levels
1343
+ - Security considerations (passwords, tokens, CORS, input validation)
1344
+ - Performance considerations (indexing, caching, lazy loading, N+1 prevention)
1345
+ - Manual testing checklists grouped by feature flow
1346
+
1347
+ Output only valid JSON unless instructed otherwise.`;var Ra=`## Full Plan Context:
1348
+ {context}
1349
+
1350
+ Create a comprehensive execution plan. Include:
1351
+
1352
+ 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").
1353
+ 2. **currentState**: What the project starts with (e.g. "vanilla Next.js, no DB, no auth").
1354
+ 3. **desiredEndState**: What must work when done (user capabilities + technical verification).
1355
+ 4. **edgeCases**: Edge cases per area with scenario, handling strategy, and severity (critical/warning/info).
1356
+ 5. **securityNotes**: Security considerations (password hashing, JWT config, rate limiting, etc.).
1357
+ 6. **performanceNotes**: Performance considerations (indexing, caching, lazy loading, etc.).
1358
+ 7. **testingChecklist**: Manual testing items per flow with expected results.
1359
+
1360
+ Return ONLY valid JSON:
1361
+ {
1362
+ "phases": [{ "name": "Phase 1: Foundation", "description": "...", "steps": [{ "order": 1, "action": "Install dependencies", "details": "npm install mongoose bcryptjs jsonwebtoken" }] }],
1363
+ "currentState": "...",
1364
+ "desiredEndState": "...",
1365
+ "edgeCases": [{ "area": "Authentication", "scenario": "Email already exists", "handling": "Return 400 with clear message", "severity": "critical" }],
1366
+ "securityNotes": ["..."],
1367
+ "performanceNotes": ["..."],
1368
+ "testingChecklist": [{ "flow": "Auth Flow", "item": "Sign up with valid credentials", "expectedResult": "Account created, redirected to dashboard" }]
1369
+ }`;function cn(t){return Ra.replace("{context}",t)}var sr=u({name:"validate_execution_plan",description:"Validates an execution plan JSON string against the ExecutionPlan schema. Returns valid: true or valid: false with errors.",input:z.object({plan:z.string().describe("JSON string of the execution plan to validate")}),handler:async({plan:t})=>{try{let e=JSON.parse(t);return $e.parse(e),{valid:!0}}catch(e){return e instanceof z.ZodError?{valid:false,errors:e.issues.map(r=>`${r.path.join(".")}: ${r.message}`)}:e instanceof SyntaxError?{valid:false,errors:[`Invalid JSON: ${e.message}`]}:{valid:false,errors:[String(e)]}}}});function ar(t){return u({name:"create_execution_plan",description:"Generate a comprehensive execution plan with phases, edge cases, and testing checklist from the full plan context.",input:z.object({context:z.string().describe("Full plan context: all sections generated so far")}),handler:async({context:e})=>{let r=cn(e),o=[{role:"system",content:"You are a tech lead. Return only valid JSON."},{role:"user",content:r}],n=await t.invoke(o,{temperature:.3,maxOutputTokens:16384});return M(n.text,$e)}})}function dn(t){return {validate_execution_plan:sr,create_execution_plan:ar(t)}}var Ll=`${ln}
1370
+
1371
+ You are the execution planning orchestrator. When the user provides plan sections:
1372
+
1373
+ 1. **Analyze edge cases**: Use subagent_edge-case-analyzer to identify edge cases per domain area with handling strategies.
1374
+ 2. **Design testing**: Use subagent_testing-strategist to design manual testing checklists grouped by feature flow.
1375
+ 3. **Generate plan**: Use create_execution_plan to produce the complete execution plan with phases, edge cases, and testing checklist.
1376
+ 4. **Validate**: Use validate_execution_plan to check the final plan JSON before returning.
1377
+
1378
+ Respond with the final execution plan as JSON.`;async function Fl(t){let{input:e,model:r,maxIterations:o=15,onStep:n,logger:a}=t,s=E(r??{provider:"openai",model:"gpt-4o-mini"}),i=dn(s),l=q([Ie,ke],{parentModel:s}),p={...i,...l};return D({model:s,tools:p,systemPrompt:Ll,input:e,maxIterations:o,onStep:n,logger:a})}var va=t=>z.string().transform(e=>e.toLowerCase().trim()).pipe(z.enum(t)),Ea=z.object({name:z.string(),purpose:z.string(),appliesTo: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(z.enum(["global","route","resource"])),config:z.record(z.string(),z.unknown()).default({})}),Aa=z.object({name:z.string(),entity:z.string(),operations:z.array(z.string()).default([]),dependencies:z.array(z.string()).default([])}),Gl=z.string().transform(t=>t.toUpperCase().trim()).pipe(z.enum(["GET","POST","PUT","PATCH","DELETE"])),Oa=z.object({resource:z.string(),basePath:z.string(),endpoints:z.array(z.object({method:Gl,path:z.string(),handler:z.string(),auth:z.coerce.boolean().default(true),roles:z.array(z.string()).default([])})).default([])}),He=z.object({framework:va(["express","apollo","both"]),language:va(["typescript","javascript"]).default("typescript"),database:z.string().default("mongodb"),services:z.array(Aa).default([]),middleware:z.array(Ea).default([]),routes:z.array(Oa).default([]),folderStructure:z.array(z.string()).default([]),envVars:z.array(z.string()).default([]),notes:z.string().default("")});var un=`You are a senior backend architect specializing in Node.js server design.
1379
+
1380
+ You analyze data models, API designs, and auth requirements to produce enterprise-quality backend architectures with:
1381
+ - Framework selection (Express REST, Apollo GraphQL, or both)
1382
+ - Service layer design with clear operation contracts per entity
1383
+ - Middleware stack (auth, validation, error handling, CORS, rate limiting)
1384
+ - Route/resolver organization grouped by resource
1385
+ - Folder structure following domain-driven conventions
1386
+ - Environment variable inventory
1387
+ - Database connection and ORM/ODM strategy
1388
+
1389
+ When "both" is selected (Express + Apollo), use the Apollo Gateway pattern:
1390
+ - Apollo Gateway as the single public entry point for GraphQL queries
1391
+ - Subgraphs as internal services composed via IntrospectAndCompose
1392
+ - RemoteGraphQLDataSource for header forwarding (auth tokens, service tokens)
1393
+ - Express for webhooks, file uploads, and health checks only
1394
+ - Gateway has no business logic, all logic lives in subgraphs
1395
+
1396
+ Output only valid JSON unless instructed otherwise.`;var Ma=`## Requirements:
1397
+ {requirement}
1398
+
1399
+ Design the backend architecture. Include:
1400
+
1401
+ 1. Framework: choose "express" (REST API), "apollo" (GraphQL subgraph), or "both" (Apollo subgraph + Express gateway).
1402
+ 2. Services: one per entity with CRUD operations and dependencies.
1403
+ 3. Middleware: auth (JWT/session), validation (Zod/Joi), error handling, CORS, rate limiting.
1404
+ 4. Routes (if Express): RESTful routes grouped by resource with method, path, handler, auth, and roles.
1405
+ 5. Folder structure: list of directories and key files.
1406
+ 6. Env vars: list all required environment variables.
1407
+
1408
+ Return ONLY valid JSON:
1409
+ {
1410
+ "framework": "express" | "apollo" | "both",
1411
+ "language": "typescript",
1412
+ "database": "mongodb",
1413
+ "services": [{ "name": "UserService", "entity": "User", "operations": ["create", "findById", "findAll", "update", "delete"], "dependencies": [] }],
1414
+ "middleware": [{ "name": "authMiddleware", "purpose": "JWT token verification", "appliesTo": "global", "config": {} }],
1415
+ "routes": [{ "resource": "users", "basePath": "/api/users", "endpoints": [{ "method": "GET", "path": "/", "handler": "getAll", "auth": true, "roles": ["admin"] }] }],
1416
+ "folderStructure": ["src/", "src/routes/", "src/services/", "src/middleware/", "src/models/", "src/config/"],
1417
+ "envVars": ["PORT", "DATABASE_URL", "JWT_SECRET"],
1418
+ "notes": ""
1419
+ }`;function mn(t){return Ma.replace("{requirement}",t)}var ir=u({name:"validate_backend",description:"Validates a backend design JSON string against the BackendDesign schema. Returns valid: true or valid: false with errors.",input:z.object({design:z.string().describe("JSON string of the backend design to validate")}),handler:async({design:t})=>{try{let e=JSON.parse(t);return He.parse(e),{valid:!0}}catch(e){return e instanceof z.ZodError?{valid:false,errors:e.issues.map(r=>`${r.path.join(".")}: ${r.message}`)}:e instanceof SyntaxError?{valid:false,errors:[`Invalid JSON: ${e.message}`]}:{valid:false,errors:[String(e)]}}}});function lr(t){return u({name:"design_backend",description:"Generate a complete backend architecture design from requirements. Returns framework, services, middleware, routes, and folder structure as JSON.",input:z.object({requirement:z.string().describe("Data model, API design, and project requirements")}),handler:async({requirement:e})=>{let r=mn(e),o=[{role:"system",content:"You are a backend architect. Return only valid JSON."},{role:"user",content:r}],n=await t.invoke(o,{temperature:.3,maxOutputTokens:16384});return M(n.text,He)}})}function fn(t){return {validate_backend:ir,design_backend:lr(t)}}var Jl=`You are a backend service architect. Given a data model and API design, you plan the service layer.
1420
+
1421
+ ## Service Design
1422
+ For each entity:
1423
+ - Service name (PascalCase + "Service")
1424
+ - CRUD operations: create, findById, findAll, update, delete
1425
+ - Custom operations from user flows (e.g. searchByName, bulkImport)
1426
+ - Dependencies on other services (e.g. OrderService depends on UserService)
1427
+
1428
+ ## Middleware Stack
1429
+ - Authentication middleware: JWT verification, session check
1430
+ - Authorization middleware: role-based access, resource ownership
1431
+ - Validation middleware: request body/params validation
1432
+ - Error handling: centralized error handler with typed errors
1433
+ - Logging: request/response logging
1434
+ - Rate limiting: per-IP or per-user limits
1435
+ - CORS: origin whitelist
1436
+
1437
+ ## Folder Structure
1438
+ Recommend a clean folder layout:
1439
+ - src/services/ (one file per service)
1440
+ - src/middleware/ (one file per middleware)
1441
+ - src/models/ (one file per entity)
1442
+ - src/routes/ or src/modules/ (grouped by resource)
1443
+ - src/config/ (env, database, auth config)
1444
+ - src/utils/ (shared helpers)
1445
+
1446
+ Respond with structured analysis. Do NOT return JSON.`,cr=f({name:"service-planner",description:"Plans service layer, middleware stack, and folder structure for a backend project. Use before generating the backend design.",systemPrompt:Jl,tools:{},maxIterations:2});var Bl=`You are a backend technology advisor. Given project requirements, you recommend the best backend framework.
1447
+
1448
+ ## Decision Criteria
1449
+
1450
+ ### Choose "express" (REST API) when:
1451
+ - The API is primarily CRUD with RESTful resources
1452
+ - The frontend is a traditional SPA (React/Vue) consuming REST
1453
+ - Simple request/response patterns without complex data fetching
1454
+ - No need for real-time subscriptions
1455
+ - Team is more familiar with REST
1456
+
1457
+ ### Choose "apollo" (GraphQL subgraph) when:
1458
+ - The frontend needs flexible data fetching (avoid over/under-fetching)
1459
+ - Multiple frontends consume the same API (web, mobile, admin)
1460
+ - Complex nested data relationships
1461
+ - Need for real-time subscriptions
1462
+ - Part of a federated GraphQL architecture
1463
+
1464
+ ### Choose "both" when:
1465
+ - Apollo subgraph for main data API + Express for webhooks, file uploads, health checks
1466
+ - Need both REST endpoints (for external integrations) and GraphQL (for frontend)
1467
+ - When "both" is selected, an Apollo Gateway is used to compose subgraphs into a unified API:
1468
+ - Gateway is the only public entry point for GraphQL
1469
+ - Subgraphs are internal services, not exposed to clients directly
1470
+ - Gateway uses IntrospectAndCompose for schema discovery
1471
+ - RemoteGraphQLDataSource forwards auth headers to subgraphs
1472
+ - Express handles non-GraphQL concerns (webhooks, file uploads)
1473
+
1474
+ ## Output Format
1475
+ State your recommendation clearly:
1476
+ - Framework: express | apollo | both
1477
+ - Reasoning: 2-3 sentences explaining why
1478
+ - Trade-offs: what you'd lose with the alternative
1479
+ - If "both": describe which concerns go to Express vs Apollo Gateway vs subgraphs
1480
+
1481
+ Respond with structured analysis. Do NOT return JSON.`,pr=f({name:"framework-selector",description:"Analyzes project requirements and recommends Express, Apollo, or both. Use to determine the backend framework before designing.",systemPrompt:Bl,tools:{},maxIterations:2});var zl=`${un}
1482
+
1483
+ You are the backend architecture orchestrator. When the user provides requirements:
1484
+
1485
+ 1. **Select framework**: Use subagent_framework-selector to analyze requirements and recommend Express, Apollo, or both.
1486
+ 2. **Plan services**: Use subagent_service-planner to design the service layer, middleware stack, and folder structure.
1487
+ 3. **Generate design**: Use design_backend to produce the complete backend architecture as JSON.
1488
+ 4. **Validate**: Use validate_backend to check the final design JSON before returning.
1489
+
1490
+ After generating the design, note the "framework" field in the result:
1491
+ - If "express": the downstream express-builder should be used to scaffold the project.
1492
+ - If "apollo": the downstream apollo-builder should be used to scaffold the project.
1493
+ - If "both": both builders should be invoked sequentially.
1494
+
1495
+ Respond with the final backend design as JSON.`;async function Yl(t){let{input:e,model:r,maxIterations:o=15,onStep:n,logger:a}=t,s=E(r??{provider:"openai",model:"gpt-4o-mini"}),i=fn(s),l=q([cr,pr],{parentModel:s}),p={...i,...l};return D({model:s,tools:p,systemPrompt:zl,input:e,maxIterations:o,onStep:n,logger:a})}var Da=t=>z.string().transform(e=>e.toLowerCase().trim()).pipe(z.enum(t)),hn=z.object({name:z.string(),type:z.string(),nullable:z.coerce.boolean().default(false),isList:z.coerce.boolean().default(false),description:z.string().default("")}),yn=z.object({name:z.string(),kind:Da(["type","input","enum","interface","union"]),fields:z.array(hn).default([]),values:z.array(z.string()).default([]),description:z.string().default(""),isEntity:z.coerce.boolean().default(false),keyFields:z.array(z.string()).default([])}),Na=z.object({name:z.string(),type:Da(["query","mutation","subscription"]),args:z.array(hn).default([]),returnType:z.string(),auth:z.coerce.boolean().default(true),roles:z.array(z.string()).default([]),description:z.string().default("")}),Ia=z.object({name:z.string(),entity:z.string(),types:z.array(yn).default([]),operations:z.array(Na).default([]),datasource:z.string().default(""),loader:z.string().default("")}),Qe=z.object({appName:z.string().default("app"),port:z.number().default(4e3),database:z.string().default("mongodb"),modules:z.array(Ia).default([]),sharedTypes:z.array(yn).default([]),authDirective:z.coerce.boolean().default(true),cacheDirective:z.coerce.boolean().default(false),envVars:z.array(z.string()).default([])});var Sn=`You are an expert Apollo GraphQL subgraph architect using Apollo Federation v2.
1496
+
1497
+ You generate production-ready Apollo subgraph configurations from data models and API designs:
1498
+ - 4-file module pattern per entity: {module}.graphql, {module}.resolver.ts, {module}.datasource.ts, {module}.loader.ts
1499
+ - GraphQL type definitions with proper nullability, lists, and descriptions
1500
+ - Input types for mutations with validation annotations
1501
+ - Enum types from domain values
1502
+ - Federation directives: @key for entity references, @external for fields owned by other subgraphs, @requires for field dependencies, @provides for fields resolvable by this subgraph
1503
+ - __resolveReference for cross-subgraph entity resolution via buildSubgraphSchema
1504
+ - DataLoader per module for batching and caching database lookups (solves N+1)
1505
+ - Query and mutation resolvers with auth/role requirements
1506
+ - Datasource classes per entity (MongoDB datasource pattern)
1507
+ - Auth directive (@auth) configuration
1508
+ - Redis cache directives: @cacheSet on queries, @cachePurge on mutations
1509
+ - GraphQL CodeGen for TypeScript types (generates base-types.ts)
1510
+ - Module-based organization (one module per entity/domain)
1511
+
1512
+ Output only valid JSON unless instructed otherwise.`;var ka=`## Requirements:
1513
+ {requirement}
1514
+
1515
+ Generate an Apollo GraphQL subgraph configuration (Federation v2). Include:
1516
+
1517
+ 1. Modules: one per entity with 4 files each ({module}.graphql, {module}.resolver.ts, {module}.datasource.ts, {module}.loader.ts).
1518
+ 2. Types: GraphQL object types with isEntity/keyFields for federation, input types, enums with fields/values.
1519
+ 3. Operations: queries (getById, getAll, search) and mutations (create, update, delete) per module.
1520
+ 4. Auth: mark which operations require authentication and which roles.
1521
+ 5. DataLoader: one loader per module for batching lookups (loader name).
1522
+ 6. Shared types: types used across modules (e.g. Pagination, SortOrder).
1523
+ 7. Cache: set cacheDirective to true if Redis caching (@cacheSet/@cachePurge) is needed.
1524
+ 8. Env vars: PORT, DATABASE_URL, JWT_SECRET, REDIS_URL, etc.
1525
+
1526
+ Return ONLY valid JSON:
1527
+ {
1528
+ "appName": "my-subgraph",
1529
+ "port": 4000,
1530
+ "database": "mongodb",
1531
+ "modules": [{
1532
+ "name": "user",
1533
+ "entity": "User",
1534
+ "types": [{ "name": "User", "kind": "type", "fields": [{ "name": "id", "type": "ID", "nullable": false }], "isEntity": true, "keyFields": ["id"] }],
1535
+ "operations": [{ "name": "getUser", "type": "query", "args": [{ "name": "id", "type": "ID", "nullable": false }], "returnType": "User", "auth": true, "roles": [] }],
1536
+ "datasource": "UserDataSource",
1537
+ "loader": "UserLoader"
1538
+ }],
1539
+ "sharedTypes": [],
1540
+ "authDirective": true,
1541
+ "cacheDirective": false,
1542
+ "envVars": ["PORT", "DATABASE_URL", "JWT_SECRET", "REDIS_URL"]
1543
+ }`;function bn(t){return ka.replace("{requirement}",t)}var dr=u({name:"validate_subgraph",description:"Validates a subgraph config JSON string against the SubgraphConfig schema. Returns valid: true or valid: false with errors.",input:z.object({config:z.string().describe("JSON string of the subgraph config to validate")}),handler:async({config:t})=>{try{let e=JSON.parse(t);return Qe.parse(e),{valid:!0}}catch(e){return e instanceof z.ZodError?{valid:false,errors:e.issues.map(r=>`${r.path.join(".")}: ${r.message}`)}:e instanceof SyntaxError?{valid:false,errors:[`Invalid JSON: ${e.message}`]}:{valid:false,errors:[String(e)]}}}});function ur(t){return u({name:"generate_subgraph",description:"Generate a complete Apollo GraphQL subgraph configuration from data model and API design. Returns modules, types, operations, and datasources as JSON.",input:z.object({requirement:z.string().describe("Data model, API design, and project requirements")}),handler:async({requirement:e})=>{let r=bn(e),o=[{role:"system",content:"You are an Apollo GraphQL architect. Return only valid JSON."},{role:"user",content:r}],n=await t.invoke(o,{temperature:.3,maxOutputTokens:16384});return M(n.text,Qe)}})}function $l(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 mr=u({name:"scaffold_subgraph",description:"Scaffold an Apollo GraphQL subgraph project from a validated config. Compiles Handlebars templates and writes the project to the output directory.",input:z.object({config:z.string().describe("JSON string of the validated subgraph config"),outputDir:z.string().describe("Absolute path to the output directory")}),handler:async({config:t,outputDir:e})=>{let r=Se(t,"subgraph config"),o=xe.resolve(process.cwd(),".ref/templates/subgraph"),n=$l(r);return le({templateDir:o,outputDir:e,context:n})}});function Pn(t){return {validate_subgraph:dr,generate_subgraph:ur(t),scaffold_subgraph:mr}}var Hl=`You are a GraphQL schema specialist for Apollo Federation v2 subgraphs. Given a data model, you generate GraphQL type definitions using buildSubgraphSchema.
1544
+
1545
+ ## Type Generation
1546
+ For each entity in the data model:
1547
+ - Create the main object type with all fields mapped to GraphQL scalars (String, Int, Float, Boolean, ID)
1548
+ - Create input types for create and update mutations (omit auto-generated fields like id, createdAt)
1549
+ - Create enum types for status fields and role fields
1550
+ - Add proper nullability (! for required fields)
1551
+ - Add [Type] for array/list fields
1552
+
1553
+ ## Federation Directives
1554
+ - @key(fields: "id") on entity types that can be referenced across subgraphs
1555
+ - @external marks a field as owned by another subgraph
1556
+ - @requires(fields: "weight") declares fields needed from the entity to resolve a field
1557
+ - @provides(fields: "name") declares fields on a return type that this subgraph can resolve
1558
+ - @auth directive on types/fields that require authentication
1559
+
1560
+ ## Cache Directives (Redis)
1561
+ - @cacheSet(type: "Entity", identifier: "_id") on query resolvers
1562
+ - @cachePurge(type: "Entity", identifier: "_id") on mutation resolvers
1563
+
1564
+ ## Relationships
1565
+ - Reference types for foreign keys (e.g. author: User instead of authorId: ID)
1566
+ - Use [Type] for one-to-many relationships
1567
+
1568
+ ## Naming Conventions
1569
+ - Types: PascalCase (User, BlogPost)
1570
+ - Fields: camelCase (firstName, createdAt)
1571
+ - Inputs: PascalCase + Input suffix (CreateUserInput, UpdateUserInput)
1572
+ - Enums: SCREAMING_SNAKE_CASE values (ADMIN, ACTIVE)
1573
+
1574
+ Respond with the full GraphQL SDL. Do NOT return JSON.`,gr=f({name:"schema-generator",description:"Generates GraphQL type definitions, input types, and enums from a data model. Use before generating the subgraph config.",systemPrompt:Hl,tools:{},maxIterations:2});var Ql=`You are a GraphQL resolver architect for Apollo Federation v2 subgraphs. Given types and operations, you plan resolver implementations.
1575
+
1576
+ ## 4-File Module Pattern
1577
+ Each module has four files:
1578
+ - {module}.graphql -- Type definitions with federation directives
1579
+ - {module}.resolver.ts -- Query/Mutation/Field resolvers including __resolveReference
1580
+ - {module}.datasource.ts -- Business logic and database access
1581
+ - {module}.loader.ts -- DataLoader for batching and caching lookups
1582
+
1583
+ ## Resolver Planning
1584
+ For each module/entity:
1585
+
1586
+ ### __resolveReference (Federation)
1587
+ - Every entity type with @key must implement __resolveReference
1588
+ - Called by the gateway when another subgraph references this entity
1589
+ - Receives { __typename, id } and returns the full entity from datasource
1590
+
1591
+ ### Query Resolvers
1592
+ - getById: fetch single record by ID from datasource
1593
+ - getAll: fetch paginated list with filters and sorting
1594
+ - search: text search across relevant fields
1595
+
1596
+ ### Mutation Resolvers
1597
+ - create: validate input, create record, return created entity
1598
+ - update: validate input, find existing, merge changes, return updated entity
1599
+ - delete: find existing, remove, return success status
1600
+
1601
+ ### Field Resolvers
1602
+ - For relationship fields: resolve references via DataLoader (NOT direct DB calls)
1603
+ - For computed fields: calculate from existing data
1604
+
1605
+ ## DataLoader Pattern
1606
+ Each module has a loader file that creates DataLoader instances:
1607
+ - Batches multiple lookups into a single database query
1608
+ - Caches results within a single request to solve the N+1 problem
1609
+ - Created per-request in the context, not shared across requests
1610
+
1611
+ ## Datasource Pattern
1612
+ - Each module has a datasource class extending MongoDataSource or similar
1613
+ - Datasource handles all database operations
1614
+ - Resolvers call datasource methods, never touch the DB directly
1615
+
1616
+ ## Auth Integration
1617
+ - Check auth context in resolver before executing
1618
+ - Verify role permissions per operation
1619
+ - Resource ownership checks for user-specific data
1620
+
1621
+ Respond with structured analysis per module. Do NOT return JSON.`,fr=f({name:"resolver-planner",description:"Plans resolver implementations, datasource methods, and auth integration per GraphQL module. Use after schema generation.",systemPrompt:Ql,tools:{},maxIterations:2});var Vl=`${Sn}
1622
+
1623
+ You are the Apollo subgraph builder orchestrator. When the user provides requirements:
1624
+
1625
+ 1. **Generate schema**: Use subagent_schema-generator to create GraphQL type definitions from the data model.
1626
+ 2. **Plan resolvers**: Use subagent_resolver-planner to design resolver implementations per module.
1627
+ 3. **Generate config**: Use generate_subgraph to produce the complete subgraph configuration as JSON.
1628
+ 4. **Validate**: Use validate_subgraph to check the config JSON before returning.
1629
+ 5. **Scaffold (optional)**: If an output directory is provided, use scaffold_subgraph to compile templates.
1630
+
1631
+ Respond with the final subgraph config as JSON.`;async function Wl(t){let{input:e,model:r,maxIterations:o=15,onStep:n,logger:a}=t,s=E(r??{provider:"openai",model:"gpt-4o-mini"}),i=Pn(s),l=q([gr,fr],{parentModel:s}),p={...i,...l};return D({model:s,tools:p,systemPrompt:Vl,input:e,maxIterations:o,onStep:n,logger:a})}var Kl=z.string().transform(t=>t.toUpperCase().trim()).pipe(z.enum(["GET","POST","PUT","PATCH","DELETE"])),qa=z.object({name:z.string(),httpMethod:Kl,path:z.string(),auth:z.coerce.boolean().default(true),roles:z.array(z.string()).default([]),validation:z.string().default(""),description:z.string().default("")}),Ua=z.object({name:z.string(),resource:z.string(),basePath:z.string(),methods:z.array(qa).default([])}),La=z.object({name:z.string(),type:z.string(),required:z.coerce.boolean().default(false),unique:z.coerce.boolean().default(false),ref:z.string().optional(),default:z.string().optional()}),Fa=z.object({name:z.string(),collection:z.string(),fields:z.array(La).default([]),timestamps:z.coerce.boolean().default(true),indexes:z.array(z.string()).default([])}),Ga=z.object({name:z.string(),type: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(z.enum(["auth","validation","errorHandler","cors","rateLimit","logging","custom"])),config:z.record(z.string(),z.unknown()).default({})}),Ve=z.object({appName:z.string().default("app"),port:z.number().default(3e3),database:z.string().default("mongodb"),routers:z.array(Ua).default([]),models:z.array(Fa).default([]),middleware:z.array(Ga).default([]),envVars:z.array(z.string()).default([])});var Rn=`You are an expert Express.js backend architect.
1632
+
1633
+ You generate production-ready Express application configurations from data models and API designs:
1634
+ - Co-located router pattern: each feature lives in src/routers/{name}/ with {name}.controller.ts, {name}.router.ts, and {name}.spec.ts
1635
+ - Mongoose/Prisma models with field types, validation, and relationships
1636
+ - Middleware stack (auth JWT, validation Zod, error handler, CORS, rate limiting)
1637
+ - Route organization with proper HTTP methods and paths
1638
+ - Health check endpoint at /health (included by default)
1639
+ - Jest tests per router using supertest
1640
+ - Environment variable inventory
1641
+
1642
+ Output only valid JSON unless instructed otherwise.`;var Ja=`## Requirements:
1643
+ {requirement}
1644
+
1645
+ Generate an Express.js application configuration. Include:
1646
+
1647
+ 1. Routers: one per resource, co-located with controller and test spec. Each router has RESTful methods (GET, POST, PUT, DELETE).
1648
+ 2. Health check: a default /health router is always included.
1649
+ 3. Models: Mongoose models with fields, types, required, unique, refs, defaults, indexes.
1650
+ 4. Middleware: auth (JWT), validation (Zod), error handler, CORS, rate limiting, logging.
1651
+ 5. Env vars: PORT, DATABASE_URL, JWT_SECRET, NODE_ENV, etc.
1652
+ 6. Folder structure: src/routers/{name}/ with {name}.controller.ts, {name}.router.ts, {name}.spec.ts per feature.
1653
+
1654
+ Return ONLY valid JSON:
1655
+ {
1656
+ "appName": "my-api",
1657
+ "port": 3000,
1658
+ "database": "mongodb",
1659
+ "routers": [{
1660
+ "name": "users",
1661
+ "resource": "users",
1662
+ "basePath": "/api/users",
1663
+ "methods": [{
1664
+ "name": "getAll",
1665
+ "httpMethod": "GET",
1666
+ "path": "/",
1667
+ "auth": true,
1668
+ "roles": ["admin"],
1669
+ "validation": "",
1670
+ "description": "Get all users with pagination"
1671
+ }]
1672
+ }],
1673
+ "models": [{
1674
+ "name": "User",
1675
+ "collection": "users",
1676
+ "fields": [{ "name": "email", "type": "String", "required": true, "unique": true }],
1677
+ "timestamps": true,
1678
+ "indexes": ["email"]
1679
+ }],
1680
+ "middleware": [{ "name": "authMiddleware", "type": "auth", "config": {} }],
1681
+ "envVars": ["PORT", "DATABASE_URL", "JWT_SECRET", "NODE_ENV"]
1682
+ }`;function wn(t){return Ja.replace("{requirement}",t)}var hr=u({name:"validate_express",description:"Validates an Express config JSON string against the ExpressConfig schema. Returns valid: true or valid: false with errors.",input:z.object({config:z.string().describe("JSON string of the Express config to validate")}),handler:async({config:t})=>{try{let e=JSON.parse(t);return Ve.parse(e),{valid:!0}}catch(e){return e instanceof z.ZodError?{valid:false,errors:e.issues.map(r=>`${r.path.join(".")}: ${r.message}`)}:e instanceof SyntaxError?{valid:false,errors:[`Invalid JSON: ${e.message}`]}:{valid:false,errors:[String(e)]}}}});function yr(t){return u({name:"generate_express",description:"Generate a complete Express.js application configuration from data model and API design. Returns routers, models, middleware, and env vars as JSON.",input:z.object({requirement:z.string().describe("Data model, API design, and project requirements")}),handler:async({requirement:e})=>{let r=wn(e),o=[{role:"system",content:"You are an Express.js architect. Return only valid JSON."},{role:"user",content:r}],n=await t.invoke(o,{temperature:.3,maxOutputTokens:16384});return M(n.text,Ve)}})}function Xl(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 Sr=u({name:"scaffold_express",description:"Scaffold an Express.js project from a validated config. Compiles Handlebars templates and writes the project to the output directory.",input:z.object({config:z.string().describe("JSON string of the validated Express config"),outputDir:z.string().describe("Absolute path to the output directory")}),handler:async({config:t,outputDir:e})=>{let r=Se(t,"express config"),o=xe.resolve(process.cwd(),".ref/templates/express"),n=Xl(r);return le({templateDir:o,outputDir:e,context:n})}});function An(t){return {validate_express:hr,generate_express:yr(t),scaffold_express:Sr}}var Zl=`You are an Express.js route specialist. Given an API design, you generate route definitions using a co-located router pattern.
1683
+
1684
+ ## Co-located Router Pattern
1685
+ Each feature lives in src/routers/{name}/ with three files:
1686
+ - {name}.router.ts -- Express Router with route definitions
1687
+ - {name}.controller.ts -- Request handler logic
1688
+ - {name}.spec.ts -- Jest tests using supertest
1689
+
1690
+ ## Route Design
1691
+ For each resource:
1692
+ - Base path: /api/{resource} (pluralized, lowercase)
1693
+ - GET / -> list all (with pagination: page, limit, sort query params)
1694
+ - GET /:id -> get by ID
1695
+ - POST / -> create new
1696
+ - PUT /:id -> update by ID
1697
+ - DELETE /:id -> delete by ID
1698
+ - Custom routes for non-CRUD operations
1699
+
1700
+ ## Health Check
1701
+ Every app includes a /health router in src/routers/health/:
1702
+ - health.router.ts -- GET /health returning server status
1703
+ - health.controller.ts -- Health check handler
1704
+ - health.spec.ts -- Health check tests
1705
+
1706
+ ## Route Organization
1707
+ - One router directory per resource with co-located controller and spec
1708
+ - Central src/routers/index.ts mounts all routers
1709
+ - Middleware applied per-route or per-router
1710
+
1711
+ ## Controller Mapping
1712
+ - Each route maps to a controller method in the co-located controller file
1713
+ - Controller method name follows convention: getAll, getById, create, update, delete
1714
+
1715
+ ## Validation
1716
+ - Request body validation using Zod schemas
1717
+ - Param validation (e.g. valid ObjectId)
1718
+ - Query param parsing and defaults
1719
+
1720
+ Respond with structured route definitions. Do NOT return JSON.`,br=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:Zl,tools:{},maxIterations:2});var ec=`You are an Express.js middleware specialist. You design the complete middleware stack.
1721
+
1722
+ ## Core Middleware
1723
+ 1. **CORS**: Configure allowed origins, methods, headers, credentials
1724
+ 2. **Body parser**: JSON and URL-encoded body parsing with size limits
1725
+ 3. **Helmet**: Security headers (CSP, HSTS, X-Frame-Options)
1726
+ 4. **Morgan/Logger**: Request logging with format and stream
1727
+
1728
+ ## Auth Middleware
1729
+ 1. **JWT verification**: Extract token from Authorization header or cookie
1730
+ 2. **Role check**: Verify user role against required roles
1731
+ 3. **Resource ownership**: Check if user owns the resource they're accessing
1732
+
1733
+ ## Validation Middleware
1734
+ 1. **Request validation**: Validate body, params, query using Zod schemas
1735
+ 2. **Sanitization**: Strip HTML, trim whitespace
1736
+
1737
+ ## Error Handling
1738
+ 1. **Not found handler**: 404 for unmatched routes
1739
+ 2. **Error handler**: Centralized error response with status codes
1740
+ 3. **Async wrapper**: Catch async errors without try-catch
1741
+
1742
+ ## Rate Limiting
1743
+ 1. **Global**: Limit requests per IP per time window
1744
+ 2. **Auth routes**: Stricter limits on login/signup
1745
+
1746
+ Respond with structured middleware analysis. Do NOT return JSON.`,xr=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:ec,tools:{},maxIterations:2});var tc=`${Rn}
1747
+
1748
+ You are the Express builder orchestrator. When the user provides requirements:
1749
+
1750
+ 1. **Generate routes**: Use subagent_route-generator to design route definitions from the API design.
1751
+ 2. **Configure middleware**: Use subagent_middleware-configurator to design the middleware stack.
1752
+ 3. **Generate config**: Use generate_express to produce the complete Express configuration as JSON.
1753
+ 4. **Validate**: Use validate_express to check the config JSON before returning.
1754
+ 5. **Scaffold (optional)**: If an output directory is provided, use scaffold_express to compile templates.
1755
+
1756
+ Respond with the final Express config as JSON.`;async function rc(t){let{input:e,model:r,maxIterations:o=15,onStep:n,logger:a}=t,s=E(r??{provider:"openai",model:"gpt-4o-mini"}),i=An(s),l=q([br,xr],{parentModel:s}),p={...i,...l};return D({model:s,tools:p,systemPrompt:tc,input:e,maxIterations:o,onStep:n,logger:a})}var Ya=t=>z.string().transform(e=>e.toLowerCase().trim()).pipe(z.enum(t)),oc=z.string().transform(t=>t.toUpperCase().trim()).pipe(z.enum(["GET","POST","PUT","PATCH","DELETE"])),$a=z.object({path:z.string(),name:z.string(),access:Ya(["public","protected"]),routeGroup:z.string().default(""),purpose:z.string(),hasForm:z.coerce.boolean().default(false),formFields:z.array(z.string()).default([]),dataFetching:Ya(["server","client","hybrid"]).default("server"),actions:z.array(z.string()).default([])}),Ha=z.object({name:z.string(),path:z.string(),routeGroup:z.string().default(""),components:z.array(z.string()).default([]),purpose:z.string()}),Qa=z.object({path:z.string(),methods:z.array(oc).default([]),auth:z.coerce.boolean().default(true),description:z.string()}),Va=z.object({name:z.string(),module:z.string(),description:z.string(),revalidates:z.array(z.string()).default([])}),We=z.object({appName:z.string().default("app"),pages:z.array($a).default([]),layouts:z.array(Ha).default([]),apiRoutes:z.array(Qa).default([]),serverActions:z.array(Va).default([]),middleware:z.array(z.string()).default([]),envVars:z.array(z.string()).default([]),packages:z.array(z.string()).default([])});var On=`You are an expert Next.js application architect using the App Router.
1757
+
1758
+ You generate production-ready Next.js configurations from frontend designs and API designs:
1759
+ - App Router file structure with route groups, layouts, pages, loading, and error boundaries
1760
+ - Server Components by default, Client Components only when interactivity is needed
1761
+ - Server Actions for mutations (form submissions, data writes)
1762
+ - API Route Handlers for external integrations, webhooks, and file uploads
1763
+ - Next.js middleware for auth guards and redirects
1764
+ - Data fetching strategy (server vs client vs hybrid per page)
1765
+ - Package recommendations (next-auth, prisma, tailwindcss, shadcn/ui)
1766
+
1767
+ Output only valid JSON unless instructed otherwise.`;var Wa=`## Requirements:
1768
+ {requirement}
1769
+
1770
+ Generate a Next.js App Router application configuration. Include:
1771
+
1772
+ 1. Pages: app router pages with path, name, access level, route group, purpose, data fetching strategy.
1773
+ 2. Layouts: shared layouts with route groups (e.g. (auth), (dashboard)), components they include.
1774
+ 3. API Routes: route handlers with path, HTTP methods, auth requirement, description.
1775
+ 4. Server Actions: named actions with module, description, and paths they revalidate.
1776
+ 5. Middleware: list of middleware behaviors (e.g. "redirect unauthenticated to /login").
1777
+ 6. Env vars: NEXTAUTH_SECRET, DATABASE_URL, etc.
1778
+ 7. Packages: recommended npm packages.
1779
+
1780
+ Return ONLY valid JSON:
1781
+ {
1782
+ "appName": "my-app",
1783
+ "pages": [{
1784
+ "path": "/dashboard",
1785
+ "name": "Dashboard",
1786
+ "access": "protected",
1787
+ "routeGroup": "(dashboard)",
1788
+ "purpose": "Main dashboard with stats",
1789
+ "hasForm": false,
1790
+ "formFields": [],
1791
+ "dataFetching": "server",
1792
+ "actions": []
1793
+ }],
1794
+ "layouts": [{
1795
+ "name": "DashboardLayout",
1796
+ "path": "app/(dashboard)/layout.tsx",
1797
+ "routeGroup": "(dashboard)",
1798
+ "components": ["Sidebar", "Header"],
1799
+ "purpose": "Shared layout for authenticated pages"
1800
+ }],
1801
+ "apiRoutes": [{
1802
+ "path": "/api/users",
1803
+ "methods": ["GET", "POST"],
1804
+ "auth": true,
1805
+ "description": "User CRUD endpoints"
1806
+ }],
1807
+ "serverActions": [{
1808
+ "name": "createUser",
1809
+ "module": "users",
1810
+ "description": "Create a new user",
1811
+ "revalidates": ["/dashboard/users"]
1812
+ }],
1813
+ "middleware": ["Redirect unauthenticated users to /login"],
1814
+ "envVars": ["DATABASE_URL", "NEXTAUTH_SECRET"],
1815
+ "packages": ["next-auth", "prisma", "@prisma/client", "tailwindcss"]
1816
+ }`;function Mn(t){return Wa.replace("{requirement}",t)}var Tr=u({name:"validate_nextjs",description:"Validates a Next.js config JSON string against the NextjsConfig schema. Returns valid: true or valid: false with errors.",input:z.object({config:z.string().describe("JSON string of the Next.js config to validate")}),handler:async({config:t})=>{try{let e=JSON.parse(t);return We.parse(e),{valid:!0}}catch(e){return e instanceof z.ZodError?{valid:false,errors:e.issues.map(r=>`${r.path.join(".")}: ${r.message}`)}:e instanceof SyntaxError?{valid:false,errors:[`Invalid JSON: ${e.message}`]}:{valid:false,errors:[String(e)]}}}});function Pr(t){return u({name:"generate_nextjs",description:"Generate a complete Next.js App Router configuration from frontend design and requirements. Returns pages, layouts, API routes, server actions, and middleware as JSON.",input:z.object({requirement:z.string().describe("Frontend design, API design, and project requirements")}),handler:async({requirement:e})=>{let r=Mn(e),o=[{role:"system",content:"You are a Next.js architect. Return only valid JSON."},{role:"user",content:r}],n=await t.invoke(o,{temperature:.3,maxOutputTokens:16384});return M(n.text,We)}})}function Dn(t){return {validate_nextjs:Tr,generate_nextjs:Pr(t)}}var nc=`You are a Next.js App Router specialist. Given page specs, you plan the file structure.
1817
+
1818
+ ## Route Groups
1819
+ - (auth) for public auth pages: login, signup, forgot-password
1820
+ - (dashboard) or (app) for protected pages
1821
+ - (marketing) for public landing pages
1822
+
1823
+ ## File Structure Per Route
1824
+ - page.tsx: the page component (Server Component by default)
1825
+ - layout.tsx: shared layout for the route group
1826
+ - loading.tsx: Suspense fallback
1827
+ - error.tsx: error boundary (must be Client Component)
1828
+ - not-found.tsx: 404 page
1829
+
1830
+ ## Data Fetching
1831
+ - Server Components: fetch data directly in the component (async function)
1832
+ - Client Components: use SWR or React Query for client-side fetching
1833
+ - Server Actions: for form submissions and mutations
1834
+
1835
+ ## Conventions
1836
+ - Use lowercase kebab-case for route segments
1837
+ - Dynamic segments: [id], [slug]
1838
+ - Catch-all: [...slug]
1839
+ - Parallel routes: @modal, @sidebar
1840
+ - Intercepting routes: (.)photo, (..)details
1841
+
1842
+ Respond with the full file tree and route structure. Do NOT return JSON.`,Rr=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:nc,tools:{},maxIterations:2});var sc=`You are a Next.js API specialist. Given an API design, you plan route handlers and server actions.
1843
+
1844
+ ## API Route Handlers (app/api/)
1845
+ For external integrations, webhooks, and file uploads:
1846
+ - One route.ts file per resource: app/api/[resource]/route.ts
1847
+ - Export named functions: GET, POST, PUT, DELETE
1848
+ - Use NextRequest and NextResponse
1849
+ - Add auth checks using next-auth getServerSession
1850
+
1851
+ ## Server Actions (preferred for mutations)
1852
+ For form submissions and data writes:
1853
+ - Define in separate files: app/actions/[module].ts
1854
+ - Use 'use server' directive
1855
+ - Use revalidatePath or revalidateTag after mutations
1856
+ - Return typed results with error handling
1857
+
1858
+ ## When to Use Which
1859
+ - Server Actions: form submissions, data CRUD, anything triggered by user action
1860
+ - API Routes: webhooks from external services, file uploads, OAuth callbacks, public APIs
1861
+
1862
+ ## Auth Integration
1863
+ - API Routes: check session with getServerSession
1864
+ - Server Actions: check session at the start of each action
1865
+ - Middleware: protect route groups with matcher patterns
1866
+
1867
+ Respond with structured analysis per module. Do NOT return JSON.`,wr=f({name:"api-route-generator",description:"Generates Next.js API route handlers and server actions from API design. Use after route planning.",systemPrompt:sc,tools:{},maxIterations:2});var ac=`${On}
1868
+
1869
+ You are the Next.js builder orchestrator. When the user provides requirements:
1870
+
1871
+ 1. **Plan routes**: Use subagent_route-planner to design the App Router file structure with route groups and layouts.
1872
+ 2. **Generate API routes**: Use subagent_api-route-generator to design API route handlers and server actions.
1873
+ 3. **Generate config**: Use generate_nextjs to produce the complete Next.js configuration as JSON.
1874
+ 4. **Validate**: Use validate_nextjs to check the config JSON before returning.
1875
+
1876
+ Respond with the final Next.js config as JSON.`;async function ic(t){let{input:e,model:r,maxIterations:o=15,onStep:n,logger:a}=t,s=E(r??{provider:"openai",model:"gpt-4o-mini"}),i=Dn(s),l=q([Rr,wr],{parentModel:s}),p={...i,...l};return D({model:s,tools:p,systemPrompt:ac,input:e,maxIterations:o,onStep:n,logger:a})}export{Kt as API_DESIGNER_SYSTEM_PROMPT,Sn as APOLLO_BUILDER_SYSTEM_PROMPT,Zo as AUTH_DESIGNER_SYSTEM_PROMPT,Ke as AgentError,$r as ApiResponseTypeSchema,Br as AppConfigSchema,Le as ApplicationSchema,ns as AuthPageApiSchema,ss as AuthPageSchema,un as BACKEND_ARCHITECT_SYSTEM_PROMPT,rt as BaseMcpClient,Jr as BrandingSchema,Ra as CREATE_EXECUTION_PLAN_PROMPT,zr as ColumnSchema,vi as CreateUserInputSchema,$t as DATA_MODELER_SYSTEM_PROMPT,ce as DB_DESIGN_SYSTEM_PROMPT,po as DESIGN_APIS_SYSTEM_PROMPT,ua as DESIGN_AUTH_PROMPT,Ma as DESIGN_BACKEND_PROMPT,co as DESIGN_DATABASE_SYSTEM_PROMPT,Ja as DESIGN_EXPRESS_PROMPT,ya as DESIGN_FRONTEND_PROMPT,Wa as DESIGN_NEXTJS_PROMPT,ka as DESIGN_SUBGRAPH_PROMPT,oo as DISCOVERY_SYSTEM_FRAGMENT,ws as DISCOVERY_USER_PROMPT,Yr as DrawerSchema,cs as EXAMPLE_GRAPHQL_SCHEMA,ps as EXAMPLE_JSON_OUTPUT,ln as EXECUTION_PLANNER_SYSTEM_PROMPT,Rn as EXPRESS_BUILDER_SYSTEM_PROMPT,vs as EXTRACT_ACTORS_PROMPT,Os as EXTRACT_MODULES_PROMPT,on as FRONTEND_ARCHITECT_SYSTEM_PROMPT,rs as FieldOptionsSchema,Ai as ForgotPasswordSchema,pt as FormFieldSchema,Es as GENERATE_FLOWS_PROMPT,As as GENERATE_STORIES_PROMPT,de as LibraryError,os as ListingPageApiSchema,as as ListingPageSchema,Ri as LoginInputSchema,ae as ModelError,is as ModuleSchema,On as NEXTJS_BUILDER_SYSTEM_PROMPT,X as PLANNING_SYSTEM_PROMPT,Hr as PageSchema,Yt as PlanningContextBuilder,dt as REACT_BUILDER_INSTRUCTION,Fe as REACT_BUILDER_SYSTEM_PROMPT,fe as REQUIREMENT_GATHERER_SYSTEM_PROMPT,Nt as RequirementContextBuilder,Oi as ResetPasswordSchema,go as SYNTHESIS_SYSTEM_FRAGMENT,Ms as SYNTHESIS_USER_PROMPT,ls as SpecializationSchema,ye as SubagentError,Q as ToolError,Ei as UpdateUserInputSchema,wi as UserSchema,In as ValidationError,ts as ValidationSchema,Re as actorSchema,ht as actorsResultSchema,pe as adApiDesignSchema,Qo as adGraphqlOperationSchema,Ho as adRestEndpointSchema,Ge as addChatEntry,Pt as advanceStage,ge as apiDesignSchema,wr as apiRouteGeneratorSubagent,ko as assemblePlan,ze as authDesignSchema,la as authFlowSchema,ia as authFlowStepSchema,ca as authMiddlewareSchema,He as backendDesignSchema,cn as buildCreateExecutionPlanPrompt,mo as buildDesignApisPrompt,en as buildDesignAuthPrompt,mn as buildDesignBackendPrompt,uo as buildDesignDatabasePrompt,wn as buildDesignExpressPrompt,nn as buildDesignFrontendPrompt,Mn as buildDesignNextjsPrompt,bn as buildDesignSubgraphPrompt,no as buildDiscoveryPrompt,Vr as buildExampleShotPrompt,so as buildExtractActorsPrompt,lo as buildExtractModulesPrompt,Mi as buildFeedbackPrompt,ao as buildGenerateFlowsPrompt,io as buildGenerateStoriesPrompt,Qr as buildInstructionPrompt,Zn as buildPromptVariables,fo as buildSynthesisPrompt,Ps as chatEntrySchema,Dr as compileTemplate,Lt as componentAnalyzerSubagent,ha as componentDesignSchema,Ne as contractDesignerSubagent,et as createAnthropicModel,Xo as createApiDesignerTools,Pn as createApolloBuilderTools,rn as createAuthDesignerTools,fn as createBackendArchitectTools,ft as createConfigValidatorSubagent,Yo as createDataModelerTools,kr as createDbDesignPrompt,Gr as createDbDesignerTools,er as createDesignApiProTool,Zt as createDesignApiTool,rr as createDesignAuthTool,lr as createDesignBackendTool,at as createDesignDatabaseProTool,st as createDesignDatabaseTool,nr as createDesignFrontendTool,Vt as createDesignSchemaProTool,Qt as createDesignSchemaTool,ar as createExecutionPlanTool,dn as createExecutionPlannerTools,An as createExpressBuilderTools,an as createFrontendArchitectTools,yr as createGenerateExpressTool,mt as createGenerateFeatureBreakdownTool,ut as createGenerateFrontendTool,Pr as createGenerateNextjsTool,ur as createGenerateSubgraphTool,tt as createGoogleModel,ho as createInitialContext,dc as createLogger,E as createModel,Dn as createNextjsBuilderTools,Ze as createOpenAIModel,wl as createPlanningContextBuilder,qr as createProDbDesignPrompt,Zr as createReactBuilderTools,it as createRedesignDatabaseTool,Ur as createRedesignPrompt,Wt as createRefineSchemaTools,Qi as createRequirementContextBuilder,ct as createSchemaRefinerSubagent,Cr as createSubagentTool,q as createSubagentToolSet,j as createToolSet,ms as crudApiSchema,me as databaseDesignSchema,ys as databaseEntitySchema,f as defineSubagent,u as defineTool,Ut as dmCreateSchemaRefinerSubagent,Lo as dmDataEntitySchema,Z as dmDataModelDesignSchema,Oe as dmEntityAnalyzerSubagent,Ht as dmValidateSchemaTool,Ie as edgeCaseAnalyzerSubagent,Ta as edgeCaseSchema,Pl as editPlan,De as endpointAnalyzerSubagent,lt as entityAnalyzerSubagent,gs as entityFieldSchema,fs as entityIndexSchema,hs as entityRelationSchema,Or as executeTool,Xe as executeToolByName,$e as executionPlanSchema,Ve as expressConfigSchema,_r as extractDataEntities,Xa as extractJson,jr as extractRoles,Ee as extractedModuleSchema,ot as fieldSchema,ro as finalRequirementSchema,Ce as flowDesignerSubagent,we as flowSchema,yt as flowsResultSchema,ga as formFieldSchema,Xn as formatTechnicalRequirements,Wn as formatUserFlows,Kn as formatUserStories,Vn as formatUserTypes,pr as frameworkSelectorSubagent,Ye as frontendDesignSchema,qn as getTool,jn as getTools,gt as graphqlAnalyzerSubagent,Ts as graphqlApiDesignSchema,hn as graphqlFieldSchema,to as graphqlOperationSchema,xs as graphqlTypeDefinitionSchema,yn as graphqlTypeSchema,Ir as helloWorldTool,xa as implementationPhaseSchema,uc as loggerConfigFromEnv,yo as mergeStageResult,Ga as middlewareConfigSchema,xr as middlewareConfiguratorSubagent,Ea as middlewareSchema,La as modelFieldSchema,Fa as modelSchema,nt as moduleSchema,bt as modulesResultSchema,Qa as nextjsApiRouteSchema,We as nextjsConfigSchema,Ha as nextjsLayoutSchema,$a as nextjsPageSchema,fa as pageDesignSchema,Me as pagePlannerSubagent,M as parseModelJsonResponse,ba as phaseStepSchema,zt as processPlanningChat,Dt as processRequirementChat,Ae as projectBriefSchema,oe as projectSchema,xt as questionSchema,Nr as registerHelpers,qt as relationshipMapperSubagent,Gi as requirementContextSchema,Rs as requirementSummarySchema,Na as resolverOperationSchema,fr as resolverPlannerSubagent,bs as restApiDesignSchema,Ss as restEndpointSchema,pa as roleDefinitionSchema,br as routeGeneratorSubagent,Oa as routeGroupSchema,Rr as routePlannerSubagent,qa as routerMethodSchema,Ua as routerSchema,D as runAgent,Nl as runApiDesignerAgent,Wl as runApolloBuilderAgent,kl as runAuthDesignerAgent,Yl as runBackendArchitectAgent,Ol as runDataModelerAgent,Pi as runDbDesignerAgent,Fl as runExecutionPlannerAgent,rc as runExpressBuilderAgent,Ul as runFrontendArchitectAgent,yi as runHelloWorldAgent,ic as runNextjsBuilderAgent,Tl as runPlanningAgent,_i as runReactBuilderAgent,$i as runRequirementGathererAgent,Y as runSubagent,Se as safeJsonParse,Sr as scaffoldExpressTool,le as scaffoldProject,mr as scaffoldSubgraphTool,gr as schemaGeneratorSubagent,Ft as securityAnalyzerSubagent,da as securityPolicySchema,Va as serverActionSchema,cr as servicePlannerSubagent,Aa as serviceSchema,St as storiesResultSchema,ve as storySchema,Qe as subgraphConfigSchema,Ia as subgraphModuleSchema,Ar as sumTokenUsage,Pa as testChecklistItemSchema,ke as testingStrategistSubagent,Xt as validateApiTool,tr as validateAuthTool,ir as validateBackendTool,sr as validateExecutionPlanTool,hr as validateExpressTool,Pe as validateFrontendConfigTool,or as validateFrontendTool,Tr as validateNextjsTool,Te as validateSchemaTool,dr as validateSubgraphTool,fl as writePlanToFile};//# sourceMappingURL=index.js.map
487
1877
  //# sourceMappingURL=index.js.map