sweagent 0.0.4 → 0.0.6

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/utils/errors.ts","../src/lib/utils/json-parse.ts","../src/lib/utils/logger.ts","../src/lib/utils/utils.ts","../src/lib/tools/tools.ts","../src/lib/tools/validation-factory.ts","../src/lib/agents/agent-observers.ts","../src/lib/agents/agent.ts","../src/lib/models/providers/base.ts","../src/lib/models/providers/openai.ts","../src/lib/models/providers/anthropic.ts","../src/lib/models/providers/google.ts","../src/lib/models/create-model.ts","../src/lib/subagents/subagent.ts","../src/lib/template-engine/compiler.ts","../src/lib/mcp/transports.ts","../src/lib/mcp/client.ts","../src/modules/planning/context.ts","../src/modules/planning/stages/base.ts","../src/modules/planning/prompts/system.prompt.ts","../src/modules/planning/prompts/discovery.prompt.ts","../src/modules/planning/prompts/requirements.prompt.ts","../src/modules/planning/prompts/design.prompt.ts","../src/modules/planning/prompts/synthesis.prompt.ts","../src/modules/planning/prompts/edit.prompt.ts","../src/modules/planning/stages/discovery.stage.ts","../src/modules/planning/stages/discovery.state.ts","../src/modules/data-modeler/subagents/entity-analyzer.ts","../src/modules/data-modeler/subagents/relationship-mapper.ts","../src/modules/data-modeler/subagents/schema-refiner.ts","../src/modules/frontend-architect/subagents/page-planner.ts","../src/modules/frontend-architect/subagents/component-analyzer.ts","../src/modules/frontend-architect/subagents/framework-selector.ts","../src/modules/auth-designer/subagents/security-analyzer.ts","../src/modules/auth-designer/subagents/flow-designer.ts","../src/modules/planning/stages/requirements.stage.ts","../src/modules/planning/stages/requirements.state.ts","../src/modules/api-designer/subagents/endpoint-analyzer.ts","../src/modules/api-designer/subagents/contract-designer.ts","../src/modules/planning/stages/design.stage.ts","../src/modules/planning/stages/design.state.ts","../src/modules/planning/writer.ts","../src/modules/execution-planner/subagents/edge-case-analyzer.ts","../src/modules/execution-planner/subagents/testing-strategist.ts","../src/modules/planning/stages/synthesis.stage.ts","../src/modules/planning/stages/synthesis.state.ts","../src/modules/planning/stages/state-registry.ts","../src/modules/planning/router.ts","../src/modules/planning/chat.ts","../src/modules/planning/agent.ts","../src/modules/planning/edit-agent.ts","../src/modules/planning/from-requirements.ts","../src/modules/planning/context-builder.ts","../src/modules/requirement-gatherer/schemas/actor.schema.ts","../src/modules/requirement-gatherer/schemas/flow.schema.ts","../src/modules/requirement-gatherer/schemas/story.schema.ts","../src/modules/requirement-gatherer/schemas/module.schema.ts","../src/modules/requirement-gatherer/schemas/database.schema.ts","../src/modules/requirement-gatherer/schemas/context.schema.ts","../src/modules/requirement-gatherer/schemas/requirement.schema.ts","../src/modules/requirement-gatherer/prompts/system.prompt.ts","../src/modules/requirement-gatherer/prompts/discovery.prompt.ts","../src/modules/requirement-gatherer/prompts/requirements.prompt.ts","../src/modules/requirement-gatherer/prompts/design.prompt.ts","../src/modules/requirement-gatherer/prompts/synthesis.prompt.ts","../src/modules/requirement-gatherer/context.ts","../src/modules/requirement-gatherer/stages/base.ts","../src/modules/requirement-gatherer/stages/discovery.stage.ts","../src/modules/requirement-gatherer/stages/requirements-invoke.ts","../src/modules/requirement-gatherer/stages/requirements.stage.ts","../src/modules/requirement-gatherer/stages/design.stage.ts","../src/modules/requirement-gatherer/stages/synthesis.stage.ts","../src/modules/requirement-gatherer/stages/discovery.state.ts","../src/modules/requirement-gatherer/stages/requirements.state.ts","../src/modules/requirement-gatherer/stages/design.state.ts","../src/modules/requirement-gatherer/stages/synthesis.state.ts","../src/modules/requirement-gatherer/stages/state-registry.ts","../src/modules/requirement-gatherer/router.ts","../src/modules/requirement-gatherer/chat.ts","../src/modules/requirement-gatherer/agent.ts","../src/modules/requirement-gatherer/context-builder.ts","../src/modules/data-modeler/schemas/data-model.schema.ts","../src/modules/data-modeler/schemas/mongodb-field.schema.ts","../src/modules/data-modeler/schemas/mongodb-module.schema.ts","../src/modules/data-modeler/schemas/mongodb-project.schema.ts","../src/modules/data-modeler/prompts/system.prompt.ts","../src/modules/data-modeler/prompts/design.prompt.ts","../src/modules/data-modeler/prompts/pro-design.prompt.ts","../src/modules/data-modeler/prompts/mongodb-system.prompt.ts","../src/modules/data-modeler/prompts/mongodb-formatters.ts","../src/modules/data-modeler/prompts/mongodb-design.prompt.ts","../src/modules/data-modeler/prompts/mongodb-redesign.prompt.ts","../src/modules/data-modeler/tools/validate-schema.ts","../src/modules/data-modeler/tools/design-schema.ts","../src/modules/data-modeler/tools/design-schema-pro.ts","../src/modules/data-modeler/tools/refine-schema.ts","../src/modules/data-modeler/tools/validate-mongodb.ts","../src/modules/data-modeler/tools/design-mongodb.ts","../src/modules/data-modeler/tools/design-mongodb-pro.ts","../src/modules/data-modeler/tools/redesign-mongodb.ts","../src/modules/data-modeler/tools/index.ts","../src/modules/data-modeler/agent.ts","../src/modules/data-modeler/mongodb-agent.ts","../src/modules/api-designer/schemas/api-design.schema.ts","../src/modules/api-designer/prompts/system.prompt.ts","../src/modules/api-designer/prompts/design.prompt.ts","../src/modules/api-designer/tools/validate-api.ts","../src/modules/api-designer/tools/design-api.ts","../src/modules/api-designer/tools/design-api-pro.ts","../src/modules/api-designer/tools/index.ts","../src/modules/api-designer/agent.ts","../src/modules/auth-designer/schemas/auth-design.schema.ts","../src/modules/auth-designer/prompts/system.prompt.ts","../src/modules/auth-designer/prompts/design.prompt.ts","../src/modules/auth-designer/tools/validate-auth.ts","../src/modules/auth-designer/tools/design-auth.ts","../src/modules/auth-designer/tools/index.ts","../src/modules/auth-designer/agent.ts","../src/modules/backend-architect/schemas/backend-design.schema.ts","../src/modules/backend-architect/prompts/system.prompt.ts","../src/modules/backend-architect/prompts/design.prompt.ts","../src/modules/backend-architect/tools/validate-backend.ts","../src/modules/backend-architect/tools/design-backend.ts","../src/modules/backend-architect/tools/index.ts","../src/modules/backend-architect/subagents/service-planner.ts","../src/modules/backend-architect/subagents/framework-selector.ts","../src/modules/backend-architect/agent.ts","../src/modules/frontend-architect/schemas/frontend-design.schema.ts","../src/modules/frontend-architect/prompts/system.prompt.ts","../src/modules/frontend-architect/prompts/design.prompt.ts","../src/modules/frontend-architect/tools/validate-frontend.ts","../src/modules/frontend-architect/tools/design-frontend.ts","../src/modules/frontend-architect/tools/index.ts","../src/modules/frontend-architect/agent.ts","../src/modules/express-builder/schemas/express-config.schema.ts","../src/modules/express-builder/prompts/system.prompt.ts","../src/modules/express-builder/prompts/design.prompt.ts","../src/modules/express-builder/tools/validate-express.ts","../src/modules/express-builder/tools/generate-express.ts","../src/modules/express-builder/tools/scaffold-express.ts","../src/modules/express-builder/tools/index.ts","../src/modules/express-builder/subagents/route-generator.ts","../src/modules/express-builder/subagents/middleware-configurator.ts","../src/modules/express-builder/agent.ts","../src/modules/apollo-builder/schemas/subgraph-config.schema.ts","../src/modules/apollo-builder/prompts/system.prompt.ts","../src/modules/apollo-builder/prompts/design.prompt.ts","../src/modules/apollo-builder/tools/validate-subgraph.ts","../src/modules/apollo-builder/tools/generate-subgraph.ts","../src/modules/apollo-builder/tools/scaffold-subgraph.ts","../src/modules/apollo-builder/tools/index.ts","../src/modules/apollo-builder/subagents/schema-generator.ts","../src/modules/apollo-builder/subagents/resolver-planner.ts","../src/modules/apollo-builder/agent.ts","../src/modules/react-builder/schemas/branding.schema.ts","../src/modules/react-builder/schemas/app-config.schema.ts","../src/modules/react-builder/schemas/field.schema.ts","../src/modules/react-builder/schemas/page.schema.ts","../src/modules/react-builder/schemas/application.schema.ts","../src/modules/react-builder/schemas/user.schema.ts","../src/modules/react-builder/prompts/system.prompt.ts","../src/modules/react-builder/prompts/instruction.prompt.ts","../src/modules/react-builder/prompts/examples.prompt.ts","../src/modules/react-builder/prompts/feedback.prompt.ts","../src/modules/react-builder/tools/validate-frontend-config.tool.ts","../src/modules/react-builder/tools/generate-frontend.tool.ts","../src/modules/react-builder/tools/generate-feature-breakdown.tool.ts","../src/modules/react-builder/tools/scaffold-vite.ts","../src/modules/react-builder/tools/index.ts","../src/modules/react-builder/subagents/graphql-analyzer.subagent.ts","../src/modules/react-builder/subagents/config-validator.subagent.ts","../src/modules/react-builder/agent.ts","../src/modules/nextjs-builder/schemas/nextjs-config.schema.ts","../src/modules/nextjs-builder/prompts/system.prompt.ts","../src/modules/nextjs-builder/prompts/design.prompt.ts","../src/modules/nextjs-builder/tools/validate-nextjs.ts","../src/modules/nextjs-builder/tools/generate-nextjs.ts","../src/modules/nextjs-builder/tools/index.ts","../src/modules/nextjs-builder/subagents/route-planner.ts","../src/modules/nextjs-builder/subagents/api-route-generator.ts","../src/modules/nextjs-builder/agent.ts","../src/modules/execution-planner/schemas/execution-plan.schema.ts","../src/modules/execution-planner/prompts/system.prompt.ts","../src/modules/execution-planner/prompts/design.prompt.ts","../src/modules/execution-planner/tools/validate-plan.ts","../src/modules/execution-planner/tools/create-plan.ts","../src/modules/execution-planner/tools/index.ts","../src/modules/execution-planner/agent.ts","../src/modules/hello-world/tool.ts","../src/modules/hello-world/agent.ts","../src/lib/mcp/server/tool-registry.ts","../src/lib/mcp/server/types.ts","../src/lib/mcp/server/server.ts"],"names":["LibraryError","message","cause","ModelError","provider","ToolError","toolName","ValidationError","errors","AgentError","iteration","SubagentError","subagentName","extractJson","text","trimmed","codeBlock","parseModelJsonResponse","schema","jsonStr","parsed","err","preview","result","issues","i","safeJsonParse","label","NOOP_LOGGER","createLogger","config","name","level","pretty","file","stream","destination","streamFd","pinoLogger","pino","targets","transport","wrapPino","loggerConfigFromEnv","overrides","raw","enabledRaw","enabled","levelRaw","streamRaw","prettyRaw","p","msg","data","bindings","emptyDetails","emptyOutputDetails","sumTokenUsage","usages","inputTokens","outputTokens","totalTokens","usage","defineTool","description","inputSchema","handler","tool","args","e","createToolSet","tools","getTools","toolSet","getTool","executeTool","toolImpl","input","options","logger","out","executeToolByName","createValidationTool","inputParamName","z","notifyObserversStep","observers","step","notifyObserversTool","o","notifyObserversError","error","runAgent","model","systemPrompt","maxIterations","onStep","messages","steps","response","s","tc","assistantContent","toolResults","toolCall","execResult","agentResult","outputVal","createAIModel","params","modelName","getModel","schemaOnlyTools","t","_execute","rest","generateText","toolCalls","prompt","images","content","img","schemaWrapped","zodSchema","generateObject","createOpenAIModel","apiKey","baseUrl","createOpenAI","createAnthropicModel","createAnthropic","createGoogleModel","createGoogleGenerativeAI","createModel","NAME_REGEX","defineSubagent","resolveTools","definition","parentTools","base","disallowed","filtered","key","runSubagent","parentModel","createSubagentTool","createSubagentToolSet","definitions","def","compileTemplate","template","context","Handlebars","findHbsFiles","dir","results","Z","entries","entry","fullPath","le","toOutputPath","hbsRelPath","shouldSkip","relativePath","skipPatterns","pattern","scaffoldProject","templateDir","outputDir","hbsFiles","files","hbsFile","outputRelPath","inputPath","outputPath","templateSource","compiled","registerHelpers","a","b","obj","str","_","c","getSdkRoot","createRequire","path","sdkRoot","parseToolResult","first","createHttpTransport","url","headers","modPath","mod","pathToFileURL","requestInit","createStdioTransport","command","BaseMcpClient","info","resolveOpts","envPrefix","serverLabel","apiKeyHeader","argsEnv","client","Client","EMPTY_SECTIONS","createInitialContext","mergeStageResult","newSections","projectDescription","pendingQuestions","sections","v","addChatEntry","role","advanceStage","order","idx","next","isConfirmation","normalized","PLANNING_SYSTEM_PROMPT","DISCOVERY_SYSTEM_FRAGMENT","DISCOVERY_USER_PROMPT","buildDiscoveryPrompt","userMessage","history","CONTEXT_BLOCK","REQUIREMENTS_OVERVIEW_PROMPT","REQUIREMENTS_FEATURE_DATA_PROMPT","buildRequirementsOverviewPrompt","buildRequirementsFeatureDataPrompt","overviewAndTechStack","DESIGN_CONTEXT","DESIGN_IMPLEMENTATION_PROMPT","buildDesignImplementationPrompt","priorSections","apiRoutes","SYNTHESIS_CONTEXT","SYNTHESIS_SYSTEM_FRAGMENT","SYNTHESIS_USER_PROMPT","buildSynthesisPrompt","EDIT_PLAN_SYSTEM_PROMPT","buildEditPlanPrompt","existingPlan","feedback","hasProjectOverview","lower","runDiscoveryStage","hasOverview","userConfirmed","forceAdvance","advance","storeDescription","DiscoveryState","ENTITY_ANALYZER_SYSTEM_PROMPT","entityAnalyzerSubagent","RELATIONSHIP_MAPPER_SYSTEM_PROMPT","relationshipMapperSubagent","SCHEMA_REFINER_SYSTEM_PROMPT","createSchemaRefinerSubagent","PAGE_PLANNER_SYSTEM_PROMPT","pagePlannerSubagent","COMPONENT_ANALYZER_SYSTEM_PROMPT","componentAnalyzerSubagent","FRAMEWORK_SELECTOR_SYSTEM_PROMPT","frameworkSelectorSubagent","SECURITY_ANALYZER_SYSTEM_PROMPT","securityAnalyzerSubagent","FLOW_DESIGNER_SYSTEM_PROMPT","flowDesignerSubagent","invokeMarkdown","userPrompt","r","splitOverviewAndTechStack","splitFeatureDecisionsAndDataModels","runRequirementsStage","_userMessage","ctx","part1","overview","techStack","part2","featureDecisions","dataModels","priorContext","pagesAndRoutes","fullContext","authFlow","RequirementsState","ENDPOINT_ANALYZER_SYSTEM_PROMPT","endpointAnalyzerSubagent","CONTRACT_DESIGNER_SYSTEM_PROMPT","contractDesignerSubagent","gatherPriorSections","parts","runDesignStage","contractResult","implementation","DesignState","assemblePlan","projectName","writePlanToFile","markdown","writeFile","EDGE_CASE_ANALYZER_SYSTEM_PROMPT","edgeCaseAnalyzerSubagent","TESTING_STRATEGIST_SYSTEM_PROMPT","testingStrategistSubagent","gatherAllSections","extractProjectName","firstLine","match","runSynthesisStage","executionPlan","edgeCases","testingChecklist","fullSections","fullMarkdown","SynthesisState","states","getStateForStage","stage","runStage","merged","STAGE_ORDER","processPlanningChat","modelConfig","planMarkdown","runOne","runResult","nextStage","MAX_TURNS","runPlanningAgent","lastResult","turns","continueMsg","output","editPlan","revised","formatEntityFields","entity","f","flags","formatDatabaseAsMarkdown","db","header","entities","fields","relParts","relations","idxParts","indexes","formatModulesAsMarkdown","modules","m","apis","formatProjectOverview","req","features","formatTechStack","formatActorsContext","actors","flows","stories","actor","actorFlows","convertRequirementToContext","runPlanningFromRequirements","requirement","triggerMsg","DEFAULT_STAGE","PlanningContextBuilder","createPlanningContextBuilder","actorSchema","actorsResultSchema","flowSchema","flowsResultSchema","storySchema","storiesResultSchema","crudApiSchema","extractedModuleSchema","modulesResultSchema","entityFieldSchema","entityIndexSchema","entityRelationSchema","databaseEntitySchema","databaseDesignSchema","projectBriefSchema","questionSchema","chatEntrySchema","requirementContextSchema","requirementSummarySchema","finalRequirementSchema","REQUIREMENT_GATHERER_SYSTEM_PROMPT","PROJECT_BLOCK","EXTRACT_ACTORS_PROMPT","GENERATE_FLOWS_PROMPT","GENERATE_STORIES_PROMPT","EXTRACT_MODULES_PROMPT","buildExtractActorsPrompt","projectGoal","projectFeatures","buildGenerateFlowsPrompt","actorsJson","buildGenerateStoriesPrompt","flowsJson","buildExtractModulesPrompt","storiesJson","DESIGN_DB_PROMPT","DESIGN_DATABASE_SYSTEM_PROMPT","buildDesignDatabasePrompt","projectBrief","database","summarizeModules","summarizeStories","safeParseJson","needsClarification","questions","q","validated","pb","getActors","_logger","getFlows","_actors","getStories","_flows","getModules","_stories","brief","projectBriefStr","modulesSummary","storiesSummary","dbPrompt","dbMessages","dbResponse","dbJsonStr","dbParsed","databaseResult","finalRequirement","finalReq","processRequirementChat","runRequirementGathererAgent","RequirementContextBuilder","createRequirementContextBuilder","relationTypeSchema","n","dataEntitySchema","issue","dbTypeSchema","dataModelDesignSchema","mongoFieldSchema","mongoModuleSchema","mongoProjectSchema","DATA_MODELER_SYSTEM_PROMPT","DESIGN_SCHEMA_PROMPT","REFINE_SCHEMA_PROMPT","buildDesignSchemaPrompt","buildRefineSchemaPrompt","existingSchema","PRO_DESIGN_PROMPT","buildProDesignPrompt","databaseType","MONGODB_SYSTEM_PROMPT","formatUserTypes","goals","g","formatUserFlows","flow","formatUserStories","byFlow","arr","flowStories","story","pre","post","d","orphans","formatTechnicalRequirements","tech","lines","extractDataEntities","extractRoles","buildPromptVariables","createMongoDesignPrompt","createMongoProDesignPrompt","vars","createMongoRedesignPrompt","validateSchemaTool","createDesignSchemaTool","createDesignSchemaProTool","createRefineSchemaTools","validateMongoSchemaTool","createDesignDatabaseTool","structuredInputSchema","createDesignDatabaseProTool","dbDesign","metadata","createRedesignDatabaseTool","createDataModelerTools","createDbDesignerTools","ORCHESTRATOR_SYSTEM_PROMPT","runDataModelerAgent","schemaRefiner","subagentTools","allTools","runDbDesignerAgent","dbTools","httpMethodSchema","stringRecordSchema","k","stringOrObjectArraySchema","restEndpointSchema","graphqlOperationSchema","apiStyleSchema","apiDesignSchema","API_DESIGNER_SYSTEM_PROMPT","DESIGN_API_PROMPT","PRO_DESIGN_API_PROMPT","buildDesignApiPrompt","buildProDesignApiPrompt","apiStyle","dataModel","validateApiTool","createDesignApiTool","createDesignApiProTool","createApiDesignerTools","runApiDesignerAgent","authFlowStepSchema","authFlowSchema","authMiddlewareSchema","roleDefinitionSchema","securityPolicySchema","authDesignSchema","AUTH_DESIGNER_SYSTEM_PROMPT","DESIGN_AUTH_PROMPT","buildDesignAuthPrompt","validateAuthTool","createDesignAuthTool","createAuthDesignerTools","runAuthDesignerAgent","ciEnum","values","middlewareSchema","serviceSchema","routeGroupSchema","backendDesignSchema","BACKEND_ARCHITECT_SYSTEM_PROMPT","DESIGN_BACKEND_PROMPT","buildDesignBackendPrompt","validateBackendTool","createDesignBackendTool","createBackendArchitectTools","SERVICE_PLANNER_SYSTEM_PROMPT","servicePlannerSubagent","runBackendArchitectAgent","formFieldSchema","pageDesignSchema","componentDesignSchema","frontendDesignSchema","FRONTEND_ARCHITECT_SYSTEM_PROMPT","DESIGN_FRONTEND_PROMPT","buildDesignFrontendPrompt","validateFrontendTool","createDesignFrontendTool","createFrontendArchitectTools","reactBuilderSubagent","nextjsBuilderSubagent","runFrontendArchitectAgent","routerMethodSchema","routerSchema","modelFieldSchema","modelSchema","middlewareConfigSchema","expressConfigSchema","EXPRESS_BUILDER_SYSTEM_PROMPT","DESIGN_EXPRESS_PROMPT","buildDesignExpressPrompt","validateExpressTool","createGenerateExpressTool","toTemplateContext","scaffoldExpressTool","fa","createExpressBuilderTools","ROUTE_GENERATOR_SYSTEM_PROMPT","routeGeneratorSubagent","MIDDLEWARE_CONFIGURATOR_SYSTEM_PROMPT","middlewareConfiguratorSubagent","runExpressBuilderAgent","graphqlFieldSchema","graphqlTypeSchema","resolverOperationSchema","subgraphModuleSchema","subgraphConfigSchema","APOLLO_BUILDER_SYSTEM_PROMPT","DESIGN_SUBGRAPH_PROMPT","buildDesignSubgraphPrompt","validateSubgraphTool","createGenerateSubgraphTool","scaffoldSubgraphTool","Ta","createApolloBuilderTools","SCHEMA_GENERATOR_SYSTEM_PROMPT","schemaGeneratorSubagent","RESOLVER_PLANNER_SYSTEM_PROMPT","resolverPlannerSubagent","runApolloBuilderAgent","BrandingSchema","AppConfigSchema","ValidationSchema","FieldOptionsSchema","FormFieldSchema","ColumnSchema","ApiResponseTypeSchema","ListingPageApiSchema","AuthPageApiSchema","DrawerSchema","AuthPageSchema","ListingPageSchema","PageSchema","ModuleSchema","ApplicationSchema","LoginInputSchema","SpecializationSchema","UserSchema","CreateUserInputSchema","UpdateUserInputSchema","ForgotPasswordSchema","ResetPasswordSchema","REACT_BUILDER_SYSTEM_PROMPT","REACT_BUILDER_INSTRUCTION","buildInstructionPrompt","EXAMPLE_GRAPHQL_SCHEMA","EXAMPLE_JSON_OUTPUT","buildExampleShotPrompt","buildFeedbackPrompt","userFeedback","schemaFile","validateFrontendConfigTool","buildGeneratePrompt","graphqlSchema","appInfo","instruction","example","appInfoBlock","createGenerateFrontendTool","createGenerateFeatureBreakdownTool","scaffoldViteTool","_a","createReactBuilderTools","GRAPHQL_ANALYZER_SYSTEM_PROMPT","graphqlAnalyzerSubagent","CONFIG_VALIDATOR_SYSTEM_PROMPT","createConfigValidatorSubagent","runReactBuilderAgent","reactTools","configValidator","nextjsPageSchema","nextjsLayoutSchema","nextjsApiRouteSchema","serverActionSchema","nextjsConfigSchema","NEXTJS_BUILDER_SYSTEM_PROMPT","DESIGN_NEXTJS_PROMPT","buildDesignNextjsPrompt","validateNextjsTool","createGenerateNextjsTool","createNextjsBuilderTools","ROUTE_PLANNER_SYSTEM_PROMPT","routePlannerSubagent","API_ROUTE_GENERATOR_SYSTEM_PROMPT","apiRouteGeneratorSubagent","runNextjsBuilderAgent","phaseStepSchema","implementationPhaseSchema","edgeCaseSchema","testChecklistItemSchema","executionPlanSchema","EXECUTION_PLANNER_SYSTEM_PROMPT","CREATE_EXECUTION_PLAN_PROMPT","buildCreateExecutionPlanPrompt","validateExecutionPlanTool","createExecutionPlanTool","createExecutionPlannerTools","runExecutionPlannerAgent","helloWorldTool","DEFAULT_SYSTEM_PROMPT","runHelloWorldAgent","runner","TOOL_REGISTRY","findTool","AGENT_TOOL_INPUT_SHAPE","buildModelConfig","SERVER_NAME","SERVER_VERSION","log","MAX_PREVIEW","createStepLogger","prefix","createSweagentServer","server","McpServer"],"mappings":"2jCAOO,IAAMA,EAAAA,CAAN,cAA2B,KAAM,CACtC,WAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAAe,CAC1C,KAAA,CAAMD,CAAAA,CAASC,CAAAA,GAAU,MAAA,CAAY,MAAA,CAAY,CAAE,KAAA,CAAAA,CAAM,CAAC,CAAA,CAC1D,IAAA,CAAK,IAAA,CAAO,cAAA,CACRA,CAAAA,EAAO,KAAA,GACT,IAAA,CAAK,KAAA,CAAQ,CAAA,EAAG,IAAA,CAAK,KAAK;AAAA,WAAA,EAAgBA,CAAAA,CAAM,KAAK,CAAA,CAAA,EAEzD,CACF,EAKaC,EAAAA,CAAN,cAAyBH,EAAa,CAC3C,WAAA,CACEC,CAAAA,CACgBG,EAChBF,CAAAA,CACA,CACA,MAAMD,CAAAA,CAASC,CAAK,EAHJ,IAAA,CAAA,QAAA,CAAAE,CAAAA,CAIhB,IAAA,CAAK,IAAA,CAAO,aACd,CACF,EAKaC,CAAAA,CAAN,cAAwBL,EAAa,CAC1C,WAAA,CACEC,EACgBK,CAAAA,CAChBJ,CAAAA,CACA,CACA,KAAA,CAAMD,CAAAA,CAASC,CAAK,EAHJ,IAAA,CAAA,QAA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oB,CAAAA,YAAe,KAAA,CAAQA,EAAI,OAAA,CAAU,MAAA,CAAOA,CAAG,CAAA,CAC/D,OAAAuqB,EAAAA,CAAI,GAAG9hB,CAAAA,CAAM,IAAI,kBAAa7J,CAAO,CAAA,CAAE,EAChC,CAAE,OAAA,CAAS,CAAC,CAAE,IAAA,CAAM,MAAA,CAAiB,KAAMA,CAAQ,CAAC,EAAG,OAAA,CAAS,IAAK,CAC9E,CACF,CACF,CAAA,CAGF,OAAOgsB,CACT","file":"index.cjs","sourcesContent":["/**\n * Custom error classes for the library\n */\n\n/**\n * Base error class for all library errors\n */\nexport class LibraryError extends Error {\n constructor(message: string, cause?: Error) {\n super(message, cause === undefined ? undefined : { cause });\n this.name = 'LibraryError';\n if (cause?.stack) {\n this.stack = `${this.stack}\\nCaused by: ${cause.stack}`;\n }\n }\n}\n\n/**\n * Error thrown when model operations fail\n */\nexport class ModelError extends LibraryError {\n constructor(\n message: string,\n public readonly provider?: string,\n cause?: Error\n ) {\n super(message, cause);\n this.name = 'ModelError';\n }\n}\n\n/**\n * Error thrown when tool execution fails\n */\nexport class ToolError extends LibraryError {\n constructor(\n message: string,\n public readonly toolName?: string,\n cause?: Error\n ) {\n super(message, cause);\n this.name = 'ToolError';\n }\n}\n\n/**\n * Error thrown when tool input validation fails\n */\nexport class ValidationError extends LibraryError {\n constructor(\n message: string,\n public readonly errors?: unknown[]\n ) {\n super(message);\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Error thrown when agent execution fails\n */\nexport class AgentError extends LibraryError {\n constructor(\n message: string,\n public readonly iteration?: number,\n cause?: Error\n ) {\n super(message, cause);\n this.name = 'AgentError';\n }\n}\n\n/**\n * Error thrown when subagent execution fails\n */\nexport class SubagentError extends LibraryError {\n constructor(\n message: string,\n public readonly subagentName?: string,\n cause?: Error\n ) {\n super(message, cause);\n this.name = 'SubagentError';\n }\n}\n","/**\n * Shared utilities for extracting and parsing JSON from model responses.\n *\n * Models frequently wrap JSON in markdown code blocks or include extra text.\n * These helpers handle extraction, parsing, and Zod validation with clear errors\n * so the agent can retry on failure.\n */\n\nimport type { z } from 'zod';\n\n/**\n * Extract a JSON string from model output.\n * Handles markdown code blocks (```json ... ``` or ``` ... ```) and bare JSON.\n */\nexport function extractJson(text: string): string {\n const trimmed = text.trim();\n const codeBlock = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n if (codeBlock?.[1]) return codeBlock[1].trim();\n return trimmed;\n}\n\n/**\n * Parse a model text response as JSON then validate with a Zod schema.\n * Throws a descriptive error on failure (JSON syntax or validation) so the\n * wrapping ToolError gives the agent enough context to retry.\n */\nexport function parseModelJsonResponse<T>(text: string, schema: z.ZodType<T>): T {\n const jsonStr = extractJson(text);\n let parsed: unknown;\n try {\n parsed = JSON.parse(jsonStr);\n } catch (err) {\n const preview = jsonStr.length > 300 ? jsonStr.slice(0, 300) + '...' : jsonStr;\n throw new Error(\n `Failed to parse model response as JSON: ${err instanceof Error ? err.message : String(err)}. Preview: ${preview}`\n );\n }\n const result = schema.safeParse(parsed);\n if (!result.success) {\n const issues = result.error.issues\n .slice(0, 5)\n .map(i => ` ${i.path.join('.')}: ${i.message}`)\n .join('\\n');\n throw new Error(`Model JSON does not match expected schema:\\n${issues}`);\n }\n return result.data;\n}\n\n/**\n * Parse a raw JSON string (e.g. tool input) with a descriptive error on failure.\n */\nexport function safeJsonParse(jsonStr: string, label?: string): unknown {\n try {\n return JSON.parse(jsonStr) as unknown;\n } catch (err) {\n const preview = jsonStr.length > 200 ? jsonStr.slice(0, 200) + '...' : jsonStr;\n throw new Error(\n `Invalid JSON${label ? ` for ${label}` : ''}: ${err instanceof Error ? err.message : String(err)}. Preview: ${preview}`\n );\n }\n}\n","/**\n * Structured logger using Pino (JSON by default, optional pretty/file).\n * Use loggerConfigFromEnv() for .env-driven config (SWE_LOG_* vars).\n */\n\nimport pino from 'pino';\nimport type { Logger } from '../types/common';\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nexport interface LoggerConfig {\n /** Logger name (appears in logs) */\n name?: string;\n /** Minimum log level */\n level?: LogLevel;\n /** Use pino-pretty for readable output */\n pretty?: boolean;\n /** File path for JSON logs */\n file?: string;\n /** Console stream: stderr avoids mixing with stdout prompts (e.g. inquirer). Default: stderr when pretty, else stdout. */\n stream?: 'stdout' | 'stderr';\n /** When false, returns a no-op logger (no output). Set via SWE_LOG_ENABLED=0. */\n enabled?: boolean;\n /** Optional stream for testing (bypasses transport) */\n destination?: pino.DestinationStream;\n}\n\nconst NOOP_LOGGER: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n child: () => NOOP_LOGGER,\n};\n\nexport function createLogger(config: LoggerConfig = {}): Logger {\n if (config.enabled === false) {\n return NOOP_LOGGER;\n }\n\n const { name, level = 'info', pretty = false, file, stream, destination } = config;\n\n const streamFd = stream === 'stderr' ? 2 : stream === 'stdout' ? 1 : pretty ? 2 : 1;\n\n let pinoLogger: pino.Logger;\n\n if (destination) {\n pinoLogger = pino({ name, level }, destination);\n } else {\n const targets: pino.TransportTargetOptions[] = [];\n\n if (pretty) {\n targets.push({\n target: 'pino-pretty',\n options: {\n colorize: true,\n destination: streamFd,\n singleLine: true,\n ignore: 'time,pid,hostname',\n translateTime: false,\n },\n level,\n });\n } else {\n targets.push({\n target: 'pino/file',\n options: { destination: streamFd },\n level,\n });\n }\n\n if (file) {\n targets.push({\n target: 'pino/file',\n options: { destination: file, mkdir: true },\n level,\n });\n }\n\n const transport = pino.transport({ targets }) as pino.DestinationStream;\n pinoLogger = pino({ name, level }, transport);\n }\n\n return wrapPino(pinoLogger);\n}\n\n/**\n * Build logger config from process.env (SWE_* vars). Caller loads .env if desired (e.g. dotenv or `node --env-file=.env`).\n *\n * Env vars (all optional):\n * - SWE_LOG_ENABLED: 1|true|yes (default) = on; 0|false|no|disabled = off (no-op logger).\n * - SWE_LOG_LEVEL: debug|info|warn|error (default: info).\n * - SWE_LOG_STREAM: stdout|stderr; default stderr when SWE_LOG_PRETTY is true, else stdout.\n * - SWE_LOG_PRETTY: 1|true|yes = human-readable (pino-pretty); 0|false (default) = JSON.\n * - SWE_LOG_FILE: path to also write JSON logs to a file.\n * - SWE_LOG_NAME: logger name in output.\n *\n * For interactive CLIs (e.g. inquirer), use pretty and stderr so logs do not mix with stdout prompts.\n */\nexport function loggerConfigFromEnv(overrides: Partial<LoggerConfig> = {}): LoggerConfig {\n const raw = process.env;\n const enabledRaw = (raw.SWE_LOG_ENABLED ?? 'true').trim().toLowerCase();\n const enabled =\n enabledRaw !== '0' &&\n enabledRaw !== 'false' &&\n enabledRaw !== 'no' &&\n enabledRaw !== 'disabled';\n\n const levelRaw = (raw.SWE_LOG_LEVEL ?? 'info').trim().toLowerCase();\n const level: LogLevel =\n levelRaw === 'debug' || levelRaw === 'info' || levelRaw === 'warn' || levelRaw === 'error'\n ? levelRaw\n : 'info';\n\n const streamRaw = (raw.SWE_LOG_STREAM ?? '').trim().toLowerCase();\n const prettyRaw = (raw.SWE_LOG_PRETTY ?? '0').trim().toLowerCase();\n const pretty = prettyRaw === '1' || prettyRaw === 'true' || prettyRaw === 'yes';\n const stream: 'stdout' | 'stderr' =\n streamRaw === 'stdout'\n ? 'stdout'\n : streamRaw === 'stderr'\n ? 'stderr'\n : pretty\n ? 'stderr'\n : 'stdout';\n\n const file = raw.SWE_LOG_FILE?.trim() || undefined;\n const name = raw.SWE_LOG_NAME?.trim() || undefined;\n\n return {\n enabled,\n level,\n stream,\n pretty,\n ...(file && { file }),\n ...(name && { name }),\n ...overrides,\n };\n}\n\nfunction wrapPino(p: pino.Logger): Logger {\n return {\n debug: (msg, data) => {\n p.debug(data ?? {}, msg);\n },\n info: (msg, data) => {\n p.info(data ?? {}, msg);\n },\n warn: (msg, data) => {\n p.warn(data ?? {}, msg);\n },\n error: (msg, err) => {\n if (err instanceof Error) {\n p.error({ err }, msg);\n } else {\n p.error(err ?? {}, msg);\n }\n },\n child: (bindings: Record<string, unknown>) => wrapPino(p.child(bindings as pino.Bindings)),\n };\n}\n","/**\n * Utility functions\n */\n\nimport type { LanguageModelUsage } from 'ai';\n\nconst emptyDetails = {\n noCacheTokens: undefined as number | undefined,\n cacheReadTokens: undefined as number | undefined,\n cacheWriteTokens: undefined as number | undefined,\n};\nconst emptyOutputDetails = {\n textTokens: undefined as number | undefined,\n reasoningTokens: undefined as number | undefined,\n};\n\n/**\n * Sum token usage from multiple steps (AI SDK LanguageModelUsage)\n */\nexport function sumTokenUsage(usages: (LanguageModelUsage | undefined)[]): LanguageModelUsage {\n let inputTokens = 0;\n let outputTokens = 0;\n let totalTokens = 0;\n\n for (const usage of usages) {\n if (usage) {\n inputTokens += usage.inputTokens ?? 0;\n outputTokens += usage.outputTokens ?? 0;\n totalTokens += usage.totalTokens ?? 0;\n }\n }\n\n return {\n inputTokens,\n outputTokens,\n totalTokens,\n inputTokenDetails: emptyDetails,\n outputTokenDetails: emptyOutputDetails,\n };\n}\n","/**\n * Tools: defineTool, createToolSet, execute, zodToJsonSchema\n */\n\nimport { z } from 'zod';\nimport { tool } from 'ai';\nimport type { Tool, ToolExecutionOptions } from 'ai';\nimport type { Logger } from '../types/common';\nimport type { ToolConfig, ToolContext, ToolExecutionResult } from '../types/tool';\nimport { ToolError } from '../utils/errors';\n\n/** Tool has description (and optional title) in config; name is the key in createToolSet. */\nexport function defineTool<TInput extends z.ZodType, TOutput>(\n config: ToolConfig<TInput, TOutput>\n): Tool {\n const { name, description, input: inputSchema, handler } = config;\n return tool({\n description,\n inputSchema,\n execute: async (args: unknown): Promise<TOutput> => {\n const parsed = inputSchema.safeParse(args);\n if (!parsed.success)\n throw new ToolError(`Invalid input: ${parsed.error.message}`, name, parsed.error);\n try {\n return await handler(parsed.data as z.infer<TInput>, undefined as ToolContext | undefined);\n } catch (e) {\n if (e instanceof ToolError) throw e;\n throw new ToolError(\n `Tool \"${name}\" failed: ${e instanceof Error ? e.message : String(e)}`,\n name,\n e instanceof Error ? e : undefined\n );\n }\n },\n } as unknown as Parameters<typeof tool>[0]);\n}\n\nexport type ToolSet = Record<string, Tool>;\n\n/** Pass a record: key = tool name (same as in defineTool config). */\nexport function createToolSet(tools: ToolSet): ToolSet {\n return tools;\n}\n\nexport function getTools(toolSet: ToolSet): Tool[] {\n return Object.values(toolSet);\n}\n\nexport function getTool(toolSet: ToolSet, name: string): Tool | undefined {\n return toolSet[name];\n}\n\nexport interface ExecuteToolOptions {\n toolCallId?: string;\n abortSignal?: AbortSignal;\n logger?: Logger;\n}\n\nexport async function executeTool<TInput, TOutput>(\n toolImpl: Tool<TInput, TOutput>,\n input: TInput,\n options?: ExecuteToolOptions & { toolName?: string }\n): Promise<ToolExecutionResult<TOutput>> {\n const { logger } = options ?? {};\n const toolName =\n options?.toolName ??\n ('name' in toolImpl && typeof toolImpl.name === 'string' ? toolImpl.name : 'unknown');\n\n if (!toolImpl.execute) {\n logger?.error('Tool has no execute function', { toolName });\n return { success: false, error: 'Tool has no execute function' };\n }\n logger?.debug('Executing tool', { toolName, toolCallId: options?.toolCallId });\n try {\n const out = await toolImpl.execute(input, {\n toolCallId: options?.toolCallId ?? '',\n messages: [],\n abortSignal: options?.abortSignal,\n } as ToolExecutionOptions);\n logger?.info('Tool completed', { toolName, toolCallId: options?.toolCallId });\n return { success: true, output: out as TOutput };\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n logger?.error('Tool failed', {\n toolName,\n toolCallId: options?.toolCallId,\n error: msg,\n });\n return { success: false, error: msg };\n }\n}\n\nexport async function executeToolByName(\n tools: ToolSet,\n name: string,\n input: unknown,\n options?: ExecuteToolOptions\n): Promise<ToolExecutionResult> {\n const toolImpl = tools[name];\n if (!toolImpl) {\n options?.logger?.error('Tool not found', {\n name,\n availableTools: Object.keys(tools),\n });\n throw new ToolError(`Tool not found: ${name}`);\n }\n return executeTool(toolImpl, input, { ...options, toolName: name });\n}\n\nexport type JsonSchemaObject = Record<string, unknown>;\n\nexport function zodToJsonSchema(schema: z.ZodType): JsonSchemaObject {\n const result = z.toJSONSchema(schema) as JsonSchemaObject & {\n $schema?: string;\n definitions?: unknown;\n };\n const { $schema: _s, definitions: _d, ...rest } = result;\n return rest as JsonSchemaObject;\n}\n","/**\n * Shared validation tool factory - generates a validate_* tool from a Zod schema.\n * Eliminates boilerplate across modules that all follow the same pattern.\n */\n\nimport { z } from 'zod';\nimport type { Tool } from 'ai';\nimport { defineTool } from './tools';\n\nexport interface ValidationResult {\n valid: boolean;\n errors?: string[];\n}\n\n/**\n * Create a validation tool that parses JSON input against a Zod schema.\n * Every module can replace its hand-written validate_* tool with this one-liner.\n *\n * @param name - Tool name (e.g. 'validate_schema', 'validate_api')\n * @param schema - Zod schema to validate against\n * @param description - Tool description for the agent\n * @param inputParamName - Name of the input parameter (default: 'json')\n */\nexport function createValidationTool(\n name: string,\n schema: z.ZodType,\n description: string,\n inputParamName = 'json'\n): Tool {\n return defineTool({\n name,\n description,\n input: z.object({\n [inputParamName]: z.string().describe('JSON string to validate'),\n }),\n handler: async (args: Record<string, string>): Promise<ValidationResult> => {\n const raw = args[inputParamName] ?? '';\n try {\n const parsed = JSON.parse(raw) as unknown;\n schema.parse(parsed);\n return { valid: true };\n } catch (err) {\n if (err instanceof z.ZodError) {\n return {\n valid: false,\n errors: err.issues.map(e => `${e.path.join('.')}: ${e.message}`),\n };\n }\n if (err instanceof SyntaxError) {\n return { valid: false, errors: [`Invalid JSON: ${err.message}`] };\n }\n return { valid: false, errors: [String(err)] };\n }\n },\n });\n}\n","/**\n * Notify agent observers (step, tool, error). Keeps agent.ts under 150 lines.\n */\n\nimport type { AgentObserver, AgentStep } from '../types/agent';\n\nexport function notifyObserversStep(observers: AgentObserver[] | undefined, step: AgentStep): void {\n observers?.forEach(o => o.onStep?.(step));\n}\n\nexport function notifyObserversTool(\n observers: AgentObserver[] | undefined,\n toolName: string,\n result: unknown\n): void {\n observers?.forEach(o => o.onToolExecution?.(toolName, result));\n}\n\nexport function notifyObserversError(observers: AgentObserver[] | undefined, error: Error): void {\n observers?.forEach(o => o.onError?.(error));\n}\n","/**\n * Agent loop: model + tools, AI SDK message shapes\n */\n\nimport type { AgentConfig, AgentResult, AgentStep, AgentToolResult } from '../types/agent';\nimport type { ModelMessage } from '../types/common';\nimport type { ModelToolCall } from '../types/model';\nimport { AgentError } from '../utils/errors';\nimport { sumTokenUsage } from '../utils/utils';\nimport { executeToolByName } from '../tools';\nimport { notifyObserversStep, notifyObserversTool, notifyObserversError } from './agent-observers';\n\n/**\n * Run an agent with the given configuration.\n *\n * 1. Calls the model with ModelMessage[] and tools\n * 2. If no tool calls, returns the response\n * 3. If tool calls, executes them and appends assistant + tool messages (AI SDK shape)\n * 4. Repeats until done or max iterations reached\n *\n * @example\n * ```typescript\n * const result = await runAgent({\n * model: createModel({ provider: 'openai', model: 'gpt-4o' }),\n * tools: createToolSet({ search: searchTool, calculator: calculatorTool }),\n * systemPrompt: 'You are a helpful assistant.',\n * input: 'What is 2 + 2?',\n * maxIterations: 10\n * });\n * console.log(result.output);\n * ```\n */\nexport async function runAgent(config: AgentConfig): Promise<AgentResult> {\n const {\n model,\n tools,\n systemPrompt,\n input,\n maxIterations = 10,\n onStep,\n observers,\n logger,\n } = config;\n\n logger?.info('Starting agent', { maxIterations });\n\n const messages: ModelMessage[] = [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: input },\n ];\n\n const steps: AgentStep[] = [];\n\n for (let iteration = 0; iteration < maxIterations; iteration++) {\n if (iteration > 0 && iteration >= maxIterations - 2) {\n logger?.warn('Approaching max iterations', { iteration, maxIterations });\n }\n logger?.debug('Agent iteration', { iteration });\n\n const response = await model.invoke(messages, { tools });\n\n const step: AgentStep = {\n iteration,\n content: response.text,\n toolCalls: response.toolCalls,\n usage: response.usage,\n };\n\n if (response.text) {\n logger?.debug('Model response', { iteration, textLength: response.text.length });\n }\n\n if (!response.toolCalls?.length) {\n steps.push(step);\n onStep?.(step);\n notifyObserversStep(observers, step);\n logger?.info('Agent completed', {\n steps: steps.length,\n totalUsage: sumTokenUsage(steps.map(s => s.usage)),\n });\n return {\n output: response.text,\n steps,\n totalUsage: sumTokenUsage(steps.map(s => s.usage)),\n messages,\n };\n }\n\n logger?.debug('Tool calls', {\n iteration,\n toolCalls: response.toolCalls.map((tc: ModelToolCall) => ({\n name: tc.toolName,\n toolCallId: tc.toolCallId,\n })),\n });\n\n const assistantContent = [\n ...(response.text ? [{ type: 'text' as const, text: response.text }] : []),\n ...response.toolCalls.map((tc: ModelToolCall) => ({\n type: 'tool-call' as const,\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n input: tc.input,\n })),\n ];\n messages.push({ role: 'assistant', content: assistantContent });\n\n const toolResults: AgentToolResult[] = [];\n\n for (const toolCall of response.toolCalls) {\n const execResult = await executeToolByName(tools, toolCall.toolName, toolCall.input, {\n toolCallId: toolCall.toolCallId,\n logger,\n });\n\n const agentResult: AgentToolResult = {\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n output: execResult.success ? execResult.output : execResult.error,\n isError: !execResult.success,\n };\n toolResults.push(agentResult);\n notifyObserversTool(observers, toolCall.toolName, agentResult.output);\n\n const outputVal = agentResult.isError\n ? { type: 'error-text' as const, value: String(agentResult.output) }\n : {\n type: 'text' as const,\n value:\n typeof agentResult.output === 'string'\n ? agentResult.output\n : JSON.stringify(agentResult.output),\n };\n\n messages.push({\n role: 'tool',\n content: [\n {\n type: 'tool-result' as const,\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n output: outputVal,\n },\n ],\n });\n }\n\n step.toolResults = toolResults;\n steps.push(step);\n onStep?.(step);\n notifyObserversStep(observers, step);\n }\n\n const err = new AgentError(\n `Agent reached maximum iterations (${maxIterations}) without completing`,\n maxIterations - 1\n );\n notifyObserversError(observers, err);\n logger?.error('Agent failed: max iterations reached', { maxIterations, error: err });\n throw err;\n}\n","/**\n * Shared AI SDK adapter - pass-through to generateText (no conversions)\n */\n\nimport { generateText, generateObject, zodSchema } from 'ai';\nimport type { LanguageModelV3 } from '@ai-sdk/provider';\nimport type {\n Model,\n ModelResponse,\n InvokeOptions,\n InvokeObjectOptions,\n InvokeObjectResult,\n VisionOptions,\n ModelProvider,\n ModelTool,\n ModelToolCall,\n} from '../../types/model';\nimport type { ModelMessage, ImageInput } from '../../types/common';\nimport { ModelError } from '../../utils/errors';\n\nexport interface CreateAIModelParams {\n provider: ModelProvider;\n modelName: string;\n getModel: () => LanguageModelV3 | Promise<LanguageModelV3>;\n}\n\n/**\n * Create a sweagent Model that uses an AI SDK LanguageModel.\n * Messages and tools are passed through to generateText; result returned as ModelResponse.\n */\nexport function createAIModel(params: CreateAIModelParams): Model {\n const { provider, modelName, getModel } = params;\n\n return {\n provider,\n modelName,\n\n async invoke(messages: ModelMessage[], options?: InvokeOptions): Promise<ModelResponse> {\n try {\n const model = await getModel();\n const schemaOnlyTools: Record<string, ModelTool> | undefined = options?.tools\n ? (Object.fromEntries(\n Object.entries(options.tools).map(([name, t]) => {\n const { execute: _execute, ...rest } = t as Record<string, unknown>;\n return [name, rest];\n })\n ) as Record<string, ModelTool>)\n : undefined;\n const result = await generateText({\n model,\n messages,\n tools: schemaOnlyTools,\n maxOutputTokens: options?.maxOutputTokens,\n temperature: options?.temperature,\n stopSequences: options?.stop,\n });\n\n const toolCalls: ModelToolCall[] = result.toolCalls.map(tc => ({\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n input: tc.input as unknown,\n }));\n\n return {\n text: result.text,\n toolCalls,\n usage: result.usage,\n finishReason: result.finishReason,\n };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n throw new ModelError(`Failed to invoke ${provider} model`, provider, err);\n }\n },\n\n async generateVision(\n prompt: string,\n images: ImageInput[],\n options?: VisionOptions\n ): Promise<ModelResponse> {\n try {\n const model = await getModel();\n\n const content: (\n | { type: 'text'; text: string }\n | { type: 'image'; image: string; mimeType?: string }\n )[] = [];\n for (const img of images) {\n content.push({\n type: 'image',\n image: `data:${img.mimeType};base64,${img.base64}`,\n mimeType: img.mimeType,\n });\n }\n content.push({ type: 'text', text: prompt });\n\n const messages: ModelMessage[] = [];\n if (options?.systemPrompt) {\n messages.push({ role: 'system', content: options.systemPrompt });\n }\n messages.push({ role: 'user', content });\n\n const result = await generateText({\n model,\n messages,\n maxOutputTokens: options?.maxOutputTokens,\n temperature: options?.temperature,\n });\n\n return {\n text: result.text,\n toolCalls: [],\n usage: result.usage,\n finishReason: result.finishReason,\n };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n throw new ModelError(`Failed to generate vision response`, provider, err);\n }\n },\n\n async invokeObject<T>(\n messages: ModelMessage[],\n schema: unknown,\n options?: InvokeObjectOptions\n ): Promise<InvokeObjectResult<T>> {\n try {\n const model = await getModel();\n const schemaWrapped = zodSchema(schema as Parameters<typeof zodSchema>[0]);\n // Structured output; prefer generateObject until migrate to generateText+output\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n const result = await generateObject({\n model,\n messages,\n schema: schemaWrapped,\n temperature: options?.temperature,\n maxOutputTokens: options?.maxOutputTokens,\n });\n return {\n data: result.object as T,\n usage: result.usage,\n };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n throw new ModelError(`Failed to invokeObject ${provider} model`, provider, err);\n }\n },\n };\n}\n","/**\n * OpenAI model provider using AI SDK\n */\n\nimport type { Model, ModelConfig } from '../../types/model';\nimport { createAIModel } from './base';\nimport { createOpenAI } from '@ai-sdk/openai';\n\n/**\n * Create an OpenAI model instance\n */\nexport function createOpenAIModel(config: ModelConfig): Model {\n const { model: modelName, apiKey, baseUrl } = config;\n\n const provider = createOpenAI({\n apiKey: apiKey ?? process.env.OPENAI_API_KEY,\n baseURL: baseUrl,\n });\n\n return createAIModel({\n provider: 'openai',\n modelName,\n getModel: () => provider.chat(modelName),\n });\n}\n","/**\n * Anthropic model provider using AI SDK\n */\n\nimport type { Model, ModelConfig } from '../../types/model';\nimport { createAIModel } from './base';\nimport { createAnthropic } from '@ai-sdk/anthropic';\n\n/**\n * Create an Anthropic model instance\n */\nexport function createAnthropicModel(config: ModelConfig): Model {\n const { model: modelName, apiKey } = config;\n\n const provider = createAnthropic({\n apiKey: apiKey ?? process.env.ANTHROPIC_API_KEY,\n });\n\n return createAIModel({\n provider: 'anthropic',\n modelName,\n getModel: () => provider(modelName),\n });\n}\n","/**\n * Google (Gemini) model provider using AI SDK\n */\n\nimport type { Model, ModelConfig } from '../../types/model';\nimport { createAIModel } from './base';\nimport { createGoogleGenerativeAI } from '@ai-sdk/google';\n\n/**\n * Create a Google (Gemini) model instance\n */\nexport function createGoogleModel(config: ModelConfig): Model {\n const { model: modelName, apiKey } = config;\n\n const provider = createGoogleGenerativeAI({\n apiKey: apiKey ?? process.env.GOOGLE_GENERATIVE_AI_API_KEY,\n });\n\n return createAIModel({\n provider: 'google',\n modelName,\n getModel: () => provider(modelName),\n });\n}\n","/**\n * Create a model instance based on provider\n */\n\nimport type { Model, ModelConfig } from '../types/model';\nimport { ModelError } from '../utils/errors';\nimport { createOpenAIModel } from './providers/openai';\nimport { createAnthropicModel } from './providers/anthropic';\nimport { createGoogleModel } from './providers/google';\n\n/**\n * Create a model instance for the given provider\n *\n * @example\n * ```typescript\n * const model = createModel({\n * provider: 'openai',\n * model: 'gpt-4o',\n * temperature: 0.7\n * });\n *\n * const response = await model.invoke([\n * { role: 'user', content: 'Hello!' }\n * ]);\n * ```\n */\nexport function createModel(config: ModelConfig): Model {\n const { provider } = config;\n\n switch (provider) {\n case 'openai':\n return createOpenAIModel(config);\n case 'anthropic':\n return createAnthropicModel(config);\n case 'google':\n return createGoogleModel(config);\n default:\n throw new ModelError(\n `Unsupported provider: ${provider}. Supported providers: openai, anthropic, google`\n );\n }\n}\n","/**\n * Subagents: define, run, and expose as tools to a parent agent\n */\n\nimport { z } from 'zod';\nimport type { SubagentConfig, SubagentDefinition, SubagentResult } from '../types/subagent';\nimport type { AgentTool } from '../types/agent';\nimport type { Model } from '../types/model';\nimport { runAgent } from '../agents';\nimport { createModel } from '../models/create-model';\nimport { defineTool } from '../tools';\nimport type { ToolSet } from '../tools';\nimport { SubagentError } from '../utils/errors';\n\nconst NAME_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;\n\n/**\n * Validates and creates a subagent definition (analogous to defineTool).\n * Name must be kebab-case.\n */\nexport function defineSubagent(config: SubagentConfig): SubagentDefinition {\n if (!config.name.trim()) {\n throw new SubagentError('Subagent name is required', undefined);\n }\n if (!NAME_REGEX.test(config.name)) {\n throw new SubagentError(\n `Subagent name must be kebab-case (lowercase letters, numbers, hyphens): ${config.name}`,\n config.name\n );\n }\n return { ...config };\n}\n\nexport interface RunSubagentOptions {\n /** Parent's tools; used when definition does not specify tools (filtered by disallowedTools) */\n parentTools?: Record<string, AgentTool>;\n /** Parent's model; used when definition does not specify model */\n parentModel?: Model;\n}\n\n/**\n * Resolves the tool set for a subagent: definition.tools if set,\n * otherwise parentTools with disallowedTools removed.\n * Subagent tools (keys starting with \"subagent_\") are never inherited (no nesting).\n */\nfunction resolveTools(\n definition: SubagentDefinition,\n parentTools?: Record<string, AgentTool>\n): Record<string, AgentTool> {\n if (definition.tools != null && Object.keys(definition.tools).length > 0) {\n return definition.tools;\n }\n const base = parentTools ?? {};\n const disallowed = new Set(definition.disallowedTools ?? []);\n const filtered: Record<string, AgentTool> = {};\n for (const [key, t] of Object.entries(base)) {\n if (key.startsWith('subagent_')) continue; // no nesting\n if (!disallowed.has(key)) {\n filtered[key] = t;\n }\n }\n return filtered;\n}\n\n/**\n * Executes the subagent in isolation: resolves tools and model, runs runAgent, returns SubagentResult.\n */\nexport async function runSubagent(\n definition: SubagentDefinition,\n input: string,\n options?: RunSubagentOptions\n): Promise<SubagentResult> {\n const { parentTools, parentModel } = options ?? {};\n const tools = resolveTools(definition, parentTools);\n\n const model = definition.model == null ? parentModel : createModel(definition.model);\n if (!model) {\n throw new SubagentError(\n 'Subagent has no model: set definition.model or pass parentModel in options',\n definition.name\n );\n }\n const result = await runAgent({\n model,\n tools,\n systemPrompt: definition.systemPrompt,\n input,\n maxIterations: definition.maxIterations ?? 10,\n onStep: definition.onStep,\n });\n return { ...result, subagentName: definition.name };\n}\n\nexport interface CreateSubagentToolOptions {\n parentTools?: Record<string, AgentTool>;\n parentModel?: Model;\n}\n\n/**\n * Wraps a subagent as an AI SDK Tool so a parent agent can delegate via a tool call.\n * Input: { prompt: string }. Returns the subagent's final output string.\n */\nexport function createSubagentTool(\n definition: SubagentDefinition,\n options?: CreateSubagentToolOptions\n): AgentTool {\n const toolName = `subagent_${definition.name}`;\n return defineTool({\n name: toolName,\n description: definition.description,\n input: z.object({\n prompt: z.string().describe('The task or question to delegate to this subagent'),\n }),\n handler: async ({ prompt }) => {\n const result = await runSubagent(definition, prompt, {\n parentTools: options?.parentTools,\n parentModel: options?.parentModel,\n });\n return result.output;\n },\n });\n}\n\n/**\n * Creates a Record<string, Tool> from multiple subagent definitions, keyed by subagent_<name>.\n */\nexport function createSubagentToolSet(\n definitions: SubagentDefinition[],\n options?: CreateSubagentToolOptions\n): ToolSet {\n const out: ToolSet = {};\n for (const def of definitions) {\n const tool = createSubagentTool(def, options);\n out[`subagent_${def.name}`] = tool;\n }\n return out;\n}\n","/**\n * Handlebars template compiler - reads .hbs files, compiles with context, writes output\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport Handlebars from 'handlebars';\nimport type { TemplateContext, ScaffoldConfig, ScaffoldResult, ScaffoldError } from './types';\n\n/** Compile a single Handlebars template string with context */\nexport function compileTemplate(template: string, context: TemplateContext): string {\n const compiled = Handlebars.compile(template, { noEscape: true });\n return compiled(context);\n}\n\n/** Recursively find all .hbs files in a directory */\nfunction findHbsFiles(dir: string, base: string = dir): string[] {\n const results: string[] = [];\n if (!fs.existsSync(dir)) return results;\n\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n results.push(...findHbsFiles(fullPath, base));\n } else if (entry.name.endsWith('.hbs')) {\n results.push(path.relative(base, fullPath));\n }\n }\n return results;\n}\n\n/** Convert a .hbs relative path to the output file path (strip .hbs extension) */\nfunction toOutputPath(hbsRelPath: string): string {\n return hbsRelPath.replace(/\\.hbs$/, '');\n}\n\n/** Check if a path matches any skip pattern (simple glob: * matches any segment) */\nfunction shouldSkip(relativePath: string, skipPatterns: string[]): boolean {\n for (const pattern of skipPatterns) {\n const regex = new RegExp(\n '^' +\n pattern\n .replace(/\\./g, '\\\\.')\n .replace(/\\*\\*/g, '<<GLOBSTAR>>')\n .replace(/\\*/g, '[^/]*')\n .replace(/<<GLOBSTAR>>/g, '.*') +\n '$'\n );\n if (regex.test(relativePath)) return true;\n }\n return false;\n}\n\n/**\n * Scaffold a project: compile all .hbs templates in templateDir with context,\n * write results to outputDir, return summary.\n */\nexport async function scaffoldProject(config: ScaffoldConfig): Promise<ScaffoldResult> {\n const { templateDir, outputDir, context, skipPatterns = [] } = config;\n const hbsFiles = findHbsFiles(templateDir);\n const files: string[] = [];\n const errors: ScaffoldError[] = [];\n\n for (const hbsFile of hbsFiles) {\n if (shouldSkip(hbsFile, skipPatterns)) continue;\n\n const outputRelPath = toOutputPath(hbsFile);\n const inputPath = path.join(templateDir, hbsFile);\n const outputPath = path.join(outputDir, outputRelPath);\n\n try {\n const templateSource = fs.readFileSync(inputPath, 'utf-8');\n const compiled = compileTemplate(templateSource, context);\n\n fs.mkdirSync(path.dirname(outputPath), { recursive: true });\n fs.writeFileSync(outputPath, compiled, 'utf-8');\n files.push(outputRelPath);\n } catch (err) {\n errors.push({\n file: hbsFile,\n message: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n return { fileCount: files.length, files, errors };\n}\n\n/** Register common Handlebars helpers */\nexport function registerHelpers(): void {\n Handlebars.registerHelper('eq', (a, b) => a === b);\n Handlebars.registerHelper('neq', (a, b) => a !== b);\n Handlebars.registerHelper('json', obj => JSON.stringify(obj, null, 2));\n Handlebars.registerHelper('uppercase', (str: string) =>\n typeof str === 'string' ? str.toUpperCase() : ''\n );\n Handlebars.registerHelper('lowercase', (str: string) =>\n typeof str === 'string' ? str.toLowerCase() : ''\n );\n Handlebars.registerHelper('capitalize', (str: string) =>\n typeof str === 'string' ? str.charAt(0).toUpperCase() + str.slice(1) : ''\n );\n Handlebars.registerHelper('camelCase', (str: string) => {\n if (typeof str !== 'string') return '';\n return str\n .replace(/[-_\\s]+(.)?/g, (_, c: string) => (c ? c.toUpperCase() : ''))\n .replace(/^(.)/, c => c.toLowerCase());\n });\n Handlebars.registerHelper('pascalCase', (str: string) => {\n if (typeof str !== 'string') return '';\n return str\n .replace(/[-_\\s]+(.)?/g, (_, c: string) => (c ? c.toUpperCase() : ''))\n .replace(/^(.)/, c => c.toUpperCase());\n });\n}\n\n// Register helpers on module load\nregisterHelpers();\n","/**\n * MCP SDK transport creation and result parsing. Isolates SDK path and dynamic imports.\n */\n\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { McpTransport, McpToolContent } from './types';\n\nfunction getSdkRoot(): string {\n const require = createRequire(import.meta.url);\n const entry = require.resolve('@modelcontextprotocol/sdk/client');\n return path.dirname(path.dirname(path.dirname(path.dirname(entry))));\n}\n\nconst sdkRoot = getSdkRoot();\n\n/** Parse first text content block of an MCP tool result to JSON or { text } / { raw }. */\nexport function parseToolResult(result: { content?: McpToolContent[] }): unknown {\n const content = result.content;\n if (!content?.length) return {};\n const first = content[0];\n if (first?.type === 'text' && typeof first.text === 'string') {\n const text = first.text.trim();\n if (text.startsWith('{') || text.startsWith('[')) {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return { raw: text };\n }\n }\n return { text };\n }\n return result;\n}\n\n/** Build StreamableHTTPClientTransport from the MCP SDK. */\nexport async function createHttpTransport(\n url: string,\n headers?: Record<string, string>\n): Promise<McpTransport> {\n const modPath = path.join(sdkRoot, 'dist', 'esm', 'client', 'streamableHttp.js');\n const mod = (await import(pathToFileURL(modPath).href)) as {\n StreamableHTTPClientTransport: new (\n url: URL,\n opts?: { requestInit?: RequestInit }\n ) => McpTransport;\n };\n const requestInit: RequestInit | undefined = headers\n ? { headers: new Headers(headers) }\n : undefined;\n return new mod.StreamableHTTPClientTransport(\n new URL(url),\n requestInit ? { requestInit } : undefined\n );\n}\n\n/** Build StdioClientTransport from the MCP SDK. */\nexport async function createStdioTransport(command: string, args: string[]): Promise<McpTransport> {\n const modPath = path.join(sdkRoot, 'dist', 'esm', 'client', 'stdio.js');\n const mod = (await import(pathToFileURL(modPath).href)) as {\n StdioClientTransport: new (params: { command: string; args: string[] }) => McpTransport;\n };\n return new mod.StdioClientTransport({ command, args });\n}\n","/**\n * BaseMcpClient - reusable MCP client with lazy connection and typed tool invocation.\n * Extend and add domain methods that call this.callTool(name, args).\n */\n\nimport { Client } from '@modelcontextprotocol/sdk/client';\nimport { ToolError } from '../utils/errors';\nimport { createHttpTransport, createStdioTransport, parseToolResult } from './transports';\nimport type {\n McpClientConfig,\n McpClientInfo,\n McpToolContent,\n McpTransport,\n McpResolveOptions,\n} from './types';\n\nexport class BaseMcpClient {\n private readonly info: McpClientInfo;\n private readonly config: McpClientConfig;\n private client: Client | null = null;\n private transport: McpTransport | null = null;\n private connectPromise: Promise<void> | null = null;\n\n constructor(info: McpClientInfo, config: McpClientConfig) {\n this.info = info;\n this.config = config;\n }\n\n /** Build config from options + env (<PREFIX>_URL, _API_KEY, _COMMAND, _ARGS). */\n static resolveConfig(\n options?: McpClientConfig,\n resolveOpts: McpResolveOptions = { envPrefix: 'MCP' }\n ): McpClientConfig {\n const { envPrefix, serverLabel, apiKeyHeader } = resolveOpts;\n const url = options?.url ?? process.env[`${envPrefix}_URL`];\n const apiKey = process.env[`${envPrefix}_API_KEY`];\n const command = options?.command ?? process.env[`${envPrefix}_COMMAND`];\n const argsEnv = process.env[`${envPrefix}_ARGS`];\n const args = options?.args ?? (argsEnv ? argsEnv.split(',').map(a => a.trim()) : undefined);\n\n let headers = options?.headers ? { ...options.headers } : undefined;\n if (apiKey) {\n const name = apiKeyHeader ?? 'Authorization';\n\n headers = headers ?? {};\n\n headers[name] = name === 'Authorization' ? `Bearer ${apiKey}` : apiKey;\n }\n\n if (url) return { url, headers };\n if (command) return { command, args: args?.length ? args : [] };\n throw new ToolError(\n `${serverLabel ?? envPrefix} uses MCP only. Set ${envPrefix}_URL or ${envPrefix}_COMMAND (and optionally ${envPrefix}_ARGS).`,\n 'mcp_client'\n );\n }\n\n private async ensureConnected(): Promise<Client> {\n if (this.client) return this.client;\n if (this.connectPromise) {\n await this.connectPromise;\n if (!this.client) throw new ToolError('MCP connection failed.', 'mcp_client');\n return this.client;\n }\n this.connectPromise = this.doConnect();\n await this.connectPromise;\n this.connectPromise = null;\n if (!this.client) throw new ToolError('MCP connection failed.', 'mcp_client');\n return this.client;\n }\n\n private async doConnect(): Promise<void> {\n const client = new Client(\n { name: this.info.name, version: this.info.version },\n { capabilities: {} }\n );\n if (this.config.url) {\n this.transport = await createHttpTransport(this.config.url, this.config.headers);\n } else if (this.config.command) {\n this.transport = await createStdioTransport(this.config.command, this.config.args ?? []);\n } else {\n throw new ToolError('MCP config missing: provide url or command.', 'mcp_client');\n }\n await client.connect(this.transport as Parameters<Client['connect']>[0]);\n this.client = client;\n }\n\n /** Call MCP tool and parse result. Subclasses use this for typed domain methods. */\n protected async callTool<T>(name: string, args: Record<string, unknown> = {}): Promise<T> {\n const client = await this.ensureConnected();\n const result = await client.callTool({ name, arguments: args });\n if (result && typeof result === 'object' && 'content' in result) {\n return parseToolResult(result as { content?: McpToolContent[] }) as T;\n }\n return result as T;\n }\n\n async close(): Promise<void> {\n if (this.transport) {\n await this.transport.close();\n this.transport = null;\n }\n this.client = null;\n this.connectPromise = null;\n }\n}\n","/**\n * Context management for planning chat\n */\n\nimport type { PlanningContext, PlanStageResult, PlanSections, Stage, ChatEntry } from './types';\n\nconst EMPTY_SECTIONS: PlanSections = {\n overview: null,\n techStack: null,\n featureDecisions: null,\n dataModels: null,\n pagesAndRoutes: null,\n authFlow: null,\n apiRoutes: null,\n implementation: null,\n executionPlan: null,\n edgeCases: null,\n testingChecklist: null,\n};\n\nexport function createInitialContext(): PlanningContext {\n return {\n stage: 'discovery',\n projectDescription: null,\n sections: { ...EMPTY_SECTIONS },\n history: [],\n pendingQuestions: [],\n };\n}\n\nexport function mergeStageResult(\n context: PlanningContext,\n result: PlanStageResult\n): PlanningContext {\n const { sections: newSections, projectDescription, pendingQuestions } = result;\n const sections: PlanSections = { ...context.sections };\n if (newSections) {\n for (const key of Object.keys(newSections) as (keyof PlanSections)[]) {\n const v = newSections[key];\n if (v !== undefined && v !== null) sections[key] = v;\n }\n }\n return {\n ...context,\n ...(projectDescription !== undefined && { projectDescription }),\n sections,\n ...(pendingQuestions !== undefined && { pendingQuestions }),\n };\n}\n\nexport function addChatEntry(\n context: PlanningContext,\n role: 'user' | 'assistant',\n content: string\n): PlanningContext {\n const entry: ChatEntry = { role, content };\n return {\n ...context,\n history: [...context.history, entry],\n };\n}\n\nexport function advanceStage(context: PlanningContext): PlanningContext {\n const order: Stage[] = ['discovery', 'requirements', 'design', 'complete'];\n const idx = order.indexOf(context.stage);\n const nextStage = idx >= 0 && idx < order.length - 1 ? order[idx + 1] : undefined;\n const next: Stage = nextStage ?? context.stage;\n return { ...context, stage: next };\n}\n","/**\n * Shared utilities for planning stages - no JSON extraction or parsing\n */\n\nimport type { PlanningContext } from '../types';\n\n/** Whether the user message is a confirmation (continue / yes / looks good) */\nexport function isConfirmation(message: string): boolean {\n const normalized = message.trim().toLowerCase();\n const confirmations = [\n 'continue',\n 'yes',\n 'yeah',\n 'yep',\n 'looks good',\n 'good',\n 'ok',\n 'okay',\n 'next',\n 'proceed',\n 'sure',\n ];\n return confirmations.some(c => normalized === c || normalized.startsWith(c + ' '));\n}\n\n/** Build a short text summary of context for logging */\nexport function buildContextSummary(ctx: PlanningContext): string {\n const parts: string[] = [];\n if (ctx.projectDescription) parts.push('Project description set');\n const sections = Object.entries(ctx.sections).filter(\n (entry): entry is [string, string] => typeof entry[1] === 'string' && entry[1].length > 0\n );\n if (sections.length) parts.push(`Sections: ${sections.map(([k]) => k).join(', ')}`);\n return parts.join('. ') || 'No context yet';\n}\n","/**\n * System prompt for planning module - markdown-only, pro-level output\n */\n\nexport const PLANNING_SYSTEM_PROMPT = `You are a senior software architect creating a single, implementation-ready plan that a developer can follow without ambiguity.\n\nCRITICAL RULES:\n- 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.\n- 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**).\n- 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.`;\n","/**\n * Discovery stage prompt - understand project, ask questions; pro format when ready\n */\n\nexport const DISCOVERY_SYSTEM_FRAGMENT = `You are in the discovery stage. Your goal is to understand what the user wants to build.\n\nRespond in natural language only. Do NOT output JSON.\n\n- 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.\n- When you have enough to proceed: output the project overview in this exact pro format so it matches the rest of the plan:\n - **## Overview** — One paragraph (2–4 sentences) summarizing the project and its purpose.\n - **## Core Features** — Numbered list: 1. **Feature Name** - Short description. (one line per feature)\n - **## Tech Stack** — Bullet list with category labels: - **Frontend**: ... (versions if known), - **Database**: ..., - **Authentication**: ..., - **API**: ..., - **Backend**: ... Include versions and key libraries where relevant.\n\nWhen 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.`;\n\nexport const DISCOVERY_USER_PROMPT = `## Current user message:\n{userMessage}\n\n## Prior conversation (if any):\n{history}\n\nRespond 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.`;\n\nexport function buildDiscoveryPrompt(userMessage: string, history: string): string {\n return DISCOVERY_USER_PROMPT.replace('{userMessage}', userMessage).replace(\n '{history}',\n history || '(No prior messages)'\n );\n}\n","/**\n * Requirements stage prompts - pro-level markdown sections\n */\n\nconst CONTEXT_BLOCK = `## Project description / context:\n{context}`;\n\nexport const REQUIREMENTS_OVERVIEW_PROMPT = `${CONTEXT_BLOCK}\n\nUsing the project description above, write two markdown sections in this exact format:\n\n1. **## Overview** — One paragraph only (2–4 sentences) summarizing the project and its purpose.\n2. **## Tech Stack** — 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.\n\nOutput only these two sections in markdown. Do NOT output JSON.`;\n\nexport const REQUIREMENTS_FEATURE_DATA_PROMPT = `${CONTEXT_BLOCK}\n\n## Already written (Overview + Tech Stack):\n{overviewAndTechStack}\n\nWrite the next two markdown sections in this exact format:\n\n1. **## Feature Decisions** — 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).\n2. **## Data Models** — 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.\n\nOutput only markdown. Do NOT output JSON.`;\n\nexport const REQUIREMENTS_PAGES_PROMPT = `${CONTEXT_BLOCK}\n\n## Already written:\n{priorSections}\n\nWrite the next markdown section in this exact format:\n\n**## Pages and Routes**\n- **### Public Pages (No Authentication Required)** and **### Protected Pages (Authentication Required)**.\n- For each page use: #### \\`/path\\` - Page Title\n- Under each page, include bullets for: purpose, form fields and validation (e.g. \"Form validation: Required fields, valid email format\"), buttons/actions, empty states, redirects on success/error (e.g. \"On success: Redirect to /dashboard\"), key UI (cards, sidebar, charts). Match the depth of a pro implementation spec so a developer can build the page from this alone.\n\nOutput only markdown. Do NOT output JSON.`;\n\nexport const REQUIREMENTS_AUTH_PROMPT = `${CONTEXT_BLOCK}\n\n## Already written:\n{priorSections}\n\nWrite the next markdown section in this exact format:\n\n**## Authentication Flow** — Use these subsections: ### Sign Up Flow, ### Login Flow, ### Logout Flow, ### Protected Route Middleware, ### API Authentication Middleware.\n- Use **numbered steps** in each flow. Include both frontend and backend steps (e.g. \"4. Frontend sends POST to /api/auth/signup with { name, email, password }\", \"5. Backend validates input\", \"6. Backend hashes password with bcrypt (10 rounds)\", \"7. Backend sets JWT in HTTP-only cookie (name, maxAge, httpOnly, secure, sameSite)\").\n- For middleware: steps for cookie check, JWT verify, attach userId to request, return 401 when invalid.\n\nOutput only markdown. Do NOT output JSON.`;\n\nexport function buildRequirementsOverviewPrompt(context: string): string {\n return REQUIREMENTS_OVERVIEW_PROMPT.replace('{context}', context);\n}\n\nexport function buildRequirementsFeatureDataPrompt(\n context: string,\n overviewAndTechStack: string\n): string {\n return REQUIREMENTS_FEATURE_DATA_PROMPT.replace('{context}', context).replace(\n '{overviewAndTechStack}',\n overviewAndTechStack\n );\n}\n\nexport function buildRequirementsPagesPrompt(context: string, priorSections: string): string {\n return REQUIREMENTS_PAGES_PROMPT.replace('{context}', context).replace(\n '{priorSections}',\n priorSections\n );\n}\n\nexport function buildRequirementsAuthPrompt(context: string, priorSections: string): string {\n return REQUIREMENTS_AUTH_PROMPT.replace('{context}', context).replace(\n '{priorSections}',\n priorSections\n );\n}\n","/**\n * Design stage prompts - pro-level API routes and implementation details\n */\n\nconst DESIGN_CONTEXT = `## Project context (all sections so far):\n{priorSections}`;\n\nexport const DESIGN_API_ROUTES_PROMPT = `${DESIGN_CONTEXT}\n\nWrite the next markdown section in this exact format:\n\n**## API Routes**\n- Group by domain: ### Authentication Endpoints, ### Exercise Endpoints, ### Workout Endpoints, etc.\n- For each endpoint use: #### METHOD \\`/path\\` (e.g. #### POST \\`/api/auth/signup\\`)\n- Under each endpoint include:\n - **Purpose**: one line\n - **Request Body** or **Query Parameters** (and **Validation** bullets: required, format, lengths)\n - **Response on Success (status)**: code block with example JSON (e.g. 200, 201)\n - **Response on Error**: bullets (e.g. 400 validation, 401, 403, 404, 500 with message)\n - **Side Effects** or **Implementation** where relevant (e.g. \"Creates User and UserProfile; sets auth cookie\")\n- Use code blocks ONLY for request/response JSON examples. No JSON elsewhere.\n\nOutput only markdown. Do NOT output JSON except inside code blocks.`;\n\nexport const DESIGN_IMPLEMENTATION_PROMPT = `${DESIGN_CONTEXT}\n\n## API Routes (already written):\n{apiRoutes}\n\nWrite the next markdown section in this exact format:\n\n**## Implementation Details**\n- **### File Structure** — 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.\n- **### Environment Variables** — List with comments (e.g. MONGODB_URI=... # connection string, JWT_SECRET=... # change in production).\n- **### Dependencies to Install** — npm install line and short explanation per dependency (e.g. mongoose: MongoDB ODM; bcryptjs: password hashing; jsonwebtoken: JWT; cookie: cookie parsing).\n- **### Key Setup** — One subsection per concern: **MongoDB connection** (file path, purpose, 3–5 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).\n- 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).\n\nOutput only markdown. Do NOT output JSON.`;\n\nexport function buildDesignApiRoutesPrompt(priorSections: string): string {\n return DESIGN_API_ROUTES_PROMPT.replace('{priorSections}', priorSections);\n}\n\nexport function buildDesignImplementationPrompt(priorSections: string, apiRoutes: string): string {\n return DESIGN_IMPLEMENTATION_PROMPT.replace('{priorSections}', priorSections).replace(\n '{apiRoutes}',\n apiRoutes\n );\n}\n","/**\n * Synthesis stage prompt - pro-level final sections (order matters for splitting)\n */\n\nconst SYNTHESIS_CONTEXT = `## Full plan so far (all sections):\n{priorSections}`;\n\nexport const SYNTHESIS_SYSTEM_FRAGMENT = `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.`;\n\nexport const SYNTHESIS_USER_PROMPT = `${SYNTHESIS_CONTEXT}\n\nWrite the following sections in this exact order. Output only markdown. Do NOT output JSON.\n\n**Block 1 — Implementation Order, Current State, Desired End State**\n\n1. **## Implementation Order** — 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.\n\n2. **## Current State Analysis** — 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.).\n\n3. **## Desired End State** — 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.\n\n**Block 2 — Edge Cases, Security, Performance, Future Enhancements**\n\n4. **## Edge Cases and Considerations** — ### 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\").\n\n5. **## Security Considerations** — 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).\n\n6. **## Performance Considerations** — 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.\n\n7. **## Future Enhancements (Not in Current Scope)** — Short grouped list (e.g. Social, Analytics, Integrations, Mobile, Premium) so scope is clear. One line per group is enough.\n\n**Block 3 — Manual Testing Checklist**\n\n8. **## Manual Testing Checklist** — ### 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\").\n\nOutput all eight sections in the order above. Do NOT output JSON.`;\n\nexport function buildSynthesisPrompt(priorSections: string): string {\n return SYNTHESIS_USER_PROMPT.replace('{priorSections}', priorSections);\n}\n","/**\n * System prompt for the edit-plan pipeline.\n * Instructs the LLM to revise an existing plan based on feedback.\n */\n\nexport const EDIT_PLAN_SYSTEM_PROMPT = `You are a senior software architect revising an existing implementation plan.\n\nCRITICAL RULES:\n- You will receive the FULL existing plan and the user's feedback or edit instructions.\n- Output ONLY the complete revised plan in markdown. Do NOT output partial plans, explanations, or commentary.\n- Preserve the same section structure (## headings) as the original plan.\n- Only modify sections that are affected by the feedback. Leave unrelated sections intact.\n- Use code blocks ONLY for: request/response JSON examples, file/directory trees, and env or config snippets.\n- Be concrete and actionable: include validation rules, HTTP status codes, redirects, field-level data model descriptions, and step-by-step auth flows.\n- 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).`;\n\nexport function buildEditPlanPrompt(existingPlan: string, feedback: string): string {\n return `## Existing Plan\\n\\n${existingPlan}\\n\\n---\\n\\n## Edit Instructions\\n\\n${feedback}`;\n}\n","/**\n * Discovery stage - understand project, optional questions; output is raw markdown\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { PlanningContext, PlanStageResult } from '../types';\nimport {\n PLANNING_SYSTEM_PROMPT,\n DISCOVERY_SYSTEM_FRAGMENT,\n buildDiscoveryPrompt,\n} from '../prompts';\nimport { isConfirmation } from './base';\n\n/** Heuristic: response contains project overview (markdown headers we expect when ready to advance) */\nfunction hasProjectOverview(text: string): boolean {\n const t = text.trim();\n if (t.length < 100) return false;\n // Primary: exact markdown headers\n if (t.includes('## Overview') || t.includes('## Core Features')) return true;\n // Secondary: bold-label or h1 variants the LLM might use\n const lower = t.toLowerCase();\n if (\n (lower.includes('overview') || lower.includes('core features')) &&\n (lower.includes('tech stack') || lower.includes('technology'))\n ) {\n return true;\n }\n return false;\n}\n\nexport async function runDiscoveryStage(\n userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<PlanStageResult> {\n logger?.debug('Discovery stage started', { historyLength: context.history.length });\n\n // Exclude the last entry from history if it duplicates the current userMessage\n // (processPlanningChat calls addChatEntry before runStage)\n const historyEntries = context.history.slice(0, -1);\n const history = historyEntries\n .map(e => `${e.role}: ${e.content}`)\n .slice(-10)\n .join('\\n');\n const prompt = buildDiscoveryPrompt(userMessage, history);\n const systemContent = `${PLANNING_SYSTEM_PROMPT}\\n\\n${DISCOVERY_SYSTEM_FRAGMENT}`;\n const messages = [\n { role: 'system' as const, content: systemContent },\n { role: 'user' as const, content: prompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 4096 });\n const message = response.text?.trim() ?? '';\n\n const hasOverview = hasProjectOverview(message);\n const userConfirmed = isConfirmation(userMessage);\n // Safety net: after enough discovery turns with confirmations, force advance\n const forceAdvance = userConfirmed && context.history.length >= 7 && message.length > 50;\n // Advance when: (1) we got overview, (2) user confirmed & description exists, or (3) safety net\n const advance =\n (hasOverview && (context.projectDescription == null || userConfirmed)) ||\n (userConfirmed && context.projectDescription != null) ||\n forceAdvance;\n const storeDescription = hasOverview || (forceAdvance && message.length > 50);\n\n logger?.debug('Discovery stage complete', {\n advance,\n hasOverview,\n userConfirmed,\n forceAdvance,\n });\n\n return {\n message,\n advance,\n sections: {},\n ...(storeDescription && { projectDescription: message }),\n };\n}\n","/**\n * Discovery state - placeholder until discovery.stage is implemented\n */\n\nimport type { PlanningContext, PlanStageResult, StageInput } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { runDiscoveryStage } from './discovery.stage';\n\nexport class DiscoveryState implements PlanningStageState {\n readonly stageName = 'discovery' as const;\n\n async process(context: PlanningContext, input: StageInput): Promise<PlanStageResult> {\n return runDiscoveryStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: PlanStageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): 'requirements' | null {\n return 'requirements';\n }\n}\n","/**\n * entity-analyzer subagent - extracts entities, fields, and relationships from requirements\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ENTITY_ANALYZER_SYSTEM_PROMPT = `You are an expert database entity analyst. Your job is to extract data model signals from requirements.\n\nPerform these analyses:\n\n## Entity Discovery\n- List every entity implied by the requirements (users, domain objects, settings, logs).\n- For each entity: name, purpose, key fields (with types), and which user type owns it.\n- Identify status enums from flow transitions (e.g. pending -> active -> completed).\n\n## Field Analysis\n- For each entity, list fields with: name, likely type, required/optional, unique constraints.\n- Identify computed vs stored fields.\n- Note fields that need indexing (lookups, sorting, filtering).\n\n## Relationship Signals\n- List entity pairs that reference each other.\n- Note ownership direction (which entity \"belongs to\" which).\n- Identify potential M:N relationships that may need join tables.\n\nRespond with a clear, structured analysis using headings and bullet points. Do NOT return JSON.`;\n\nexport const entityAnalyzerSubagent = defineSubagent({\n name: 'entity-analyzer',\n description:\n 'Analyzes requirements to extract entities, fields, relationships, and data model signals. Use when you need to understand the data before designing the schema.',\n systemPrompt: ENTITY_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * relationship-mapper subagent - maps cardinality, foreign keys, indexes\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst RELATIONSHIP_MAPPER_SYSTEM_PROMPT = `You are a database relationship specialist. Given a list of entities and their fields, you determine:\n\n## Cardinality Analysis\n- For every entity pair that references each other, classify: 1:1, 1:N, or M:N.\n- Explain the reasoning (e.g. \"A User has many Orders, but an Order belongs to one User -> 1:N\").\n\n## Foreign Key / Reference Strategy\n- For MongoDB: recommend ObjectId references vs embedding. Embed when: data is small, always read together, rarely updated independently.\n- For PostgreSQL: define foreign key columns, ON DELETE behavior (CASCADE, SET NULL, RESTRICT).\n\n## Join Table Design (M:N)\n- When M:N is detected, design the join table with: both foreign keys, any extra fields (e.g. role in a membership), indexes.\n\n## Index Recommendations\n- Suggest compound indexes for common query patterns.\n- Suggest unique indexes for natural keys (email, slug, etc.).\n- Note partial indexes where applicable (e.g. only active records).\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const relationshipMapperSubagent = defineSubagent({\n name: 'relationship-mapper',\n description:\n 'Maps cardinality (1:1, 1:N, M:N), foreign keys, join tables, and index recommendations for entity relationships. Use after entity analysis.',\n systemPrompt: RELATIONSHIP_MAPPER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * schema-refiner subagent - reviews schema for completeness and performance\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst SCHEMA_REFINER_SYSTEM_PROMPT = `You are an expert database schema reviewer. Your job is to:\n\n1. Validate the schema structure: every entity has fields, indexes, and relations properly defined.\n2. Check completeness: all entities from requirements are present, all relationships are bidirectional where needed.\n3. Check normalization: no redundant data, proper use of references vs embedding.\n4. Check performance: indexes cover common query patterns, no missing indexes on foreign keys.\n5. Check security: passwords are marked as hashed, sensitive fields noted, no plaintext secrets.\n6. Check conventions: consistent naming (camelCase or snake_case), timestamps on all entities.\n\nIf you have access to the validate_schema tool, use it first. Then provide a detailed review with:\n- Issues found (with severity: critical, warning, suggestion)\n- Specific fixes for each issue\n- Overall assessment (ready / needs work)\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport function createSchemaRefinerSubagent() {\n return defineSubagent({\n name: 'schema-refiner',\n description:\n 'Reviews a data model schema for completeness, normalization, performance, and security. Has access to validate_schema tool.',\n systemPrompt: SCHEMA_REFINER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 3,\n });\n}\n","/**\n * page-planner subagent - designs page structure, routes, and layouts\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst PAGE_PLANNER_SYSTEM_PROMPT = `You are a UX-focused frontend architect. You design detailed page specifications.\n\n## Page Planning\nFor each page in the application:\n\n### Route Definition\n- Path (e.g. /login, /dashboard, /workouts/:id)\n- Access level: public (no auth) or protected (requires auth)\n- Page name and purpose (one sentence)\n\n### Page Detail\n- **Form fields**: name, type (text, email, password, number, select, textarea, date, checkbox), required flag, validation rule.\n- **Actions**: buttons and what they do (e.g. \"Submit form\", \"Delete item\", \"Export CSV\").\n- **Empty state**: what to show when there's no data (e.g. \"No workouts yet. Click + to add one.\").\n- **Error state**: how to handle errors (e.g. \"Show inline validation errors\", \"Toast notification\").\n- **Redirect on success**: where to go after successful action (e.g. \"/dashboard\").\n- **Key UI elements**: cards, tables, charts, sidebar, modals, tabs.\n\n### Page Grouping\n- Group by access: public pages first, then protected.\n- Order by user flow: signup -> login -> dashboard -> feature pages -> settings -> admin.\n\nRespond with structured page specs. Do NOT return JSON.`;\n\nexport const pagePlannerSubagent = defineSubagent({\n name: 'page-planner',\n description:\n 'Designs detailed page specifications with routes, form fields, actions, states, and UI elements. Use for frontend page design.',\n systemPrompt: PAGE_PLANNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * component-analyzer subagent - identifies reusable components and shared layouts\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst COMPONENT_ANALYZER_SYSTEM_PROMPT = `You are a component design specialist. Given page specifications, you identify reusable components and shared patterns.\n\n## Component Identification\n- **Layout components**: main layout (with nav, sidebar, content area), auth layout (centered form), admin layout.\n- **Navigation components**: navbar, sidebar, breadcrumbs, mobile menu.\n- **Form components**: reusable form inputs, form wrappers, validation display.\n- **Display components**: cards, tables, lists, stat widgets, charts, badges.\n- **Shared components**: modals, toasts, loading spinners, empty state illustrations, error boundaries.\n\n## Component Analysis\nFor each component:\n- Name (PascalCase)\n- Type: layout, shared, form, display, navigation\n- Purpose (one sentence)\n- Props it accepts (e.g. \"user\", \"items\", \"onSubmit\", \"isLoading\")\n- Which pages use it\n\n## State Management\n- Identify which state is per-page (form state, UI state) vs global (auth state, user preferences).\n- Recommend server vs client state strategy.\n- Identify data fetching patterns (on mount, on action, real-time).\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const componentAnalyzerSubagent = defineSubagent({\n name: 'component-analyzer',\n description:\n 'Identifies reusable components, shared layouts, and state management patterns from page specifications. Use after page planning.',\n systemPrompt: COMPONENT_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * framework-selector subagent - recommends React/Vite or Next.js\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst FRAMEWORK_SELECTOR_SYSTEM_PROMPT = `You are a frontend technology advisor. Given project requirements, you recommend the best frontend framework.\n\n## Decision Criteria\n\n### Choose \"react-vite\" (Vite + React SPA) when:\n- The app is a single-page application (SPA) behind authentication\n- No SEO requirements (admin dashboards, internal tools, B2B apps)\n- Backend is a separate API (GraphQL or REST) already built\n- Simple routing with client-side navigation\n- Team prefers traditional React patterns (hooks, context)\n\n### Choose \"nextjs\" (Next.js App Router) when:\n- SEO is important (marketing pages, blogs, e-commerce storefronts)\n- Need server-side rendering (SSR) or static site generation (SSG)\n- Want unified frontend + API in one project (server actions, API routes)\n- Need streaming and progressive rendering\n- Complex data fetching with caching requirements\n- Mix of public and authenticated pages\n\n## Output Format\nState your recommendation clearly:\n- Framework: react-vite | nextjs\n- Reasoning: 2-3 sentences explaining why\n- Trade-offs: what you would lose with the alternative\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const frameworkSelectorSubagent = defineSubagent({\n name: 'framework-selector',\n description:\n 'Analyzes project requirements and recommends React/Vite SPA or Next.js. Use to determine the frontend framework before delegating to a builder.',\n systemPrompt: FRAMEWORK_SELECTOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * security-analyzer subagent - analyzes security requirements and threat vectors\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst SECURITY_ANALYZER_SYSTEM_PROMPT = `You are a web security specialist. You analyze project requirements for security concerns and design security policies.\n\n## Authentication Analysis\n- Determine the best auth strategy (JWT, session, OAuth) based on requirements.\n- JWT: token expiry, refresh strategy, cookie vs header, httpOnly/secure/sameSite flags.\n- Session: session store (memory, Redis, DB), cookie config, session expiry.\n- OAuth: which providers, callback flow, token exchange, account linking.\n\n## Password Security\n- Hashing algorithm (bcrypt recommended), cost factor (10+ rounds).\n- Password requirements: minimum length, complexity rules.\n- Password reset flow: token generation, expiry, one-time use.\n\n## Authorization Analysis\n- Identify role hierarchy (e.g. admin > moderator > user).\n- Map roles to permissions per resource (CRUD matrix).\n- Resource ownership checks (users can only modify their own data).\n\n## Threat Analysis\n- Rate limiting: login attempts, API calls, password reset requests.\n- CORS: allowed origins, methods, headers.\n- Input sanitization: XSS prevention, SQL injection prevention.\n- Brute force protection: account lockout, exponential backoff.\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const securityAnalyzerSubagent = defineSubagent({\n name: 'security-analyzer',\n description:\n 'Analyzes security requirements, threat vectors, and designs security policies. Use to understand auth needs before designing flows.',\n systemPrompt: SECURITY_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * flow-designer subagent - designs step-by-step auth flows\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst FLOW_DESIGNER_SYSTEM_PROMPT = `You are an authentication flow architect. You design detailed, numbered step-by-step auth flows.\n\nFor each flow (signup, login, logout, password reset, protected route middleware, API auth middleware):\n\n## Flow Design Pattern\n1. Number each step sequentially.\n2. Mark each step as \"frontend\" or \"backend\".\n3. Describe the action clearly (e.g. \"Frontend sends POST to /api/auth/signup with { name, email, password }\").\n4. Include implementation details (e.g. \"Backend hashes password with bcrypt (10 rounds)\").\n\n## Signup Flow\n- Frontend: form validation, submit request.\n- Backend: validate input, check existing user, hash password, create user + profile, generate token, set cookie.\n- Frontend: redirect to dashboard.\n\n## Login Flow\n- Frontend: form validation, submit credentials.\n- Backend: find user, compare password hash, generate token, set cookie.\n- Frontend: redirect to dashboard.\n\n## Password Reset Flow\n- Frontend: request reset (email).\n- Backend: generate reset token, send email.\n- Frontend: enter new password with token.\n- Backend: validate token, hash new password, update user, invalidate token.\n\n## Middleware Flows\n- Protected route: check cookie/header, verify token, attach user to request, reject if invalid.\n- API auth: same as above but for API routes, return 401 JSON.\n\nRespond with structured numbered flows. Do NOT return JSON.`;\n\nexport const flowDesignerSubagent = defineSubagent({\n name: 'flow-designer',\n description:\n 'Designs detailed step-by-step authentication flows (signup, login, logout, password reset, middleware). Use after security analysis.',\n systemPrompt: FLOW_DESIGNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * Requirements stage - delegates to specialist agents:\n * data-modeler (data models), auth-designer (auth flow), frontend-architect (pages/routes)\n * Overview, tech stack, and feature decisions use direct LLM calls for markdown output.\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { PlanningContext, PlanStageResult } from '../types';\nimport { PLANNING_SYSTEM_PROMPT } from '../prompts';\nimport { buildRequirementsOverviewPrompt, buildRequirementsFeatureDataPrompt } from '../prompts';\nimport { runSubagent } from '../../../lib/subagents';\nimport { entityAnalyzerSubagent } from '../../data-modeler/subagents';\nimport { pagePlannerSubagent } from '../../frontend-architect/subagents';\nimport { flowDesignerSubagent } from '../../auth-designer/subagents';\n\nfunction invokeMarkdown(model: Model, systemPrompt: string, userPrompt: string): Promise<string> {\n const messages = [\n { role: 'system' as const, content: systemPrompt },\n { role: 'user' as const, content: userPrompt },\n ];\n return model\n .invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 })\n .then(r => r.text?.trim() ?? '');\n}\n\nfunction splitOverviewAndTechStack(text: string): { overview: string; techStack: string } {\n const idx = text.indexOf('## Tech Stack');\n if (idx < 0) return { overview: text, techStack: '' };\n return { overview: text.slice(0, idx).trim(), techStack: text.slice(idx).trim() };\n}\n\nfunction splitFeatureDecisionsAndDataModels(text: string): {\n featureDecisions: string;\n dataModels: string;\n} {\n const idx = text.indexOf('## Data Models');\n if (idx < 0) return { featureDecisions: text, dataModels: '' };\n return { featureDecisions: text.slice(0, idx).trim(), dataModels: text.slice(idx).trim() };\n}\n\nexport async function runRequirementsStage(\n _userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<PlanStageResult> {\n logger?.debug('Requirements stage started (specialist agents)');\n\n const ctx = context.projectDescription ?? '';\n if (!ctx) {\n return {\n message: 'No project description yet. Complete discovery first.',\n advance: false,\n sections: {},\n };\n }\n\n const systemPrompt = `${PLANNING_SYSTEM_PROMPT}\\n\\nOutput only markdown. Do NOT output JSON.`;\n\n // Part 1: Overview + Tech Stack (direct LLM call)\n const part1 = await invokeMarkdown(model, systemPrompt, buildRequirementsOverviewPrompt(ctx));\n const { overview, techStack } = splitOverviewAndTechStack(part1);\n\n // Part 2: Feature Decisions + Data Models via entity-analyzer specialist\n const part2 = await invokeMarkdown(\n model,\n systemPrompt,\n buildRequirementsFeatureDataPrompt(ctx, part1)\n );\n const { featureDecisions } = splitFeatureDecisionsAndDataModels(part2);\n\n logger?.info('Delegating to data-modeler specialist');\n const dataModelResult = await runSubagent(\n entityAnalyzerSubagent,\n `Analyze the data model for this project:\\n\\n${ctx}\\n\\nFeatures:\\n${featureDecisions}`,\n { parentModel: model }\n );\n const dataModels = dataModelResult.output;\n\n // Part 3: Pages and Routes via frontend-architect specialist\n logger?.info('Delegating to frontend-architect specialist');\n const priorContext = [part1, featureDecisions, dataModels].join('\\n\\n---\\n\\n');\n const pagesResult = await runSubagent(\n pagePlannerSubagent,\n `Design the pages and routes for this project:\\n\\n${ctx}\\n\\nContext:\\n${priorContext}`,\n { parentModel: model }\n );\n const pagesAndRoutes = pagesResult.output;\n\n // Part 4: Auth Flow via auth-designer specialist\n logger?.info('Delegating to auth-designer specialist');\n const fullContext = [priorContext, pagesAndRoutes].join('\\n\\n---\\n\\n');\n const authResult = await runSubagent(\n flowDesignerSubagent,\n `Design the authentication flows for this project:\\n\\n${ctx}\\n\\nContext:\\n${fullContext}`,\n { parentModel: model }\n );\n const authFlow = authResult.output;\n\n logger?.info('Requirements stage complete (specialist agents)');\n return {\n message:\n 'Requirements generated via specialist agents (Data Modeler, Frontend Architect, Auth Designer).',\n advance: true,\n sections: { overview, techStack, featureDecisions, dataModels, pagesAndRoutes, authFlow },\n };\n}\n","/**\n * Requirements state - delegates to requirements stage\n */\n\nimport type { PlanningContext, PlanStageResult, StageInput } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { runRequirementsStage } from './requirements.stage';\n\nexport class RequirementsState implements PlanningStageState {\n readonly stageName = 'requirements' as const;\n\n async process(context: PlanningContext, input: StageInput): Promise<PlanStageResult> {\n return runRequirementsStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: PlanStageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): 'design' | null {\n return 'design';\n }\n}\n","/**\n * endpoint-analyzer subagent - derives API endpoints from data model and requirements\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ENDPOINT_ANALYZER_SYSTEM_PROMPT = `You are an API endpoint analyst. Given a data model and requirements, you derive the complete API surface.\n\n## Endpoint Discovery\n- For each entity in the data model, determine CRUD operations: create, read (by ID), list (with filters/pagination), update, delete.\n- From user stories/flows, identify custom operations beyond CRUD (e.g. searchUsers, bulkImport, exportCsv, toggleStatus).\n- Group endpoints by resource name (pluralized entity name).\n\n## Route Design\n- Design RESTful routes: POST /resource, GET /resource/:id, GET /resource, PUT /resource/:id, DELETE /resource/:id.\n- For nested resources: GET /users/:userId/orders, POST /users/:userId/orders.\n- For custom operations: POST /resource/:id/actions/activate, GET /resource/search.\n\n## Auth Annotations\n- Mark which endpoints require authentication.\n- Mark which endpoints require specific roles (admin, owner).\n- Identify resource-ownership checks (user can only access their own data).\n\nRespond with structured analysis using headings and bullet points. Do NOT return JSON.`;\n\nexport const endpointAnalyzerSubagent = defineSubagent({\n name: 'endpoint-analyzer',\n description:\n 'Analyzes data model and requirements to derive API endpoints, routes, and auth annotations. Use before generating the API design.',\n systemPrompt: ENDPOINT_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * contract-designer subagent - designs request/response contracts per endpoint\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst CONTRACT_DESIGNER_SYSTEM_PROMPT = `You are an API contract specialist. Given endpoints and a data model, you design detailed request/response contracts.\n\n## Request Design\n- For each endpoint, define: required fields, optional fields, field types, validation rules.\n- Validation rules: required, min/max length, email format, enum values, numeric ranges.\n- For list endpoints: pagination (page, limit, offset), sorting (sortBy, order), filtering (query params).\n\n## Response Design\n- Success responses: HTTP status (200, 201, 204), response body shape.\n- For list endpoints: { items: T[], total: number, page: number, limit: number }.\n- For single item: the entity shape with all fields.\n\n## Error Responses\n- 400: validation errors with field-level messages.\n- 401: unauthenticated (missing or invalid token).\n- 403: forbidden (insufficient role or not resource owner).\n- 404: resource not found.\n- 409: conflict (duplicate unique field).\n- 500: internal server error.\n\n## Naming Conventions\n- Use consistent field naming (camelCase for JSON, snake_case for query params if preferred).\n- Use ISO 8601 for dates in responses.\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const contractDesignerSubagent = defineSubagent({\n name: 'contract-designer',\n description:\n 'Designs detailed request/response contracts, validation rules, and error responses per API endpoint. Use after endpoint analysis.',\n systemPrompt: CONTRACT_DESIGNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * Design stage - delegates to api-designer specialists:\n * endpoint-analyzer (API routes), contract-designer (implementation details)\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { PlanningContext, PlanStageResult } from '../types';\nimport { PLANNING_SYSTEM_PROMPT } from '../prompts';\nimport { buildDesignImplementationPrompt } from '../prompts';\nimport { runSubagent } from '../../../lib/subagents';\nimport { endpointAnalyzerSubagent, contractDesignerSubagent } from '../../api-designer/subagents';\n\nfunction gatherPriorSections(ctx: PlanningContext): string {\n const parts: string[] = [];\n if (ctx.projectDescription) parts.push(ctx.projectDescription);\n const s = ctx.sections;\n if (s.overview) parts.push(s.overview);\n if (s.techStack) parts.push(s.techStack);\n if (s.featureDecisions) parts.push(s.featureDecisions);\n if (s.dataModels) parts.push(s.dataModels);\n if (s.pagesAndRoutes) parts.push(s.pagesAndRoutes);\n if (s.authFlow) parts.push(s.authFlow);\n return parts.join('\\n\\n---\\n\\n');\n}\n\nexport async function runDesignStage(\n _userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<PlanStageResult> {\n logger?.debug('Design stage started (specialist agents)');\n\n const priorSections = gatherPriorSections(context);\n if (!priorSections) {\n return {\n message: 'No prior sections. Complete discovery and requirements first.',\n advance: false,\n sections: {},\n };\n }\n\n // API Routes via endpoint-analyzer specialist\n logger?.info('Delegating to api-designer endpoint-analyzer specialist');\n const apiResult = await runSubagent(\n endpointAnalyzerSubagent,\n `Design the API routes for this project:\\n\\n${priorSections}`,\n { parentModel: model }\n );\n const apiRoutes = apiResult.output;\n\n // Implementation Details via contract-designer specialist + direct LLM call\n logger?.info('Delegating to api-designer contract-designer specialist');\n const contractResult = await runSubagent(\n contractDesignerSubagent,\n `Design detailed request/response contracts for these API endpoints:\\n\\n${apiRoutes}\\n\\nProject context:\\n${priorSections}`,\n { parentModel: model }\n );\n\n const systemPrompt = `${PLANNING_SYSTEM_PROMPT}\\n\\nOutput only markdown. Do NOT output JSON.`;\n const implementation = await model\n .invoke(\n [\n { role: 'system' as const, content: systemPrompt },\n {\n role: 'user' as const,\n content: buildDesignImplementationPrompt(\n priorSections,\n apiRoutes + '\\n\\n' + contractResult.output\n ),\n },\n ],\n { temperature: 0.3, maxOutputTokens: 8192 }\n )\n .then(r => r.text?.trim() ?? '');\n\n logger?.info('Design stage complete (specialist agents)');\n return {\n message: 'Design generated via specialist agents (Endpoint Analyzer, Contract Designer).',\n advance: true,\n sections: { apiRoutes, implementation },\n };\n}\n","/**\n * Design state - delegates to design stage\n */\n\nimport type { PlanningContext, PlanStageResult, StageInput } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { runDesignStage } from './design.stage';\n\nexport class DesignState implements PlanningStageState {\n readonly stageName = 'design' as const;\n\n async process(context: PlanningContext, input: StageInput): Promise<PlanStageResult> {\n return runDesignStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: PlanStageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): 'complete' | null {\n return 'complete';\n }\n}\n","/**\n * Assemble plan sections into markdown and write to file\n */\n\nimport { writeFile } from 'fs/promises';\nimport type { PlanSections } from './types';\n\nexport function assemblePlan(projectName: string, sections: PlanSections): string {\n const parts: (string | null)[] = [\n `# ${projectName} Implementation Plan\\n`,\n sections.overview,\n sections.techStack,\n sections.featureDecisions,\n '---',\n sections.dataModels,\n '---',\n sections.pagesAndRoutes,\n '---',\n sections.authFlow,\n '---',\n sections.apiRoutes,\n '---',\n sections.implementation,\n '---',\n sections.executionPlan,\n '---',\n sections.edgeCases,\n '---',\n sections.testingChecklist,\n ];\n return parts.filter(Boolean).join('\\n\\n');\n}\n\nexport async function writePlanToFile(markdown: string, outputPath: string): Promise<void> {\n await writeFile(outputPath, markdown, 'utf-8');\n}\n","/**\n * edge-case-analyzer subagent - identifies edge cases per domain area\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst EDGE_CASE_ANALYZER_SYSTEM_PROMPT = `You are a QA-minded tech lead. You identify edge cases that developers often miss.\n\nFor each domain area (Authentication, Data, API, Frontend, Integrations):\n\n## Edge Case Analysis\n- **Scenario**: Describe the edge case concretely (e.g. \"User submits signup form with email that already exists\").\n- **Handling**: How to handle it (e.g. \"Return 400 with message 'Email already in use'\").\n- **Severity**: critical (must handle or app breaks), warning (should handle for good UX), info (nice to have).\n\n## Common Areas to Check\n- **Authentication**: duplicate email, invalid credentials, expired token, concurrent sessions, password reset with invalid token.\n- **Data**: empty collections, max field lengths, special characters in input, date timezone issues, null references.\n- **API**: missing required fields, invalid field types, unauthorized access, rate limiting, pagination edge (page 0, negative page).\n- **Frontend**: empty states, loading states, network errors, form resubmission, back button behavior.\n- **Integrations**: external API down, timeout, rate limited, invalid response format.\n\nRespond with structured edge cases grouped by area. Do NOT return JSON.`;\n\nexport const edgeCaseAnalyzerSubagent = defineSubagent({\n name: 'edge-case-analyzer',\n description:\n 'Identifies edge cases per domain area with scenarios, handling strategies, and severity levels. Use for comprehensive edge case analysis.',\n systemPrompt: EDGE_CASE_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * testing-strategist subagent - designs manual testing checklists\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst TESTING_STRATEGIST_SYSTEM_PROMPT = `You are a testing strategy specialist. You design comprehensive manual testing checklists.\n\n## Testing Checklist Design\nGroup test items by flow (Authentication, CRUD operations, Edge cases, etc.).\n\nFor each test item:\n- **Flow name**: which feature flow this tests (e.g. \"Authentication Flow\", \"Workout CRUD Flow\").\n- **Test item**: what to verify (e.g. \"Sign up with valid credentials creates account\").\n- **Expected result**: what should happen (e.g. \"User created in DB, JWT cookie set, redirected to /dashboard\").\n\n## Coverage Areas\n- **Happy paths**: normal user flows work end-to-end.\n- **Validation**: invalid inputs are rejected with clear messages.\n- **Authorization**: users can only access what they should.\n- **Error handling**: errors are caught and displayed properly.\n- **Data integrity**: data is saved correctly, relationships maintained.\n- **UI states**: loading, empty, error, success states display correctly.\n\n## Checklist Format\nPresent as grouped checklist items using markdown checkboxes:\n### Flow Name\n- [ ] Test item description -> Expected result\n\nRespond with structured checklist. Do NOT return JSON.`;\n\nexport const testingStrategistSubagent = defineSubagent({\n name: 'testing-strategist',\n description:\n 'Designs comprehensive manual testing checklists grouped by feature flow. Use for testing strategy and QA planning.',\n systemPrompt: TESTING_STRATEGIST_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * Synthesis stage - delegates to execution-planner specialists:\n * edge-case-analyzer (edge cases), testing-strategist (testing checklist)\n * Then assembles plan.md from all sections.\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { PlanningContext, PlanStageResult } from '../types';\nimport { PLANNING_SYSTEM_PROMPT } from '../prompts';\nimport { SYNTHESIS_SYSTEM_FRAGMENT, buildSynthesisPrompt } from '../prompts';\nimport { assemblePlan } from '../writer';\nimport { runSubagent } from '../../../lib/subagents';\nimport {\n edgeCaseAnalyzerSubagent,\n testingStrategistSubagent,\n} from '../../execution-planner/subagents';\n\nfunction gatherAllSections(ctx: PlanningContext): string {\n const parts: string[] = [];\n if (ctx.projectDescription) parts.push(ctx.projectDescription);\n const s = ctx.sections;\n [\n s.overview,\n s.techStack,\n s.featureDecisions,\n s.dataModels,\n s.pagesAndRoutes,\n s.authFlow,\n s.apiRoutes,\n s.implementation,\n ].forEach(p => {\n if (p) parts.push(p);\n });\n return parts.join('\\n\\n---\\n\\n');\n}\n\nfunction extractProjectName(ctx: PlanningContext): string {\n const raw = ctx.sections.overview ?? ctx.projectDescription ?? '';\n const firstLine = raw.split('\\n')[0]?.trim() ?? '';\n const regex = /^#+\\s*(.+?)(?:\\s+Implementation Plan)?$/i;\n const match = regex.exec(firstLine);\n if (match?.[1]) return match[1].trim();\n if (firstLine.length > 0 && firstLine.length < 80) return firstLine.replace(/^#+\\s*/, '').trim();\n return 'Project Implementation Plan';\n}\n\nexport async function runSynthesisStage(\n _userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<PlanStageResult> {\n logger?.debug('Synthesis stage started (specialist agents)');\n\n const priorSections = gatherAllSections(context);\n if (!priorSections) {\n return {\n message: 'No prior sections. Complete earlier stages first.',\n advance: false,\n sections: {},\n };\n }\n\n // Execution plan via direct LLM call (phased implementation order)\n const systemPrompt = `${PLANNING_SYSTEM_PROMPT}\\n\\n${SYNTHESIS_SYSTEM_FRAGMENT}\\n\\nOutput only markdown. Do NOT output JSON.`;\n const executionPlan = await model\n .invoke(\n [\n { role: 'system' as const, content: systemPrompt },\n { role: 'user' as const, content: buildSynthesisPrompt(priorSections) },\n ],\n { temperature: 0.3, maxOutputTokens: 8192 }\n )\n .then(r => r.text?.trim() ?? '');\n\n // Edge cases via edge-case-analyzer specialist\n logger?.info('Delegating to execution-planner edge-case-analyzer specialist');\n const edgeCaseResult = await runSubagent(\n edgeCaseAnalyzerSubagent,\n `Identify edge cases for this project:\\n\\n${priorSections}`,\n { parentModel: model }\n );\n const edgeCases = edgeCaseResult.output;\n\n // Testing checklist via testing-strategist specialist\n logger?.info('Delegating to execution-planner testing-strategist specialist');\n const testingResult = await runSubagent(\n testingStrategistSubagent,\n `Design the manual testing checklist for this project:\\n\\n${priorSections}`,\n { parentModel: model }\n );\n const testingChecklist = testingResult.output;\n\n const projectName = extractProjectName(context);\n const fullSections = {\n ...context.sections,\n executionPlan: executionPlan || null,\n edgeCases: edgeCases || null,\n testingChecklist: testingChecklist || null,\n };\n const fullMarkdown = assemblePlan(projectName, fullSections);\n\n logger?.info('Synthesis stage complete (specialist agents)', { projectName });\n return {\n message: `Plan complete: ${projectName}. Generated via specialist agents.`,\n advance: true,\n sections: { executionPlan, edgeCases, testingChecklist },\n planMarkdown: fullMarkdown,\n };\n}\n","/**\n * Synthesis state - delegates to synthesis stage\n */\n\nimport type { PlanningContext, PlanStageResult, StageInput } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { runSynthesisStage } from './synthesis.stage';\n\nexport class SynthesisState implements PlanningStageState {\n readonly stageName = 'complete' as const;\n\n async process(context: PlanningContext, input: StageInput): Promise<PlanStageResult> {\n return runSynthesisStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: PlanStageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): null {\n return null;\n }\n}\n","/**\n * Registry: map Stage to State instance for State pattern routing\n */\n\nimport type { Stage } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { DiscoveryState } from './discovery.state';\nimport { RequirementsState } from './requirements.state';\nimport { DesignState } from './design.state';\nimport { SynthesisState } from './synthesis.state';\n\nconst states: Record<Stage, PlanningStageState> = {\n discovery: new DiscoveryState(),\n requirements: new RequirementsState(),\n design: new DesignState(),\n complete: new SynthesisState(),\n};\n\nexport function getStateForStage(stage: Stage): PlanningStageState {\n return states[stage];\n}\n","/**\n * Stage routing and auto-advance logic (State pattern)\n */\n\nimport type { Logger } from '../../lib/types/common';\nimport type { Model } from '../../lib/types/model';\nimport type { PlanningContext, Stage } from './types';\nimport { getStateForStage } from './stages';\nimport { isConfirmation } from './stages/base';\nimport { advanceStage, mergeStageResult, addChatEntry } from './context';\n\nexport function getStageForTurn(context: PlanningContext, _userMessage: string): Stage {\n return context.stage;\n}\n\n/**\n * Run the current stage via State pattern; merge result into context.\n * Returns planMarkdown when synthesis stage completes.\n */\nexport async function runStage(\n stage: Stage,\n userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<{\n message: string;\n pendingQuestions: string[];\n advance: boolean;\n data: PlanningContext;\n planMarkdown?: string;\n}> {\n logger?.debug('Stage processor invoked', { stage });\n const state = getStateForStage(stage);\n const result = await state.process(context, { userMessage, model, logger });\n const merged = mergeStageResult(context, result);\n const data: PlanningContext = {\n ...merged,\n pendingQuestions: result.pendingQuestions ?? merged.pendingQuestions,\n };\n logger?.debug('Stage result', {\n stage,\n advance: result.advance,\n hasPlanMarkdown: !!result.planMarkdown,\n });\n return {\n message: result.message,\n pendingQuestions: result.pendingQuestions ?? merged.pendingQuestions,\n advance: result.advance,\n data,\n planMarkdown: result.planMarkdown,\n };\n}\n\nexport { isConfirmation, advanceStage, addChatEntry };\n","/**\n * processPlanningChat - main entry point for chat-based planning\n */\n\nimport { createModel } from '../../lib/models/create-model';\nimport type { PlanningContext, PlanChatTurnResult, PlanningChatConfig, Stage } from './types';\nimport { createInitialContext, addChatEntry, advanceStage } from './context';\nimport { runStage } from './router';\n\nconst STAGE_ORDER: Stage[] = ['discovery', 'requirements', 'design', 'complete'];\n\nexport async function processPlanningChat(\n userMessage: string,\n context: PlanningContext | null,\n config: PlanningChatConfig\n): Promise<PlanChatTurnResult> {\n const { logger } = config;\n\n const modelConfig = config.model ?? { provider: 'openai', model: 'gpt-4o-mini' };\n const model = createModel(modelConfig);\n\n let ctx: PlanningContext = context ?? createInitialContext();\n ctx = addChatEntry(ctx, 'user', userMessage);\n\n logger?.info('Planning chat turn', { stage: ctx.stage, messageLength: userMessage.length });\n\n let message = '';\n let pendingQuestions: string[] = [];\n let planMarkdown: string | null = null;\n\n const runOne = async (stage: Stage): Promise<{ advance: boolean; planMarkdown?: string }> => {\n const result = await runStage(stage, userMessage, ctx, model, logger);\n message = result.message;\n pendingQuestions = result.pendingQuestions;\n ctx = result.data;\n if (result.planMarkdown) planMarkdown = result.planMarkdown;\n return { advance: result.advance, planMarkdown: result.planMarkdown };\n };\n\n let stage = ctx.stage;\n logger?.info('Stage', { stage });\n let runResult = await runOne(stage);\n\n while (runResult.advance && !planMarkdown) {\n const idx = STAGE_ORDER.indexOf(stage);\n const nextStage = idx >= 0 && idx < STAGE_ORDER.length - 1 ? STAGE_ORDER[idx + 1] : undefined;\n if (nextStage === undefined) break;\n logger?.info('Stage transition', { from: stage, to: nextStage });\n stage = nextStage;\n ctx = advanceStage(ctx);\n ctx = { ...ctx, stage };\n logger?.info('Stage', { stage });\n runResult = await runOne(stage);\n }\n\n ctx = addChatEntry(ctx, 'assistant', message);\n\n logger?.info('Planning chat turn done', { stage, hasPlanMarkdown: !!planMarkdown });\n return {\n message,\n context: ctx,\n pendingQuestions,\n planMarkdown,\n };\n}\n","/**\n * runPlanningAgent - one-shot wrapper around processPlanningChat\n * Auto-advances with \"continue\"; returns plan markdown. Does not write to file.\n */\n\nimport type { PlanningAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\nimport { processPlanningChat } from './chat';\n\nconst MAX_TURNS = 10;\n\n/**\n * Run the planning agent in one-shot mode: single input, auto-advance through stages,\n * return plan markdown as AgentResult. Does not write to file.\n */\nexport async function runPlanningAgent(config: PlanningAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, onStep, logger } = config;\n logger?.info('Starting planning agent', { maxTurns: MAX_TURNS });\n\n let context = null;\n let lastResult = await processPlanningChat(input, context, {\n model: modelConfig,\n onStep,\n logger,\n });\n context = lastResult.context;\n let turns = 1;\n while (!lastResult.planMarkdown && turns < MAX_TURNS) {\n logger?.debug('Planning agent turn', { turn: turns });\n const continueMsg =\n `continue - proceed with the project: \"${input}\". ` +\n 'Make reasonable assumptions for any unresolved details and produce the required output format.';\n lastResult = await processPlanningChat(continueMsg, context, {\n model: modelConfig,\n onStep,\n logger,\n });\n context = lastResult.context;\n turns++;\n }\n const output = lastResult.planMarkdown ?? lastResult.message;\n const messages = context.history.map(e => ({\n role: e.role as 'user' | 'system' | 'assistant',\n content: e.content,\n }));\n\n logger?.info('Planning agent completed', {\n turns,\n hasPlanMarkdown: !!lastResult.planMarkdown,\n });\n return {\n output,\n steps: [],\n totalUsage: undefined,\n messages,\n };\n}\n","/**\n * editPlan - single LLM call to revise an existing plan based on feedback.\n * Takes existing plan markdown + edit instructions, returns updated markdown.\n */\n\nimport type { EditPlanConfig } from './types';\nimport { createModel } from '../../lib/models/create-model';\nimport { EDIT_PLAN_SYSTEM_PROMPT, buildEditPlanPrompt } from './prompts';\n\n/**\n * Edit an existing plan based on feedback or additional context.\n * Single focused LLM call -- no multi-stage pipeline needed.\n * Returns the full revised plan as a markdown string.\n */\nexport async function editPlan(config: EditPlanConfig): Promise<string> {\n const { existingPlan, feedback, logger } = config;\n logger?.info('Editing plan', { feedbackLength: feedback.length });\n\n if (!existingPlan || existingPlan.trim().length < 50) {\n throw new Error('existingPlan is too short or empty. Provide a valid plan to edit.');\n }\n if (!feedback || feedback.trim().length === 0) {\n throw new Error('feedback is empty. Provide edit instructions.');\n }\n\n const modelConfig = config.model ?? { provider: 'openai' as const, model: 'gpt-4o-mini' };\n const model = createModel(modelConfig);\n\n const response = await model.invoke(\n [\n { role: 'system' as const, content: EDIT_PLAN_SYSTEM_PROMPT },\n { role: 'user' as const, content: buildEditPlanPrompt(existingPlan, feedback) },\n ],\n { temperature: 0.3, maxOutputTokens: 16384 }\n );\n\n const revised = response.text?.trim() ?? '';\n if (!revised) {\n throw new Error('Model returned empty response when editing plan.');\n }\n\n logger?.info('Plan edited successfully', { outputLength: revised.length });\n return revised;\n}\n","/**\n * Wire requirement-gatherer output into the planning module.\n * Converts a FinalRequirement into a pre-filled PlanningContext at the design stage,\n * skipping the redundant discovery + requirements stages.\n */\n\nimport type { AgentResult } from '../../lib/types/agent';\nimport type { PlanningContext, PlanSections } from './types';\nimport type { PlanFromRequirementsConfig } from './from-requirements.types';\nimport type {\n FinalRequirement,\n DatabaseDesign,\n DatabaseEntity,\n Module,\n Actor,\n Flow,\n Story,\n} from '../requirement-gatherer/types';\nimport { processPlanningChat } from './chat';\n\n/* ── Markdown formatters ─────────────────────────────────── */\n\nfunction formatEntityFields(entity: DatabaseEntity): string {\n if (!entity.fields.length) return '';\n const rows = entity.fields.map(f => {\n const flags = [f.required ? 'required' : '', f.unique ? 'unique' : '']\n .filter(Boolean)\n .join(', ');\n return `| ${f.name} | ${f.type} | ${flags || '-'} | ${f.description} |`;\n });\n return `| Field | Type | Constraints | Description |\\n| --- | --- | --- | --- |\\n${rows.join('\\n')}`;\n}\n\nfunction formatDatabaseAsMarkdown(db: DatabaseDesign): string {\n const header = `## Data Models\\n\\n**Database:** ${db.type}\\n**Reasoning:** ${db.reasoning}\\n`;\n const entities = db.entities\n .map(e => {\n const fields = formatEntityFields(e);\n const relParts = e.relations.map(\n r => r.field + ' → ' + r.references + ' (' + r.description + ')'\n );\n const relations = relParts.length ? '\\n**Relations:** ' + relParts.join('; ') : '';\n const idxParts = e.indexes.map(\n i => i.name + ' [' + i.fields.join(', ') + ']' + (i.unique ? ' (unique)' : '')\n );\n const indexes = idxParts.length ? '\\n**Indexes:** ' + idxParts.join('; ') : '';\n return `### ${e.name}\\n\\n${e.description}\\n\\n${fields}${relations}${indexes}`;\n })\n .join('\\n\\n');\n return `${header}\\n${entities}`;\n}\n\nfunction formatModulesAsMarkdown(modules: Module[]): string {\n const items = modules\n .map(m => {\n const apis = m.apis.map(a => ` - \\`${a.operation}\\` ${a.name}: ${a.description}`).join('\\n');\n return `### ${m.name}\\n\\n${m.description} (entity: ${m.entity})\\n\\n**APIs:**\\n${apis}`;\n })\n .join('\\n\\n');\n return `## Feature Decisions\\n\\n${items}`;\n}\n\nfunction formatProjectOverview(req: FinalRequirement): string {\n const p = req.project;\n const features = p.features.map(f => `- ${f}`).join('\\n');\n return `# ${p.name}\\n\\n**Goal:** ${p.goal}\\n**Domain:** ${p.domain}\\n\\n${req.summary.overview}\\n\\n**Key Features:**\\n${features}`;\n}\n\nfunction formatTechStack(req: FinalRequirement): string {\n const p = req.project;\n return [\n '## Tech Stack',\n '',\n `- **Database:** ${p.database}`,\n `- **Backend Runtime:** ${p.backendRuntime}`,\n `- **API Style:** ${p.apiStyle}`,\n ].join('\\n');\n}\n\nfunction formatActorsContext(actors: Actor[], flows: Flow[], stories: Story[]): string {\n const parts: string[] = ['## Actors and Flows'];\n for (const actor of actors) {\n parts.push(`\\n### ${actor.name}\\n${actor.description}`);\n const actorFlows = flows.filter(f => f.actorId === actor.id);\n if (actorFlows.length) {\n parts.push('**Flows:**');\n for (const f of actorFlows) {\n parts.push(`- ${f.name}: ${f.description} (trigger: ${f.trigger}, outcome: ${f.outcome})`);\n }\n }\n }\n if (stories.length) {\n parts.push('\\n### Key User Stories');\n for (const s of stories.slice(0, 10)) {\n parts.push(`- As **${s.actor}**, I want to **${s.action}**, so that **${s.benefit}**`);\n }\n if (stories.length > 10) parts.push(`- ... and ${stories.length - 10} more stories`);\n }\n return parts.join('\\n');\n}\n\n/* ── Converter ───────────────────────────────────────────── */\n\n/**\n * Convert a FinalRequirement (from requirement-gatherer) into a PlanningContext\n * pre-filled at the design stage, skipping discovery + requirements.\n */\nexport function convertRequirementToContext(req: FinalRequirement): PlanningContext {\n const sections: PlanSections = {\n overview: `## Overview\\n\\n${req.summary.overview}`,\n techStack: formatTechStack(req),\n featureDecisions: formatModulesAsMarkdown(req.modules),\n dataModels: formatDatabaseAsMarkdown(req.database),\n pagesAndRoutes: null,\n authFlow: null,\n apiRoutes: null,\n implementation: null,\n executionPlan: null,\n edgeCases: null,\n testingChecklist: null,\n };\n\n return {\n stage: 'design',\n projectDescription:\n formatProjectOverview(req) + '\\n\\n' + formatActorsContext(req.actors, req.flows, req.stories),\n sections,\n history: [],\n pendingQuestions: [],\n };\n}\n\n/* ── Runner ──────────────────────────────────────────────── */\n\nconst MAX_TURNS = 8;\n\n/**\n * Run the planning pipeline starting from a FinalRequirement.\n * Skips discovery + requirements stages; begins at design.\n */\nexport async function runPlanningFromRequirements(\n config: PlanFromRequirementsConfig\n): Promise<AgentResult> {\n const { requirement, model: modelConfig, onStep, logger } = config;\n\n logger?.info('Starting planning from requirements (fast path)', {\n project: requirement.project.name,\n });\n\n const context = convertRequirementToContext(requirement);\n\n const triggerMsg =\n `Generate the implementation plan for \"${requirement.project.name}\". ` +\n 'The project description, tech stack, features, and data models are already provided in context. ' +\n 'Proceed with API routes, implementation details, execution plan, edge cases, and testing checklist.';\n\n let lastResult = await processPlanningChat(triggerMsg, context, {\n model: modelConfig,\n onStep,\n logger,\n });\n let turns = 1;\n\n while (!lastResult.planMarkdown && turns < MAX_TURNS) {\n logger?.debug('Planning from requirements turn', { turn: turns });\n lastResult = await processPlanningChat(\n 'continue - produce the complete implementation plan.',\n lastResult.context,\n { model: modelConfig, onStep, logger }\n );\n turns++;\n }\n\n const output = lastResult.planMarkdown ?? lastResult.message;\n const messages = lastResult.context.history.map(e => ({\n role: e.role as 'user' | 'system' | 'assistant',\n content: e.content,\n }));\n\n logger?.info('Planning from requirements completed', {\n turns,\n hasPlanMarkdown: !!lastResult.planMarkdown,\n });\n\n return { output, steps: [], totalUsage: undefined, messages };\n}\n","/**\n * Builder for PlanningContext - fluent API\n */\n\nimport type { PlanningContext, Stage, PlanSections, ChatEntry } from './types';\n\nconst DEFAULT_STAGE: Stage = 'discovery';\n\nconst EMPTY_SECTIONS: PlanSections = {\n overview: null,\n techStack: null,\n featureDecisions: null,\n dataModels: null,\n pagesAndRoutes: null,\n authFlow: null,\n apiRoutes: null,\n implementation: null,\n executionPlan: null,\n edgeCases: null,\n testingChecklist: null,\n};\n\nexport class PlanningContextBuilder {\n private data: Partial<PlanningContext> = {};\n\n withStage(stage: Stage): this {\n this.data.stage = stage;\n return this;\n }\n\n withProjectDescription(projectDescription: string | null): this {\n this.data.projectDescription = projectDescription;\n return this;\n }\n\n withSections(sections: Partial<PlanSections>): this {\n this.data.sections = { ...(this.data.sections ?? EMPTY_SECTIONS), ...sections };\n return this;\n }\n\n withHistory(history: ChatEntry[]): this {\n this.data.history = history;\n return this;\n }\n\n withPendingQuestions(pendingQuestions: string[]): this {\n this.data.pendingQuestions = pendingQuestions;\n return this;\n }\n\n reset(): this {\n this.data = {};\n return this;\n }\n\n build(): PlanningContext {\n return {\n stage: this.data.stage ?? DEFAULT_STAGE,\n projectDescription: this.data.projectDescription ?? null,\n sections: this.data.sections ?? { ...EMPTY_SECTIONS },\n history: this.data.history ?? [],\n pendingQuestions: this.data.pendingQuestions ?? [],\n };\n }\n}\n\nexport function createPlanningContextBuilder(): PlanningContextBuilder {\n return new PlanningContextBuilder();\n}\n","/**\n * Zod schema for extract_actors tool output\n */\n\nimport { z } from 'zod';\n\nexport const actorSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n goals: z.array(z.string()),\n});\n\nexport const actorsResultSchema = z.object({\n actors: z.array(actorSchema),\n message: z.string(),\n});\n\nexport type ActorResult = z.infer<typeof actorsResultSchema>;\n","/**\n * Zod schema for generate_flows tool output\n */\n\nimport { z } from 'zod';\n\nexport const flowSchema = z.object({\n id: z.string(),\n actorId: z.string(),\n name: z.string(),\n description: z.string(),\n trigger: z.string(),\n outcome: z.string(),\n});\n\nexport const flowsResultSchema = z.object({\n flows: z.array(flowSchema),\n message: z.string(),\n});\n\nexport type FlowsResult = z.infer<typeof flowsResultSchema>;\n","/**\n * Zod schema for generate_stories tool output\n */\n\nimport { z } from 'zod';\n\nexport const storySchema = z.object({\n id: z.string(),\n flowId: z.string(),\n actor: z.string(),\n action: z.string(),\n benefit: z.string(),\n preconditions: z.array(z.string()),\n postconditions: z.array(z.string()),\n dataInvolved: z.array(z.string()),\n});\n\nexport const storiesResultSchema = z.object({\n stories: z.array(storySchema),\n message: z.string(),\n});\n\nexport type StoriesResult = z.infer<typeof storiesResultSchema>;\n","/**\n * Zod schema for extract_modules tool output\n */\n\nimport { z } from 'zod';\n\nexport const crudApiSchema = z.object({\n id: z.string(),\n name: z.string(),\n operation: z.enum(['create', 'read', 'readAll', 'update', 'delete']),\n description: z.string(),\n inputs: z.array(z.string()),\n outputs: z.array(z.string()),\n});\n\nexport const extractedModuleSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n entity: z.string(),\n apis: z.array(crudApiSchema),\n});\n\nexport const modulesResultSchema = z.object({\n modules: z.array(extractedModuleSchema),\n summary: z.object({\n totalModules: z.number(),\n totalApis: z.number(),\n }),\n message: z.string(),\n});\n\nexport type ModulesResult = z.infer<typeof modulesResultSchema>;\n","/**\n * Zod schemas for DatabaseDesign, DatabaseEntity, EntityField, EntityIndex, EntityRelation\n */\n\nimport { z } from 'zod';\n\nexport const entityFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.boolean(),\n unique: z.boolean(),\n description: z.string(),\n default: z.string().optional(),\n});\n\nexport const entityIndexSchema = z.object({\n name: z.string(),\n fields: z.array(z.string()),\n unique: z.boolean(),\n});\n\nexport const entityRelationSchema = z.object({\n field: z.string(),\n references: z.string(),\n description: z.string(),\n});\n\nexport const databaseEntitySchema = z.object({\n name: z.string(),\n description: z.string(),\n fields: z.array(entityFieldSchema),\n indexes: z.array(entityIndexSchema),\n relations: z.array(entityRelationSchema),\n});\n\nexport const databaseDesignSchema = z.object({\n type: z.enum(['mongodb', 'postgresql']),\n reasoning: z.string(),\n entities: z.array(databaseEntitySchema),\n});\n\nexport type EntityField = z.infer<typeof entityFieldSchema>;\nexport type EntityIndex = z.infer<typeof entityIndexSchema>;\nexport type EntityRelation = z.infer<typeof entityRelationSchema>;\nexport type DatabaseEntity = z.infer<typeof databaseEntitySchema>;\nexport type DatabaseDesign = z.infer<typeof databaseDesignSchema>;\n","/**\n * Zod schemas for RequirementContext, ProjectBrief, Question, ChatEntry\n * Note: apiDesign removed -- API design is delegated to the api-designer module.\n */\n\nimport { z } from 'zod';\nimport { actorSchema } from './actor.schema';\nimport { flowSchema } from './flow.schema';\nimport { storySchema } from './story.schema';\nimport { extractedModuleSchema } from './module.schema';\nimport { databaseDesignSchema } from './database.schema';\n\nexport const projectBriefSchema = z.object({\n name: z.string(),\n goal: z.string(),\n features: z.array(z.string()),\n domain: z.string(),\n database: z.enum(['mongodb', 'postgresql']),\n backendRuntime: z.literal('nodejs'),\n apiStyle: z.enum(['rest', 'graphql']),\n});\n\nexport const questionSchema = z.object({\n id: z.string(),\n question: z.string(),\n context: z.string(),\n suggestions: z.array(z.string()),\n multiSelect: z.boolean(),\n required: z.boolean(),\n});\n\nexport const chatEntrySchema = z.object({\n role: z.enum(['user', 'assistant']),\n content: z.string(),\n});\n\nexport const requirementContextSchema = z.object({\n stage: z.enum(['discovery', 'requirements', 'design', 'complete']),\n projectBrief: projectBriefSchema.nullable(),\n actors: z.array(actorSchema),\n flows: z.array(flowSchema),\n stories: z.array(storySchema),\n modules: z.array(extractedModuleSchema),\n database: databaseDesignSchema.nullable(),\n history: z.array(chatEntrySchema),\n pendingQuestions: z.array(questionSchema),\n});\n\nexport type ProjectBrief = z.infer<typeof projectBriefSchema>;\nexport type Question = z.infer<typeof questionSchema>;\nexport type ChatEntry = z.infer<typeof chatEntrySchema>;\nexport type RequirementContext = z.infer<typeof requirementContextSchema>;\n","/**\n * Zod schemas for FinalRequirement, RequirementSummary\n * Note: apiDesign removed -- API design is delegated to the api-designer module.\n */\n\nimport { z } from 'zod';\nimport { projectBriefSchema } from './context.schema';\nimport { actorSchema } from './actor.schema';\nimport { flowSchema } from './flow.schema';\nimport { storySchema } from './story.schema';\nimport { extractedModuleSchema } from './module.schema';\nimport { databaseDesignSchema } from './database.schema';\n\nexport const requirementSummarySchema = z.object({\n totalActors: z.number(),\n totalFlows: z.number(),\n totalStories: z.number(),\n totalModules: z.number(),\n totalEntities: z.number(),\n overview: z.string(),\n});\n\nexport const finalRequirementSchema = z.object({\n project: projectBriefSchema,\n actors: z.array(actorSchema),\n flows: z.array(flowSchema),\n stories: z.array(storySchema),\n modules: z.array(extractedModuleSchema),\n database: databaseDesignSchema,\n summary: requirementSummarySchema,\n});\n\nexport type RequirementSummary = z.infer<typeof requirementSummarySchema>;\nexport type FinalRequirement = z.infer<typeof finalRequirementSchema>;\n","/**\n * System prompt for chat-based requirement gathering\n */\n\nexport const REQUIREMENT_GATHERER_SYSTEM_PROMPT = `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.\n\nYou work in stages: discovery (understand the project and tech preferences), requirements (actors, flows, stories, modules), design (database + APIs), and complete (final document).\n\nThink 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.\n\nGuidelines:\n- For tech choices (API style: REST vs GraphQL; database: MongoDB vs PostgreSQL), offer predefined options and ask what the user is comfortable with.\n- For everything else, ask open-ended, context-specific questions based on what the user described. Leave suggestions empty for those.\n- Never repeat a question already answered in the conversation history.\n- When the user says \"continue\", \"yes\", \"looks good\", or similar, treat it as confirmation and advance.\n- Return valid JSON only when the prompt asks for JSON (no markdown code fences unless specified).\n- Backend is Node.js only; database is MongoDB or PostgreSQL per user preference.`;\n","/**\n * Discovery stage prompt - understand project and optionally ask questions\n */\n\nexport const DISCOVERY_SYSTEM_FRAGMENT = `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.\n\nDetermine from the user's words:\n- Project name and goal\n- Key features (array of strings)\n- Domain (e.g. e-commerce, healthcare, saas)\n- API style: \"rest\" | \"graphql\" — infer from context or ask with predefined options\n- Database: \"mongodb\" | \"postgresql\" — ask which they are comfortable with, with predefined options\n- Backend is always \"nodejs\"\n\nQuestion rules:\n- Tech stack (API style, database): Always provide \"suggestions\" with predefined options (e.g. [\"REST\", \"GraphQL\"], [\"MongoDB\", \"PostgreSQL\"]). Frame as \"which are you comfortable with?\"\n- 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).\n- Never ask: scale, \"how many users?\", \"what's the complexity?\", or generic intake-form questions.\n- Before asking, check conversation history — never repeat something already answered.\n- 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.`;\n\nexport const DISCOVERY_USER_PROMPT = `## Current user message:\n{userMessage}\n\n## Prior conversation (if any):\n{history}\n\nAnalyze 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.\n\nReturn ONLY valid JSON (no markdown, no explanation) in this shape:\n{\n \"needsClarification\": boolean,\n \"questions\": [\n {\n \"id\": \"q1\",\n \"question\": \"Question text\",\n \"context\": \"Why this helps\",\n \"suggestions\": [],\n \"multiSelect\": false,\n \"required\": true\n }\n ],\n \"conversationalMessage\": \"Brief friendly message to the user\",\n \"projectBrief\": {\n \"name\": \"string\",\n \"goal\": \"string\",\n \"features\": [\"string\"],\n \"domain\": \"string\",\n \"database\": \"mongodb\" | \"postgresql\",\n \"backendRuntime\": \"nodejs\",\n \"apiStyle\": \"rest\" | \"graphql\"\n }\n}\n\nFor tech choices (API style, database), populate \"suggestions\" with the predefined options. For all other questions, use \"suggestions\": [].\nIf needsClarification is true, projectBrief can have empty/default values. If false, projectBrief must be complete.`;\n\nexport function buildDiscoveryPrompt(userMessage: string, history: string): string {\n return DISCOVERY_USER_PROMPT.replace('{userMessage}', userMessage).replace(\n '{history}',\n history || '(No prior messages)'\n );\n}\n","/**\n * Requirements stage prompts - actors, flows, stories, modules (chained)\n */\n\nconst PROJECT_BLOCK = `## Project:\n- **Name**: {projectName}\n- **Goal**: {projectGoal}\n- **Features**: {projectFeatures}`;\n\nexport const EXTRACT_ACTORS_PROMPT = `${PROJECT_BLOCK}\n\nIdentify ALL distinct user types (actors) who will use this system. 2-5 actors. Include unauthenticated and admin roles if applicable.\n\nReturn ONLY valid JSON:\n{\n \"actors\": [\n { \"id\": \"actor-1\", \"name\": \"Name\", \"description\": \"Who they are\", \"goals\": [\"goal1\", \"goal2\"] }\n ],\n \"message\": \"Brief explanation\"\n}`;\n\nexport const GENERATE_FLOWS_PROMPT = `${PROJECT_BLOCK}\n\n## Actors (JSON):\n{actors}\n\nFor EACH actor, identify 2-5 key user journeys (flows). Each flow: id, actorId, name, description, trigger, outcome.\n\nReturn ONLY valid JSON:\n{\n \"flows\": [\n { \"id\": \"flow-1\", \"actorId\": \"actor-1\", \"name\": \"Flow Name\", \"description\": \"...\", \"trigger\": \"...\", \"outcome\": \"...\" }\n ],\n \"message\": \"Brief explanation\"\n}`;\n\nexport const GENERATE_STORIES_PROMPT = `${PROJECT_BLOCK}\n\n## Actors: {actors}\n\n## Flows (JSON):\n{flows}\n\nFor EACH flow, generate 2-5 user stories. Each story MUST include dataInvolved (entity.field names) for DB design. Include preconditions, postconditions.\n\nReturn ONLY valid JSON:\n{\n \"stories\": [\n { \"id\": \"story-1\", \"flowId\": \"flow-1\", \"actor\": \"ActorName\", \"action\": \"...\", \"benefit\": \"...\", \"preconditions\": [], \"postconditions\": [], \"dataInvolved\": [\"User.email\", \"Order.total\"] }\n ],\n \"message\": \"Brief explanation\"\n}`;\n\nexport const EXTRACT_MODULES_PROMPT = `${PROJECT_BLOCK}\n\n## Actors: {actors}\n## Flows: {flows}\n## Stories (JSON):\n{stories}\n\nExtract 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.\n\nReturn ONLY valid JSON:\n{\n \"modules\": [\n { \"id\": \"module-1\", \"name\": \"User\", \"description\": \"...\", \"entity\": \"User\", \"apis\": [ { \"id\": \"api-1-1\", \"name\": \"createUser\", \"operation\": \"create\", \"description\": \"...\", \"inputs\": [], \"outputs\": [] } ] }\n ],\n \"summary\": { \"totalModules\": 0, \"totalApis\": 0 },\n \"message\": \"Brief explanation\"\n}`;\n\nexport function buildExtractActorsPrompt(\n projectName: string,\n projectGoal: string,\n projectFeatures: string\n): string {\n return EXTRACT_ACTORS_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{projectFeatures}', projectFeatures);\n}\n\nexport function buildGenerateFlowsPrompt(\n projectName: string,\n projectGoal: string,\n projectFeatures: string,\n actorsJson: string\n): string {\n return GENERATE_FLOWS_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{projectFeatures}', projectFeatures)\n .replace('{actors}', actorsJson);\n}\n\nexport function buildGenerateStoriesPrompt(\n projectName: string,\n projectGoal: string,\n projectFeatures: string,\n actorsJson: string,\n flowsJson: string\n): string {\n return GENERATE_STORIES_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{projectFeatures}', projectFeatures)\n .replace('{actors}', actorsJson)\n .replace('{flows}', flowsJson);\n}\n\nexport function buildExtractModulesPrompt(\n projectName: string,\n projectGoal: string,\n projectFeatures: string,\n actorsJson: string,\n flowsJson: string,\n storiesJson: string\n): string {\n return EXTRACT_MODULES_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{projectFeatures}', projectFeatures)\n .replace('{actors}', actorsJson)\n .replace('{flows}', flowsJson)\n .replace('{stories}', storiesJson);\n}\n","/**\n * Design stage prompts - direct LLM invocation for database and API design\n */\n\nconst DESIGN_DB_PROMPT = `You are a database architect. The project brief includes a \"database\" field (mongodb or postgresql)—use that database. Do not choose a different one. Output a single JSON object.\n\n## Project brief (includes database: \"mongodb\" | \"postgresql\"):\n{projectBrief}\n\n## Modules (entities and CRUD):\n{modules}\n\n## User stories (data involved):\n{stories}\n\nDesign 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.\n\nReturn ONLY valid JSON (no markdown) in this exact shape. Set \"type\" to the database from the project brief.\n{\n \"type\": \"mongodb\" | \"postgresql\",\n \"reasoning\": \"2-4 sentences on how the schema fits the project\",\n \"entities\": [\n {\n \"name\": \"EntityName\",\n \"description\": \"Brief description\",\n \"fields\": [\n { \"name\": \"fieldName\", \"type\": \"DB-native type\", \"required\": true, \"unique\": false, \"description\": \"...\" }\n ],\n \"indexes\": [ { \"name\": \"index_name\", \"fields\": [\"field1\"], \"unique\": false } ],\n \"relations\": [ { \"field\": \"refField\", \"references\": \"OtherEntity\", \"description\": \"...\" } ]\n }\n ]\n}`;\n\nconst DESIGN_APIS_PROMPT = `You are an API architect for Node.js backends. Design the API according to apiStyle in the project brief.\n\n## Project brief (includes apiStyle: \"rest\" | \"graphql\"):\n{projectBrief}\n\n## Modules:\n{modules}\n\n## Actors:\n{actors}\n\n## Stories:\n{stories}\n\n## Database design (entities and fields):\n{database}\n\nProduce an API design:\n- 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—even for list endpoints use a single object describing the shape (e.g. for GET /users use \"responseBody\": { \"items\": \"array of user objects\", \"total\": \"number\" }).\n- 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.\n\nReturn ONLY valid JSON (no markdown, no code fences). Required shape:\n{\n \"style\": \"rest\" or \"graphql\",\n \"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\": {} } ] },\n \"graphql\": { \"types\": [], \"queries\": [], \"mutations\": [] }\n}\n- Use lowercase \"rest\" or \"graphql\" for style. Omit the branch not used (omit \"graphql\" when style is \"rest\", omit \"rest\" when style is \"graphql\").`;\n\nexport const DESIGN_DATABASE_SYSTEM_PROMPT =\n 'You output only valid JSON. No markdown, no explanation.';\n\nexport const DESIGN_APIS_SYSTEM_PROMPT = 'You output only valid JSON. No markdown, no explanation.';\n\nexport function buildDesignDatabasePrompt(\n projectBrief: string,\n modules: string,\n stories: string\n): string {\n return DESIGN_DB_PROMPT.replace('{projectBrief}', projectBrief)\n .replace('{modules}', modules)\n .replace('{stories}', stories);\n}\n\nexport function buildDesignApisPrompt(\n projectBrief: string,\n modules: string,\n actors: string,\n stories: string,\n database: string\n): string {\n return DESIGN_APIS_PROMPT.replace('{projectBrief}', projectBrief)\n .replace('{modules}', modules)\n .replace('{actors}', actors)\n .replace('{stories}', stories)\n .replace('{database}', database);\n}\n","/**\n * Synthesis stage prompt - compile FinalRequirement document\n * Note: apiDesign removed; API design is delegated to the api-designer module.\n */\n\nexport const SYNTHESIS_SYSTEM_FRAGMENT = `You are in the complete stage. You have the full context: project brief, actors, flows, stories, modules, and database design. Your job is to produce a single final requirement document (JSON) that matches the FinalRequirement schema, with a summary that includes totalActors, totalFlows, totalStories, totalModules, totalEntities, and a short overview paragraph.`;\n\nexport const SYNTHESIS_USER_PROMPT = `## Project brief (JSON):\n{projectBrief}\n\n## Actors (JSON):\n{actors}\n\n## Flows (JSON):\n{flows}\n\n## Stories (JSON):\n{stories}\n\n## Modules (JSON):\n{modules}\n\n## Database design (JSON):\n{database}\n\nCompile the above into one FinalRequirement JSON. Include a \"summary\" object with: totalActors, totalFlows, totalStories, totalModules, totalEntities (from database.entities.length), and \"overview\" (2-4 sentence paragraph summarizing the project and tech choices).\n\nReturn ONLY valid JSON in this shape (no markdown, no extra text):\n{\n \"project\": { ... },\n \"actors\": [ ... ],\n \"flows\": [ ... ],\n \"stories\": [ ... ],\n \"modules\": [ ... ],\n \"database\": { ... },\n \"summary\": {\n \"totalActors\": 0,\n \"totalFlows\": 0,\n \"totalStories\": 0,\n \"totalModules\": 0,\n \"totalEntities\": 0,\n \"overview\": \"string\"\n }\n}`;\n\nexport function buildSynthesisPrompt(\n projectBrief: string,\n actors: string,\n flows: string,\n stories: string,\n modules: string,\n database: string\n): string {\n return SYNTHESIS_USER_PROMPT.replace('{projectBrief}', projectBrief)\n .replace('{actors}', actors)\n .replace('{flows}', flows)\n .replace('{stories}', stories)\n .replace('{modules}', modules)\n .replace('{database}', database);\n}\n","/**\n * Context management for requirement chat\n */\n\nimport type { RequirementContext, StageResult, Stage, ChatEntry } from './types';\n\nexport function createInitialContext(): RequirementContext {\n return {\n stage: 'discovery',\n projectBrief: null,\n actors: [],\n flows: [],\n stories: [],\n modules: [],\n database: null,\n history: [],\n pendingQuestions: [],\n };\n}\n\nexport function mergeStageResult(\n context: RequirementContext,\n result: StageResult\n): RequirementContext {\n const data = result.data;\n return {\n ...context,\n ...(data.stage !== undefined && { stage: data.stage }),\n ...(data.projectBrief !== undefined && { projectBrief: data.projectBrief }),\n ...(data.actors !== undefined && { actors: data.actors }),\n ...(data.flows !== undefined && { flows: data.flows }),\n ...(data.stories !== undefined && { stories: data.stories }),\n ...(data.modules !== undefined && { modules: data.modules }),\n ...(data.database !== undefined && { database: data.database }),\n ...(data.pendingQuestions !== undefined && { pendingQuestions: data.pendingQuestions }),\n };\n}\n\nexport function addChatEntry(\n context: RequirementContext,\n role: 'user' | 'assistant',\n content: string\n): RequirementContext {\n const entry: ChatEntry = { role, content };\n return {\n ...context,\n history: [...context.history, entry],\n };\n}\n\nexport function advanceStage(context: RequirementContext): RequirementContext {\n const order: Stage[] = ['discovery', 'requirements', 'design', 'complete'];\n const idx = order.indexOf(context.stage);\n const nextStage = idx >= 0 && idx < order.length - 1 ? order[idx + 1] : undefined;\n const next: Stage = nextStage ?? context.stage;\n return { ...context, stage: next };\n}\n","/**\n * Stage processor interface and shared helpers\n */\n\nimport type { RequirementContext, Module, Story } from '../types';\n\nexport type { StageProcessor } from '../types';\n\n/** Summarize modules for token-efficient prompts (name, entity, API count) */\nexport function summarizeModules(modules: Module[]): string {\n return modules.map(m => `${m.name}: ${m.entity} (${m.apis.length} APIs)`).join('\\n');\n}\n\n/** Summarize stories for token-efficient prompts (actor + action) */\nexport function summarizeStories(stories: Story[]): string {\n return stories.map(s => `- ${s.actor}: ${s.action}`).join('\\n');\n}\n\nexport function extractJson(text: string): string {\n const trimmed = text.trim();\n const codeBlock = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n if (codeBlock?.[1]) return codeBlock[1].trim();\n return trimmed;\n}\n\nexport function safeParseJson(\n text: string\n): { success: true; data: unknown } | { success: false; error: string } {\n try {\n return { success: true, data: JSON.parse(text) };\n } catch (e) {\n return {\n success: false,\n error: e instanceof Error ? e.message : String(e),\n };\n }\n}\n\n/** Build a short text summary of context for inclusion in prompts */\nexport function buildContextSummary(ctx: RequirementContext): string {\n const parts: string[] = [];\n if (ctx.projectBrief) {\n parts.push(\n `Project: ${ctx.projectBrief.name}, Goal: ${ctx.projectBrief.goal}, API: ${ctx.projectBrief.apiStyle}`\n );\n }\n if (ctx.actors.length) parts.push(`Actors: ${ctx.actors.length}`);\n if (ctx.flows.length) parts.push(`Flows: ${ctx.flows.length}`);\n if (ctx.stories.length) parts.push(`Stories: ${ctx.stories.length}`);\n if (ctx.modules.length) parts.push(`Modules: ${ctx.modules.length}`);\n if (ctx.database) parts.push(`Database: ${ctx.database.type}`);\n return parts.join('. ') || 'No context yet';\n}\n\nexport function isConfirmation(message: string): boolean {\n const normalized = message.trim().toLowerCase();\n const confirmations = [\n 'continue',\n 'yes',\n 'yeah',\n 'yep',\n 'looks good',\n 'good',\n 'ok',\n 'okay',\n 'next',\n 'proceed',\n 'sure',\n ];\n return confirmations.some(c => normalized === c || normalized.startsWith(c + ' '));\n}\n","/**\n * Discovery stage - understand project, optional clarifying questions\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { RequirementContext, StageResult } from '../types';\nimport { projectBriefSchema, questionSchema } from '../schemas';\nimport { REQUIREMENT_GATHERER_SYSTEM_PROMPT } from '../prompts';\nimport { DISCOVERY_SYSTEM_FRAGMENT, buildDiscoveryPrompt } from '../prompts';\nimport { extractJson, safeParseJson } from './base';\n\nexport async function runDiscoveryStage(\n userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<StageResult> {\n logger?.debug('Discovery stage started', { historyLength: context.history.length });\n\n const history = context.history\n .map(e => `${e.role}: ${e.content}`)\n .slice(-10)\n .join('\\n');\n const prompt = buildDiscoveryPrompt(userMessage, history);\n const systemContent = `${REQUIREMENT_GATHERER_SYSTEM_PROMPT}\\n\\n${DISCOVERY_SYSTEM_FRAGMENT}`;\n const messages = [\n { role: 'system' as const, content: systemContent },\n { role: 'user' as const, content: prompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 4096 });\n const jsonStr = extractJson(response.text);\n const parsed = safeParseJson(jsonStr);\n if (!parsed.success) {\n logger?.warn('Discovery response was not valid JSON', { error: parsed.error });\n return {\n message: \"I couldn't parse that. Could you describe your project in a few sentences?\",\n advance: false,\n data: {},\n };\n }\n const data = parsed.data as {\n needsClarification?: boolean;\n questions?: unknown[];\n conversationalMessage?: string;\n projectBrief?: unknown;\n };\n const message =\n data.conversationalMessage ?? response.text?.slice(0, 500) ?? 'Thanks for the details.';\n const needsClarification = data.needsClarification === true;\n const questions: RequirementContext['pendingQuestions'] = [];\n if (Array.isArray(data.questions)) {\n for (const q of data.questions) {\n const validated = questionSchema.safeParse(q);\n if (validated.success) questions.push(validated.data);\n }\n }\n let projectBrief: RequirementContext['projectBrief'] = null;\n if (data.projectBrief && !needsClarification) {\n const pb = projectBriefSchema.safeParse(data.projectBrief);\n if (pb.success) projectBrief = pb.data;\n }\n logger?.debug('Discovery stage complete', {\n advance: !needsClarification && projectBrief !== null,\n hasProjectBrief: !!projectBrief,\n questionsCount: questions.length,\n });\n return {\n message,\n questions: questions.length ? questions : undefined,\n advance: !needsClarification && projectBrief !== null,\n data: {\n ...(projectBrief && { projectBrief }),\n pendingQuestions: questions,\n },\n };\n}\n","/**\n * Requirements stage: structured output via invokeObject, or invoke + parse\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { ModelMessage } from '../../../lib/types/common';\nimport type { ActorResult, FlowsResult, StoriesResult, ModulesResult } from '../schemas';\nimport {\n actorsResultSchema,\n flowsResultSchema,\n storiesResultSchema,\n modulesResultSchema,\n} from '../schemas';\nimport { extractJson, safeParseJson } from './base';\n\nexport async function getActors(\n model: Model,\n messages: ModelMessage[],\n _logger?: Logger\n): Promise<ActorResult> {\n if (model.invokeObject) {\n const result = await model.invokeObject<ActorResult>(messages, actorsResultSchema, {\n temperature: 0.4,\n maxOutputTokens: 4096,\n });\n return result.data;\n }\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 4096 });\n const parsed = safeParseJson(extractJson(response.text));\n if (!parsed.success) throw new Error(`Actors: ${parsed.error}`);\n const validated = actorsResultSchema.safeParse(parsed.data);\n if (!validated.success) throw new Error(`Actors schema: ${validated.error.message}`);\n return validated.data;\n}\n\nexport async function getFlows(\n model: Model,\n messages: ModelMessage[],\n _actors: ActorResult['actors'],\n _logger?: Logger\n): Promise<FlowsResult> {\n if (model.invokeObject) {\n const result = await model.invokeObject<FlowsResult>(messages, flowsResultSchema, {\n temperature: 0.4,\n maxOutputTokens: 8192,\n });\n return result.data;\n }\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 8192 });\n const parsed = safeParseJson(extractJson(response.text));\n if (!parsed.success) throw new Error(`Flows: ${parsed.error}`);\n const validated = flowsResultSchema.safeParse(parsed.data);\n if (!validated.success) throw new Error(`Flows schema: ${validated.error.message}`);\n return validated.data;\n}\n\nexport async function getStories(\n model: Model,\n messages: ModelMessage[],\n _actors: ActorResult['actors'],\n _flows: FlowsResult['flows'],\n _logger?: Logger\n): Promise<StoriesResult> {\n if (model.invokeObject) {\n const result = await model.invokeObject<StoriesResult>(messages, storiesResultSchema, {\n temperature: 0.4,\n maxOutputTokens: 16384,\n });\n return result.data;\n }\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 16384 });\n const parsed = safeParseJson(extractJson(response.text));\n if (!parsed.success) throw new Error(`Stories: ${parsed.error}`);\n const validated = storiesResultSchema.safeParse(parsed.data);\n if (!validated.success) throw new Error(`Stories schema: ${validated.error.message}`);\n return validated.data;\n}\n\nexport async function getModules(\n model: Model,\n messages: ModelMessage[],\n _actors: ActorResult['actors'],\n _flows: FlowsResult['flows'],\n _stories: StoriesResult['stories'],\n _logger?: Logger\n): Promise<ModulesResult> {\n if (model.invokeObject) {\n const result = await model.invokeObject<ModulesResult>(messages, modulesResultSchema, {\n temperature: 0.4,\n maxOutputTokens: 16384,\n });\n return result.data;\n }\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 16384 });\n const parsed = safeParseJson(extractJson(response.text));\n if (!parsed.success) throw new Error(`Modules: ${parsed.error}`);\n const validated = modulesResultSchema.safeParse(parsed.data);\n if (!validated.success) throw new Error(`Modules schema: ${validated.error.message}`);\n return validated.data;\n}\n","/**\n * Requirements stage - chain actors -> flows -> stories -> modules\n * Uses AI SDK structured output (invokeObject); no fallback data.\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { ModelMessage } from '../../../lib/types/common';\nimport type { RequirementContext, StageResult } from '../types';\nimport { REQUIREMENT_GATHERER_SYSTEM_PROMPT } from '../prompts';\nimport {\n buildExtractActorsPrompt,\n buildGenerateFlowsPrompt,\n buildGenerateStoriesPrompt,\n buildExtractModulesPrompt,\n} from '../prompts';\nimport { getActors, getFlows, getStories, getModules } from './requirements-invoke';\n\nexport async function runRequirementsStage(\n _userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<StageResult> {\n logger?.debug('Requirements stage started');\n\n const brief = context.projectBrief;\n if (!brief) {\n return {\n message: 'Project brief is missing. Complete discovery first.',\n advance: false,\n data: {},\n };\n }\n const projectName = brief.name;\n const projectGoal = brief.goal;\n const projectFeatures = brief.features.join('. ');\n\n const messages: ModelMessage[] = [\n { role: 'system', content: REQUIREMENT_GATHERER_SYSTEM_PROMPT },\n ];\n\n try {\n messages.push({\n role: 'user',\n content: buildExtractActorsPrompt(projectName, projectGoal, projectFeatures),\n });\n const actorsResult = await getActors(model, messages, logger);\n const actors = actorsResult.actors;\n logger?.debug('Requirements: actors', { count: actors.length });\n\n messages.push({\n role: 'assistant',\n content: `[Extracted ${actors.length} actors]`,\n });\n messages.push({\n role: 'user',\n content: buildGenerateFlowsPrompt(\n projectName,\n projectGoal,\n projectFeatures,\n JSON.stringify(actors)\n ),\n });\n const flowsResult = await getFlows(model, messages, actors, logger);\n const flows = flowsResult.flows;\n logger?.debug('Requirements: flows', { count: flows.length });\n\n messages.push({\n role: 'assistant',\n content: `[Generated ${flows.length} flows]`,\n });\n messages.push({\n role: 'user',\n content: buildGenerateStoriesPrompt(\n projectName,\n projectGoal,\n projectFeatures,\n JSON.stringify(actors),\n JSON.stringify(flows)\n ),\n });\n const storiesResult = await getStories(model, messages, actors, flows, logger);\n const stories = storiesResult.stories;\n logger?.debug('Requirements: stories', { count: stories.length });\n\n messages.push({\n role: 'assistant',\n content: `[Generated ${stories.length} stories]`,\n });\n messages.push({\n role: 'user',\n content: buildExtractModulesPrompt(\n projectName,\n projectGoal,\n projectFeatures,\n JSON.stringify(actors),\n JSON.stringify(flows),\n JSON.stringify(stories)\n ),\n });\n const modulesResult = await getModules(model, messages, actors, flows, stories, logger);\n const modules = modulesResult.modules;\n logger?.debug('Requirements stage complete', {\n actors: actors.length,\n flows: flows.length,\n stories: stories.length,\n modules: modules.length,\n });\n\n return {\n message: `I've identified ${actors.length} actors, ${flows.length} flows, ${stories.length} stories, and ${modules.length} modules. Proceeding to technical design.`,\n advance: true,\n data: { actors, flows, stories, modules, pendingQuestions: [] },\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n logger?.warn('Requirements stage failed', { error: message });\n return {\n message: `Requirements step failed: ${message}. Please try again.`,\n advance: false,\n data: {},\n };\n }\n}\n","/**\n * Design stage - direct LLM call for database design (prompt chaining)\n * Note: API design removed; delegated to the api-designer module downstream.\n */\n\nimport { z } from 'zod';\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { RequirementContext, StageResult } from '../types';\nimport { databaseDesignSchema } from '../schemas';\nimport { extractJson, safeParseJson, summarizeModules, summarizeStories } from './base';\nimport { DESIGN_DATABASE_SYSTEM_PROMPT, buildDesignDatabasePrompt } from '../prompts';\n\nexport async function runDesignStage(\n _userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<StageResult> {\n const brief = context.projectBrief;\n if (!brief) {\n return { message: 'Project brief is missing.', advance: false, data: {} };\n }\n if (!context.modules.length || !context.stories.length) {\n return {\n message: 'Requirements (modules and stories) are missing. Run requirements stage first.',\n advance: false,\n data: {},\n };\n }\n\n logger?.info('Design stage: database design', {\n modules: context.modules.length,\n stories: context.stories.length,\n });\n\n const projectBriefStr = JSON.stringify(brief);\n const modulesSummary = summarizeModules(context.modules);\n const storiesSummary = summarizeStories(context.stories);\n\n const dbPrompt = buildDesignDatabasePrompt(projectBriefStr, modulesSummary, storiesSummary);\n const dbMessages = [\n { role: 'system' as const, content: DESIGN_DATABASE_SYSTEM_PROMPT },\n { role: 'user' as const, content: dbPrompt },\n ];\n const dbResponse = await model.invoke(dbMessages, {\n temperature: 0.3,\n maxOutputTokens: 8192,\n });\n const dbJsonStr = extractJson(dbResponse.text);\n const dbParsed = safeParseJson(dbJsonStr);\n if (!dbParsed.success) {\n logger?.warn('Database design response was not valid JSON', { error: dbParsed.error });\n return {\n message: 'Failed to parse database design response. Please try again.',\n advance: false,\n data: {},\n };\n }\n const databaseResult = databaseDesignSchema.safeParse(dbParsed.data);\n if (!databaseResult.success) {\n const err = databaseResult.error;\n logger?.warn('Database design schema validation failed', { error: z.treeifyError(err) });\n return {\n message: 'Failed to produce database design. Please try again.',\n advance: false,\n data: {},\n };\n }\n const database = databaseResult.data;\n\n return {\n message: `Database design complete: ${database.type}. API design will be handled by the api-designer module.`,\n advance: true,\n data: { database, pendingQuestions: [] },\n };\n}\n","/**\n * Synthesis stage - compile FinalRequirement document\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { RequirementContext, StageResult } from '../types';\nimport type { FinalRequirement } from '../types';\nimport { finalRequirementSchema } from '../schemas';\nimport { REQUIREMENT_GATHERER_SYSTEM_PROMPT } from '../prompts';\nimport { SYNTHESIS_SYSTEM_FRAGMENT, buildSynthesisPrompt } from '../prompts';\nimport { extractJson, safeParseJson } from './base';\n\nexport async function runSynthesisStage(\n _userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<StageResult> {\n logger?.debug('Synthesis stage started');\n\n const brief = context.projectBrief;\n if (!brief || !context.database) {\n return {\n message: 'Missing project brief or database design. Complete earlier stages first.',\n advance: false,\n data: {},\n };\n }\n const prompt = buildSynthesisPrompt(\n JSON.stringify(brief),\n JSON.stringify(context.actors),\n JSON.stringify(context.flows),\n JSON.stringify(context.stories),\n JSON.stringify(context.modules),\n JSON.stringify(context.database)\n );\n const systemContent = `${REQUIREMENT_GATHERER_SYSTEM_PROMPT}\\n\\n${SYNTHESIS_SYSTEM_FRAGMENT}`;\n const messages = [\n { role: 'system' as const, content: systemContent },\n { role: 'user' as const, content: prompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 16384 });\n const jsonStr = extractJson(response.text);\n const parsed = safeParseJson(jsonStr);\n if (!parsed.success) {\n logger?.warn('Synthesis response was not valid JSON', { error: parsed.error });\n return {\n message: 'Failed to compile final requirement document. Please try again.',\n advance: false,\n data: {},\n };\n }\n const validated = finalRequirementSchema.safeParse(parsed.data);\n if (!validated.success) {\n logger?.warn('Synthesis: final requirement schema validation failed', {\n error: validated.error.message,\n });\n return {\n message: 'Final document did not match schema. ' + (response.text?.slice(0, 300) ?? ''),\n advance: false,\n data: {},\n };\n }\n const finalRequirement: FinalRequirement = validated.data;\n logger?.info('Synthesis stage complete', { overview: finalRequirement.summary?.overview });\n return {\n message: `Requirement document ready. ${finalRequirement.summary.overview}`,\n advance: true,\n data: { finalRequirement },\n };\n}\n","/**\n * Discovery stage - State pattern wrapper\n */\n\nimport type { RequirementContext, Stage, StageResult } from '../types';\nimport type { RequirementStageState, StageInput } from './state-types';\nimport { runDiscoveryStage } from './discovery.stage';\n\nexport class DiscoveryState implements RequirementStageState {\n readonly stageName: Stage = 'discovery';\n\n async process(context: RequirementContext, input: StageInput): Promise<StageResult> {\n return runDiscoveryStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: StageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): Stage | null {\n return 'requirements';\n }\n}\n","/**\n * Requirements stage - State pattern wrapper\n */\n\nimport type { RequirementContext, Stage, StageResult } from '../types';\nimport type { RequirementStageState, StageInput } from './state-types';\nimport { runRequirementsStage } from './requirements.stage';\n\nexport class RequirementsState implements RequirementStageState {\n readonly stageName: Stage = 'requirements';\n\n async process(context: RequirementContext, input: StageInput): Promise<StageResult> {\n return runRequirementsStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: StageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): Stage | null {\n return 'design';\n }\n}\n","/**\n * Design stage - State pattern wrapper\n */\n\nimport type { RequirementContext, Stage, StageResult } from '../types';\nimport type { RequirementStageState, StageInput } from './state-types';\nimport { runDesignStage } from './design.stage';\n\nexport class DesignState implements RequirementStageState {\n readonly stageName: Stage = 'design';\n\n async process(context: RequirementContext, input: StageInput): Promise<StageResult> {\n return runDesignStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: StageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): Stage | null {\n return 'complete';\n }\n}\n","/**\n * Synthesis (complete) stage - State pattern wrapper\n */\n\nimport type { RequirementContext, Stage, StageResult } from '../types';\nimport type { RequirementStageState, StageInput } from './state-types';\nimport { runSynthesisStage } from './synthesis.stage';\n\nexport class SynthesisState implements RequirementStageState {\n readonly stageName: Stage = 'complete';\n\n async process(context: RequirementContext, input: StageInput): Promise<StageResult> {\n return runSynthesisStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: StageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): Stage | null {\n return null;\n }\n}\n","/**\n * Registry: map Stage (string) to State instance for State pattern routing.\n */\n\nimport type { Stage } from '../types';\nimport type { RequirementStageState } from './state-types';\nimport { DiscoveryState } from './discovery.state';\nimport { RequirementsState } from './requirements.state';\nimport { DesignState } from './design.state';\nimport { SynthesisState } from './synthesis.state';\n\nconst states: Record<Stage, RequirementStageState> = {\n discovery: new DiscoveryState(),\n requirements: new RequirementsState(),\n design: new DesignState(),\n complete: new SynthesisState(),\n};\n\nexport function getStateForStage(stage: Stage): RequirementStageState {\n return states[stage];\n}\n","/**\n * Stage routing and auto-advance logic (State pattern)\n */\n\nimport type { Logger } from '../../lib/types/common';\nimport type { Model } from '../../lib/types/model';\nimport type { RequirementContext, Stage, FinalRequirement } from './types';\nimport { getStateForStage } from './stages';\nimport { isConfirmation } from './stages/base';\nimport { advanceStage, mergeStageResult, addChatEntry } from './context';\n\n/**\n * Determine which stage to run for this turn.\n */\nexport function getStageForTurn(context: RequirementContext, _userMessage: string): Stage {\n return context.stage;\n}\n\n/**\n * Run the current stage via State pattern: get state for context.stage, process, merge result.\n * If result.advance, context.stage is advanced to the next state's stage name.\n */\nexport async function runStage(\n stage: Stage,\n userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<{\n message: string;\n questions: RequirementContext['pendingQuestions'];\n advance: boolean;\n data: RequirementContext;\n finalRequirement?: FinalRequirement;\n}> {\n logger?.debug('Stage processor invoked', { stage });\n const state = getStateForStage(stage);\n const result = await state.process(context, { userMessage, model, logger });\n const merged = mergeStageResult(context, result);\n const finalReq = 'finalRequirement' in result.data ? result.data.finalRequirement : undefined;\n logger?.debug('Stage result', {\n stage,\n advance: result.advance,\n hasFinalRequirement: !!finalReq,\n });\n const data: RequirementContext = {\n ...merged,\n pendingQuestions: result.questions ?? merged.pendingQuestions,\n };\n return {\n message: result.message,\n questions: result.questions ?? merged.pendingQuestions,\n advance: result.advance,\n data,\n finalRequirement: finalReq,\n };\n}\n\n/**\n * Whether the user message is a confirmation (continue / yes / looks good)\n */\nexport { isConfirmation };\n\n/**\n * Advance context to next stage\n */\nexport { advanceStage };\n\n/**\n * Add a chat entry to context history\n */\nexport { addChatEntry };\n","/**\n * processRequirementChat - main entry point for chat-based requirement gathering\n */\n\nimport { createModel } from '../../lib/models/create-model';\nimport type { RequirementContext, ChatTurnResult, RequirementChatConfig, Stage } from './types';\nimport { createInitialContext, addChatEntry, advanceStage } from './context';\nimport { runStage } from './router';\n\nconst STAGE_ORDER: Stage[] = ['discovery', 'requirements', 'design', 'complete'];\n\nexport async function processRequirementChat(\n userMessage: string,\n context: RequirementContext | null,\n config: RequirementChatConfig\n): Promise<ChatTurnResult> {\n const { logger } = config;\n\n const modelConfig = config.model ?? { provider: 'openai', model: 'gpt-4o-mini' };\n const model = createModel(modelConfig);\n\n let ctx: RequirementContext = context ?? createInitialContext();\n ctx = addChatEntry(ctx, 'user', userMessage);\n\n logger?.info('Chat turn', { stage: ctx.stage, messageLength: userMessage.length });\n\n let message = '';\n let questions: RequirementContext['pendingQuestions'] = [];\n let finalRequirement: ChatTurnResult['finalRequirement'] = null;\n\n const runOne = async (\n stage: Stage\n ): Promise<{ advance: boolean; finalReq?: ChatTurnResult['finalRequirement'] }> => {\n const result = await runStage(stage, userMessage, ctx, model, logger);\n message = result.message;\n questions = result.questions;\n ctx = result.data;\n if (result.finalRequirement) finalRequirement = result.finalRequirement;\n return { advance: result.advance, finalReq: result.finalRequirement };\n };\n\n let stage = ctx.stage;\n logger?.info('Stage', { stage });\n let runResult = await runOne(stage);\n ctx = { ...ctx, pendingQuestions: questions };\n\n while (runResult.advance && !finalRequirement) {\n const idx = STAGE_ORDER.indexOf(stage);\n const nextStage = idx >= 0 && idx < STAGE_ORDER.length - 1 ? STAGE_ORDER[idx + 1] : undefined;\n if (nextStage === undefined) break;\n logger?.info('Stage transition', { from: stage, to: nextStage });\n stage = nextStage;\n ctx = advanceStage(ctx);\n ctx = { ...ctx, stage };\n logger?.info('Stage', { stage });\n runResult = await runOne(stage);\n ctx = { ...ctx, pendingQuestions: questions };\n }\n\n ctx = addChatEntry(ctx, 'assistant', message);\n\n logger?.info('Chat turn done', { stage, hasFinalRequirement: !!finalRequirement });\n return {\n message,\n context: ctx,\n questions,\n finalRequirement,\n };\n}\n","/**\n * runRequirementGathererAgent - one-shot wrapper around processRequirementChat\n * Runs the full chat flow non-interactively, auto-advancing with \"continue\" when questions are asked.\n */\n\nimport type { RequirementGathererAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\nimport { processRequirementChat } from './chat';\n\nconst MAX_TURNS = 10;\n\n/**\n * Run the requirement gatherer in one-shot mode: single input, auto-advance through stages,\n * return final requirement document or last message as AgentResult.\n */\nexport async function runRequirementGathererAgent(\n config: RequirementGathererAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, onStep, logger } = config;\n logger?.info('Starting requirement gatherer agent', { maxTurns: MAX_TURNS });\n\n let context = null;\n let lastResult = await processRequirementChat(input, context, {\n model: modelConfig,\n onStep,\n logger,\n });\n context = lastResult.context;\n let turns = 1;\n while (!lastResult.finalRequirement && turns < MAX_TURNS) {\n logger?.debug('Requirement gatherer turn', { turn: turns });\n lastResult = await processRequirementChat('continue', context, {\n model: modelConfig,\n onStep,\n logger,\n });\n context = lastResult.context;\n turns++;\n }\n const output = lastResult.finalRequirement\n ? JSON.stringify(lastResult.finalRequirement, null, 2)\n : lastResult.message;\n const messages = context.history.map(e => ({\n role: e.role as 'user' | 'system' | 'assistant',\n content: e.content,\n }));\n\n logger?.info('Requirement gatherer agent completed', {\n turns,\n hasFinalRequirement: !!lastResult.finalRequirement,\n });\n return {\n output,\n steps: [],\n totalUsage: undefined,\n messages,\n };\n}\n","/**\n * Builder for RequirementContext - fluent API, max 150 lines.\n */\n\nimport type {\n RequirementContext,\n Stage,\n ProjectBrief,\n Actor,\n Flow,\n Story,\n Module,\n DatabaseDesign,\n ChatEntry,\n Question,\n} from './types';\n\nconst DEFAULT_STAGE: Stage = 'discovery';\n\nexport class RequirementContextBuilder {\n private data: Partial<RequirementContext> = {};\n\n withStage(stage: Stage): this {\n this.data.stage = stage;\n return this;\n }\n\n withProjectBrief(projectBrief: ProjectBrief | null): this {\n this.data.projectBrief = projectBrief;\n return this;\n }\n\n withActors(actors: Actor[]): this {\n this.data.actors = actors;\n return this;\n }\n\n withFlows(flows: Flow[]): this {\n this.data.flows = flows;\n return this;\n }\n\n withStories(stories: Story[]): this {\n this.data.stories = stories;\n return this;\n }\n\n withModules(modules: Module[]): this {\n this.data.modules = modules;\n return this;\n }\n\n withDatabase(database: DatabaseDesign | null): this {\n this.data.database = database;\n return this;\n }\n\n withHistory(history: ChatEntry[]): this {\n this.data.history = history;\n return this;\n }\n\n withPendingQuestions(pendingQuestions: Question[]): this {\n this.data.pendingQuestions = pendingQuestions;\n return this;\n }\n\n reset(): this {\n this.data = {};\n return this;\n }\n\n build(): RequirementContext {\n return {\n stage: this.data.stage ?? DEFAULT_STAGE,\n projectBrief: this.data.projectBrief ?? null,\n actors: this.data.actors ?? [],\n flows: this.data.flows ?? [],\n stories: this.data.stories ?? [],\n modules: this.data.modules ?? [],\n database: this.data.database ?? null,\n history: this.data.history ?? [],\n pendingQuestions: this.data.pendingQuestions ?? [],\n };\n }\n}\n\nexport function createRequirementContextBuilder(): RequirementContextBuilder {\n return new RequirementContextBuilder();\n}\n","/**\n * Zod schemas for DataModelDesign\n */\n\nimport { z } from 'zod';\n\nexport const entityFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean().default(false),\n unique: z.coerce.boolean().default(false),\n description: z.string().default(''),\n default: z.string().optional(),\n});\n\nexport const entityIndexSchema = z.object({\n name: z.string().default(''),\n fields: z.array(z.string()).default([]),\n unique: z.coerce.boolean().default(false),\n});\n\n/** Normalize common relation type variants to canonical form. */\nconst relationTypeSchema = z\n .string()\n .transform(s => {\n const n = s.toLowerCase().replace(/[\\s_-]+/g, '');\n if (['1:1', 'onetoone'].includes(n)) return '1:1' as const;\n if (['1:n', '1:m', 'n:1', 'onetomany', 'manytoone'].includes(n)) return '1:N' as const;\n if (['m:n', 'n:m', 'manytomany'].includes(n)) return 'M:N' as const;\n return s;\n })\n .pipe(z.enum(['1:1', '1:N', 'M:N']));\n\nexport const entityRelationSchema = z.object({\n field: z.string(),\n references: z.string(),\n type: relationTypeSchema,\n description: z.string().default(''),\n});\n\nexport const dataEntitySchema = z.object({\n name: z.string(),\n description: z.string().default(''),\n fields: z\n .union([z.array(entityFieldSchema), z.record(z.string(), z.unknown())])\n .transform((v, ctx) => {\n if (Array.isArray(v)) return v;\n const results: z.infer<typeof entityFieldSchema>[] = [];\n for (const [key, raw] of Object.entries(v)) {\n const obj =\n typeof raw === 'object' && raw !== null ? { ...(raw as Record<string, unknown>) } : {};\n if (!obj.name) obj.name = key;\n const result = entityFieldSchema.safeParse(obj);\n if (result.success) {\n results.push(result.data);\n } else {\n for (const issue of result.error.issues) {\n ctx.addIssue({ ...issue, path: [key, ...issue.path] });\n }\n }\n }\n return results;\n }),\n indexes: z.array(entityIndexSchema).default([]),\n relations: z.array(entityRelationSchema).default([]),\n});\n\n/** Case-insensitive database type */\nconst dbTypeSchema = z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(['mongodb', 'postgresql']));\n\nexport const dataModelDesignSchema = z.object({\n type: dbTypeSchema,\n reasoning: z.string().default(''),\n entities: z.array(dataEntitySchema).default([]),\n});\n\nexport type TDataModelDesign = z.infer<typeof dataModelDesignSchema>;\n","/**\n * MongoDB field-level schema (merged from db-designer)\n */\n\nimport { z } from 'zod';\n\nexport const mongoFieldSchema = z.object({\n fieldName: z.string().describe('fieldName must be in camelCase'),\n fieldType: z\n .string()\n .default('string')\n .transform(s => {\n const n = s.toLowerCase().trim();\n if (['string', 'text', 'varchar'].includes(n)) return 'string' as const;\n if (['number', 'int', 'integer', 'float', 'double', 'decimal'].includes(n))\n return 'number' as const;\n if (['boolean', 'bool'].includes(n)) return 'boolean' as const;\n if (['types.objectid', 'objectid', 'ref', 'reference'].includes(n))\n return 'Types.ObjectId' as const;\n if (['date', 'datetime', 'timestamp'].includes(n)) return 'Date' as const;\n if (['object', 'json', 'mixed'].includes(n)) return 'object' as const;\n if (['email'].includes(n)) return 'email' as const;\n if (['password', 'hash'].includes(n)) return 'password' as const;\n if (['enum', 'select'].includes(n)) return 'enum' as const;\n if (['array'].includes(n)) return 'string' as const;\n return 'string' as const;\n })\n .pipe(\n z.enum([\n 'string',\n 'number',\n 'boolean',\n 'Types.ObjectId',\n 'Date',\n 'object',\n 'email',\n 'password',\n 'enum',\n ])\n ),\n isArray: z.coerce.boolean().default(false),\n isRequired: z.coerce.boolean().default(true),\n isUnique: z.coerce.boolean().default(false),\n values: z\n .array(z.string())\n .default([])\n .describe('Enum values if fieldType is enum, else empty array'),\n defaultVal: z.union([z.string(), z.boolean(), z.number(), z.null()]).optional(),\n relationTo: z.string().optional().describe('Module name for relations'),\n relationType: z\n .string()\n .transform(s => {\n const n = s.toLowerCase().replace(/[\\s_]+/g, '-');\n if (['one-to-one', '1:1', '1-to-1'].includes(n)) return 'one-to-one' as const;\n if (['many-to-one', 'n:1', 'n-to-1', 'many-to-1', '*:1'].includes(n))\n return 'many-to-one' as const;\n return '' as const;\n })\n .pipe(z.enum(['one-to-one', 'many-to-one', '']))\n .optional(),\n isPrivate: z.coerce.boolean().default(false).describe('True if password field, else false'),\n});\n\nexport type TMongoFieldSchema = z.infer<typeof mongoFieldSchema>;\n","/**\n * MongoDB module (collection) schema with RBAC (merged from db-designer)\n */\n\nimport { z } from 'zod';\nimport { mongoFieldSchema } from './mongodb-field.schema';\n\nexport const mongoModuleSchema = z.object({\n moduleName: z.string().describe('camelCase, single word, never auth/authentication'),\n isUserModule: z.coerce.boolean().default(false),\n authMethod: z\n .string()\n .transform(s => {\n const n = s.toUpperCase().replace(/[\\s-]+/g, '_');\n if (['EMAIL_AND_PASSWORD', 'EMAIL_PASSWORD', 'EMAIL'].includes(n))\n return 'EMAIL_AND_PASSWORD' as const;\n if (['PHONE_AND_OTP', 'PHONE_OTP', 'PHONE', 'SMS'].includes(n))\n return 'PHONE_AND_OTP' as const;\n return '' as const;\n })\n .pipe(z.enum(['EMAIL_AND_PASSWORD', 'PHONE_AND_OTP', '']))\n .optional(),\n emailField: z.string().optional(),\n passwordField: z.string().optional(),\n phoneField: z.string().optional(),\n roleField: z.string().optional(),\n permissions: z\n .record(z.string(), z.array(z.enum(['CREATE', 'READ', 'UPDATE', 'DELETE'])))\n .optional()\n .describe('Permissions per role'),\n fields: z\n .union([z.array(mongoFieldSchema), z.record(z.string(), z.unknown())])\n .transform((v, ctx) => {\n if (Array.isArray(v)) return v;\n const results: z.infer<typeof mongoFieldSchema>[] = [];\n for (const [key, raw] of Object.entries(v)) {\n const obj =\n typeof raw === 'object' && raw !== null ? { ...(raw as Record<string, unknown>) } : {};\n if (!obj.fieldName) obj.fieldName = key;\n const result = mongoFieldSchema.safeParse(obj);\n if (result.success) {\n results.push(result.data);\n } else {\n for (const issue of result.error.issues) {\n ctx.addIssue({ ...issue, path: [key, ...issue.path] });\n }\n }\n }\n return results;\n }),\n});\n\nexport type TMongoModuleSchema = z.infer<typeof mongoModuleSchema>;\n","/**\n * MongoDB root project schema with RBAC (merged from db-designer)\n */\n\nimport { z } from 'zod';\nimport { mongoModuleSchema } from './mongodb-module.schema';\n\nexport const mongoProjectSchema = z.object({\n projectName: z.string().default('project').describe('projectName must be in kebab-case'),\n projectDescription: z.string().default(''),\n modules: z\n .union([z.array(mongoModuleSchema), z.record(z.string(), z.unknown())])\n .transform((v, ctx) => {\n if (Array.isArray(v)) return v;\n const results: z.infer<typeof mongoModuleSchema>[] = [];\n for (const [key, raw] of Object.entries(v)) {\n const obj =\n typeof raw === 'object' && raw !== null ? { ...(raw as Record<string, unknown>) } : {};\n if (!obj.moduleName) obj.moduleName = key;\n const result = mongoModuleSchema.safeParse(obj);\n if (result.success) {\n results.push(result.data);\n } else {\n for (const issue of result.error.issues) {\n ctx.addIssue({ ...issue, path: [key, ...issue.path] });\n }\n }\n }\n return results;\n }),\n author: z.string().default('sijeeshmiziha'),\n});\n\nexport type TMongoProjectSchema = z.infer<typeof mongoProjectSchema>;\n","/**\n * System prompt for data-modeler orchestrator\n */\n\nexport const DATA_MODELER_SYSTEM_PROMPT = `You are a senior database architect specializing in both MongoDB and PostgreSQL schema design.\n\nYou analyze requirements and produce enterprise-quality data models with:\n- Properly typed fields (MongoDB: ObjectId, string, number, date, array; PostgreSQL: uuid, varchar, text, integer, timestamp, jsonb)\n- Indexes optimized for query patterns\n- Relationships with correct cardinality (1:1, 1:N, M:N)\n- Validation constraints and default values\n- Security considerations (hashed passwords, encrypted fields)\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for data-modeler\n */\n\nexport const DESIGN_SCHEMA_PROMPT = `## Requirements:\n{requirement}\n\nDesign the database schema. Determine the best database type (mongodb or postgresql) based on the requirements, or use the one specified.\n\nFor MongoDB use types: ObjectId, string, number, boolean, date, array, mixed.\nFor PostgreSQL use types: uuid, varchar(n), text, integer, bigint, boolean, timestamp, jsonb, and proper foreign key relations.\n\nReturn ONLY valid JSON:\n{\n \"type\": \"mongodb\" | \"postgresql\",\n \"reasoning\": \"2-4 sentences explaining the choice and design approach\",\n \"entities\": [\n {\n \"name\": \"EntityName\",\n \"description\": \"Brief description\",\n \"fields\": [\n { \"name\": \"fieldName\", \"type\": \"DB-native type\", \"required\": true, \"unique\": false, \"description\": \"...\" }\n ],\n \"indexes\": [ { \"name\": \"idx_name\", \"fields\": [\"field1\"], \"unique\": false } ],\n \"relations\": [ { \"field\": \"refField\", \"references\": \"OtherEntity\", \"type\": \"1:N\", \"description\": \"...\" } ]\n }\n ]\n}`;\n\nexport const REFINE_SCHEMA_PROMPT = `## Current Schema (JSON):\n{existingSchema}\n\n## Feedback:\n{feedback}\n\nUpdate the schema based on the feedback. Return the complete updated schema as valid JSON in the same format.`;\n\nexport function buildDesignSchemaPrompt(requirement: string): string {\n return DESIGN_SCHEMA_PROMPT.replace('{requirement}', requirement);\n}\n\nexport function buildRefineSchemaPrompt(existingSchema: string, feedback: string): string {\n return REFINE_SCHEMA_PROMPT.replace('{existingSchema}', existingSchema).replace(\n '{feedback}',\n feedback\n );\n}\n","/**\n * Pro-level 5-phase data modeling prompt\n */\n\nexport const PRO_DESIGN_PROMPT = `## Project: {projectName}\n## Goal: {projectGoal}\n## Database: {databaseType}\n\n## Context:\n{context}\n\nApply the 5-phase enterprise data modeling process:\n\n### Phase 1: Entity Discovery\n- Extract every entity from the context (user types, domain objects, settings, logs).\n- Identify status enums from flow transitions.\n\n### Phase 2: Relationship Mapping\n- For each entity pair, determine ownership and cardinality (1:1, 1:N, M:N).\n- Note bidirectional references and join tables (PostgreSQL) or embedded arrays (MongoDB).\n\n### Phase 3: Permission Derivation\n- Map actor types to role names.\n- From actions, derive which role can CRUD which entity.\n\n### Phase 4: Schema Generation\n- Generate fields with DB-native types, required/unique flags, defaults.\n- Add indexes for common queries (user lookups, date ranges, foreign keys).\n- Include timestamps (createdAt, updatedAt) on all entities.\n\n### Phase 5: Validation\n- Verify every entity referenced in relations exists.\n- Verify no orphan fields or missing indexes.\n\nReturn ONLY valid JSON in the DataModelDesign format.`;\n\nexport function buildProDesignPrompt(\n projectName: string,\n projectGoal: string,\n databaseType: string,\n context: string\n): string {\n return PRO_DESIGN_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{databaseType}', databaseType)\n .replace('{context}', context);\n}\n","/**\n * MongoDB 5-phase system prompt (merged from db-designer)\n */\n\nexport const MONGODB_SYSTEM_PROMPT = `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.\n\n## ANALYSIS FRAMEWORK\n\nYou MUST follow this 5-phase analysis process before generating the schema:\n\n### PHASE 1: Entity Discovery\nSystematically extract all entities from the provided requirements:\n\n1. **From dataInvolved fields**: Every item in user stories' dataInvolved[] array indicates a potential entity or field\n2. **From User Types (Actors)**: Each actor type may indicate a User variant or role\n3. **From User Flow Actions**: Action verbs reveal implicit entities\n4. **From Flow States**: Transitions reveal status enums\n\n### PHASE 2: Relationship Mapping\nFor each entity pair, determine relationships based on:\n\n1. **Ownership Patterns** (from actor actions)\n2. **Cardinality from Flow Context** (one-to-one, many-to-one)\n3. **Shared Entities** (referenced across flows)\n4. **Bidirectional References** (for one-to-one)\n\n### PHASE 3: Permission Derivation\nMap actors to RBAC permissions:\n\n1. **Role Extraction**: Each actor type becomes a role value\n2. **Permission Mining from User Stories**: Map actions to CRUD per role\n3. **Data Visibility Rules**: \"view own\" vs \"view all\" vs \"manage\"\n\n### PHASE 4: Query Pattern Inference\nAnalyze flows to predict database access patterns:\n\n1. **Read Patterns** (suggest indexes)\n2. **Write Patterns** (affect schema design)\n3. **Aggregation Needs** (from reporting flows)\n\n### PHASE 5: Schema Construction\nSynthesize all analyses into the final schema:\n\n1. **Module Definition**: One module per core entity, camelCase names\n2. **Field Completeness**: All fields from dataInvolved, relationships, status enums, timestamps\n3. **Validation Constraints**: isRequired, isUnique, enum values\n4. **Security Fields**: password fields with isPrivate: true\n\n## CORE CONSTRAINTS (MUST FOLLOW)\n\n1. **Primary Key**: _id with Types.ObjectId (auto-generated, do not include in fields)\n2. **Relationships**: One-to-One: reference in BOTH collections; Many-to-One: reference in \"many\" side; One-to-Many: FORBIDDEN - invert to many-to-one\n3. **Data Types**: NO arrays of ObjectIds; Timestamps: createdAt, updatedAt in EVERY collection; Enums: fieldType: 'enum' with values array\n4. **Security**: NO separate \"Auth\" collection; NO token storage; Password fields: isPrivate: true\n5. **Authorization (RBAC)**: Define permissions per role on user modules`;\n","/**\n * MongoDB prompt formatters - format structured requirements for prompts\n * (merged from db-designer)\n */\n\nimport type {\n MongoActor,\n MongoExtractedFlow,\n MongoExtractedStory,\n MongoTechnicalRequirements,\n MongoStructuredInput,\n} from '../types';\n\nexport function formatUserTypes(actors: MongoActor[]): string {\n if (!actors || actors.length === 0) {\n return 'No specific user types defined. Assume a general \"User\" role.';\n }\n return actors\n .map((actor, i) => {\n const goals = actor.goals.filter(g => g.trim()).join('\\n - ');\n return `### ${i + 1}. ${actor.name}\\n**Description:** ${actor.description}\\n**Goals:**\\n - ${goals || 'No specific goals defined'}`;\n })\n .join('\\n\\n');\n}\n\nexport function formatUserFlows(flows: MongoExtractedFlow[], actors: MongoActor[]): string {\n if (!flows || flows.length === 0) return 'No specific user flows defined.';\n return flows\n .map((flow, i) => {\n const actor = actors.find(a => a.id === flow.actorId);\n return `### ${i + 1}. ${flow.name}\\n**Actor:** ${actor?.name || 'User'}\\n**Description:** ${flow.description}\\n**Trigger:** ${flow.trigger || 'User initiates action'}\\n**Outcome:** ${flow.outcome || 'Action completed'}`;\n })\n .join('\\n\\n');\n}\n\nexport function formatUserStories(\n stories: MongoExtractedStory[],\n flows: MongoExtractedFlow[]\n): string {\n if (!stories || stories.length === 0) return 'No specific user stories defined.';\n const byFlow = new Map<string, MongoExtractedStory[]>();\n for (const s of stories) {\n const arr = byFlow.get(s.flowId) || [];\n arr.push(s);\n byFlow.set(s.flowId, arr);\n }\n const sections: string[] = [];\n for (const flow of flows) {\n const flowStories = byFlow.get(flow.id) || [];\n if (flowStories.length === 0) continue;\n sections.push(`### Flow: ${flow.name}\\n`);\n for (const story of flowStories) {\n const pre = story.preconditions.filter(p => p.trim());\n const post = story.postconditions.filter(p => p.trim());\n const data = story.dataInvolved.filter(d => d.trim());\n let t = `**As a** ${story.actor}, **I want to** ${story.action}, **so that** ${story.benefit}\\n`;\n if (pre.length) t += `\\n**Preconditions:**\\n${pre.map(p => `- ${p}`).join('\\n')}\\n`;\n if (post.length) t += `\\n**Postconditions:**\\n${post.map(p => `- ${p}`).join('\\n')}\\n`;\n if (data.length)\n t += `\\n**Data Involved (IMPORTANT):**\\n${data.map(d => `- ${d}`).join('\\n')}\\n`;\n sections.push(t);\n }\n }\n const orphans = stories.filter(s => !flows.some(f => f.id === s.flowId));\n if (orphans.length) {\n sections.push(`### Other Stories\\n`);\n for (const s of orphans) {\n const data = s.dataInvolved.filter(d => d.trim());\n let t = `**As a** ${s.actor}, **I want to** ${s.action}, **so that** ${s.benefit}\\n`;\n if (data.length) t += `\\n**Data Involved:** ${data.join(', ')}\\n`;\n sections.push(t);\n }\n }\n return sections.join('\\n');\n}\n\nexport function formatTechnicalRequirements(tech?: MongoTechnicalRequirements): string {\n if (!tech) return 'No specific technical requirements. Use defaults.';\n const lines: string[] = [`**Authentication:** ${tech.authentication || 'none'}`];\n if (tech.authorization) {\n lines.push('**Authorization (RBAC):** Enabled');\n if (tech.roles?.length) lines.push(`**Defined Roles:** ${tech.roles.join(', ')}`);\n } else {\n lines.push('**Authorization:** Disabled');\n }\n if (tech.realtime) lines.push('**Realtime Features:** Required');\n if (tech.fileUpload) lines.push('**File Upload:** Required');\n if (tech.search) lines.push('**Search Functionality:** Required');\n if (tech.integrations?.length) lines.push(`**Integrations:** ${tech.integrations.join(', ')}`);\n return lines.join('\\n');\n}\n\nexport function extractDataEntities(stories: MongoExtractedStory[]): string[] {\n const entities = new Set<string>();\n for (const s of stories) for (const d of s.dataInvolved) if (d.trim()) entities.add(d.trim());\n return Array.from(entities);\n}\n\nexport function extractRoles(actors: MongoActor[]): string[] {\n return actors.map(a => a.name.toLowerCase().replaceAll(/\\s+/g, '_'));\n}\n\nexport function buildPromptVariables(input: MongoStructuredInput): Record<string, string> {\n return {\n projectName: input.projectName,\n projectGoal: input.projectGoal,\n projectDescription: input.projectDescription || input.projectGoal,\n userTypes: formatUserTypes(input.actors),\n userFlows: formatUserFlows(input.flows, input.actors),\n userStories: formatUserStories(input.stories, input.flows),\n technicalRequirements: formatTechnicalRequirements(input.technicalRequirements),\n };\n}\n","/**\n * MongoDB design prompt builders (merged from db-designer)\n */\n\nimport type { MongoStructuredInput } from '../types';\nimport { MONGODB_SYSTEM_PROMPT } from './mongodb-system.prompt';\nimport { buildPromptVariables } from './mongodb-formatters';\n\n/**\n * Legacy: build design prompt from plain requirement string\n */\nexport function createMongoDesignPrompt(requirement: string): string {\n return `${MONGODB_SYSTEM_PROMPT}\n\nDesign a robust and efficient MongoDB database schema based on the following requirements:\n\n## Requirements\n${requirement}\n\n## Guidelines\n1. Use camelCase for module names and field names\n2. Include createdAt and updatedAt Date fields in every module\n3. Define proper relationships between modules\n4. Set appropriate permissions for user modules\n\nReturn ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`;\n}\n\n/**\n * Pro-level MongoDB design prompt from structured requirements\n */\nexport function createMongoProDesignPrompt(input: MongoStructuredInput): string {\n const vars = buildPromptVariables(input);\n return `${MONGODB_SYSTEM_PROMPT}\n\n---\n\n## PROJECT CONTEXT\n\n**Project Name:** ${vars.projectName}\n**Project Goal:** ${vars.projectGoal}\n**Description:** ${vars.projectDescription}\n\n---\n\n## USER TYPES (ACTORS)\n\n${vars.userTypes}\n\n---\n\n## USER FLOWS\n\n${vars.userFlows}\n\n---\n\n## USER STORIES WITH DATA REQUIREMENTS\n\n${vars.userStories}\n\n---\n\n## TECHNICAL REQUIREMENTS\n\n${vars.technicalRequirements}\n\n---\n\n## YOUR TASK\n\nFollow the 5-phase analysis framework:\n\n### Step 1: Entity Discovery\n- List ALL entities extracted from dataInvolved fields\n- Identify implicit entities from user flow actions\n- Map user types to User collection roles\n- Extract status enums from flow transitions\n\n### Step 2: Relationship Mapping\n- Define ownership: which actor creates/owns each entity\n- Determine cardinality from flow context\n\n### Step 3: Permission Derivation\n- Map each actor to a role\n- Extract CRUD permissions from user story actions\n\n### Step 4: Query Pattern Inference\n- Identify likely query patterns from flows\n\n### Step 5: Schema Construction\nGenerate the final schema with complete module definitions, fields, relationships, RBAC permissions, and timestamps.\n\nReturn ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`;\n}\n","/**\n * MongoDB redesign prompt - update existing schema based on feedback\n * (merged from db-designer)\n */\n\nimport { MONGODB_SYSTEM_PROMPT } from './mongodb-system.prompt';\n\nexport function createMongoRedesignPrompt(existingSchema: string, feedback: string): string {\n return `${MONGODB_SYSTEM_PROMPT}\n\nUpdate the existing MongoDB schema based on user feedback.\n\n## Steps\n1. Analyze the existing MongoDB schema provided\n2. Review the user feedback to understand the required updates\n3. Update the schema to incorporate the requested changes while adhering to best practices\n\n## Existing Schema\n${existingSchema}\n\n## User Feedback\n${feedback}\n\nReturn the updated schema as a valid JSON object matching the original schema format.\nIMPORTANT: Return ONLY the JSON object, no markdown code blocks, no explanations.`;\n}\n","/**\n * validate_schema tool - validates JSON against dataModelDesignSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { dataModelDesignSchema } from '../schemas';\n\nexport const validateSchemaTool = createValidationTool(\n 'validate_data_model',\n dataModelDesignSchema,\n 'Validates a data model JSON string against the DataModelDesign schema. Returns valid: true or valid: false with errors.',\n 'schema'\n);\n","/**\n * design_schema tool - generates data model from plain text requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { dataModelDesignSchema, type TDataModelDesign } from '../schemas';\nimport { buildDesignSchemaPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_schema tool. Requires a model for generation.\n */\nexport function createDesignSchemaTool(model: Model) {\n return defineTool({\n name: 'design_schema',\n description:\n 'Generate a database schema (MongoDB or PostgreSQL) from plain text requirements. Returns the full data model as JSON.',\n input: z.object({\n requirement: z.string().describe('Plain text description of the data modeling requirements'),\n }),\n handler: async ({ requirement }): Promise<TDataModelDesign> => {\n const userPrompt = buildDesignSchemaPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a database schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, dataModelDesignSchema);\n },\n });\n}\n","/**\n * design_schema_pro tool - 5-phase structured data modeling (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { dataModelDesignSchema, type TDataModelDesign } from '../schemas';\nimport { buildProDesignPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_schema_pro tool for structured 5-phase data modeling.\n */\nexport function createDesignSchemaProTool(model: Model) {\n return defineTool({\n name: 'design_schema_pro',\n description:\n '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.',\n input: z.object({\n projectName: z.string().describe('Project name'),\n projectGoal: z.string().describe('Project goal / purpose'),\n databaseType: z.enum(['mongodb', 'postgresql']).describe('Target database type'),\n context: z.string().describe('Full project context: features, actors, flows, stories'),\n }),\n handler: async ({\n projectName,\n projectGoal,\n databaseType,\n context,\n }): Promise<TDataModelDesign> => {\n const userPrompt = buildProDesignPrompt(projectName, projectGoal, databaseType, context);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a database schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.2, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, dataModelDesignSchema);\n },\n });\n}\n","/**\n * refine_schema tool - updates existing schema based on feedback (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { dataModelDesignSchema, type TDataModelDesign } from '../schemas';\nimport { buildRefineSchemaPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the refine_schema tool for iterating on an existing data model.\n */\nexport function createRefineSchemaTools(model: Model) {\n return defineTool({\n name: 'refine_schema',\n description:\n 'Update an existing data model schema based on user feedback. Provide the current schema JSON and feedback describing desired changes.',\n input: z.object({\n existingSchema: z.string().describe('Current data model schema as JSON string'),\n feedback: z.string().describe('Feedback describing desired changes'),\n }),\n handler: async ({ existingSchema, feedback }): Promise<TDataModelDesign> => {\n const userPrompt = buildRefineSchemaPrompt(existingSchema, feedback);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a database schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, dataModelDesignSchema);\n },\n });\n}\n","/**\n * validate_schema tool - validates JSON against mongoProjectSchema (merged from db-designer)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { mongoProjectSchema } from '../schemas';\n\nexport const validateMongoSchemaTool = createValidationTool(\n 'validate_schema',\n mongoProjectSchema,\n 'Validates a MongoDB project schema JSON string against the expected schema. Returns valid: true or valid: false with errors.',\n 'schema'\n);\n","/**\n * design_database tool - generates MongoDB schema from plain text (merged from db-designer)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { mongoProjectSchema, type TMongoProjectSchema } from '../schemas';\nimport { createMongoDesignPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_database tool for MongoDB schema generation.\n */\nexport function createDesignDatabaseTool(model: Model) {\n return defineTool({\n name: 'design_database',\n description:\n 'Generate a MongoDB database schema from plain text requirements. Returns the full project schema as JSON.',\n input: z.object({\n requirement: z.string().describe('Plain text description of the database requirements'),\n }),\n handler: async ({ requirement }): Promise<TMongoProjectSchema> => {\n const userPrompt = createMongoDesignPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a MongoDB schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, mongoProjectSchema);\n },\n });\n}\n","/**\n * design_database_pro tool - MongoDB schema from structured requirements (merged from db-designer)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { mongoProjectSchema, type TMongoProjectSchema } from '../schemas';\nimport { createMongoProDesignPrompt, extractDataEntities, extractRoles } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\nconst structuredInputSchema = z.object({\n projectName: z.string(),\n projectGoal: z.string(),\n projectDescription: z.string().optional(),\n actors: z.array(\n z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n goals: z.array(z.string()),\n })\n ),\n flows: z.array(\n z.object({\n id: z.string(),\n actorId: z.string(),\n name: z.string(),\n description: z.string(),\n trigger: z.string(),\n outcome: z.string(),\n })\n ),\n stories: z.array(\n z.object({\n id: z.string(),\n flowId: z.string(),\n actor: z.string(),\n action: z.string(),\n benefit: z.string(),\n preconditions: z.array(z.string()),\n postconditions: z.array(z.string()),\n dataInvolved: z.array(z.string()),\n })\n ),\n technicalRequirements: z\n .object({\n authentication: z\n .string()\n .transform(s => {\n const n = s.toLowerCase().replace(/[\\s_-]+/g, '');\n if (['none', 'no', ''].includes(n)) return 'none' as const;\n if (['email', 'emailpassword', 'emailandpassword'].includes(n)) return 'email' as const;\n if (['oauth', 'oauth2', 'social'].includes(n)) return 'oauth' as const;\n if (['phone', 'phoneotp', 'sms'].includes(n)) return 'phone' as const;\n if (['emailandphone', 'emailphone', 'both'].includes(n))\n return 'email_and_phone' as const;\n return 'email' as const;\n })\n .pipe(z.enum(['none', 'email', 'oauth', 'phone', 'email_and_phone'])),\n authorization: z.coerce.boolean().default(false),\n roles: z.array(z.string()).optional(),\n integrations: z.array(z.string()).optional(),\n realtime: z.boolean().optional(),\n fileUpload: z.boolean().optional(),\n search: z.boolean().optional(),\n })\n .optional(),\n});\n\n/**\n * Creates the design_database_pro tool for structured 5-phase MongoDB analysis.\n */\nexport function createDesignDatabaseProTool(model: Model) {\n return defineTool({\n name: 'design_database_pro',\n description:\n 'Generate a MongoDB schema from structured requirements (actors, flows, stories, technical requirements). Returns dbDesign and metadata.',\n input: structuredInputSchema,\n handler: async (\n input\n ): Promise<{\n dbDesign: TMongoProjectSchema;\n metadata: { entitiesDetected: string[]; rolesExtracted: string[] };\n }> => {\n const userPrompt = createMongoProDesignPrompt(input);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a MongoDB schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.2, maxOutputTokens: 16384 });\n const dbDesign = parseModelJsonResponse(response.text, mongoProjectSchema);\n const metadata = {\n entitiesDetected: extractDataEntities(input.stories),\n rolesExtracted: extractRoles(input.actors),\n };\n return { dbDesign, metadata };\n },\n });\n}\n","/**\n * redesign_database tool - updates existing MongoDB schema from feedback (merged from db-designer)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { mongoProjectSchema, type TMongoProjectSchema } from '../schemas';\nimport { createMongoRedesignPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the redesign_database tool for iterating on MongoDB schemas.\n */\nexport function createRedesignDatabaseTool(model: Model) {\n return defineTool({\n name: 'redesign_database',\n description:\n 'Update an existing MongoDB project schema based on user feedback. Provide the current schema JSON string and the feedback.',\n input: z.object({\n existingSchema: z.string().describe('Current project schema as JSON string'),\n feedback: z.string().describe('User feedback describing desired changes'),\n }),\n handler: async ({ existingSchema, feedback }): Promise<TMongoProjectSchema> => {\n const userPrompt = createMongoRedesignPrompt(existingSchema, feedback);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a MongoDB schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, mongoProjectSchema);\n },\n });\n}\n","/**\n * data-modeler tools (generic + MongoDB)\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateSchemaTool } from './validate-schema';\nimport { createDesignSchemaTool } from './design-schema';\nimport { createDesignSchemaProTool } from './design-schema-pro';\nimport { createRefineSchemaTools } from './refine-schema';\nimport { validateMongoSchemaTool } from './validate-mongodb';\nimport { createDesignDatabaseTool } from './design-mongodb';\nimport { createDesignDatabaseProTool } from './design-mongodb-pro';\nimport { createRedesignDatabaseTool } from './redesign-mongodb';\n\nexport { validateSchemaTool } from './validate-schema';\nexport { createDesignSchemaTool } from './design-schema';\nexport { createDesignSchemaProTool } from './design-schema-pro';\nexport { createRefineSchemaTools } from './refine-schema';\n\n/* MongoDB-specific tools (merged from db-designer) */\nexport { validateMongoSchemaTool } from './validate-mongodb';\nexport { createDesignDatabaseTool } from './design-mongodb';\nexport { createDesignDatabaseProTool } from './design-mongodb-pro';\nexport { createRedesignDatabaseTool } from './redesign-mongodb';\n\n/**\n * Create all generic data-modeler tools. Pass the model for AI-backed tools.\n */\nexport function createDataModelerTools(model: Model) {\n return createToolSet({\n validate_data_model: validateSchemaTool,\n design_schema: createDesignSchemaTool(model),\n design_schema_pro: createDesignSchemaProTool(model),\n refine_schema: createRefineSchemaTools(model),\n });\n}\n\n/**\n * Create all MongoDB-specific tools (merged from db-designer).\n */\nexport function createDbDesignerTools(model: Model) {\n return createToolSet({\n validate_schema: validateMongoSchemaTool,\n design_database: createDesignDatabaseTool(model),\n design_database_pro: createDesignDatabaseProTool(model),\n redesign_database: createRedesignDatabaseTool(model),\n });\n}\n","/**\n * runDataModelerAgent - orchestrator for data model design\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { DATA_MODELER_SYSTEM_PROMPT } from './prompts';\nimport { createDataModelerTools } from './tools';\nimport {\n entityAnalyzerSubagent,\n relationshipMapperSubagent,\n createSchemaRefinerSubagent,\n} from './subagents';\nimport type { DataModelerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${DATA_MODELER_SYSTEM_PROMPT}\n\nYou are the data modeling orchestrator. When the user asks for a data model:\n\n1. **Analyze first**: Use subagent_entity-analyzer to extract entities, fields, and relationships from the requirements.\n2. **Map relationships**: Use subagent_relationship-mapper with the entity analysis to determine cardinality, foreign keys, and indexes.\n3. **Generate schema**: Use design_schema (plain text) or design_schema_pro (when structured context is available) to produce the data model.\n4. **Refine (optional)**: Use subagent_schema-refiner to validate and suggest improvements to the generated schema.\n5. **Validate**: Use validate_data_model to check the final schema JSON before returning.\n\nRespond with the final data model schema as JSON.`;\n\n/**\n * Run the data-modeler orchestrator agent with all tools and subagents.\n */\nexport async function runDataModelerAgent(config: DataModelerAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createDataModelerTools(model);\n const schemaRefiner = createSchemaRefinerSubagent();\n const subagentTools = createSubagentToolSet(\n [entityAnalyzerSubagent, relationshipMapperSubagent, schemaRefiner],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * runDbDesignerAgent - MongoDB-specific orchestrator (merged from db-designer)\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { MONGODB_SYSTEM_PROMPT } from './prompts';\nimport { createDbDesignerTools } from './tools';\nimport { entityAnalyzerSubagent, createSchemaRefinerSubagent } from './subagents';\nimport type { MongoDbDesignerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${MONGODB_SYSTEM_PROMPT}\n\nYou are the MongoDB database design orchestrator. When the user asks for a database design:\n\n1. **Analyze first**: Use subagent_entity-analyzer to extract entities, relationships, and roles.\n2. **Generate schema**: Use design_database (plain text) or design_database_pro (structured requirements) to produce the MongoDB schema.\n3. **Refine (optional)**: Use subagent_schema-refiner to validate and suggest improvements.\n4. **Validate**: Use validate_schema to check the final schema JSON.\n5. **Redesign**: If changes are requested, use redesign_database with existing schema and feedback.\n\nRespond with the final schema as JSON.`;\n\n/**\n * Run the MongoDB db-designer orchestrator agent with all tools and subagents.\n */\nexport async function runDbDesignerAgent(config: MongoDbDesignerAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const dbTools = createDbDesignerTools(model);\n const schemaRefiner = createSchemaRefinerSubagent();\n const subagentTools = createSubagentToolSet([entityAnalyzerSubagent, schemaRefiner], {\n parentModel: model,\n });\n const tools = createToolSet({ ...dbTools, ...subagentTools });\n\n return runAgent({\n model,\n tools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for ApiDesign\n */\n\nimport { z } from 'zod';\n\nconst httpMethodSchema = z\n .union([z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']), z.string()])\n .transform(s => (typeof s === 'string' ? s.toUpperCase() : s))\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nconst stringRecordSchema = z\n .record(z.string(), z.unknown())\n .optional()\n .default({})\n .transform(m =>\n Object.fromEntries(\n Object.entries(m ?? {}).map(([k, v]) => [k, typeof v === 'string' ? v : String(v)])\n )\n );\n\n/** Coerce arrays of mixed strings/objects to string arrays (models often return objects). */\nconst stringOrObjectArraySchema = z\n .array(z.unknown())\n .default([])\n .transform(arr => arr.map(v => (typeof v === 'string' ? v : JSON.stringify(v))));\n\nexport const restEndpointSchema = z.object({\n id: z.string(),\n resource: z.string(),\n method: httpMethodSchema,\n path: z.string(),\n description: z.string(),\n auth: z.coerce.boolean(),\n roles: z.array(z.string()).default([]),\n requestBody: stringRecordSchema,\n responseBody: stringRecordSchema,\n queryParams: stringRecordSchema,\n validation: stringOrObjectArraySchema,\n errorResponses: stringOrObjectArraySchema,\n});\n\nexport const graphqlOperationSchema = z.object({\n name: z.string(),\n type: z.enum(['query', 'mutation', 'subscription']),\n description: z.string(),\n auth: z.coerce.boolean(),\n roles: z.array(z.string()).default([]),\n args: z.array(\n z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean(),\n })\n ),\n returnType: z.string(),\n});\n\nconst apiStyleSchema = z.unknown().transform(v => {\n const s = typeof v === 'string' ? v.toLowerCase().trim() : 'rest';\n if (s.includes('graphql')) return 'graphql' as const;\n return 'rest' as const;\n});\n\nexport const apiDesignSchema = z.object({\n style: apiStyleSchema,\n baseUrl: z.string().default('/api/v1'),\n endpoints: z.array(restEndpointSchema).default([]),\n graphqlOperations: z.array(graphqlOperationSchema).default([]),\n});\n\nexport type TApiDesign = z.infer<typeof apiDesignSchema>;\n","/**\n * System prompt for api-designer orchestrator\n */\n\nexport const API_DESIGNER_SYSTEM_PROMPT = `You are a senior API architect specializing in REST and GraphQL API design.\n\nYou analyze data models and requirements to produce enterprise-quality API designs with:\n- RESTful endpoints grouped by resource with proper HTTP methods\n- Request/response contracts with field types and validation rules\n- Error responses with appropriate HTTP status codes (400, 401, 403, 404, 500)\n- Pagination, filtering, and sorting patterns\n- Authentication and authorization annotations per endpoint\n- GraphQL types, queries, mutations, and subscriptions when applicable\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for api-designer\n */\n\nexport const DESIGN_API_PROMPT = `## Requirements:\n{requirement}\n\nDesign the API. Determine the best API style (rest or graphql) based on the requirements, or use the one specified.\n\nFor REST: group endpoints by resource. Each endpoint needs method, path, description, auth flag, roles, requestBody, responseBody, queryParams, validation rules, and error responses.\nFor GraphQL: define operations (queries, mutations, subscriptions) with args and return types.\n\nReturn ONLY valid JSON:\n{\n \"style\": \"rest\" | \"graphql\",\n \"baseUrl\": \"/api/v1\",\n \"endpoints\": [\n { \"id\": \"ep-1\", \"resource\": \"users\", \"method\": \"POST\", \"path\": \"/api/v1/users\", \"description\": \"Create user\", \"auth\": false, \"roles\": [], \"requestBody\": {}, \"responseBody\": {}, \"queryParams\": {}, \"validation\": [], \"errorResponses\": [] }\n ],\n \"graphqlOperations\": []\n}`;\n\nexport const PRO_DESIGN_API_PROMPT = `## Project: {projectName}\n## API Style: {apiStyle}\n## Data Model:\n{dataModel}\n## Requirements:\n{context}\n\nDesign 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.\n\nInclude 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.\n\nReturn ONLY valid JSON in the ApiDesign format.`;\n\nexport function buildDesignApiPrompt(requirement: string): string {\n return DESIGN_API_PROMPT.replace('{requirement}', requirement);\n}\n\nexport function buildProDesignApiPrompt(\n projectName: string,\n apiStyle: string,\n dataModel: string,\n context: string\n): string {\n return PRO_DESIGN_API_PROMPT.replace('{projectName}', projectName)\n .replace('{apiStyle}', apiStyle)\n .replace('{dataModel}', dataModel)\n .replace('{context}', context);\n}\n","/**\n * validate_api tool - validates JSON against apiDesignSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { apiDesignSchema } from '../schemas';\n\nexport const validateApiTool = createValidationTool(\n 'validate_api',\n apiDesignSchema,\n 'Validates an API design JSON string against the ApiDesign schema. Returns valid: true or valid: false with errors.',\n 'design'\n);\n","/**\n * design_api tool - generates API design from plain text requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { apiDesignSchema, type TApiDesign } from '../schemas';\nimport { buildDesignApiPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_api tool for plain text requirements.\n */\nexport function createDesignApiTool(model: Model) {\n return defineTool({\n name: 'design_api',\n description:\n 'Generate an API design (REST or GraphQL) from plain text requirements. Returns the full API design as JSON.',\n input: z.object({\n requirement: z.string().describe('Plain text description of the API requirements'),\n }),\n handler: async ({ requirement }): Promise<TApiDesign> => {\n const userPrompt = buildDesignApiPrompt(requirement);\n const messages = [\n { role: 'system' as const, content: 'You are an API architect. Return only valid JSON.' },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, apiDesignSchema);\n },\n });\n}\n","/**\n * design_api_pro tool - structured API design from data model + context (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { apiDesignSchema, type TApiDesign } from '../schemas';\nimport { buildProDesignApiPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_api_pro tool for structured API design.\n */\nexport function createDesignApiProTool(model: Model) {\n return defineTool({\n name: 'design_api_pro',\n description:\n 'Generate a comprehensive API design from a data model and project context. Produces detailed endpoints with validation, error responses, and auth annotations.',\n input: z.object({\n projectName: z.string().describe('Project name'),\n apiStyle: z.enum(['rest', 'graphql']).describe('Target API style'),\n dataModel: z.string().describe('Data model JSON or description'),\n context: z.string().describe('Project context: features, actors, stories'),\n }),\n handler: async ({ projectName, apiStyle, dataModel, context }): Promise<TApiDesign> => {\n const userPrompt = buildProDesignApiPrompt(projectName, apiStyle, dataModel, context);\n const messages = [\n { role: 'system' as const, content: 'You are an API architect. Return only valid JSON.' },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.2, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, apiDesignSchema);\n },\n });\n}\n","/**\n * api-designer tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateApiTool } from './validate-api';\nimport { createDesignApiTool } from './design-api';\nimport { createDesignApiProTool } from './design-api-pro';\n\nexport { validateApiTool } from './validate-api';\nexport { createDesignApiTool } from './design-api';\nexport { createDesignApiProTool } from './design-api-pro';\n\n/**\n * Create all api-designer tools. Pass the model for AI-backed tools.\n */\nexport function createApiDesignerTools(model: Model) {\n return createToolSet({\n validate_api: validateApiTool,\n design_api: createDesignApiTool(model),\n design_api_pro: createDesignApiProTool(model),\n });\n}\n","/**\n * runApiDesignerAgent - orchestrator for API design\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { API_DESIGNER_SYSTEM_PROMPT } from './prompts';\nimport { createApiDesignerTools } from './tools';\nimport { endpointAnalyzerSubagent, contractDesignerSubagent } from './subagents';\nimport type { ApiDesignerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${API_DESIGNER_SYSTEM_PROMPT}\n\nYou are the API design orchestrator. When the user asks for an API design:\n\n1. **Analyze endpoints**: Use subagent_endpoint-analyzer to derive endpoints from the data model and requirements.\n2. **Design contracts**: Use subagent_contract-designer to design request/response contracts, validation rules, and error responses.\n3. **Generate design**: Use design_api (plain text) or design_api_pro (when data model and structured context are available) to produce the API design.\n4. **Validate**: Use validate_api to check the final API design JSON before returning.\n\nRespond with the final API design as JSON.`;\n\n/**\n * Run the api-designer orchestrator agent with all tools and subagents.\n */\nexport async function runApiDesignerAgent(config: ApiDesignerAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createApiDesignerTools(model);\n const subagentTools = createSubagentToolSet(\n [endpointAnalyzerSubagent, contractDesignerSubagent],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for AuthDesign\n */\n\nimport { z } from 'zod';\n\nexport const authFlowStepSchema = z.object({\n order: z.number(),\n side: z.enum(['frontend', 'backend']),\n action: z.string(),\n details: z.string(),\n});\n\nexport const authFlowSchema = z.object({\n name: z.string(),\n description: z.string(),\n steps: z.array(authFlowStepSchema),\n});\n\nexport const authMiddlewareSchema = z.object({\n name: z.string(),\n purpose: z.string(),\n behavior: z.array(z.string()),\n});\n\nexport const roleDefinitionSchema = z.object({\n name: z.string(),\n description: z.string(),\n permissions: z.array(z.string()),\n});\n\nexport const securityPolicySchema = z.object({\n area: z.string(),\n rules: z.array(z.string()),\n});\n\nexport const authDesignSchema = z.object({\n strategy: z.enum(['jwt', 'session', 'oauth']),\n flows: z.array(authFlowSchema),\n middleware: z.array(authMiddlewareSchema),\n roles: z.array(roleDefinitionSchema),\n policies: z.array(securityPolicySchema),\n});\n\nexport type TAuthDesign = z.infer<typeof authDesignSchema>;\n","/**\n * System prompt for auth-designer orchestrator\n */\n\nexport const AUTH_DESIGNER_SYSTEM_PROMPT = `You are a senior security engineer specializing in authentication, authorization, and web security.\n\nYou design enterprise-quality auth systems with:\n- Step-by-step auth flows (signup, login, logout, password reset) with both frontend and backend steps\n- JWT or session strategy with proper cookie configuration (httpOnly, secure, sameSite, maxAge)\n- Role-based access control (RBAC) with permission matrices\n- Middleware chains for route protection and API authentication\n- Security policies: password hashing (bcrypt), rate limiting, CORS, input sanitization, brute force protection\n- OAuth integration patterns when needed\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for auth-designer\n */\n\nexport const DESIGN_AUTH_PROMPT = `## Requirements:\n{requirement}\n\nDesign the authentication and authorization system. Include:\n\n1. Strategy: jwt, session, or oauth (choose based on requirements).\n2. Flows: signup, login, logout, password reset (if applicable). Each flow with numbered steps, frontend/backend side, action, and details.\n3. Middleware: route protection middleware, API auth middleware. Each with name, purpose, and behavior list.\n4. Roles: role definitions with name, description, and permissions list.\n5. Policies: security policies grouped by area (passwords, tokens, CORS, rate limiting, etc.).\n\nReturn ONLY valid JSON:\n{\n \"strategy\": \"jwt\" | \"session\" | \"oauth\",\n \"flows\": [{ \"name\": \"signup\", \"description\": \"...\", \"steps\": [{ \"order\": 1, \"side\": \"frontend\", \"action\": \"...\", \"details\": \"...\" }] }],\n \"middleware\": [{ \"name\": \"authenticateRequest\", \"purpose\": \"...\", \"behavior\": [\"...\"] }],\n \"roles\": [{ \"name\": \"user\", \"description\": \"...\", \"permissions\": [\"...\"] }],\n \"policies\": [{ \"area\": \"passwords\", \"rules\": [\"...\"] }]\n}`;\n\nexport function buildDesignAuthPrompt(requirement: string): string {\n return DESIGN_AUTH_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_auth tool - validates JSON against authDesignSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { authDesignSchema } from '../schemas';\n\nexport const validateAuthTool = createValidationTool(\n 'validate_auth',\n authDesignSchema,\n 'Validates an auth design JSON string against the AuthDesign schema. Returns valid: true or valid: false with errors.',\n 'design'\n);\n","/**\n * design_auth tool - generates auth design from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { authDesignSchema, type TAuthDesign } from '../schemas';\nimport { buildDesignAuthPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_auth tool for auth flow generation.\n */\nexport function createDesignAuthTool(model: Model) {\n return defineTool({\n name: 'design_auth',\n description:\n 'Generate a complete authentication and authorization design from project requirements. Returns auth flows, middleware, roles, and security policies as JSON.',\n input: z.object({\n requirement: z.string().describe('Project context and auth requirements'),\n }),\n handler: async ({ requirement }): Promise<TAuthDesign> => {\n const userPrompt = buildDesignAuthPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a security engineer. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, authDesignSchema);\n },\n });\n}\n","/**\n * auth-designer tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateAuthTool } from './validate-auth';\nimport { createDesignAuthTool } from './design-auth';\n\nexport { validateAuthTool } from './validate-auth';\nexport { createDesignAuthTool } from './design-auth';\n\n/**\n * Create all auth-designer tools. Pass the model for AI-backed tools.\n */\nexport function createAuthDesignerTools(model: Model) {\n return createToolSet({\n validate_auth: validateAuthTool,\n design_auth: createDesignAuthTool(model),\n });\n}\n","/**\n * runAuthDesignerAgent - orchestrator for auth design\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { AUTH_DESIGNER_SYSTEM_PROMPT } from './prompts';\nimport { createAuthDesignerTools } from './tools';\nimport { securityAnalyzerSubagent, flowDesignerSubagent } from './subagents';\nimport type { AuthDesignerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${AUTH_DESIGNER_SYSTEM_PROMPT}\n\nYou are the auth design orchestrator. When the user asks for an auth design:\n\n1. **Analyze security**: Use subagent_security-analyzer to analyze security requirements, determine auth strategy, and identify threat vectors.\n2. **Design flows**: Use subagent_flow-designer to design step-by-step auth flows (signup, login, logout, password reset, middleware).\n3. **Generate design**: Use design_auth to produce the complete auth design with flows, middleware, roles, and security policies.\n4. **Validate**: Use validate_auth to check the final auth design JSON before returning.\n\nRespond with the final auth design as JSON.`;\n\n/**\n * Run the auth-designer orchestrator agent with all tools and subagents.\n */\nexport async function runAuthDesignerAgent(config: AuthDesignerAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createAuthDesignerTools(model);\n const subagentTools = createSubagentToolSet([securityAnalyzerSubagent, flowDesignerSubagent], {\n parentModel: model,\n });\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for BackendDesign\n */\n\nimport { z } from 'zod';\n\n/** Case-insensitive enum helper */\nconst ciEnum = <T extends string>(values: readonly [T, ...T[]]) =>\n z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(values));\n\nexport const middlewareSchema = z.object({\n name: z.string(),\n purpose: z.string(),\n appliesTo: z\n .string()\n .default('global')\n .transform(s => {\n const n = s.toLowerCase().trim();\n if (['global', 'all', 'app', 'application', 'every', 'server'].includes(n)) return 'global';\n if (\n [\n 'route',\n 'routes',\n 'specific',\n 'specific routes',\n 'endpoint',\n 'endpoints',\n 'path',\n ].includes(n)\n )\n return 'route';\n if (['resource', 'entity', 'module', 'controller', 'model'].includes(n)) return 'resource';\n return 'global';\n })\n .pipe(z.enum(['global', 'route', 'resource'])),\n config: z.record(z.string(), z.unknown()).default({}),\n});\n\nexport const serviceSchema = z.object({\n name: z.string(),\n entity: z.string(),\n operations: z.array(z.string()).default([]),\n dependencies: z.array(z.string()).default([]),\n});\n\nconst httpMethodSchema = z\n .string()\n .transform(s => s.toUpperCase().trim())\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nexport const routeGroupSchema = z.object({\n resource: z.string(),\n basePath: z.string(),\n endpoints: z\n .array(\n z.object({\n method: httpMethodSchema,\n path: z.string(),\n handler: z.string(),\n auth: z.coerce.boolean().default(true),\n roles: z.array(z.string()).default([]),\n })\n )\n .default([]),\n});\n\nexport const backendDesignSchema = z.object({\n framework: ciEnum(['express', 'apollo', 'both']),\n language: ciEnum(['typescript', 'javascript']).default('typescript'),\n database: z.string().default('mongodb'),\n services: z.array(serviceSchema).default([]),\n middleware: z.array(middlewareSchema).default([]),\n routes: z.array(routeGroupSchema).default([]),\n folderStructure: z.array(z.string()).default([]),\n envVars: z.array(z.string()).default([]),\n notes: z.string().default(''),\n});\n\nexport type TBackendDesign = z.infer<typeof backendDesignSchema>;\n","/**\n * System prompt for backend-architect orchestrator\n */\n\nexport const BACKEND_ARCHITECT_SYSTEM_PROMPT = `You are a senior backend architect specializing in Node.js server design.\n\nYou analyze data models, API designs, and auth requirements to produce enterprise-quality backend architectures with:\n- Framework selection (Express REST, Apollo GraphQL, or both)\n- Service layer design with clear operation contracts per entity\n- Middleware stack (auth, validation, error handling, CORS, rate limiting)\n- Route/resolver organization grouped by resource\n- Folder structure following domain-driven conventions\n- Environment variable inventory\n- Database connection and ORM/ODM strategy\n\nWhen \"both\" is selected (Express + Apollo), use the Apollo Gateway pattern:\n- Apollo Gateway as the single public entry point for GraphQL queries\n- Subgraphs as internal services composed via IntrospectAndCompose\n- RemoteGraphQLDataSource for header forwarding (auth tokens, service tokens)\n- Express for webhooks, file uploads, and health checks only\n- Gateway has no business logic, all logic lives in subgraphs\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompt for backend architecture generation\n */\n\nexport const DESIGN_BACKEND_PROMPT = `## Requirements:\n{requirement}\n\nDesign the backend architecture. Include:\n\n1. Framework: choose \"express\" (REST API), \"apollo\" (GraphQL subgraph), or \"both\" (Apollo subgraph + Express gateway).\n2. Services: one per entity with CRUD operations and dependencies.\n3. Middleware: auth (JWT/session), validation (Zod/Joi), error handling, CORS, rate limiting.\n4. Routes (if Express): RESTful routes grouped by resource with method, path, handler, auth, and roles.\n5. Folder structure: list of directories and key files.\n6. Env vars: list all required environment variables.\n\nReturn ONLY valid JSON:\n{\n \"framework\": \"express\" | \"apollo\" | \"both\",\n \"language\": \"typescript\",\n \"database\": \"mongodb\",\n \"services\": [{ \"name\": \"UserService\", \"entity\": \"User\", \"operations\": [\"create\", \"findById\", \"findAll\", \"update\", \"delete\"], \"dependencies\": [] }],\n \"middleware\": [{ \"name\": \"authMiddleware\", \"purpose\": \"JWT token verification\", \"appliesTo\": \"global\", \"config\": {} }],\n \"routes\": [{ \"resource\": \"users\", \"basePath\": \"/api/users\", \"endpoints\": [{ \"method\": \"GET\", \"path\": \"/\", \"handler\": \"getAll\", \"auth\": true, \"roles\": [\"admin\"] }] }],\n \"folderStructure\": [\"src/\", \"src/routes/\", \"src/services/\", \"src/middleware/\", \"src/models/\", \"src/config/\"],\n \"envVars\": [\"PORT\", \"DATABASE_URL\", \"JWT_SECRET\"],\n \"notes\": \"\"\n}`;\n\nexport function buildDesignBackendPrompt(requirement: string): string {\n return DESIGN_BACKEND_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_backend tool - validates JSON against backendDesignSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { backendDesignSchema } from '../schemas';\n\nexport const validateBackendTool = createValidationTool(\n 'validate_backend',\n backendDesignSchema,\n 'Validates a backend design JSON string against the BackendDesign schema. Returns valid: true or valid: false with errors.',\n 'design'\n);\n","/**\n * design_backend tool - generates backend architecture from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { backendDesignSchema, type TBackendDesign } from '../schemas';\nimport { buildDesignBackendPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_backend tool for backend architecture generation.\n */\nexport function createDesignBackendTool(model: Model) {\n return defineTool({\n name: 'design_backend',\n description:\n 'Generate a complete backend architecture design from requirements. Returns framework, services, middleware, routes, and folder structure as JSON.',\n input: z.object({\n requirement: z.string().describe('Data model, API design, and project requirements'),\n }),\n handler: async ({ requirement }): Promise<TBackendDesign> => {\n const userPrompt = buildDesignBackendPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a backend architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n return parseModelJsonResponse(response.text, backendDesignSchema);\n },\n });\n}\n","/**\n * backend-architect tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateBackendTool } from './validate-backend';\nimport { createDesignBackendTool } from './design-backend';\n\nexport { validateBackendTool } from './validate-backend';\nexport { createDesignBackendTool } from './design-backend';\n\n/**\n * Create all backend-architect tools. Pass the model for AI-backed tools.\n */\nexport function createBackendArchitectTools(model: Model) {\n return createToolSet({\n validate_backend: validateBackendTool,\n design_backend: createDesignBackendTool(model),\n });\n}\n","/**\n * service-planner subagent - plans service layer, middleware stack, folder structure\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst SERVICE_PLANNER_SYSTEM_PROMPT = `You are a backend service architect. Given a data model and API design, you plan the service layer.\n\n## Service Design\nFor each entity:\n- Service name (PascalCase + \"Service\")\n- CRUD operations: create, findById, findAll, update, delete\n- Custom operations from user flows (e.g. searchByName, bulkImport)\n- Dependencies on other services (e.g. OrderService depends on UserService)\n\n## Middleware Stack\n- Authentication middleware: JWT verification, session check\n- Authorization middleware: role-based access, resource ownership\n- Validation middleware: request body/params validation\n- Error handling: centralized error handler with typed errors\n- Logging: request/response logging\n- Rate limiting: per-IP or per-user limits\n- CORS: origin whitelist\n\n## Folder Structure\nRecommend a clean folder layout:\n- src/services/ (one file per service)\n- src/middleware/ (one file per middleware)\n- src/models/ (one file per entity)\n- src/routes/ or src/modules/ (grouped by resource)\n- src/config/ (env, database, auth config)\n- src/utils/ (shared helpers)\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const servicePlannerSubagent = defineSubagent({\n name: 'service-planner',\n description:\n 'Plans service layer, middleware stack, and folder structure for a backend project. Use before generating the backend design.',\n systemPrompt: SERVICE_PLANNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * framework-selector subagent - analyzes requirements and selects Express vs Apollo vs both\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst FRAMEWORK_SELECTOR_SYSTEM_PROMPT = `You are a backend technology advisor. Given project requirements, you recommend the best backend framework.\n\n## Decision Criteria\n\n### Choose \"express\" (REST API) when:\n- The API is primarily CRUD with RESTful resources\n- The frontend is a traditional SPA (React/Vue) consuming REST\n- Simple request/response patterns without complex data fetching\n- No need for real-time subscriptions\n- Team is more familiar with REST\n\n### Choose \"apollo\" (GraphQL subgraph) when:\n- The frontend needs flexible data fetching (avoid over/under-fetching)\n- Multiple frontends consume the same API (web, mobile, admin)\n- Complex nested data relationships\n- Need for real-time subscriptions\n- Part of a federated GraphQL architecture\n\n### Choose \"both\" when:\n- Apollo subgraph for main data API + Express for webhooks, file uploads, health checks\n- Need both REST endpoints (for external integrations) and GraphQL (for frontend)\n- When \"both\" is selected, an Apollo Gateway is used to compose subgraphs into a unified API:\n - Gateway is the only public entry point for GraphQL\n - Subgraphs are internal services, not exposed to clients directly\n - Gateway uses IntrospectAndCompose for schema discovery\n - RemoteGraphQLDataSource forwards auth headers to subgraphs\n - Express handles non-GraphQL concerns (webhooks, file uploads)\n\n## Output Format\nState your recommendation clearly:\n- Framework: express | apollo | both\n- Reasoning: 2-3 sentences explaining why\n- Trade-offs: what you'd lose with the alternative\n- If \"both\": describe which concerns go to Express vs Apollo Gateway vs subgraphs\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const frameworkSelectorSubagent = defineSubagent({\n name: 'framework-selector',\n description:\n 'Analyzes project requirements and recommends Express, Apollo, or both. Use to determine the backend framework before designing.',\n systemPrompt: FRAMEWORK_SELECTOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * runBackendArchitectAgent - routing orchestrator for backend design\n * Delegates to express-builder or apollo-builder based on framework selection.\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { BACKEND_ARCHITECT_SYSTEM_PROMPT } from './prompts';\nimport { createBackendArchitectTools } from './tools';\nimport { servicePlannerSubagent, frameworkSelectorSubagent } from './subagents';\nimport type { BackendArchitectAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${BACKEND_ARCHITECT_SYSTEM_PROMPT}\n\nYou are the backend architecture orchestrator. When the user provides requirements:\n\n1. **Select framework**: Use subagent_framework-selector to analyze requirements and recommend Express, Apollo, or both.\n2. **Plan services**: Use subagent_service-planner to design the service layer, middleware stack, and folder structure.\n3. **Generate design**: Use design_backend to produce the complete backend architecture as JSON.\n4. **Validate**: Use validate_backend to check the final design JSON before returning.\n\nAfter generating the design, note the \"framework\" field in the result:\n- If \"express\": the downstream express-builder should be used to scaffold the project.\n- If \"apollo\": the downstream apollo-builder should be used to scaffold the project.\n- If \"both\": both builders should be invoked sequentially.\n\nRespond with the final backend design as JSON.`;\n\n/**\n * Run the backend-architect orchestrator agent.\n */\nexport async function runBackendArchitectAgent(\n config: BackendArchitectAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createBackendArchitectTools(model);\n const subagentTools = createSubagentToolSet([servicePlannerSubagent, frameworkSelectorSubagent], {\n parentModel: model,\n });\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for FrontendDesign\n */\n\nimport { z } from 'zod';\n\nexport const formFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean(),\n validation: z.string(),\n});\n\nexport const pageDesignSchema = z.object({\n path: z.string(),\n name: z.string(),\n access: z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(['public', 'protected'])),\n purpose: z.string(),\n formFields: z.array(formFieldSchema).default([]),\n actions: z.array(z.string()).default([]),\n emptyState: z.string().default(''),\n errorState: z.string().default(''),\n redirectOnSuccess: z.string().default(''),\n keyUiElements: z.array(z.string()).default([]),\n});\n\nexport const componentDesignSchema = z.object({\n name: z.string(),\n type: z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(['layout', 'shared', 'form', 'display', 'navigation'])),\n purpose: z.string(),\n props: z.array(z.string()).default([]),\n usedIn: z.array(z.string()).default([]),\n});\n\nexport const frontendDesignSchema = z.object({\n pages: z.array(pageDesignSchema).default([]),\n components: z.array(componentDesignSchema).default([]),\n stateManagement: z.string().default(''),\n routingNotes: z.string().default(''),\n});\n\nexport type TFrontendDesign = z.infer<typeof frontendDesignSchema>;\n","/**\n * System prompt for frontend-architect orchestrator\n */\n\nexport const FRONTEND_ARCHITECT_SYSTEM_PROMPT = `You are a senior frontend architect specializing in page design, routing, and component architecture.\n\nYou design enterprise-quality frontend architectures targeting a Vite + React 19 + TypeScript stack with:\n- **UI Library**: ShadCN UI (Radix-based components in src/components/ui/)\n- **Styling**: Tailwind CSS v4 with OKLCH color space and dark mode support\n- **Routing**: React Router v7 with private route guards\n- **Forms**: React Hook Form + Zod validation\n- **GraphQL**: Apollo Client with CodeGen-typed hooks\n- **Path Aliases**: @/{appName}/* mapping to ./src/*\n\nArchitecture outputs:\n- Public and protected pages with detailed route definitions\n- Per-page specifications: purpose, form fields with validation, actions, empty/error states, redirects\n- Component taxonomy: layout (sidebar, navbar), shared (data tables, dialogs), form (inputs, selects), display (cards, badges), navigation (breadcrumbs, tabs)\n- State management strategy (per-page vs global, Apollo cache vs local state)\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for frontend-architect\n */\n\nexport const DESIGN_FRONTEND_PROMPT = `## Requirements:\n{requirement}\n\nDesign the frontend architecture. Include:\n\n1. 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.\n2. Components: reusable components. For each: name, type (layout/shared/form/display/navigation), purpose, props, and which pages use it.\n3. State management: describe the state strategy (e.g. React Server Components for data, client state for forms).\n4. Routing notes: any special routing behavior (redirects, guards, nested routes).\n\nReturn ONLY valid JSON:\n{\n \"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\"] }],\n \"components\": [{ \"name\": \"Navbar\", \"type\": \"navigation\", \"purpose\": \"...\", \"props\": [\"user\"], \"usedIn\": [\"/dashboard\", \"/profile\"] }],\n \"stateManagement\": \"...\",\n \"routingNotes\": \"...\"\n}`;\n\nexport function buildDesignFrontendPrompt(requirement: string): string {\n return DESIGN_FRONTEND_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_frontend tool - validates JSON against frontendDesignSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { frontendDesignSchema } from '../schemas';\n\nexport const validateFrontendTool = createValidationTool(\n 'validate_frontend',\n frontendDesignSchema,\n 'Validates a frontend design JSON string against the FrontendDesign schema. Returns valid: true or valid: false with errors.',\n 'design'\n);\n","/**\n * design_frontend tool - generates frontend architecture from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { frontendDesignSchema, type TFrontendDesign } from '../schemas';\nimport { buildDesignFrontendPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_frontend tool for frontend architecture generation.\n */\nexport function createDesignFrontendTool(model: Model) {\n return defineTool({\n name: 'design_frontend',\n description:\n 'Generate a complete frontend architecture design from project requirements. Returns pages, components, state management, and routing as JSON.',\n input: z.object({\n requirement: z.string().describe('Project context, API surface, and frontend requirements'),\n }),\n handler: async ({ requirement }): Promise<TFrontendDesign> => {\n const userPrompt = buildDesignFrontendPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a frontend architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, frontendDesignSchema);\n },\n });\n}\n","/**\n * frontend-architect tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateFrontendTool } from './validate-frontend';\nimport { createDesignFrontendTool } from './design-frontend';\n\nexport { validateFrontendTool } from './validate-frontend';\nexport { createDesignFrontendTool } from './design-frontend';\n\n/**\n * Create all frontend-architect tools. Pass the model for AI-backed tools.\n */\nexport function createFrontendArchitectTools(model: Model) {\n return createToolSet({\n validate_frontend: validateFrontendTool,\n design_frontend: createDesignFrontendTool(model),\n });\n}\n","/**\n * runFrontendArchitectAgent - routing orchestrator for frontend architecture design.\n * Delegates to react-builder or nextjs-builder based on framework selection.\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet, defineSubagent } from '../../lib/subagents';\nimport { FRONTEND_ARCHITECT_SYSTEM_PROMPT } from './prompts';\nimport { createFrontendArchitectTools } from './tools';\nimport {\n pagePlannerSubagent,\n componentAnalyzerSubagent,\n frameworkSelectorSubagent,\n} from './subagents';\nimport type { FrontendArchitectAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\n/** Subagent wrapper for react-builder orchestrator */\nconst reactBuilderSubagent = defineSubagent({\n name: 'react-builder',\n description:\n 'Generates a Vite + React SPA configuration from a frontend design and GraphQL schema. Use when the framework-selector recommends react-vite.',\n systemPrompt:\n 'You are a React/Vite frontend builder. Generate a complete frontend config JSON from the requirements.',\n tools: {},\n maxIterations: 5,\n});\n\n/** Subagent wrapper for nextjs-builder orchestrator */\nconst nextjsBuilderSubagent = defineSubagent({\n name: 'nextjs-builder',\n description:\n 'Generates a Next.js App Router configuration from a frontend design. Use when the framework-selector recommends nextjs.',\n systemPrompt:\n 'You are a Next.js App Router builder. Generate a complete Next.js config JSON from the requirements.',\n tools: {},\n maxIterations: 5,\n});\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${FRONTEND_ARCHITECT_SYSTEM_PROMPT}\n\nYou are the frontend architecture routing orchestrator. When the user asks for a frontend design:\n\n1. **Select framework**: Use subagent_framework-selector to analyze requirements (SPA vs SSR, SEO needs, API structure) and recommend React/Vite or Next.js.\n2. **Plan pages**: Use subagent_page-planner to design detailed page specifications with routes, forms, actions, and states.\n3. **Analyze components**: Use subagent_component-analyzer to identify reusable components, layouts, and state management patterns.\n4. **Generate design**: Use design_frontend to produce the complete frontend architecture as JSON.\n5. **Validate**: Use validate_frontend to check the final design JSON before returning.\n6. **Delegate to builder**: Based on the framework-selector recommendation:\n - If \"react-vite\": use subagent_react-builder with the design to generate a Vite + React SPA config.\n - If \"nextjs\": use subagent_nextjs-builder with the design to generate a Next.js App Router config.\n\nRespond with the final frontend design as JSON, including the builder output.`;\n\n/**\n * Run the frontend-architect routing orchestrator with all tools and subagents.\n */\nexport async function runFrontendArchitectAgent(\n config: FrontendArchitectAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createFrontendArchitectTools(model);\n const subagentTools = createSubagentToolSet(\n [\n pagePlannerSubagent,\n componentAnalyzerSubagent,\n frameworkSelectorSubagent,\n reactBuilderSubagent,\n nextjsBuilderSubagent,\n ],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for Express app configuration\n */\n\nimport { z } from 'zod';\n\nconst httpMethodSchema = z\n .string()\n .transform(s => s.toUpperCase().trim())\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nexport const routerMethodSchema = z.object({\n name: z.string(),\n httpMethod: httpMethodSchema,\n path: z.string(),\n auth: z.coerce.boolean().default(true),\n roles: z.array(z.string()).default([]),\n validation: z.string().default(''),\n description: z.string().default(''),\n});\n\nexport const routerSchema = z.object({\n name: z.string(),\n resource: z.string(),\n basePath: z.string(),\n methods: z.array(routerMethodSchema).default([]),\n});\n\nexport const modelFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean().default(false),\n unique: z.coerce.boolean().default(false),\n ref: z.string().optional(),\n default: z.string().optional(),\n});\n\nexport const modelSchema = z.object({\n name: z.string(),\n collection: z.string(),\n fields: z.array(modelFieldSchema).default([]),\n timestamps: z.coerce.boolean().default(true),\n indexes: z.array(z.string()).default([]),\n});\n\nexport const middlewareConfigSchema = z.object({\n name: z.string(),\n type: z\n .string()\n .transform(s => {\n const n = s.toLowerCase().replace(/[\\s_-]+/g, '');\n if (['auth', 'authentication', 'jwt', 'token'].includes(n)) return 'auth' as const;\n if (['validation', 'validate', 'validator', 'input'].includes(n))\n return 'validation' as const;\n if (['errorhandler', 'error', 'errorhandling', 'errors'].includes(n))\n return 'errorHandler' as const;\n if (['cors', 'crossorigin'].includes(n)) return 'cors' as const;\n if (['ratelimit', 'ratelimiter', 'ratelimiting', 'throttle'].includes(n))\n return 'rateLimit' as const;\n if (['logging', 'logger', 'log', 'morgan'].includes(n)) return 'logging' as const;\n return 'custom' as const;\n })\n .pipe(z.enum(['auth', 'validation', 'errorHandler', 'cors', 'rateLimit', 'logging', 'custom'])),\n config: z.record(z.string(), z.unknown()).default({}),\n});\n\nexport const expressConfigSchema = z.object({\n appName: z.string().default('app'),\n port: z.number().default(3000),\n database: z.string().default('mongodb'),\n routers: z.array(routerSchema).default([]),\n models: z.array(modelSchema).default([]),\n middleware: z.array(middlewareConfigSchema).default([]),\n envVars: z.array(z.string()).default([]),\n});\n\nexport type TExpressConfig = z.infer<typeof expressConfigSchema>;\n","/**\n * System prompt for express-builder orchestrator\n */\n\nexport const EXPRESS_BUILDER_SYSTEM_PROMPT = `You are an expert Express.js backend architect.\n\nYou generate production-ready Express application configurations from data models and API designs:\n- Co-located router pattern: each feature lives in src/routers/{name}/ with {name}.controller.ts, {name}.router.ts, and {name}.spec.ts\n- Mongoose/Prisma models with field types, validation, and relationships\n- Middleware stack (auth JWT, validation Zod, error handler, CORS, rate limiting)\n- Route organization with proper HTTP methods and paths\n- Health check endpoint at /health (included by default)\n- Jest tests per router using supertest\n- Environment variable inventory\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompt for Express config generation\n */\n\nexport const DESIGN_EXPRESS_PROMPT = `## Requirements:\n{requirement}\n\nGenerate an Express.js application configuration. Include:\n\n1. Routers: one per resource, co-located with controller and test spec. Each router has RESTful methods (GET, POST, PUT, DELETE).\n2. Health check: a default /health router is always included.\n3. Models: Mongoose models with fields, types, required, unique, refs, defaults, indexes.\n4. Middleware: auth (JWT), validation (Zod), error handler, CORS, rate limiting, logging.\n5. Env vars: PORT, DATABASE_URL, JWT_SECRET, NODE_ENV, etc.\n6. Folder structure: src/routers/{name}/ with {name}.controller.ts, {name}.router.ts, {name}.spec.ts per feature.\n\nReturn ONLY valid JSON:\n{\n \"appName\": \"my-api\",\n \"port\": 3000,\n \"database\": \"mongodb\",\n \"routers\": [{\n \"name\": \"users\",\n \"resource\": \"users\",\n \"basePath\": \"/api/users\",\n \"methods\": [{\n \"name\": \"getAll\",\n \"httpMethod\": \"GET\",\n \"path\": \"/\",\n \"auth\": true,\n \"roles\": [\"admin\"],\n \"validation\": \"\",\n \"description\": \"Get all users with pagination\"\n }]\n }],\n \"models\": [{\n \"name\": \"User\",\n \"collection\": \"users\",\n \"fields\": [{ \"name\": \"email\", \"type\": \"String\", \"required\": true, \"unique\": true }],\n \"timestamps\": true,\n \"indexes\": [\"email\"]\n }],\n \"middleware\": [{ \"name\": \"authMiddleware\", \"type\": \"auth\", \"config\": {} }],\n \"envVars\": [\"PORT\", \"DATABASE_URL\", \"JWT_SECRET\", \"NODE_ENV\"]\n}`;\n\nexport function buildDesignExpressPrompt(requirement: string): string {\n return DESIGN_EXPRESS_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_express tool - validates JSON against expressConfigSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { expressConfigSchema } from '../schemas';\n\nexport const validateExpressTool = createValidationTool(\n 'validate_express',\n expressConfigSchema,\n 'Validates an Express config JSON string against the ExpressConfig schema. Returns valid: true or valid: false with errors.',\n 'config'\n);\n","/**\n * generate_express tool - generates Express config from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { expressConfigSchema, type TExpressConfig } from '../schemas';\nimport { buildDesignExpressPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the generate_express tool for Express config generation.\n */\nexport function createGenerateExpressTool(model: Model) {\n return defineTool({\n name: 'generate_express',\n description:\n 'Generate a complete Express.js application configuration from data model and API design. Returns routers, models, middleware, and env vars as JSON.',\n input: z.object({\n requirement: z.string().describe('Data model, API design, and project requirements'),\n }),\n handler: async ({ requirement }): Promise<TExpressConfig> => {\n const userPrompt = buildDesignExpressPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are an Express.js architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n return parseModelJsonResponse(response.text, expressConfigSchema);\n },\n });\n}\n","/**\n * scaffold_express tool - compiles .ref/templates/express/ with config\n */\n\nimport * as path from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { scaffoldProject } from '../../../lib/template-engine';\nimport type { ScaffoldResult } from '../../../lib/template-engine';\nimport type { TemplateContext } from '../../../lib/template-engine';\nimport type { TExpressConfig } from '../schemas';\nimport { safeJsonParse } from '../../../lib/utils';\n\n/** Convert express config to template context */\nfunction toTemplateContext(config: TExpressConfig): TemplateContext {\n return {\n appName: config.appName,\n port: config.port,\n database: config.database,\n routers: config.routers,\n models: config.models,\n middleware: config.middleware,\n envVars: config.envVars,\n modules: config.routers.map(r => ({\n name: r.resource,\n pascalName: r.name.charAt(0).toUpperCase() + r.name.slice(1),\n camelName: r.resource,\n methods: r.methods,\n })),\n };\n}\n\nexport const scaffoldExpressTool = defineTool({\n name: 'scaffold_express',\n description:\n 'Scaffold an Express.js project from a validated config. Compiles Handlebars templates and writes the project to the output directory.',\n input: z.object({\n config: z.string().describe('JSON string of the validated Express config'),\n outputDir: z.string().describe('Absolute path to the output directory'),\n }),\n handler: async ({ config, outputDir }): Promise<ScaffoldResult> => {\n const parsed = safeJsonParse(config, 'express config') as TExpressConfig;\n const templateDir = path.resolve(process.cwd(), '.ref/templates/express');\n const context = toTemplateContext(parsed);\n\n return scaffoldProject({\n templateDir,\n outputDir,\n context,\n });\n },\n});\n","/**\n * express-builder tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateExpressTool } from './validate-express';\nimport { createGenerateExpressTool } from './generate-express';\nimport { scaffoldExpressTool } from './scaffold-express';\n\nexport { validateExpressTool } from './validate-express';\nexport { createGenerateExpressTool } from './generate-express';\nexport { scaffoldExpressTool } from './scaffold-express';\n\n/**\n * Create all express-builder tools. Pass the model for AI-backed tools.\n */\nexport function createExpressBuilderTools(model: Model) {\n return createToolSet({\n validate_express: validateExpressTool,\n generate_express: createGenerateExpressTool(model),\n scaffold_express: scaffoldExpressTool,\n });\n}\n","/**\n * route-generator subagent - generates route files from API design\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ROUTE_GENERATOR_SYSTEM_PROMPT = `You are an Express.js route specialist. Given an API design, you generate route definitions using a co-located router pattern.\n\n## Co-located Router Pattern\nEach feature lives in src/routers/{name}/ with three files:\n- {name}.router.ts -- Express Router with route definitions\n- {name}.controller.ts -- Request handler logic\n- {name}.spec.ts -- Jest tests using supertest\n\n## Route Design\nFor each resource:\n- Base path: /api/{resource} (pluralized, lowercase)\n- GET / -> list all (with pagination: page, limit, sort query params)\n- GET /:id -> get by ID\n- POST / -> create new\n- PUT /:id -> update by ID\n- DELETE /:id -> delete by ID\n- Custom routes for non-CRUD operations\n\n## Health Check\nEvery app includes a /health router in src/routers/health/:\n- health.router.ts -- GET /health returning server status\n- health.controller.ts -- Health check handler\n- health.spec.ts -- Health check tests\n\n## Route Organization\n- One router directory per resource with co-located controller and spec\n- Central src/routers/index.ts mounts all routers\n- Middleware applied per-route or per-router\n\n## Controller Mapping\n- Each route maps to a controller method in the co-located controller file\n- Controller method name follows convention: getAll, getById, create, update, delete\n\n## Validation\n- Request body validation using Zod schemas\n- Param validation (e.g. valid ObjectId)\n- Query param parsing and defaults\n\nRespond with structured route definitions. Do NOT return JSON.`;\n\nexport const routeGeneratorSubagent = defineSubagent({\n name: 'route-generator',\n description:\n '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.',\n systemPrompt: ROUTE_GENERATOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * middleware-configurator subagent - designs middleware stack\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst MIDDLEWARE_CONFIGURATOR_SYSTEM_PROMPT = `You are an Express.js middleware specialist. You design the complete middleware stack.\n\n## Core Middleware\n1. **CORS**: Configure allowed origins, methods, headers, credentials\n2. **Body parser**: JSON and URL-encoded body parsing with size limits\n3. **Helmet**: Security headers (CSP, HSTS, X-Frame-Options)\n4. **Morgan/Logger**: Request logging with format and stream\n\n## Auth Middleware\n1. **JWT verification**: Extract token from Authorization header or cookie\n2. **Role check**: Verify user role against required roles\n3. **Resource ownership**: Check if user owns the resource they're accessing\n\n## Validation Middleware\n1. **Request validation**: Validate body, params, query using Zod schemas\n2. **Sanitization**: Strip HTML, trim whitespace\n\n## Error Handling\n1. **Not found handler**: 404 for unmatched routes\n2. **Error handler**: Centralized error response with status codes\n3. **Async wrapper**: Catch async errors without try-catch\n\n## Rate Limiting\n1. **Global**: Limit requests per IP per time window\n2. **Auth routes**: Stricter limits on login/signup\n\nRespond with structured middleware analysis. Do NOT return JSON.`;\n\nexport const middlewareConfiguratorSubagent = defineSubagent({\n name: 'middleware-configurator',\n description:\n 'Designs the Express middleware stack including auth, validation, error handling, CORS, and rate limiting. Use before generating the Express config.',\n systemPrompt: MIDDLEWARE_CONFIGURATOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * runExpressBuilderAgent - orchestrator for Express.js project generation\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { EXPRESS_BUILDER_SYSTEM_PROMPT } from './prompts';\nimport { createExpressBuilderTools } from './tools';\nimport { routeGeneratorSubagent, middlewareConfiguratorSubagent } from './subagents';\nimport type { ExpressBuilderAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${EXPRESS_BUILDER_SYSTEM_PROMPT}\n\nYou are the Express builder orchestrator. When the user provides requirements:\n\n1. **Generate routes**: Use subagent_route-generator to design route definitions from the API design.\n2. **Configure middleware**: Use subagent_middleware-configurator to design the middleware stack.\n3. **Generate config**: Use generate_express to produce the complete Express configuration as JSON.\n4. **Validate**: Use validate_express to check the config JSON before returning.\n5. **Scaffold (optional)**: If an output directory is provided, use scaffold_express to compile templates.\n\nRespond with the final Express config as JSON.`;\n\n/**\n * Run the express-builder orchestrator agent.\n */\nexport async function runExpressBuilderAgent(\n config: ExpressBuilderAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createExpressBuilderTools(model);\n const subagentTools = createSubagentToolSet(\n [routeGeneratorSubagent, middlewareConfiguratorSubagent],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for Apollo subgraph configuration\n */\n\nimport { z } from 'zod';\n\n/** Case-insensitive enum */\nconst ciEnum = <T extends string>(values: readonly [T, ...T[]]) =>\n z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(values));\n\nexport const graphqlFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n nullable: z.coerce.boolean().default(false),\n isList: z.coerce.boolean().default(false),\n description: z.string().default(''),\n});\n\nexport const graphqlTypeSchema = z.object({\n name: z.string(),\n kind: ciEnum(['type', 'input', 'enum', 'interface', 'union']),\n fields: z.array(graphqlFieldSchema).default([]),\n values: z.array(z.string()).default([]),\n description: z.string().default(''),\n isEntity: z.coerce.boolean().default(false),\n keyFields: z.array(z.string()).default([]),\n});\n\nexport const resolverOperationSchema = z.object({\n name: z.string(),\n type: ciEnum(['query', 'mutation', 'subscription']),\n args: z.array(graphqlFieldSchema).default([]),\n returnType: z.string(),\n auth: z.coerce.boolean().default(true),\n roles: z.array(z.string()).default([]),\n description: z.string().default(''),\n});\n\nexport const subgraphModuleSchema = z.object({\n name: z.string(),\n entity: z.string(),\n types: z.array(graphqlTypeSchema).default([]),\n operations: z.array(resolverOperationSchema).default([]),\n datasource: z.string().default(''),\n loader: z.string().default(''),\n});\n\nexport const subgraphConfigSchema = z.object({\n appName: z.string().default('app'),\n port: z.number().default(4000),\n database: z.string().default('mongodb'),\n modules: z.array(subgraphModuleSchema).default([]),\n sharedTypes: z.array(graphqlTypeSchema).default([]),\n authDirective: z.coerce.boolean().default(true),\n cacheDirective: z.coerce.boolean().default(false),\n envVars: z.array(z.string()).default([]),\n});\n\nexport type TSubgraphConfig = z.infer<typeof subgraphConfigSchema>;\n","/**\n * System prompt for apollo-builder orchestrator\n */\n\nexport const APOLLO_BUILDER_SYSTEM_PROMPT = `You are an expert Apollo GraphQL subgraph architect using Apollo Federation v2.\n\nYou generate production-ready Apollo subgraph configurations from data models and API designs:\n- 4-file module pattern per entity: {module}.graphql, {module}.resolver.ts, {module}.datasource.ts, {module}.loader.ts\n- GraphQL type definitions with proper nullability, lists, and descriptions\n- Input types for mutations with validation annotations\n- Enum types from domain values\n- Federation directives: @key for entity references, @external for fields owned by other subgraphs, @requires for field dependencies, @provides for fields resolvable by this subgraph\n- __resolveReference for cross-subgraph entity resolution via buildSubgraphSchema\n- DataLoader per module for batching and caching database lookups (solves N+1)\n- Query and mutation resolvers with auth/role requirements\n- Datasource classes per entity (MongoDB datasource pattern)\n- Auth directive (@auth) configuration\n- Redis cache directives: @cacheSet on queries, @cachePurge on mutations\n- GraphQL CodeGen for TypeScript types (generates base-types.ts)\n- Module-based organization (one module per entity/domain)\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompt for subgraph config generation\n */\n\nexport const DESIGN_SUBGRAPH_PROMPT = `## Requirements:\n{requirement}\n\nGenerate an Apollo GraphQL subgraph configuration (Federation v2). Include:\n\n1. Modules: one per entity with 4 files each ({module}.graphql, {module}.resolver.ts, {module}.datasource.ts, {module}.loader.ts).\n2. Types: GraphQL object types with isEntity/keyFields for federation, input types, enums with fields/values.\n3. Operations: queries (getById, getAll, search) and mutations (create, update, delete) per module.\n4. Auth: mark which operations require authentication and which roles.\n5. DataLoader: one loader per module for batching lookups (loader name).\n6. Shared types: types used across modules (e.g. Pagination, SortOrder).\n7. Cache: set cacheDirective to true if Redis caching (@cacheSet/@cachePurge) is needed.\n8. Env vars: PORT, DATABASE_URL, JWT_SECRET, REDIS_URL, etc.\n\nReturn ONLY valid JSON:\n{\n \"appName\": \"my-subgraph\",\n \"port\": 4000,\n \"database\": \"mongodb\",\n \"modules\": [{\n \"name\": \"user\",\n \"entity\": \"User\",\n \"types\": [{ \"name\": \"User\", \"kind\": \"type\", \"fields\": [{ \"name\": \"id\", \"type\": \"ID\", \"nullable\": false }], \"isEntity\": true, \"keyFields\": [\"id\"] }],\n \"operations\": [{ \"name\": \"getUser\", \"type\": \"query\", \"args\": [{ \"name\": \"id\", \"type\": \"ID\", \"nullable\": false }], \"returnType\": \"User\", \"auth\": true, \"roles\": [] }],\n \"datasource\": \"UserDataSource\",\n \"loader\": \"UserLoader\"\n }],\n \"sharedTypes\": [],\n \"authDirective\": true,\n \"cacheDirective\": false,\n \"envVars\": [\"PORT\", \"DATABASE_URL\", \"JWT_SECRET\", \"REDIS_URL\"]\n}`;\n\nexport function buildDesignSubgraphPrompt(requirement: string): string {\n return DESIGN_SUBGRAPH_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_subgraph tool - validates JSON against subgraphConfigSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { subgraphConfigSchema } from '../schemas';\n\nexport const validateSubgraphTool = createValidationTool(\n 'validate_subgraph',\n subgraphConfigSchema,\n 'Validates a subgraph config JSON string against the SubgraphConfig schema. Returns valid: true or valid: false with errors.',\n 'config'\n);\n","/**\n * generate_subgraph tool - generates subgraph config from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { subgraphConfigSchema, type TSubgraphConfig } from '../schemas';\nimport { buildDesignSubgraphPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the generate_subgraph tool for Apollo subgraph config generation.\n */\nexport function createGenerateSubgraphTool(model: Model) {\n return defineTool({\n name: 'generate_subgraph',\n description:\n 'Generate a complete Apollo GraphQL subgraph configuration from data model and API design. Returns modules, types, operations, and datasources as JSON.',\n input: z.object({\n requirement: z.string().describe('Data model, API design, and project requirements'),\n }),\n handler: async ({ requirement }): Promise<TSubgraphConfig> => {\n const userPrompt = buildDesignSubgraphPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are an Apollo GraphQL architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n return parseModelJsonResponse(response.text, subgraphConfigSchema);\n },\n });\n}\n","/**\n * scaffold_subgraph tool - compiles .ref/templates/subgraph/ with config\n */\n\nimport * as path from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { scaffoldProject } from '../../../lib/template-engine';\nimport type { ScaffoldResult } from '../../../lib/template-engine';\nimport type { TemplateContext } from '../../../lib/template-engine';\nimport type { TSubgraphConfig } from '../schemas';\nimport { safeJsonParse } from '../../../lib/utils';\n\n/** Convert subgraph config to template context */\nfunction toTemplateContext(config: TSubgraphConfig): TemplateContext {\n return {\n appName: config.appName,\n port: config.port,\n database: config.database,\n modules: config.modules.map(m => ({\n name: m.name,\n pascalName: m.name.charAt(0).toUpperCase() + m.name.slice(1),\n camelName: m.name.charAt(0).toLowerCase() + m.name.slice(1),\n entity: m.entity,\n datasource: m.datasource,\n types: m.types,\n operations: m.operations,\n })),\n authDirective: config.authDirective,\n envVars: config.envVars,\n sharedTypes: config.sharedTypes,\n };\n}\n\nexport const scaffoldSubgraphTool = defineTool({\n name: 'scaffold_subgraph',\n description:\n 'Scaffold an Apollo GraphQL subgraph project from a validated config. Compiles Handlebars templates and writes the project to the output directory.',\n input: z.object({\n config: z.string().describe('JSON string of the validated subgraph config'),\n outputDir: z.string().describe('Absolute path to the output directory'),\n }),\n handler: async ({ config, outputDir }): Promise<ScaffoldResult> => {\n const parsed = safeJsonParse(config, 'subgraph config') as TSubgraphConfig;\n const templateDir = path.resolve(process.cwd(), '.ref/templates/subgraph');\n const context = toTemplateContext(parsed);\n\n return scaffoldProject({\n templateDir,\n outputDir,\n context,\n });\n },\n});\n","/**\n * apollo-builder tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateSubgraphTool } from './validate-subgraph';\nimport { createGenerateSubgraphTool } from './generate-subgraph';\nimport { scaffoldSubgraphTool } from './scaffold-subgraph';\n\nexport { validateSubgraphTool } from './validate-subgraph';\nexport { createGenerateSubgraphTool } from './generate-subgraph';\nexport { scaffoldSubgraphTool } from './scaffold-subgraph';\n\n/**\n * Create all apollo-builder tools. Pass the model for AI-backed tools.\n */\nexport function createApolloBuilderTools(model: Model) {\n return createToolSet({\n validate_subgraph: validateSubgraphTool,\n generate_subgraph: createGenerateSubgraphTool(model),\n scaffold_subgraph: scaffoldSubgraphTool,\n });\n}\n","/**\n * schema-generator subagent - generates GraphQL type definitions from data model\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst SCHEMA_GENERATOR_SYSTEM_PROMPT = `You are a GraphQL schema specialist for Apollo Federation v2 subgraphs. Given a data model, you generate GraphQL type definitions using buildSubgraphSchema.\n\n## Type Generation\nFor each entity in the data model:\n- Create the main object type with all fields mapped to GraphQL scalars (String, Int, Float, Boolean, ID)\n- Create input types for create and update mutations (omit auto-generated fields like id, createdAt)\n- Create enum types for status fields and role fields\n- Add proper nullability (! for required fields)\n- Add [Type] for array/list fields\n\n## Federation Directives\n- @key(fields: \"id\") on entity types that can be referenced across subgraphs\n- @external marks a field as owned by another subgraph\n- @requires(fields: \"weight\") declares fields needed from the entity to resolve a field\n- @provides(fields: \"name\") declares fields on a return type that this subgraph can resolve\n- @auth directive on types/fields that require authentication\n\n## Cache Directives (Redis)\n- @cacheSet(type: \"Entity\", identifier: \"_id\") on query resolvers\n- @cachePurge(type: \"Entity\", identifier: \"_id\") on mutation resolvers\n\n## Relationships\n- Reference types for foreign keys (e.g. author: User instead of authorId: ID)\n- Use [Type] for one-to-many relationships\n\n## Naming Conventions\n- Types: PascalCase (User, BlogPost)\n- Fields: camelCase (firstName, createdAt)\n- Inputs: PascalCase + Input suffix (CreateUserInput, UpdateUserInput)\n- Enums: SCREAMING_SNAKE_CASE values (ADMIN, ACTIVE)\n\nRespond with the full GraphQL SDL. Do NOT return JSON.`;\n\nexport const schemaGeneratorSubagent = defineSubagent({\n name: 'schema-generator',\n description:\n 'Generates GraphQL type definitions, input types, and enums from a data model. Use before generating the subgraph config.',\n systemPrompt: SCHEMA_GENERATOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * resolver-planner subagent - plans resolver implementations per module\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst RESOLVER_PLANNER_SYSTEM_PROMPT = `You are a GraphQL resolver architect for Apollo Federation v2 subgraphs. Given types and operations, you plan resolver implementations.\n\n## 4-File Module Pattern\nEach module has four files:\n- {module}.graphql -- Type definitions with federation directives\n- {module}.resolver.ts -- Query/Mutation/Field resolvers including __resolveReference\n- {module}.datasource.ts -- Business logic and database access\n- {module}.loader.ts -- DataLoader for batching and caching lookups\n\n## Resolver Planning\nFor each module/entity:\n\n### __resolveReference (Federation)\n- Every entity type with @key must implement __resolveReference\n- Called by the gateway when another subgraph references this entity\n- Receives { __typename, id } and returns the full entity from datasource\n\n### Query Resolvers\n- getById: fetch single record by ID from datasource\n- getAll: fetch paginated list with filters and sorting\n- search: text search across relevant fields\n\n### Mutation Resolvers\n- create: validate input, create record, return created entity\n- update: validate input, find existing, merge changes, return updated entity\n- delete: find existing, remove, return success status\n\n### Field Resolvers\n- For relationship fields: resolve references via DataLoader (NOT direct DB calls)\n- For computed fields: calculate from existing data\n\n## DataLoader Pattern\nEach module has a loader file that creates DataLoader instances:\n- Batches multiple lookups into a single database query\n- Caches results within a single request to solve the N+1 problem\n- Created per-request in the context, not shared across requests\n\n## Datasource Pattern\n- Each module has a datasource class extending MongoDataSource or similar\n- Datasource handles all database operations\n- Resolvers call datasource methods, never touch the DB directly\n\n## Auth Integration\n- Check auth context in resolver before executing\n- Verify role permissions per operation\n- Resource ownership checks for user-specific data\n\nRespond with structured analysis per module. Do NOT return JSON.`;\n\nexport const resolverPlannerSubagent = defineSubagent({\n name: 'resolver-planner',\n description:\n 'Plans resolver implementations, datasource methods, and auth integration per GraphQL module. Use after schema generation.',\n systemPrompt: RESOLVER_PLANNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * runApolloBuilderAgent - orchestrator for Apollo GraphQL subgraph generation\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { APOLLO_BUILDER_SYSTEM_PROMPT } from './prompts';\nimport { createApolloBuilderTools } from './tools';\nimport { schemaGeneratorSubagent, resolverPlannerSubagent } from './subagents';\nimport type { ApolloBuilderAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${APOLLO_BUILDER_SYSTEM_PROMPT}\n\nYou are the Apollo subgraph builder orchestrator. When the user provides requirements:\n\n1. **Generate schema**: Use subagent_schema-generator to create GraphQL type definitions from the data model.\n2. **Plan resolvers**: Use subagent_resolver-planner to design resolver implementations per module.\n3. **Generate config**: Use generate_subgraph to produce the complete subgraph configuration as JSON.\n4. **Validate**: Use validate_subgraph to check the config JSON before returning.\n5. **Scaffold (optional)**: If an output directory is provided, use scaffold_subgraph to compile templates.\n\nRespond with the final subgraph config as JSON.`;\n\n/**\n * Run the apollo-builder orchestrator agent.\n */\nexport async function runApolloBuilderAgent(\n config: ApolloBuilderAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createApolloBuilderTools(model);\n const subagentTools = createSubagentToolSet([schemaGeneratorSubagent, resolverPlannerSubagent], {\n parentModel: model,\n });\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Branding schema for frontend app config\n */\n\nimport { z } from 'zod';\n\nexport const BrandingSchema = z.object({\n brandName: z.string().describe(\"The brand's display name\"),\n primaryColor: z.string().describe(\"The brand's primary color code (e.g., #FFFFFF)\"),\n secondaryColor: z.string().describe(\"The brand's secondary color code (e.g., #000000)\"),\n logo: z.url().describe(\"URL pointing to the brand's logo\"),\n});\n\nexport type TBrandingSchema = z.infer<typeof BrandingSchema>;\n","/**\n * App configuration schema\n */\n\nimport { z } from 'zod';\nimport { BrandingSchema } from './branding.schema';\n\nexport const AppConfigSchema = z.object({\n name: z.string().describe('Application name'),\n description: z.string().describe('Brief description of the application'),\n author: z\n .string()\n .describe('Author or owner of the application')\n .default('sijeeshmiziha (HubSpire)'),\n branding: BrandingSchema.describe('Branding information for the application'),\n apiEndpoint: z.url().describe(\"URL endpoint for the app's API calls\"),\n});\n\nexport type TAppConfigSchema = z.infer<typeof AppConfigSchema>;\n","/**\n * Form field, validation, options, and column schemas\n */\n\nimport { z } from 'zod';\n\nexport const ValidationSchema = z.object({\n minLength: z.number().optional().describe('Minimum length requirement'),\n zodString: z.string().describe('Raw Zod string validation (e.g. regex)'),\n});\n\nexport const FieldOptionsSchema = z.object({\n hookName: z.string().optional().describe('Name of the hook for dynamic field options'),\n queryString: z.string().optional().describe('Optional query string for fetching field options'),\n labelKey: z.string().optional().describe('Key used as label when displaying options'),\n valueKey: z.string().optional().describe('Key used as value for a field when selecting options'),\n values: z.array(z.string()).optional().describe('Static list of possible field values'),\n});\n\nexport const FormFieldSchema = z.object({\n name: z.string().describe(\"The field's key or identifier\"),\n type: z\n .enum([\n 'text',\n 'email',\n 'password',\n 'number',\n 'multiSelect',\n 'textarea',\n 'hidden',\n 'select',\n 'date',\n 'image',\n ])\n .describe(\n '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.'\n ),\n required: z.boolean().optional().describe('Whether this field must be filled'),\n validation: ValidationSchema.optional().describe('Optional field validation requirements'),\n defaultValue: z\n .union([z.string(), z.number(), z.boolean()])\n .optional()\n .describe('Default value can be string, number, or boolean'),\n options: FieldOptionsSchema.optional().describe(\n 'Additional dynamic or static options for this field'\n ),\n});\n\nexport const ColumnSchema = z.object({\n field: z.string().describe('Key or name of the data field in the table'),\n label: z.string().describe('User-friendly label to show on the table header'),\n});\n\nexport type TFormFieldSchema = z.infer<typeof FormFieldSchema>;\nexport type TColumnSchema = z.infer<typeof ColumnSchema>;\n","/**\n * API, drawer, auth page, listing page, and page union schemas\n */\n\nimport { z } from 'zod';\nimport { FormFieldSchema, ColumnSchema } from './field.schema';\n\nexport const ApiResponseTypeSchema = z\n .object({\n type: z.string().describe(\"Indicates the response type (e.g., 'object')\"),\n properties: z\n .record(\n z.string(),\n z.object({\n type: z.string().describe('Property type as returned by the API'),\n })\n )\n .describe('Key-value record describing each field in the response'),\n })\n .optional()\n .describe('Describes the expected structure of an API response');\n\nexport type TApiResponseTypeSchema = z.infer<typeof ApiResponseTypeSchema>;\n\nexport const ListingPageApiSchema = z.object({\n type: z\n .enum(['list', 'create', 'update', 'delete', 'getById'])\n .describe('Type of API call for CRUD operations'),\n graphqlHook: z\n .string()\n .describe('Name of the GraphQL hook (e.g. useGetAllUserQuery, useCreateUserMutation)'),\n queryString: z.string().describe('Actual GraphQL query string'),\n responseType: ApiResponseTypeSchema.describe(\n 'Optional schema describing shape of the API response'\n ),\n});\n\nexport const AuthPageApiSchema = z.object({\n type: z\n .enum(['login', 'currentUser', 'forgotPassword', 'resetPassword'])\n .describe('Type of API call'),\n graphqlHook: z.string().describe('Name of the GraphQL hook (e.g. useLoginMutation)'),\n queryString: z.string().describe('Actual GraphQL query string'),\n responseType: ApiResponseTypeSchema.describe(\n 'Optional schema describing shape of the API response'\n ),\n});\n\nexport const DrawerSchema = z.object({\n title: z.string().describe('Title displayed on the drawer'),\n graphqlHook: z\n .string()\n .describe('Name of the GraphQL hook (e.g. useCreateUserMutation, useDeleteOneUserMutation)'),\n fields: z.array(FormFieldSchema).describe('List of fields displayed within the drawer'),\n});\n\nexport const AuthPageSchema = z.object({\n name: z\n .enum(['LoginPage', 'ForgotPasswordPage', 'ResetPasswordPage'])\n .describe('Internal name of the auth page'),\n type: z\n .enum(['EmailPassword', 'ForgotPassword', 'ResetPassword'])\n .describe('Type of authentication page'),\n route: z.string().describe(\"URL route for this page (e.g., '/login')\"),\n isPrivate: z.boolean().describe('Whether this page requires an authenticated session'),\n api: z.array(AuthPageApiSchema).describe('List of API calls involved in this page'),\n fields: z\n .array(FormFieldSchema)\n .optional()\n .describe('Optional form fields needed on this auth page'),\n});\n\nexport const ListingPageSchema = z.object({\n type: z.literal('Listing').describe('Indicates that this page is a listing-type page'),\n name: z.string().describe('Internal name of the listing page'),\n route: z.string().describe('URL route for this listing page'),\n isPrivate: z.boolean().describe('Whether this page is private (requires auth)'),\n api: z.array(ListingPageApiSchema).describe('List of API calls that power this listing page'),\n columns: z.array(ColumnSchema).describe('Table columns displayed on the listing page'),\n actions: z\n .array(z.string())\n .describe('List of possible actions on each row (e.g., create, edit, delete, view)'),\n drawerCreate: DrawerSchema.describe('Drawer configuration for creating new records'),\n drawerUpdate: DrawerSchema.describe('Drawer configuration for editing existing records'),\n});\n\nexport const PageSchema = z.discriminatedUnion('type', [AuthPageSchema, ListingPageSchema]);\n\nexport type TPageSchema = z.infer<typeof PageSchema>;\n","/**\n * Module and root application schema\n */\n\nimport { z } from 'zod';\nimport { AppConfigSchema } from './app-config.schema';\nimport { PageSchema } from './page.schema';\n\nexport const ModuleSchema = z.object({\n name: z.string().describe('Name of the module'),\n pages: z.array(PageSchema).describe('Pages included within this module'),\n});\n\nexport const ApplicationSchema = z.object({\n app: AppConfigSchema.describe('Overall application configuration'),\n modules: z\n .array(ModuleSchema)\n .describe(\n 'List of modules that make up the application. Ensure all modules use every available CRUD GraphQL query and mutation from the schema.'\n ),\n});\n\nexport type TApplicationSchema = z.infer<typeof ApplicationSchema>;\nexport type TModuleSchema = z.infer<typeof ModuleSchema>;\n","/**\n * User-related schemas - same as .ref/core/react/zodTypes.ts\n */\n\nimport { z } from 'zod';\n\nexport const LoginInputSchema = z.object({\n email: z.email().describe(\"User's email address, must be valid format\"),\n password: z.string().min(8).describe(\"User's password, minimum length of 8\"),\n});\n\nexport const SpecializationSchema = z.object({\n _id: z.string().describe('Unique identifier of the specialization, type: string'),\n title: z.string().describe('Display title for the specialization, type: string'),\n});\n\nexport const UserSchema = z.object({\n _id: z.string().describe('Unique ID of the user, type: string'),\n firstName: z.string().min(2).max(30).describe('First name, 2-30 characters, type: string'),\n lastName: z.string().min(2).max(30).describe('Last name, 2-30 characters, type: string'),\n email: z.email().describe('Email address in valid format, type: string'),\n phoneNumber: z.string().min(10).describe(\"User's phone number, at least 10 digits, type: string\"),\n profileImage: z\n .string()\n .optional()\n .describe(\"Optional URL to user's profile image, type: string, optional\"),\n role: z\n .enum(['ADMIN', 'TRAINER', 'CLIENT'])\n .describe(\"User's role in the system (ADMIN, TRAINER, CLIENT)\"),\n rate: z\n .number()\n .min(1)\n .optional()\n .describe(\"User's rate (e.g., hourly, etc.), type: number, optional\"),\n specializations: z\n .array(SpecializationSchema)\n .optional()\n .describe('Array of specialization objects, optional'),\n languages: z\n .array(z.string())\n .optional()\n .describe('Array of languages the user speaks, type: string[], optional'),\n about: z\n .string()\n .min(20)\n .max(500)\n .optional()\n .describe('Brief bio or description (20-500 chars), type: string, optional'),\n gender: z.string().optional().describe(\"User's gender, type: string, optional\"),\n timezone: z.string().optional().describe(\"User's timezone, type: string, optional\"),\n averageRating: z\n .number()\n .optional()\n .describe('Average rating for this user, type: number, optional'),\n});\n\nexport const CreateUserInputSchema = z.object({\n firstName: z.string().min(2).max(30).describe('First name, 2-30 characters, type: string'),\n lastName: z.string().min(2).max(30).describe('Last name, 2-30 characters, type: string'),\n email: z.email().describe('Valid email for the new user, type: string'),\n phoneNumber: z.string().min(10).describe('Phone number (at least 10 digits), type: string'),\n password: z.string().min(8).describe('Password with min length 8, type: string'),\n role: z\n .enum(['ADMIN', 'TRAINER', 'CLIENT'])\n .describe('Role of the new user (ADMIN, TRAINER, CLIENT)'),\n rate: z.number().min(1).optional().describe('Rate for the new user, type: number, optional'),\n specializationIds: z\n .array(z.string())\n .min(1)\n .optional()\n .describe('Array of specialization IDs, optional'),\n languages: z\n .array(z.string())\n .min(1)\n .optional()\n .describe('List of languages user speaks, optional'),\n about: z\n .string()\n .min(20)\n .max(500)\n .optional()\n .describe(\"User's about/bio field, 20-500 chars, optional\"),\n});\n\nexport const UpdateUserInputSchema = z.object({\n _id: z.string().describe('ID of the user to be updated, type: string'),\n firstName: z\n .string()\n .min(2)\n .max(30)\n .optional()\n .describe('Updated first name, type: string, optional'),\n lastName: z\n .string()\n .min(2)\n .max(30)\n .optional()\n .describe('Updated last name, type: string, optional'),\n email: z.email().optional().describe('Updated email, type: string, optional'),\n phoneNumber: z\n .string()\n .min(10)\n .optional()\n .describe('Updated phone number, at least 10 digits, optional'),\n rate: z.number().min(1).optional().describe('Updated rate, type: number, optional'),\n specializationIds: z\n .array(z.string())\n .min(1)\n .optional()\n .describe('Updated array of specialization IDs, optional'),\n languages: z.array(z.string()).min(1).optional().describe('Updated list of languages, optional'),\n about: z\n .string()\n .min(20)\n .max(500)\n .optional()\n .describe('Updated about/bio (20-500 chars), optional'),\n});\n\nexport const ForgotPasswordSchema = z.object({\n email: z.email().describe('Email to initiate the password reset process, type: string'),\n});\n\nexport const ResetPasswordSchema = z.object({\n type: z.enum(['EMAIL', 'SMS']).describe('How the reset code was sent (EMAIL or SMS)'),\n resetTicket: z.string().describe('Token/ticket to validate the reset request, type: string'),\n newPassword: z.string().min(8).describe('The new password, min length 8, type: string'),\n});\n\nexport type TLoginInputSchema = z.infer<typeof LoginInputSchema>;\nexport type TUserSchema = z.infer<typeof UserSchema>;\nexport type TSpecializationSchema = z.infer<typeof SpecializationSchema>;\nexport type TCreateUserInputSchema = z.infer<typeof CreateUserInputSchema>;\nexport type TUpdateUserInputSchema = z.infer<typeof UpdateUserInputSchema>;\nexport type TForgotPasswordSchema = z.infer<typeof ForgotPasswordSchema>;\nexport type TResetPasswordSchema = z.infer<typeof ResetPasswordSchema>;\n","/**\n * System prompt for GraphQL-to-frontend configuration conversion\n */\n\nexport const REACT_BUILDER_SYSTEM_PROMPT = `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.\n\n## Target Tech Stack\nThe generated configuration will be consumed by a Vite + React 19 + TypeScript template with:\n- **UI Components**: ShadCN UI (Radix-based) from src/components/ui/\n- **Styling**: Tailwind CSS v4 with OKLCH color space\n- **Routing**: React Router v7 with private route support\n- **Forms**: React Hook Form + Zod validation (zodResolver)\n- **GraphQL Client**: Apollo Client with typed hooks from CodeGen\n- **Path Aliases**: @/{appName}/* maps to ./src/*\n\n**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).\n\nStrict guidelines:\n- Use every available CRUD GraphQL query and mutation from the project schema.\n- Map GraphQL types to frontend modules and pages.\n- EmailAddress → \"type\": \"email\" with validation; DateTime → \"type\": \"date\"; enums → select with options.values.\n- Relationships → multiSelect with query-based options where appropriate.\n- Add isPrivate: true for authenticated operations (route guarded by React Router).\n- Form fields should map to React Hook Form + Zod validation schemas.\n- Maintain camelCase. Ensure valid JSON syntax.`;\n","/**\n * Instruction template for GraphQL-to-frontend conversion\n */\n\nexport const REACT_BUILDER_INSTRUCTION = `\nAct as an expert GraphQL-to-frontend configuration converter. Transform the provided schema into a structured JSON configuration for rapid app development.\n\n**Conversion Process**\n\n1. Schema Analysis:\n- Identify all modules using 100% of available CRUD operations\n- Catalog all Query/Mutation operations with arguments\n- Map GraphQL types to frontend modules\n- Detect @auth directives and role requirements\n- Analyze relationships through nested types\n\n2. Field Mapping:\n- EmailAddress → \"type\": \"email\" with Zod email validation\n- DateTime → \"type\": \"date\"\n- Enums → dropdowns with options.values\n- Relationships → multiSelect with query-based options\n\n3. API Operations:\n- For each Query/Mutation: determine CRUD type, generate query string with variables, map to React Hook, define response type shape\n\n4. Validation:\n- Generate Zod schemas from @required directives, scalar types (Password → min 8 chars), custom directives\n- Include validation error messages\n\n5. Security:\n- Add isPrivate: true for authenticated operations\n- Implement role checks from @auth directives\n\n6. Output:\n- Generate complete CRUD pages with table column mappings, validated Create/Update forms, API hooks\n- Include Zod validation strings, maintain camelCase, valid JSON only\n`.trim();\n\nexport function buildInstructionPrompt(): string {\n return REACT_BUILDER_INSTRUCTION;\n}\n","/**\n * Few-shot examples: example GraphQL schema and expected JSON output (abbreviated)\n */\n\nexport const EXAMPLE_GRAPHQL_SCHEMA = `\ntype Query {\n getCurrentUser: User\n getAllUser(limit: Int, offset: Int): [User]!\n}\ntype Mutation {\n login(data: LoginInput!): Login!\n createUser(data: CreateUserInput!): User!\n}\ntype User {\n _id: ID!\n firstName: String!\n lastName: String!\n email: String!\n role: Role!\n}\nenum Role { ADMIN TRAINER CLIENT }\ninput LoginInput { email: String! password: String! }\ninput CreateUserInput { firstName: String! lastName: String! email: String! role: Role! }\n`.trim();\n\nexport const EXAMPLE_JSON_OUTPUT = `{\n \"app\": {\n \"name\": \"my-app\",\n \"description\": \"App description\",\n \"author\": \"Author\",\n \"branding\": {\n \"brandName\": \"MyBrand\",\n \"primaryColor\": \"#333\",\n \"secondaryColor\": \"#fff\",\n \"logo\": \"https://example.com/logo.png\"\n },\n \"apiEndpoint\": \"http://localhost:4000/graphql\"\n },\n \"modules\": [\n {\n \"name\": \"auth\",\n \"pages\": [\n {\n \"name\": \"LoginPage\",\n \"type\": \"EmailPassword\",\n \"route\": \"/login\",\n \"isPrivate\": false,\n \"api\": [\n { \"type\": \"login\", \"graphqlHook\": \"useLoginMutation\", \"queryString\": \"mutation Login($data: LoginInput!) { login(data: $data) { accessToken } }\" }\n ]\n }\n ]\n },\n {\n \"name\": \"user\",\n \"pages\": [\n {\n \"type\": \"Listing\",\n \"name\": \"UserListPage\",\n \"route\": \"/users\",\n \"isPrivate\": true,\n \"api\": [\n { \"type\": \"list\", \"graphqlHook\": \"useGetAllUserQuery\", \"queryString\": \"query GetAllUser { getAllUser { _id firstName email } }\" },\n { \"type\": \"create\", \"graphqlHook\": \"useCreateUserMutation\", \"queryString\": \"mutation CreateUser($data: CreateUserInput!) { createUser(data: $data) { _id } }\" }\n ],\n \"columns\": [{ \"field\": \"firstName\", \"label\": \"First Name\" }, { \"field\": \"email\", \"label\": \"Email\" }],\n \"actions\": [\"create\", \"edit\", \"delete\"],\n \"drawerCreate\": { \"title\": \"Create User\", \"graphqlHook\": \"useCreateUserMutation\", \"fields\": [{ \"name\": \"firstName\", \"type\": \"text\", \"required\": true }, { \"name\": \"email\", \"type\": \"email\", \"required\": true }] },\n \"drawerUpdate\": { \"title\": \"Edit User\", \"graphqlHook\": \"useUpdateUserMutation\", \"fields\": [{ \"name\": \"firstName\", \"type\": \"text\" }, { \"name\": \"email\", \"type\": \"email\" }] }\n }\n ]\n }\n ]\n}`;\n\nexport function buildExampleShotPrompt(): string {\n return `\n**Reference Conversion Example**\n\nEXAMPLE GRAPHQL INPUT:\n\\`\\`\\`graphql\n${EXAMPLE_GRAPHQL_SCHEMA}\n\\`\\`\\`\n\nEXPECTED JSON OUTPUT:\n\\`\\`\\`json\n${EXAMPLE_JSON_OUTPUT}\n\\`\\`\\`\n`.trim();\n}\n","/**\n * Feedback prompt - re-generate frontend config incorporating user feedback\n */\n\nexport function buildFeedbackPrompt(userFeedback: string, schemaFile: string): string {\n return `\nReview the user feedback carefully to understand the required updates.\n\nThe user feedback for updating the generated Frontend Config JSON is provided below:\n\"\"\"\n${userFeedback}\n\"\"\"\n\nNow, generate the Frontend Config JSON for this project based on the provided feedback.\n\n**Project GRAPHQL SCHEMA INPUT:**\n\\`\\`\\`graphql\n${schemaFile}\n\\`\\`\\`\n\nUpdate the Frontend Config JSON to incorporate the requested changes. Return ONLY valid JSON, no markdown code blocks.\n`.trim();\n}\n","/**\n * validate_frontend_config tool - validates JSON against ApplicationSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { ApplicationSchema } from '../schemas';\n\nexport const validateFrontendConfigTool = createValidationTool(\n 'validate_frontend_config',\n ApplicationSchema,\n 'Validates a frontend configuration JSON string against the ApplicationSchema. Returns valid: true or valid: false with errors array.',\n 'config'\n);\n","/**\n * generate_frontend tool - converts GraphQL schema to frontend config JSON (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { ApplicationSchema, type TApplicationSchema } from '../schemas';\nimport { REACT_BUILDER_SYSTEM_PROMPT } from '../prompts/system.prompt';\nimport { buildInstructionPrompt, buildExampleShotPrompt } from '../prompts';\nimport type { AppInfo } from '../types';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\nfunction buildGeneratePrompt(graphqlSchema: string, appInfo?: AppInfo): string {\n const instruction = buildInstructionPrompt();\n const example = buildExampleShotPrompt();\n const appInfoBlock = appInfo\n ? `\n**Project context:**\n- name: ${appInfo.projectName ?? 'project'}\n- description: ${appInfo.projectDescription ?? ''}\n- modules: ${appInfo.modules ?? ''}\n- apiEndpoint: ${appInfo.apiEndpoint ?? 'http://localhost:4000/graphql'}\n`\n : '';\n return `${instruction}\n\n${example}\n${appInfoBlock}\n\n**Current Project GraphQL Schema:**\n\\`\\`\\`graphql\n${graphqlSchema}\n\\`\\`\\`\n\nGenerate the Frontend Config JSON. Use every available CRUD GraphQL query and mutation. Return ONLY valid JSON.`;\n}\n\nexport function createGenerateFrontendTool(model: Model) {\n return defineTool({\n name: 'generate_frontend',\n description:\n '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.',\n input: z.object({\n graphqlSchema: z.string().describe('The GraphQL schema string to convert'),\n appInfo: z\n .object({\n projectName: z.string().optional(),\n projectDescription: z.string().optional(),\n modules: z.string().optional(),\n apiEndpoint: z.string().optional(),\n })\n .optional()\n .describe('Optional project/app context'),\n }),\n handler: async ({ graphqlSchema, appInfo }): Promise<TApplicationSchema> => {\n const userPrompt = buildGeneratePrompt(graphqlSchema, appInfo);\n const messages = [\n { role: 'system' as const, content: REACT_BUILDER_SYSTEM_PROMPT },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.2, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, ApplicationSchema);\n },\n });\n}\n","/**\n * generate_feature_breakdown tool - breaks down GraphQL schema into components/pages (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { REACT_BUILDER_INSTRUCTION } from '../prompts/instruction.prompt';\n\nexport interface FeatureBreakdownResult {\n summary: string;\n modules: string[];\n operations: string[];\n suggestedPages?: string[];\n}\n\nexport function createGenerateFeatureBreakdownTool(model: Model) {\n return defineTool({\n name: 'generate_feature_breakdown',\n description:\n '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).',\n input: z.object({\n graphqlSchema: z.string().describe('The GraphQL schema string to analyze'),\n }),\n handler: async ({ graphqlSchema }): Promise<FeatureBreakdownResult> => {\n const userPrompt = `${REACT_BUILDER_INSTRUCTION}\n\n**Schema to analyze:**\n\\`\\`\\`graphql\n${graphqlSchema}\n\\`\\`\\`\n\nRespond 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.`;\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a GraphQL schema analyst. Return a clear, structured text breakdown.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 4096 });\n return { summary: response.text, modules: [], operations: [], suggestedPages: [] };\n },\n });\n}\n","/**\n * scaffold_vite tool - compiles .ref/templates/vite/ with ApplicationSchema config\n */\n\nimport * as path from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { scaffoldProject } from '../../../lib/template-engine';\nimport type { ScaffoldResult, TemplateContext } from '../../../lib/template-engine';\nimport type { TApplicationSchema } from '../schemas';\nimport { safeJsonParse } from '../../../lib/utils';\n\n/** Convert ApplicationSchema config to template context */\nfunction toTemplateContext(config: TApplicationSchema): TemplateContext {\n return {\n appName: config.app.name,\n description: config.app.description,\n apiEndpoint: config.app.apiEndpoint,\n branding: {\n brandName: config.app.branding.brandName,\n primaryColor: config.app.branding.primaryColor,\n secondaryColor: config.app.branding.secondaryColor,\n logo: config.app.branding.logo,\n },\n modules: config.modules.map(m => ({\n name: m.name,\n pascalName: m.name.charAt(0).toUpperCase() + m.name.slice(1),\n camelName: m.name.charAt(0).toLowerCase() + m.name.slice(1),\n })),\n author: config.app.author,\n pages: config.modules.flatMap(m => m.pages),\n };\n}\n\nexport const scaffoldViteTool = defineTool({\n name: 'scaffold_vite',\n description:\n '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.',\n input: z.object({\n config: z.string().describe('JSON string of the validated ApplicationSchema config'),\n outputDir: z.string().describe('Absolute path to the output directory'),\n }),\n handler: async ({ config, outputDir }): Promise<ScaffoldResult> => {\n const parsed = safeJsonParse(config, 'application schema config') as TApplicationSchema;\n const templateDir = path.resolve(process.cwd(), '.ref/templates/vite');\n const context = toTemplateContext(parsed);\n\n return scaffoldProject({\n templateDir,\n outputDir,\n context,\n });\n },\n});\n","/**\n * react-builder tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateFrontendConfigTool } from './validate-frontend-config.tool';\nimport { createGenerateFrontendTool } from './generate-frontend.tool';\nimport { createGenerateFeatureBreakdownTool } from './generate-feature-breakdown.tool';\nimport { scaffoldViteTool } from './scaffold-vite';\n\nexport { validateFrontendConfigTool } from './validate-frontend-config.tool';\nexport { createGenerateFrontendTool } from './generate-frontend.tool';\nexport {\n createGenerateFeatureBreakdownTool,\n type FeatureBreakdownResult,\n} from './generate-feature-breakdown.tool';\nexport { scaffoldViteTool } from './scaffold-vite';\n\nexport function createReactBuilderTools(model: Model) {\n return createToolSet({\n validate_frontend_config: validateFrontendConfigTool,\n generate_frontend: createGenerateFrontendTool(model),\n generate_feature_breakdown: createGenerateFeatureBreakdownTool(model),\n scaffold_vite: scaffoldViteTool,\n });\n}\n","/**\n * graphql-analyzer subagent - analyzes GraphQL schemas (no tools)\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst GRAPHQL_ANALYZER_SYSTEM_PROMPT = `You are an expert at analyzing GraphQL schemas. Your job is to:\n\n1. **Types**: List all object types, enums, scalars, and input types.\n2. **Queries**: List every Query field with arguments and return type.\n3. **Mutations**: List every Mutation field with arguments and return type.\n4. **Relationships**: Identify types that reference other types (e.g. User has role: Role, or Order has customer: User).\n5. **Auth/directives**: Note any @auth, @directive usage that affects access control.\n\nRespond with a clear, structured analysis (headings and bullet points). The user will use this to generate a frontend configuration.`;\n\nexport const graphqlAnalyzerSubagent = defineSubagent({\n name: 'graphql-analyzer',\n description:\n '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).',\n systemPrompt: GRAPHQL_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * config-validator subagent - validates frontend config (has validate_frontend_config tool)\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\nimport { validateFrontendConfigTool } from '../tools/validate-frontend-config.tool';\n\nconst CONFIG_VALIDATOR_SYSTEM_PROMPT = `You are a frontend configuration validator. Your job is to:\n\n1. Validate the provided frontend config JSON using the validate_frontend_config tool.\n2. Compare the config against the GraphQL schema (if provided) and check that all CRUD operations are covered.\n3. Report any missing modules, pages, or API hooks.\n\nWhen 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.`;\n\nexport function createConfigValidatorSubagent() {\n return defineSubagent({\n name: 'config-validator',\n description:\n '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.',\n systemPrompt: CONFIG_VALIDATOR_SYSTEM_PROMPT,\n tools: { validate_frontend_config: validateFrontendConfigTool },\n maxIterations: 5,\n });\n}\n","/**\n * runReactBuilderAgent - orchestrator for frontend config generation with retry and subagents\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { REACT_BUILDER_SYSTEM_PROMPT } from './prompts';\nimport { createReactBuilderTools } from './tools';\nimport { graphqlAnalyzerSubagent, createConfigValidatorSubagent } from './subagents';\nimport type { ReactBuilderAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${REACT_BUILDER_SYSTEM_PROMPT}\n\nYou are the React frontend builder orchestrator. When the user provides a GraphQL schema and asks for a frontend configuration:\n\n1. **Analyze (optional)**: For complex schemas, use subagent_graphql-analyzer with a prompt that includes the schema to get a structured analysis of types, queries, and mutations.\n2. **Generate**: Use generate_frontend with the GraphQL schema (and optional appInfo) to produce the frontend config JSON.\n3. **Validate (optional)**: Use subagent_config-validator with the generated config (and schema) to check structure and completeness.\n4. **Validate directly**: You can use validate_frontend_config to check any config JSON.\n5. **Feature breakdown**: Use generate_feature_breakdown to get a module/operation breakdown before generating.\n\nRespond 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.`;\n\n/**\n * Run the react-builder orchestrator agent with all tools and subagents.\n * Use generate_frontend tool for config generation; the tool may throw on parse failure (caller can retry with new input).\n */\nexport async function runReactBuilderAgent(config: ReactBuilderAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const reactTools = createReactBuilderTools(model);\n const configValidator = createConfigValidatorSubagent();\n const subagentTools = createSubagentToolSet([graphqlAnalyzerSubagent, configValidator], {\n parentModel: model,\n });\n const tools = createToolSet({ ...reactTools, ...subagentTools });\n\n return runAgent({\n model,\n tools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for Next.js application configuration\n */\n\nimport { z } from 'zod';\n\n/** Case-insensitive enum */\nconst ciEnum = <T extends string>(values: readonly [T, ...T[]]) =>\n z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(values));\n\nconst httpMethodSchema = z\n .string()\n .transform(s => s.toUpperCase().trim())\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nexport const nextjsPageSchema = z.object({\n path: z.string(),\n name: z.string(),\n access: ciEnum(['public', 'protected']),\n routeGroup: z.string().default(''),\n purpose: z.string(),\n hasForm: z.coerce.boolean().default(false),\n formFields: z.array(z.string()).default([]),\n dataFetching: ciEnum(['server', 'client', 'hybrid']).default('server'),\n actions: z.array(z.string()).default([]),\n});\n\nexport const nextjsLayoutSchema = z.object({\n name: z.string(),\n path: z.string(),\n routeGroup: z.string().default(''),\n components: z.array(z.string()).default([]),\n purpose: z.string(),\n});\n\nexport const nextjsApiRouteSchema = z.object({\n path: z.string(),\n methods: z.array(httpMethodSchema).default([]),\n auth: z.coerce.boolean().default(true),\n description: z.string(),\n});\n\nexport const serverActionSchema = z.object({\n name: z.string(),\n module: z.string(),\n description: z.string(),\n revalidates: z.array(z.string()).default([]),\n});\n\nexport const nextjsConfigSchema = z.object({\n appName: z.string().default('app'),\n pages: z.array(nextjsPageSchema).default([]),\n layouts: z.array(nextjsLayoutSchema).default([]),\n apiRoutes: z.array(nextjsApiRouteSchema).default([]),\n serverActions: z.array(serverActionSchema).default([]),\n middleware: z.array(z.string()).default([]),\n envVars: z.array(z.string()).default([]),\n packages: z.array(z.string()).default([]),\n});\n\nexport type TNextjsConfig = z.infer<typeof nextjsConfigSchema>;\n","/**\n * System prompt for nextjs-builder orchestrator\n */\n\nexport const NEXTJS_BUILDER_SYSTEM_PROMPT = `You are an expert Next.js application architect using the App Router.\n\nYou generate production-ready Next.js configurations from frontend designs and API designs:\n- App Router file structure with route groups, layouts, pages, loading, and error boundaries\n- Server Components by default, Client Components only when interactivity is needed\n- Server Actions for mutations (form submissions, data writes)\n- API Route Handlers for external integrations, webhooks, and file uploads\n- Next.js middleware for auth guards and redirects\n- Data fetching strategy (server vs client vs hybrid per page)\n- Package recommendations (next-auth, prisma, tailwindcss, shadcn/ui)\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompt for Next.js config generation\n */\n\nexport const DESIGN_NEXTJS_PROMPT = `## Requirements:\n{requirement}\n\nGenerate a Next.js App Router application configuration. Include:\n\n1. Pages: app router pages with path, name, access level, route group, purpose, data fetching strategy.\n2. Layouts: shared layouts with route groups (e.g. (auth), (dashboard)), components they include.\n3. API Routes: route handlers with path, HTTP methods, auth requirement, description.\n4. Server Actions: named actions with module, description, and paths they revalidate.\n5. Middleware: list of middleware behaviors (e.g. \"redirect unauthenticated to /login\").\n6. Env vars: NEXTAUTH_SECRET, DATABASE_URL, etc.\n7. Packages: recommended npm packages.\n\nReturn ONLY valid JSON:\n{\n \"appName\": \"my-app\",\n \"pages\": [{\n \"path\": \"/dashboard\",\n \"name\": \"Dashboard\",\n \"access\": \"protected\",\n \"routeGroup\": \"(dashboard)\",\n \"purpose\": \"Main dashboard with stats\",\n \"hasForm\": false,\n \"formFields\": [],\n \"dataFetching\": \"server\",\n \"actions\": []\n }],\n \"layouts\": [{\n \"name\": \"DashboardLayout\",\n \"path\": \"app/(dashboard)/layout.tsx\",\n \"routeGroup\": \"(dashboard)\",\n \"components\": [\"Sidebar\", \"Header\"],\n \"purpose\": \"Shared layout for authenticated pages\"\n }],\n \"apiRoutes\": [{\n \"path\": \"/api/users\",\n \"methods\": [\"GET\", \"POST\"],\n \"auth\": true,\n \"description\": \"User CRUD endpoints\"\n }],\n \"serverActions\": [{\n \"name\": \"createUser\",\n \"module\": \"users\",\n \"description\": \"Create a new user\",\n \"revalidates\": [\"/dashboard/users\"]\n }],\n \"middleware\": [\"Redirect unauthenticated users to /login\"],\n \"envVars\": [\"DATABASE_URL\", \"NEXTAUTH_SECRET\"],\n \"packages\": [\"next-auth\", \"prisma\", \"@prisma/client\", \"tailwindcss\"]\n}`;\n\nexport function buildDesignNextjsPrompt(requirement: string): string {\n return DESIGN_NEXTJS_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_nextjs tool - validates JSON against nextjsConfigSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { nextjsConfigSchema } from '../schemas';\n\nexport const validateNextjsTool = createValidationTool(\n 'validate_nextjs',\n nextjsConfigSchema,\n 'Validates a Next.js config JSON string against the NextjsConfig schema. Returns valid: true or valid: false with errors.',\n 'config'\n);\n","/**\n * generate_nextjs tool - generates Next.js config from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { nextjsConfigSchema, type TNextjsConfig } from '../schemas';\nimport { buildDesignNextjsPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the generate_nextjs tool for Next.js config generation.\n */\nexport function createGenerateNextjsTool(model: Model) {\n return defineTool({\n name: 'generate_nextjs',\n description:\n 'Generate a complete Next.js App Router configuration from frontend design and requirements. Returns pages, layouts, API routes, server actions, and middleware as JSON.',\n input: z.object({\n requirement: z.string().describe('Frontend design, API design, and project requirements'),\n }),\n handler: async ({ requirement }): Promise<TNextjsConfig> => {\n const userPrompt = buildDesignNextjsPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a Next.js architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n return parseModelJsonResponse(response.text, nextjsConfigSchema);\n },\n });\n}\n","/**\n * nextjs-builder tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateNextjsTool } from './validate-nextjs';\nimport { createGenerateNextjsTool } from './generate-nextjs';\n\nexport { validateNextjsTool } from './validate-nextjs';\nexport { createGenerateNextjsTool } from './generate-nextjs';\n\n/**\n * Create all nextjs-builder tools. Pass the model for AI-backed tools.\n */\nexport function createNextjsBuilderTools(model: Model) {\n return createToolSet({\n validate_nextjs: validateNextjsTool,\n generate_nextjs: createGenerateNextjsTool(model),\n });\n}\n","/**\n * route-planner subagent - plans Next.js App Router file structure\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ROUTE_PLANNER_SYSTEM_PROMPT = `You are a Next.js App Router specialist. Given page specs, you plan the file structure.\n\n## Route Groups\n- (auth) for public auth pages: login, signup, forgot-password\n- (dashboard) or (app) for protected pages\n- (marketing) for public landing pages\n\n## File Structure Per Route\n- page.tsx: the page component (Server Component by default)\n- layout.tsx: shared layout for the route group\n- loading.tsx: Suspense fallback\n- error.tsx: error boundary (must be Client Component)\n- not-found.tsx: 404 page\n\n## Data Fetching\n- Server Components: fetch data directly in the component (async function)\n- Client Components: use SWR or React Query for client-side fetching\n- Server Actions: for form submissions and mutations\n\n## Conventions\n- Use lowercase kebab-case for route segments\n- Dynamic segments: [id], [slug]\n- Catch-all: [...slug]\n- Parallel routes: @modal, @sidebar\n- Intercepting routes: (.)photo, (..)details\n\nRespond with the full file tree and route structure. Do NOT return JSON.`;\n\nexport const routePlannerSubagent = defineSubagent({\n name: 'route-planner',\n description:\n 'Plans Next.js App Router file structure with route groups, layouts, and page files. Use before generating the Next.js config.',\n systemPrompt: ROUTE_PLANNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * api-route-generator subagent - generates Next.js API routes and server actions\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst API_ROUTE_GENERATOR_SYSTEM_PROMPT = `You are a Next.js API specialist. Given an API design, you plan route handlers and server actions.\n\n## API Route Handlers (app/api/)\nFor external integrations, webhooks, and file uploads:\n- One route.ts file per resource: app/api/[resource]/route.ts\n- Export named functions: GET, POST, PUT, DELETE\n- Use NextRequest and NextResponse\n- Add auth checks using next-auth getServerSession\n\n## Server Actions (preferred for mutations)\nFor form submissions and data writes:\n- Define in separate files: app/actions/[module].ts\n- Use 'use server' directive\n- Use revalidatePath or revalidateTag after mutations\n- Return typed results with error handling\n\n## When to Use Which\n- Server Actions: form submissions, data CRUD, anything triggered by user action\n- API Routes: webhooks from external services, file uploads, OAuth callbacks, public APIs\n\n## Auth Integration\n- API Routes: check session with getServerSession\n- Server Actions: check session at the start of each action\n- Middleware: protect route groups with matcher patterns\n\nRespond with structured analysis per module. Do NOT return JSON.`;\n\nexport const apiRouteGeneratorSubagent = defineSubagent({\n name: 'api-route-generator',\n description:\n 'Generates Next.js API route handlers and server actions from API design. Use after route planning.',\n systemPrompt: API_ROUTE_GENERATOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * runNextjsBuilderAgent - orchestrator for Next.js project generation\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { NEXTJS_BUILDER_SYSTEM_PROMPT } from './prompts';\nimport { createNextjsBuilderTools } from './tools';\nimport { routePlannerSubagent, apiRouteGeneratorSubagent } from './subagents';\nimport type { NextjsBuilderAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${NEXTJS_BUILDER_SYSTEM_PROMPT}\n\nYou are the Next.js builder orchestrator. When the user provides requirements:\n\n1. **Plan routes**: Use subagent_route-planner to design the App Router file structure with route groups and layouts.\n2. **Generate API routes**: Use subagent_api-route-generator to design API route handlers and server actions.\n3. **Generate config**: Use generate_nextjs to produce the complete Next.js configuration as JSON.\n4. **Validate**: Use validate_nextjs to check the config JSON before returning.\n\nRespond with the final Next.js config as JSON.`;\n\n/**\n * Run the nextjs-builder orchestrator agent.\n */\nexport async function runNextjsBuilderAgent(\n config: NextjsBuilderAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createNextjsBuilderTools(model);\n const subagentTools = createSubagentToolSet([routePlannerSubagent, apiRouteGeneratorSubagent], {\n parentModel: model,\n });\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for ExecutionPlan\n */\n\nimport { z } from 'zod';\n\nexport const phaseStepSchema = z.object({\n order: z.number(),\n action: z.string(),\n details: z.string(),\n});\n\nexport const implementationPhaseSchema = z.object({\n name: z.string(),\n description: z.string(),\n steps: z.array(phaseStepSchema),\n});\n\nexport const edgeCaseSchema = z.object({\n area: z.string(),\n scenario: z.string(),\n handling: z.string(),\n severity: z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(['critical', 'warning', 'info'])),\n});\n\nexport const testChecklistItemSchema = z.object({\n flow: z.string(),\n item: z.string(),\n expectedResult: z.string(),\n});\n\nexport const executionPlanSchema = z.object({\n phases: z.array(implementationPhaseSchema).default([]),\n currentState: z.string().default(''),\n desiredEndState: z.string().default(''),\n edgeCases: z.array(edgeCaseSchema).default([]),\n securityNotes: z.array(z.string()).default([]),\n performanceNotes: z.array(z.string()).default([]),\n testingChecklist: z.array(testChecklistItemSchema).default([]),\n});\n\nexport type TExecutionPlan = z.infer<typeof executionPlanSchema>;\n","/**\n * System prompt for execution-planner orchestrator\n */\n\nexport const EXECUTION_PLANNER_SYSTEM_PROMPT = `You are a senior tech lead specializing in implementation strategy and project execution planning.\n\nYou create enterprise-quality execution plans with:\n- Phased implementation order with concrete, numbered steps per phase\n- Current state analysis and desired end state definition\n- Edge cases per domain area with handling strategies and severity levels\n- Security considerations (passwords, tokens, CORS, input validation)\n- Performance considerations (indexing, caching, lazy loading, N+1 prevention)\n- Manual testing checklists grouped by feature flow\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for execution-planner\n */\n\nexport const CREATE_EXECUTION_PLAN_PROMPT = `## Full Plan Context:\n{context}\n\nCreate a comprehensive execution plan. Include:\n\n1. **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\").\n2. **currentState**: What the project starts with (e.g. \"vanilla Next.js, no DB, no auth\").\n3. **desiredEndState**: What must work when done (user capabilities + technical verification).\n4. **edgeCases**: Edge cases per area with scenario, handling strategy, and severity (critical/warning/info).\n5. **securityNotes**: Security considerations (password hashing, JWT config, rate limiting, etc.).\n6. **performanceNotes**: Performance considerations (indexing, caching, lazy loading, etc.).\n7. **testingChecklist**: Manual testing items per flow with expected results.\n\nReturn ONLY valid JSON:\n{\n \"phases\": [{ \"name\": \"Phase 1: Foundation\", \"description\": \"...\", \"steps\": [{ \"order\": 1, \"action\": \"Install dependencies\", \"details\": \"npm install mongoose bcryptjs jsonwebtoken\" }] }],\n \"currentState\": \"...\",\n \"desiredEndState\": \"...\",\n \"edgeCases\": [{ \"area\": \"Authentication\", \"scenario\": \"Email already exists\", \"handling\": \"Return 400 with clear message\", \"severity\": \"critical\" }],\n \"securityNotes\": [\"...\"],\n \"performanceNotes\": [\"...\"],\n \"testingChecklist\": [{ \"flow\": \"Auth Flow\", \"item\": \"Sign up with valid credentials\", \"expectedResult\": \"Account created, redirected to dashboard\" }]\n}`;\n\nexport function buildCreateExecutionPlanPrompt(context: string): string {\n return CREATE_EXECUTION_PLAN_PROMPT.replace('{context}', context);\n}\n","/**\n * validate_execution_plan tool - validates JSON against executionPlanSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { executionPlanSchema } from '../schemas';\n\nexport const validateExecutionPlanTool = createValidationTool(\n 'validate_execution_plan',\n executionPlanSchema,\n 'Validates an execution plan JSON string against the ExecutionPlan schema. Returns valid: true or valid: false with errors.',\n 'plan'\n);\n","/**\n * create_execution_plan tool - generates execution plan from context (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { executionPlanSchema, type TExecutionPlan } from '../schemas';\nimport { buildCreateExecutionPlanPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the create_execution_plan tool for generating phased plans.\n */\nexport function createExecutionPlanTool(model: Model) {\n return defineTool({\n name: 'create_execution_plan',\n description:\n 'Generate a comprehensive execution plan with phases, edge cases, and testing checklist from the full plan context.',\n input: z.object({\n context: z.string().describe('Full plan context: all sections generated so far'),\n }),\n handler: async ({ context }): Promise<TExecutionPlan> => {\n const userPrompt = buildCreateExecutionPlanPrompt(context);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a tech lead. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, executionPlanSchema);\n },\n });\n}\n","/**\n * execution-planner tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateExecutionPlanTool } from './validate-plan';\nimport { createExecutionPlanTool } from './create-plan';\n\nexport { validateExecutionPlanTool } from './validate-plan';\nexport { createExecutionPlanTool } from './create-plan';\n\n/**\n * Create all execution-planner tools. Pass the model for AI-backed tools.\n */\nexport function createExecutionPlannerTools(model: Model) {\n return createToolSet({\n validate_execution_plan: validateExecutionPlanTool,\n create_execution_plan: createExecutionPlanTool(model),\n });\n}\n","/**\n * runExecutionPlannerAgent - orchestrator for execution plan design\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { EXECUTION_PLANNER_SYSTEM_PROMPT } from './prompts';\nimport { createExecutionPlannerTools } from './tools';\nimport { edgeCaseAnalyzerSubagent, testingStrategistSubagent } from './subagents';\nimport type { ExecutionPlannerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${EXECUTION_PLANNER_SYSTEM_PROMPT}\n\nYou are the execution planning orchestrator. When the user provides plan sections:\n\n1. **Analyze edge cases**: Use subagent_edge-case-analyzer to identify edge cases per domain area with handling strategies.\n2. **Design testing**: Use subagent_testing-strategist to design manual testing checklists grouped by feature flow.\n3. **Generate plan**: Use create_execution_plan to produce the complete execution plan with phases, edge cases, and testing checklist.\n4. **Validate**: Use validate_execution_plan to check the final plan JSON before returning.\n\nRespond with the final execution plan as JSON.`;\n\n/**\n * Run the execution-planner orchestrator agent with all tools and subagents.\n */\nexport async function runExecutionPlannerAgent(\n config: ExecutionPlannerAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createExecutionPlannerTools(model);\n const subagentTools = createSubagentToolSet(\n [edgeCaseAnalyzerSubagent, testingStrategistSubagent],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Hello World tool\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../lib/tools';\n\nexport const helloWorldTool = defineTool({\n name: 'hello_world',\n description: 'Returns a greeting message for the given name',\n input: z.object({\n name: z.string().describe('Name to greet'),\n }),\n handler: async ({ name }) => {\n return { greeting: `Hello, ${name}! Welcome to sweagent.` };\n },\n});\n","/**\n * Hello World agent - runs an agent with the hello world tool\n */\n\nimport type { AgentResult, AgentStep } from '../../lib/types/agent';\nimport type { Logger } from '../../lib/types/common';\nimport type { ModelConfig } from '../../lib/types/model';\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { helloWorldTool } from './tool';\n\nexport interface HelloWorldAgentConfig {\n /** User input (e.g. \"Say hello to Alice\") */\n input: string;\n /** Model config; defaults to OpenAI gpt-4o-mini */\n model?: ModelConfig;\n /** System prompt override */\n systemPrompt?: string;\n /** Max iterations; default 3 */\n maxIterations?: number;\n /** Callback for each step */\n onStep?: (step: AgentStep) => void;\n /** Optional logger for execution logs */\n logger?: Logger;\n}\n\nconst DEFAULT_SYSTEM_PROMPT =\n 'You are a friendly greeter. Use the hello_world tool to greet users.';\n\nexport async function runHelloWorldAgent(config: HelloWorldAgentConfig): Promise<AgentResult> {\n const {\n input,\n model: modelConfig,\n systemPrompt = DEFAULT_SYSTEM_PROMPT,\n maxIterations = 3,\n onStep,\n logger,\n } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n\n return runAgent({\n model,\n tools: createToolSet({ hello_world: helloWorldTool }),\n systemPrompt,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * MCP server tool registry - maps every sweagent module to an MCP tool entry.\n */\n\nimport type { AgentStep } from '../../types/agent';\nimport type { ModelConfig } from '../../types/model';\nimport type { AgentToolEntry } from './types';\n\nimport { runPlanningAgent } from '../../../modules/planning';\nimport { runRequirementGathererAgent } from '../../../modules/requirement-gatherer';\nimport { runDataModelerAgent } from '../../../modules/data-modeler';\nimport { runApiDesignerAgent } from '../../../modules/api-designer';\nimport { runAuthDesignerAgent } from '../../../modules/auth-designer';\nimport { runBackendArchitectAgent } from '../../../modules/backend-architect';\nimport { runFrontendArchitectAgent } from '../../../modules/frontend-architect';\nimport { runExpressBuilderAgent } from '../../../modules/express-builder';\nimport { runApolloBuilderAgent } from '../../../modules/apollo-builder';\nimport { runReactBuilderAgent } from '../../../modules/react-builder';\nimport { runNextjsBuilderAgent } from '../../../modules/nextjs-builder';\nimport { runExecutionPlannerAgent } from '../../../modules/execution-planner';\nimport { runHelloWorldAgent } from '../../../modules/hello-world';\n\nfunction entry(\n name: string,\n description: string,\n runner: (cfg: {\n input: string;\n model?: ModelConfig;\n onStep?: (step: AgentStep) => void;\n }) => Promise<{ output: string }>\n): AgentToolEntry {\n return {\n name,\n description,\n handler: (input, model, onStep) =>\n runner({ input, model, onStep }) as ReturnType<AgentToolEntry['handler']>,\n };\n}\n\n/** All registered agent tools, keyed by tool name. */\nexport const TOOL_REGISTRY: AgentToolEntry[] = [\n entry(\n 'plan',\n 'Generate a full software plan (discovery, requirements, design, synthesis) from a project description.',\n runPlanningAgent\n ),\n entry(\n 'gather_requirements',\n 'Extract structured requirements (actors, flows, stories, modules) from a project description.',\n runRequirementGathererAgent\n ),\n entry(\n 'design_data_model',\n 'Design a database schema (MongoDB or PostgreSQL) with entities, relations, and indexes.',\n runDataModelerAgent\n ),\n entry(\n 'design_api',\n 'Design REST or GraphQL API contracts (endpoints, request/response schemas) from requirements.',\n runApiDesignerAgent\n ),\n entry(\n 'design_auth',\n 'Design authentication and authorization strategy (providers, roles, permissions, flows).',\n runAuthDesignerAgent\n ),\n entry(\n 'architect_backend',\n 'Design backend architecture (folder structure, services, middleware, deployment) from requirements.',\n runBackendArchitectAgent\n ),\n entry(\n 'architect_frontend',\n 'Design frontend architecture (components, state management, routing, styling) from requirements.',\n runFrontendArchitectAgent\n ),\n entry(\n 'build_express',\n 'Generate Express.js REST API configuration and boilerplate from an API design.',\n runExpressBuilderAgent\n ),\n entry(\n 'build_apollo',\n 'Generate Apollo GraphQL subgraph configuration and resolvers from an API design.',\n runApolloBuilderAgent\n ),\n entry(\n 'build_react',\n 'Generate React + Vite application configuration and components from a GraphQL schema.',\n runReactBuilderAgent\n ),\n entry(\n 'build_nextjs',\n 'Generate Next.js App Router configuration and pages from requirements.',\n runNextjsBuilderAgent\n ),\n entry(\n 'plan_execution',\n 'Create a phased execution plan with edge-case analysis and testing strategy.',\n runExecutionPlannerAgent\n ),\n entry(\n 'hello_world',\n 'Test agent that greets users. Use to verify the MCP server is working.',\n runHelloWorldAgent\n ),\n];\n\n/** Lookup a tool by name. Returns undefined if not found. */\nexport function findTool(name: string): AgentToolEntry | undefined {\n return TOOL_REGISTRY.find(t => t.name === name);\n}\n","/**\n * MCP server types - shared Zod schema for agent tool inputs.\n */\n\nimport { z } from 'zod';\n\nimport type { AgentResult, AgentStep } from '../../types/agent';\nimport type { ModelConfig } from '../../types/model';\n\n/** Raw Zod shape for McpServer.registerTool inputSchema. */\nexport const AGENT_TOOL_INPUT_SHAPE = {\n input: z.string().describe('Natural language description of what to build or design'),\n provider: z\n .enum(['openai', 'anthropic', 'google'])\n .optional()\n .describe('LLM provider (defaults to openai)'),\n model: z.string().optional().describe('Model name, e.g. gpt-4o-mini, claude-3-5-sonnet-20241022'),\n temperature: z.number().min(0).max(1).optional().describe('Sampling temperature (0-1)'),\n} as const;\n\n/** Parsed tool input type. */\nexport interface AgentToolInput {\n input: string;\n provider?: 'openai' | 'anthropic' | 'google';\n model?: string;\n temperature?: number;\n}\n\n/** Build a ModelConfig from the optional overrides in the tool input. */\nexport function buildModelConfig(input: AgentToolInput): ModelConfig | undefined {\n if (!input.provider && !input.model) return undefined;\n return {\n provider: input.provider ?? 'openai',\n model: input.model ?? 'gpt-4o-mini',\n temperature: input.temperature,\n };\n}\n\n/** A registered agent tool entry. */\nexport interface AgentToolEntry {\n name: string;\n description: string;\n handler: (\n input: string,\n model?: ModelConfig,\n onStep?: (step: AgentStep) => void\n ) => Promise<AgentResult>;\n}\n","/**\n * MCP server - exposes all sweagent agent modules as MCP tools via McpServer.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\nimport type { AgentStep } from '../../types/agent';\nimport { TOOL_REGISTRY } from './tool-registry';\nimport { AGENT_TOOL_INPUT_SHAPE, buildModelConfig } from './types';\nimport type { AgentToolInput } from './types';\n\nconst SERVER_NAME = 'sweagent';\nconst SERVER_VERSION = '0.0.3';\n\nconst log = (msg: string): void => {\n process.stderr.write(`[sweagent] ${msg}\\n`);\n};\n\nconst MAX_PREVIEW = 200;\n\nfunction createStepLogger(toolName: string): (step: AgentStep) => void {\n return (step: AgentStep) => {\n const prefix = `${toolName} — step ${step.iteration + 1}`;\n if (step.content) {\n const preview =\n step.content.length > MAX_PREVIEW ? step.content.slice(0, MAX_PREVIEW) + '…' : step.content;\n log(`${prefix}: ${preview}`);\n } else {\n const tools = step.toolCalls?.map(tc => tc.toolName).join(', ');\n log(`${prefix}${tools ? ` (tools: ${tools})` : ''}`);\n }\n };\n}\n\n/** Create and return a configured McpServer with all agent tools registered. */\nexport function createSweagentServer(): McpServer {\n const server = new McpServer(\n { name: SERVER_NAME, version: SERVER_VERSION },\n { capabilities: { tools: {} } }\n );\n\n for (const entry of TOOL_REGISTRY) {\n server.registerTool(\n entry.name,\n { description: entry.description, inputSchema: AGENT_TOOL_INPUT_SHAPE },\n async (args: AgentToolInput) => {\n log(`${entry.name} — started`);\n try {\n const modelConfig = buildModelConfig(args);\n const onStep = createStepLogger(entry.name);\n const result = await entry.handler(args.input, modelConfig, onStep);\n log(`${entry.name} — completed`);\n return { content: [{ type: 'text' as const, text: result.output }] };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n log(`${entry.name} — error: ${message}`);\n return { content: [{ type: 'text' as const, text: message }], isError: true };\n }\n }\n );\n }\n\n return server;\n}\n"]}
1
+ {"version":3,"sources":["../src/lib/utils/errors.ts","../src/lib/utils/json-parse.ts","../src/lib/utils/logger.ts","../src/lib/utils/utils.ts","../src/lib/agents/agent-observers.ts","../src/lib/types/tool.ts","../src/lib/tools/tools.ts","../src/lib/tools/validation-factory.ts","../src/lib/stores/proposed-store.ts","../src/lib/tools/propose-output.ts","../src/lib/agents/agent-tool-executor.ts","../src/lib/context/token-estimator.ts","../src/lib/context/text-truncator.ts","../src/lib/context/message-summarizer.ts","../src/lib/context/context-pruner.ts","../src/lib/agents/agent.ts","../src/lib/agents/programmatic-step.ts","../src/lib/agents/best-of-n.ts","../src/lib/agents/agent-with-steps.ts","../src/lib/agents/response-selector.ts","../src/lib/models/providers/openai-adapter.ts","../src/lib/models/providers/openai.ts","../src/lib/models/providers/anthropic-adapter.ts","../src/lib/models/providers/anthropic.ts","../src/lib/models/providers/google-adapter.ts","../src/lib/models/providers/google.ts","../src/lib/models/create-model.ts","../src/lib/subagents/subagent.ts","../src/lib/template-engine/compiler.ts","../src/lib/mcp/transports.ts","../src/lib/mcp/client.ts","../src/modules/planning/context.ts","../src/modules/planning/stages/base.ts","../src/modules/planning/prompts/system.prompt.ts","../src/modules/planning/prompts/discovery.prompt.ts","../src/modules/planning/prompts/requirements.prompt.ts","../src/modules/planning/prompts/design.prompt.ts","../src/modules/planning/prompts/synthesis.prompt.ts","../src/modules/planning/prompts/edit.prompt.ts","../src/modules/planning/stages/discovery.stage.ts","../src/modules/planning/stages/discovery.state.ts","../src/modules/data-modeler/subagents/entity-analyzer.ts","../src/modules/data-modeler/subagents/relationship-mapper.ts","../src/modules/data-modeler/subagents/schema-refiner.ts","../src/modules/frontend-architect/subagents/page-planner.ts","../src/modules/frontend-architect/subagents/component-analyzer.ts","../src/modules/frontend-architect/subagents/framework-selector.ts","../src/modules/auth-designer/subagents/security-analyzer.ts","../src/modules/auth-designer/subagents/flow-designer.ts","../src/modules/planning/stages/requirements.stage.ts","../src/modules/planning/stages/requirements.state.ts","../src/modules/api-designer/subagents/endpoint-analyzer.ts","../src/modules/api-designer/subagents/contract-designer.ts","../src/modules/planning/stages/design.stage.ts","../src/modules/planning/stages/design.state.ts","../src/modules/planning/writer.ts","../src/modules/execution-planner/subagents/edge-case-analyzer.ts","../src/modules/execution-planner/subagents/testing-strategist.ts","../src/modules/planning/stages/synthesis.stage.ts","../src/modules/planning/stages/synthesis.state.ts","../src/modules/planning/stages/state-registry.ts","../src/modules/planning/router.ts","../src/modules/planning/chat.ts","../src/modules/planning/agent.ts","../src/modules/planning/edit-agent.ts","../src/modules/planning/from-requirements.ts","../src/modules/planning/context-builder.ts","../src/modules/requirement-gatherer/schemas/actor.schema.ts","../src/modules/requirement-gatherer/schemas/flow.schema.ts","../src/modules/requirement-gatherer/schemas/story.schema.ts","../src/modules/requirement-gatherer/schemas/module.schema.ts","../src/modules/requirement-gatherer/schemas/database.schema.ts","../src/modules/requirement-gatherer/schemas/context.schema.ts","../src/modules/requirement-gatherer/schemas/requirement.schema.ts","../src/modules/requirement-gatherer/prompts/system.prompt.ts","../src/modules/requirement-gatherer/prompts/discovery.prompt.ts","../src/modules/requirement-gatherer/prompts/requirements.prompt.ts","../src/modules/requirement-gatherer/prompts/design.prompt.ts","../src/modules/requirement-gatherer/prompts/synthesis.prompt.ts","../src/modules/requirement-gatherer/context.ts","../src/modules/requirement-gatherer/stages/base.ts","../src/modules/requirement-gatherer/stages/discovery.stage.ts","../src/modules/requirement-gatherer/stages/requirements-invoke.ts","../src/modules/requirement-gatherer/stages/requirements.stage.ts","../src/modules/requirement-gatherer/stages/design.stage.ts","../src/modules/requirement-gatherer/stages/synthesis.stage.ts","../src/modules/requirement-gatherer/stages/discovery.state.ts","../src/modules/requirement-gatherer/stages/requirements.state.ts","../src/modules/requirement-gatherer/stages/design.state.ts","../src/modules/requirement-gatherer/stages/synthesis.state.ts","../src/modules/requirement-gatherer/stages/state-registry.ts","../src/modules/requirement-gatherer/router.ts","../src/modules/requirement-gatherer/chat.ts","../src/modules/requirement-gatherer/agent.ts","../src/modules/requirement-gatherer/context-builder.ts","../src/modules/data-modeler/schemas/data-model.schema.ts","../src/modules/data-modeler/schemas/mongodb-field.schema.ts","../src/modules/data-modeler/schemas/mongodb-module.schema.ts","../src/modules/data-modeler/schemas/mongodb-project.schema.ts","../src/modules/data-modeler/prompts/system.prompt.ts","../src/modules/data-modeler/prompts/design.prompt.ts","../src/modules/data-modeler/prompts/pro-design.prompt.ts","../src/modules/data-modeler/prompts/mongodb-system.prompt.ts","../src/modules/data-modeler/prompts/mongodb-formatters.ts","../src/modules/data-modeler/prompts/mongodb-design.prompt.ts","../src/modules/data-modeler/prompts/mongodb-redesign.prompt.ts","../src/modules/data-modeler/tools/validate-schema.ts","../src/modules/data-modeler/tools/design-schema.ts","../src/modules/data-modeler/tools/design-schema-pro.ts","../src/modules/data-modeler/tools/refine-schema.ts","../src/modules/data-modeler/tools/validate-mongodb.ts","../src/modules/data-modeler/tools/design-mongodb.ts","../src/modules/data-modeler/tools/design-mongodb-pro.ts","../src/modules/data-modeler/tools/redesign-mongodb.ts","../src/modules/data-modeler/tools/index.ts","../src/modules/data-modeler/agent.ts","../src/modules/data-modeler/mongodb-agent.ts","../src/modules/api-designer/schemas/api-design.schema.ts","../src/modules/api-designer/prompts/system.prompt.ts","../src/modules/api-designer/prompts/design.prompt.ts","../src/modules/api-designer/tools/validate-api.ts","../src/modules/api-designer/tools/design-api.ts","../src/modules/api-designer/tools/design-api-pro.ts","../src/modules/api-designer/tools/index.ts","../src/modules/api-designer/agent.ts","../src/modules/auth-designer/schemas/auth-design.schema.ts","../src/modules/auth-designer/prompts/system.prompt.ts","../src/modules/auth-designer/prompts/design.prompt.ts","../src/modules/auth-designer/tools/validate-auth.ts","../src/modules/auth-designer/tools/design-auth.ts","../src/modules/auth-designer/tools/index.ts","../src/modules/auth-designer/agent.ts","../src/modules/backend-architect/schemas/backend-design.schema.ts","../src/modules/backend-architect/prompts/system.prompt.ts","../src/modules/backend-architect/prompts/design.prompt.ts","../src/modules/backend-architect/tools/validate-backend.ts","../src/modules/backend-architect/tools/design-backend.ts","../src/modules/backend-architect/tools/index.ts","../src/modules/backend-architect/subagents/service-planner.ts","../src/modules/backend-architect/subagents/framework-selector.ts","../src/modules/backend-architect/agent.ts","../src/modules/frontend-architect/schemas/frontend-design.schema.ts","../src/modules/frontend-architect/prompts/system.prompt.ts","../src/modules/frontend-architect/prompts/design.prompt.ts","../src/modules/frontend-architect/tools/validate-frontend.ts","../src/modules/frontend-architect/tools/design-frontend.ts","../src/modules/frontend-architect/tools/index.ts","../src/modules/frontend-architect/agent.ts","../src/modules/express-builder/schemas/express-config.schema.ts","../src/modules/express-builder/prompts/system.prompt.ts","../src/modules/express-builder/prompts/design.prompt.ts","../src/modules/express-builder/tools/validate-express.ts","../src/modules/express-builder/tools/generate-express.ts","../src/modules/express-builder/tools/scaffold-express.ts","../src/modules/express-builder/tools/index.ts","../src/modules/express-builder/subagents/route-generator.ts","../src/modules/express-builder/subagents/middleware-configurator.ts","../src/modules/express-builder/agent.ts","../src/modules/apollo-builder/schemas/subgraph-config.schema.ts","../src/modules/apollo-builder/prompts/system.prompt.ts","../src/modules/apollo-builder/prompts/design.prompt.ts","../src/modules/apollo-builder/tools/validate-subgraph.ts","../src/modules/apollo-builder/tools/generate-subgraph.ts","../src/modules/apollo-builder/tools/scaffold-subgraph.ts","../src/modules/apollo-builder/tools/index.ts","../src/modules/apollo-builder/subagents/schema-generator.ts","../src/modules/apollo-builder/subagents/resolver-planner.ts","../src/modules/apollo-builder/agent.ts","../src/modules/react-builder/schemas/branding.schema.ts","../src/modules/react-builder/schemas/app-config.schema.ts","../src/modules/react-builder/schemas/field.schema.ts","../src/modules/react-builder/schemas/page.schema.ts","../src/modules/react-builder/schemas/application.schema.ts","../src/modules/react-builder/schemas/user.schema.ts","../src/modules/react-builder/prompts/system.prompt.ts","../src/modules/react-builder/prompts/instruction.prompt.ts","../src/modules/react-builder/prompts/examples.prompt.ts","../src/modules/react-builder/prompts/feedback.prompt.ts","../src/modules/react-builder/tools/validate-frontend-config.tool.ts","../src/modules/react-builder/tools/generate-frontend.tool.ts","../src/modules/react-builder/tools/generate-feature-breakdown.tool.ts","../src/modules/react-builder/tools/scaffold-vite.ts","../src/modules/react-builder/tools/index.ts","../src/modules/react-builder/subagents/graphql-analyzer.subagent.ts","../src/modules/react-builder/subagents/config-validator.subagent.ts","../src/modules/react-builder/agent.ts","../src/modules/nextjs-builder/schemas/nextjs-config.schema.ts","../src/modules/nextjs-builder/prompts/system.prompt.ts","../src/modules/nextjs-builder/prompts/design.prompt.ts","../src/modules/nextjs-builder/tools/validate-nextjs.ts","../src/modules/nextjs-builder/tools/generate-nextjs.ts","../src/modules/nextjs-builder/tools/index.ts","../src/modules/nextjs-builder/subagents/route-planner.ts","../src/modules/nextjs-builder/subagents/api-route-generator.ts","../src/modules/nextjs-builder/agent.ts","../src/modules/execution-planner/schemas/execution-plan.schema.ts","../src/modules/execution-planner/prompts/system.prompt.ts","../src/modules/execution-planner/prompts/design.prompt.ts","../src/modules/execution-planner/tools/validate-plan.ts","../src/modules/execution-planner/tools/create-plan.ts","../src/modules/execution-planner/tools/index.ts","../src/modules/execution-planner/agent.ts","../src/modules/hello-world/tool.ts","../src/modules/hello-world/agent.ts","../src/modules/full-pipeline/steps.ts","../src/modules/full-pipeline/agent.ts","../src/lib/mcp/server/tool-registry.ts","../src/lib/mcp/server/types.ts","../src/lib/mcp/server/server.ts"],"names":["LibraryError","message","cause","ModelError","provider","ToolError","toolName","ValidationError","errors","AgentError","iteration","SubagentError","subagentName","extractJson","text","trimmed","codeBlock","parseModelJsonResponse","schema","jsonStr","parsed","err","preview","result","issues","i","safeJsonParse","label","NOOP_LOGGER","createLogger","config","name","level","pretty","file","stream","destination","streamFd","pinoLogger","pino","targets","transport","wrapPino","loggerConfigFromEnv","overrides","raw","enabledRaw","enabled","levelRaw","streamRaw","prettyRaw","p","msg","data","bindings","emptyDetails","emptyOutputDetails","sumTokenUsage","usages","inputTokens","outputTokens","totalTokens","usage","notifyObserversStep","observers","step","cumulativeUsage","o","notifyObserversTool","notifyObserversError","error","notifyObserversBudgetWarning","used","budget","toJsonSchema","z","_s","_d","rest","tool","description","inputSchema","execute","parameters","jsonSchema","defineTool","handler","args","e","createToolSet","tools","getTools","toolSet","getTool","executeTool","toolImpl","input","options","logger","out","executeToolByName","zodToJsonSchema","createValidationTool","inputParamName","store","key","runId","entries","propose","artifact","entry","getProposed","listProposed","finalize","discard","clearRun","createProposalTools","proposeOutputTool","finalizeOutputTool","listProposalsTool","reviewProposalTool","executeToolCalls","ctx","toolCalls","messages","onToolResult","responseText","assistantContent","tc","results","exec","outputVal","estimateTokens","value","serialized","estimateMessagesTokens","total","truncateText","limit","available","prefixLen","suffixLen","prefix","suffix","omitted","truncateToTokens","maxTokens","charLimit","USER_TEXT_LIMIT","ASSISTANT_TEXT_LIMIT","TOOL_ERROR_LIMIT","TOOL_RESULT_LIMIT","summarizeMessage","role","content","summarizeUserMessage","summarizeAssistantMessage","summarizeToolMessage","extractText","parts","part","summaries","outputType","summarizeMessages","keepRecentCount","toSummarize","kept","TOKEN_FUDGE_FACTOR","DEFAULT_MAX_CONTEXT_TOKENS","TARGET_SUMMARY_RATIO","KEEP_RECENT_COUNT","pruneContext","keepRecent","beforeTokens","systemMsg","conversationMsgs","summary","maxSummaryChars","truncatedSummary","summaryMessage","buildSummaryContent","newMessages","afterTokens","summaryText","runAgent","model","systemPrompt","maxIterations","onStep","maxContextTokens","tokenBudget","steps","cumulative","s","response","totalUsage","toolResults","output","runProgrammaticStep","opts","generator","resumeData","yielded","toolCall","toolResult","generateNResponses","n","invokeOptions","promises","responses","texts","r","t","runAgentWithSteps","handleSteps","stepPrompt","lastToolResult","stepsComplete","nResponses","action","stepAll","runLlmStep","selectByLength","bestIdx","selectByJudge","criteria","candidateList","idx","selectedIndex","messageToOpenAI","m","textParts","first","toolsToOpenAI","params","usageFromOpenAI","u","finishReasonFromOpenAI","createOpenAIModel","modelName","apiKey","baseUrl","client","OpenAI","openaiMessages","completion","choice","prompt","images","img","zodSchema","messageToAnthropic","blocks","buildAnthropicMessages","system","converted","toolsToAnthropic","usageFromAnthropic","finishReasonFromAnthropic","createAnthropicModel","Anthropic","anthropicMessages","b","messageToGeminiParts","buildGeminiContents","systemInstruction","contents","toolsToGemini","finishReasonFromGemini","createGoogleModel","GoogleGenAI","fc","usageResult","createModel","NAME_REGEX","defineSubagent","resolveTools","definition","parentTools","base","disallowed","filtered","resolveSystemPrompt","def","parentPrompt","runSubagent","parentModel","parentSystemPrompt","agentConfig","createSubagentTool","toolDesc","createSubagentToolSet","definitions","compileTemplate","template","context","Handlebars","findHbsFiles","dir","re","fullPath","me","toOutputPath","hbsRelPath","shouldSkip","relativePath","skipPatterns","pattern","scaffoldProject","templateDir","outputDir","hbsFiles","files","hbsFile","outputRelPath","inputPath","outputPath","templateSource","compiled","registerHelpers","a","obj","str","_","c","getSdkRoot","createRequire","path","sdkRoot","parseToolResult","createHttpTransport","url","headers","modPath","mod","pathToFileURL","requestInit","createStdioTransport","command","BaseMcpClient","info","resolveOpts","envPrefix","serverLabel","apiKeyHeader","argsEnv","Client","EMPTY_SECTIONS","createInitialContext","mergeStageResult","newSections","projectDescription","pendingQuestions","sections","v","addChatEntry","advanceStage","order","next","isConfirmation","normalized","PLANNING_SYSTEM_PROMPT","DISCOVERY_SYSTEM_FRAGMENT","DISCOVERY_USER_PROMPT","buildDiscoveryPrompt","userMessage","history","CONTEXT_BLOCK","REQUIREMENTS_OVERVIEW_PROMPT","REQUIREMENTS_FEATURE_DATA_PROMPT","buildRequirementsOverviewPrompt","buildRequirementsFeatureDataPrompt","overviewAndTechStack","DESIGN_CONTEXT","DESIGN_IMPLEMENTATION_PROMPT","buildDesignImplementationPrompt","priorSections","apiRoutes","SYNTHESIS_CONTEXT","SYNTHESIS_SYSTEM_FRAGMENT","SYNTHESIS_USER_PROMPT","buildSynthesisPrompt","EDIT_PLAN_SYSTEM_PROMPT","buildEditPlanPrompt","existingPlan","feedback","hasProjectOverview","lower","runDiscoveryStage","hasOverview","userConfirmed","forceAdvance","advance","storeDescription","DiscoveryState","ENTITY_ANALYZER_SYSTEM_PROMPT","entityAnalyzerSubagent","RELATIONSHIP_MAPPER_SYSTEM_PROMPT","relationshipMapperSubagent","SCHEMA_REFINER_SYSTEM_PROMPT","createSchemaRefinerSubagent","PAGE_PLANNER_SYSTEM_PROMPT","pagePlannerSubagent","COMPONENT_ANALYZER_SYSTEM_PROMPT","componentAnalyzerSubagent","FRAMEWORK_SELECTOR_SYSTEM_PROMPT","frameworkSelectorSubagent","SECURITY_ANALYZER_SYSTEM_PROMPT","securityAnalyzerSubagent","FLOW_DESIGNER_SYSTEM_PROMPT","flowDesignerSubagent","invokeMarkdown","userPrompt","splitOverviewAndTechStack","splitFeatureDecisionsAndDataModels","runRequirementsStage","_userMessage","part1","overview","techStack","part2","featureDecisions","dataModels","priorContext","pagesAndRoutes","fullContext","authFlow","RequirementsState","ENDPOINT_ANALYZER_SYSTEM_PROMPT","endpointAnalyzerSubagent","CONTRACT_DESIGNER_SYSTEM_PROMPT","contractDesignerSubagent","gatherPriorSections","runDesignStage","contractResult","implementation","DesignState","assemblePlan","projectName","writePlanToFile","markdown","writeFile","EDGE_CASE_ANALYZER_SYSTEM_PROMPT","edgeCaseAnalyzerSubagent","TESTING_STRATEGIST_SYSTEM_PROMPT","testingStrategistSubagent","gatherAllSections","extractProjectName","firstLine","match","runSynthesisStage","executionPlan","edgeCases","testingChecklist","fullSections","fullMarkdown","SynthesisState","states","getStateForStage","stage","runStage","merged","STAGE_ORDER","processPlanningChat","modelConfig","planMarkdown","runOne","runResult","nextStage","MAX_TURNS","runPlanningAgent","lastResult","turns","continueMsg","editPlan","revised","formatEntityFields","entity","f","flags","formatDatabaseAsMarkdown","db","header","entities","fields","relParts","relations","idxParts","indexes","formatModulesAsMarkdown","modules","apis","formatProjectOverview","req","features","formatTechStack","formatActorsContext","actors","flows","stories","actor","actorFlows","convertRequirementToContext","runPlanningFromRequirements","requirement","triggerMsg","DEFAULT_STAGE","PlanningContextBuilder","createPlanningContextBuilder","actorSchema","actorsResultSchema","flowSchema","flowsResultSchema","storySchema","storiesResultSchema","crudApiSchema","extractedModuleSchema","modulesResultSchema","entityFieldSchema","entityIndexSchema","entityRelationSchema","databaseEntitySchema","databaseDesignSchema","projectBriefSchema","questionSchema","chatEntrySchema","requirementContextSchema","requirementSummarySchema","finalRequirementSchema","REQUIREMENT_GATHERER_SYSTEM_PROMPT","PROJECT_BLOCK","EXTRACT_ACTORS_PROMPT","GENERATE_FLOWS_PROMPT","GENERATE_STORIES_PROMPT","EXTRACT_MODULES_PROMPT","buildExtractActorsPrompt","projectGoal","projectFeatures","buildGenerateFlowsPrompt","actorsJson","buildGenerateStoriesPrompt","flowsJson","buildExtractModulesPrompt","storiesJson","DESIGN_DB_PROMPT","DESIGN_DATABASE_SYSTEM_PROMPT","buildDesignDatabasePrompt","projectBrief","database","summarizeModules","summarizeStories","safeParseJson","needsClarification","questions","q","validated","pb","getActors","_logger","getFlows","_actors","getStories","_flows","getModules","_stories","brief","projectBriefStr","modulesSummary","storiesSummary","dbPrompt","dbMessages","dbResponse","dbJsonStr","dbParsed","databaseResult","finalRequirement","finalReq","processRequirementChat","runRequirementGathererAgent","RequirementContextBuilder","createRequirementContextBuilder","relationTypeSchema","dataEntitySchema","issue","dbTypeSchema","dataModelDesignSchema","mongoFieldSchema","mongoModuleSchema","mongoProjectSchema","DATA_MODELER_SYSTEM_PROMPT","DESIGN_SCHEMA_PROMPT","REFINE_SCHEMA_PROMPT","buildDesignSchemaPrompt","buildRefineSchemaPrompt","existingSchema","PRO_DESIGN_PROMPT","buildProDesignPrompt","databaseType","MONGODB_SYSTEM_PROMPT","formatUserTypes","goals","g","formatUserFlows","flow","formatUserStories","byFlow","arr","flowStories","story","pre","post","orphans","d","formatTechnicalRequirements","tech","lines","extractDataEntities","extractRoles","buildPromptVariables","createMongoDesignPrompt","createMongoProDesignPrompt","vars","createMongoRedesignPrompt","validateSchemaTool","createDesignSchemaTool","createDesignSchemaProTool","createRefineSchemaTools","validateMongoSchemaTool","createDesignDatabaseTool","structuredInputSchema","createDesignDatabaseProTool","dbDesign","metadata","createRedesignDatabaseTool","createDataModelerTools","createDbDesignerTools","ORCHESTRATOR_SYSTEM_PROMPT","runDataModelerAgent","schemaRefiner","subagentTools","allTools","runDbDesignerAgent","dbTools","httpMethodSchema","stringRecordSchema","k","stringOrObjectArraySchema","restEndpointSchema","graphqlOperationSchema","apiStyleSchema","apiDesignSchema","API_DESIGNER_SYSTEM_PROMPT","DESIGN_API_PROMPT","PRO_DESIGN_API_PROMPT","buildDesignApiPrompt","buildProDesignApiPrompt","apiStyle","dataModel","validateApiTool","createDesignApiTool","createDesignApiProTool","createApiDesignerTools","runApiDesignerAgent","authFlowStepSchema","authFlowSchema","authMiddlewareSchema","roleDefinitionSchema","securityPolicySchema","authDesignSchema","AUTH_DESIGNER_SYSTEM_PROMPT","DESIGN_AUTH_PROMPT","buildDesignAuthPrompt","validateAuthTool","createDesignAuthTool","createAuthDesignerTools","runAuthDesignerAgent","ciEnum","values","middlewareSchema","serviceSchema","routeGroupSchema","backendDesignSchema","BACKEND_ARCHITECT_SYSTEM_PROMPT","DESIGN_BACKEND_PROMPT","buildDesignBackendPrompt","validateBackendTool","createDesignBackendTool","createBackendArchitectTools","SERVICE_PLANNER_SYSTEM_PROMPT","servicePlannerSubagent","runBackendArchitectAgent","formFieldSchema","pageDesignSchema","componentDesignSchema","frontendDesignSchema","FRONTEND_ARCHITECT_SYSTEM_PROMPT","DESIGN_FRONTEND_PROMPT","buildDesignFrontendPrompt","validateFrontendTool","createDesignFrontendTool","createFrontendArchitectTools","reactBuilderSubagent","nextjsBuilderSubagent","runFrontendArchitectAgent","routerMethodSchema","routerSchema","modelFieldSchema","modelSchema","middlewareConfigSchema","expressConfigSchema","EXPRESS_BUILDER_SYSTEM_PROMPT","DESIGN_EXPRESS_PROMPT","buildDesignExpressPrompt","validateExpressTool","createGenerateExpressTool","toTemplateContext","scaffoldExpressTool","ri","createExpressBuilderTools","ROUTE_GENERATOR_SYSTEM_PROMPT","routeGeneratorSubagent","MIDDLEWARE_CONFIGURATOR_SYSTEM_PROMPT","middlewareConfiguratorSubagent","SCAFFOLD_STEP","buildOrchestratorPrompt","disableScaffold","runExpressBuilderAgent","graphqlFieldSchema","graphqlTypeSchema","resolverOperationSchema","subgraphModuleSchema","subgraphConfigSchema","APOLLO_BUILDER_SYSTEM_PROMPT","DESIGN_SUBGRAPH_PROMPT","buildDesignSubgraphPrompt","validateSubgraphTool","createGenerateSubgraphTool","scaffoldSubgraphTool","pi","createApolloBuilderTools","SCHEMA_GENERATOR_SYSTEM_PROMPT","schemaGeneratorSubagent","RESOLVER_PLANNER_SYSTEM_PROMPT","resolverPlannerSubagent","runApolloBuilderAgent","BrandingSchema","AppConfigSchema","ValidationSchema","FieldOptionsSchema","FormFieldSchema","ColumnSchema","ApiResponseTypeSchema","ListingPageApiSchema","AuthPageApiSchema","DrawerSchema","AuthPageSchema","ListingPageSchema","PageSchema","ModuleSchema","ApplicationSchema","LoginInputSchema","SpecializationSchema","UserSchema","CreateUserInputSchema","UpdateUserInputSchema","ForgotPasswordSchema","ResetPasswordSchema","REACT_BUILDER_SYSTEM_PROMPT","REACT_BUILDER_INSTRUCTION","buildInstructionPrompt","EXAMPLE_GRAPHQL_SCHEMA","EXAMPLE_JSON_OUTPUT","buildExampleShotPrompt","buildFeedbackPrompt","userFeedback","schemaFile","validateFrontendConfigTool","buildGeneratePrompt","graphqlSchema","appInfo","instruction","example","appInfoBlock","createGenerateFrontendTool","createGenerateFeatureBreakdownTool","scaffoldViteTool","Ti","createReactBuilderTools","GRAPHQL_ANALYZER_SYSTEM_PROMPT","graphqlAnalyzerSubagent","CONFIG_VALIDATOR_SYSTEM_PROMPT","createConfigValidatorSubagent","runReactBuilderAgent","reactTools","configValidator","nextjsPageSchema","nextjsLayoutSchema","nextjsApiRouteSchema","serverActionSchema","nextjsConfigSchema","NEXTJS_BUILDER_SYSTEM_PROMPT","DESIGN_NEXTJS_PROMPT","buildDesignNextjsPrompt","validateNextjsTool","createGenerateNextjsTool","createNextjsBuilderTools","ROUTE_PLANNER_SYSTEM_PROMPT","routePlannerSubagent","API_ROUTE_GENERATOR_SYSTEM_PROMPT","apiRouteGeneratorSubagent","runNextjsBuilderAgent","phaseStepSchema","implementationPhaseSchema","edgeCaseSchema","testChecklistItemSchema","executionPlanSchema","EXECUTION_PLANNER_SYSTEM_PROMPT","CREATE_EXECUTION_PLAN_PROMPT","buildCreateExecutionPlanPrompt","validateExecutionPlanTool","createExecutionPlanTool","createExecutionPlannerTools","runExecutionPlannerAgent","helloWorldTool","DEFAULT_SYSTEM_PROMPT","runHelloWorldAgent","agentCfg","cfg","PIPELINE_STEPS","log","assembleOutput","runFullPipelineAgent","stepCfg","outputs","stepOutput","runner","TOOL_REGISTRY","findTool","AGENT_TOOL_INPUT_SHAPE","buildModelConfig","SERVER_NAME","SERVER_VERSION","MAX_PREVIEW","createStepLogger","createSweagentServer","server","McpServer"],"mappings":"0nCAOO,IAAMA,EAAAA,CAAN,cAA2B,KAAM,CACtC,WAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAAe,CAC1C,KAAA,CAAMD,CAAAA,CAASC,CAAAA,GAAU,MAAA,CAAY,MAAA,CAAY,CAAE,KAAA,CAAAA,CAAM,CAAC,CAAA,CAC1D,IAAA,CAAK,IAAA,CAAO,cAAA,CACRA,CAAAA,EAAO,KAAA,GACT,IAAA,CAAK,KAAA,CAAQ,CAAA,EAAG,IAAA,CAAK,KAAK;AAAA,WAAA,EAAgBA,CAAAA,CAAM,KAAK,CAAA,CAAA,EAEzD,CACF,EAKaC,CAAAA,CAAN,cAAyBH,EAAa,CAC3C,WAAA,CACEC,CAAAA,CACgBG,EAChBF,CAAAA,CACA,CACA,MAAMD,CAAAA,CAASC,CAAK,EAHJ,IAAA,CAAA,QAAA,CAAAE,CAAAA,CAIhB,IAAA,CAAK,IAAA,CAAO,aACd,CACF,EAKaC,CAAAA,CAAN,cAAwBL,EAAa,CAC1C,WAAA,CACEC,EACgBK,CAAAA,CAChBJ,CAAAA,CACA,CACA,KAAA,CAAMD,CAAAA,CAASC,C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AAMpB,EAAUoB,CAAAA,YAAe,KAAA,CAAQA,EAAI,OAAA,CAAU,MAAA,CAAOA,CAAG,CAAA,CAC/D,OAAAwyB,EAAAA,CAAI,GAAG/sB,CAAAA,CAAM,IAAI,kBAAa7G,CAAO,CAAA,CAAE,EAChC,CAAE,OAAA,CAAS,CAAC,CAAE,IAAA,CAAM,MAAA,CAAiB,KAAMA,CAAQ,CAAC,EAAG,OAAA,CAAS,IAAK,CAC9E,CACF,CACF,CAAA,CAGF,OAAO40B,CACT","file":"index.cjs","sourcesContent":["/**\n * Custom error classes for the library\n */\n\n/**\n * Base error class for all library errors\n */\nexport class LibraryError extends Error {\n constructor(message: string, cause?: Error) {\n super(message, cause === undefined ? undefined : { cause });\n this.name = 'LibraryError';\n if (cause?.stack) {\n this.stack = `${this.stack}\\nCaused by: ${cause.stack}`;\n }\n }\n}\n\n/**\n * Error thrown when model operations fail\n */\nexport class ModelError extends LibraryError {\n constructor(\n message: string,\n public readonly provider?: string,\n cause?: Error\n ) {\n super(message, cause);\n this.name = 'ModelError';\n }\n}\n\n/**\n * Error thrown when tool execution fails\n */\nexport class ToolError extends LibraryError {\n constructor(\n message: string,\n public readonly toolName?: string,\n cause?: Error\n ) {\n super(message, cause);\n this.name = 'ToolError';\n }\n}\n\n/**\n * Error thrown when tool input validation fails\n */\nexport class ValidationError extends LibraryError {\n constructor(\n message: string,\n public readonly errors?: unknown[]\n ) {\n super(message);\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Error thrown when agent execution fails\n */\nexport class AgentError extends LibraryError {\n constructor(\n message: string,\n public readonly iteration?: number,\n cause?: Error\n ) {\n super(message, cause);\n this.name = 'AgentError';\n }\n}\n\n/**\n * Error thrown when subagent execution fails\n */\nexport class SubagentError extends LibraryError {\n constructor(\n message: string,\n public readonly subagentName?: string,\n cause?: Error\n ) {\n super(message, cause);\n this.name = 'SubagentError';\n }\n}\n","/**\n * Shared utilities for extracting and parsing JSON from model responses.\n *\n * Models frequently wrap JSON in markdown code blocks or include extra text.\n * These helpers handle extraction, parsing, and Zod validation with clear errors\n * so the agent can retry on failure.\n */\n\nimport type { z } from 'zod';\n\n/**\n * Extract a JSON string from model output.\n * Handles markdown code blocks (```json ... ``` or ``` ... ```) and bare JSON.\n */\nexport function extractJson(text: string): string {\n const trimmed = text.trim();\n const codeBlock = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n if (codeBlock?.[1]) return codeBlock[1].trim();\n return trimmed;\n}\n\n/**\n * Parse a model text response as JSON then validate with a Zod schema.\n * Throws a descriptive error on failure (JSON syntax or validation) so the\n * wrapping ToolError gives the agent enough context to retry.\n */\nexport function parseModelJsonResponse<T>(text: string, schema: z.ZodType<T>): T {\n const jsonStr = extractJson(text);\n let parsed: unknown;\n try {\n parsed = JSON.parse(jsonStr);\n } catch (err) {\n const preview = jsonStr.length > 300 ? jsonStr.slice(0, 300) + '...' : jsonStr;\n throw new Error(\n `Failed to parse model response as JSON: ${err instanceof Error ? err.message : String(err)}. Preview: ${preview}`\n );\n }\n const result = schema.safeParse(parsed);\n if (!result.success) {\n const issues = result.error.issues\n .slice(0, 5)\n .map(i => ` ${i.path.join('.')}: ${i.message}`)\n .join('\\n');\n throw new Error(`Model JSON does not match expected schema:\\n${issues}`);\n }\n return result.data;\n}\n\n/**\n * Parse a raw JSON string (e.g. tool input) with a descriptive error on failure.\n */\nexport function safeJsonParse(jsonStr: string, label?: string): unknown {\n try {\n return JSON.parse(jsonStr) as unknown;\n } catch (err) {\n const preview = jsonStr.length > 200 ? jsonStr.slice(0, 200) + '...' : jsonStr;\n throw new Error(\n `Invalid JSON${label ? ` for ${label}` : ''}: ${err instanceof Error ? err.message : String(err)}. Preview: ${preview}`\n );\n }\n}\n","/**\n * Structured logger using Pino (JSON by default, optional pretty/file).\n * Use loggerConfigFromEnv() for .env-driven config (SWE_LOG_* vars).\n */\n\nimport pino from 'pino';\nimport type { Logger } from '../types/common';\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nexport interface LoggerConfig {\n /** Logger name (appears in logs) */\n name?: string;\n /** Minimum log level */\n level?: LogLevel;\n /** Use pino-pretty for readable output */\n pretty?: boolean;\n /** File path for JSON logs */\n file?: string;\n /** Console stream: stderr avoids mixing with stdout prompts (e.g. inquirer). Default: stderr when pretty, else stdout. */\n stream?: 'stdout' | 'stderr';\n /** When false, returns a no-op logger (no output). Set via SWE_LOG_ENABLED=0. */\n enabled?: boolean;\n /** Optional stream for testing (bypasses transport) */\n destination?: pino.DestinationStream;\n}\n\nconst NOOP_LOGGER: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n child: () => NOOP_LOGGER,\n};\n\nexport function createLogger(config: LoggerConfig = {}): Logger {\n if (config.enabled === false) {\n return NOOP_LOGGER;\n }\n\n const { name, level = 'info', pretty = false, file, stream, destination } = config;\n\n const streamFd = stream === 'stderr' ? 2 : stream === 'stdout' ? 1 : pretty ? 2 : 1;\n\n let pinoLogger: pino.Logger;\n\n if (destination) {\n pinoLogger = pino({ name, level }, destination);\n } else {\n const targets: pino.TransportTargetOptions[] = [];\n\n if (pretty) {\n targets.push({\n target: 'pino-pretty',\n options: {\n colorize: true,\n destination: streamFd,\n singleLine: true,\n ignore: 'time,pid,hostname',\n translateTime: false,\n },\n level,\n });\n } else {\n targets.push({\n target: 'pino/file',\n options: { destination: streamFd },\n level,\n });\n }\n\n if (file) {\n targets.push({\n target: 'pino/file',\n options: { destination: file, mkdir: true },\n level,\n });\n }\n\n const transport = pino.transport({ targets }) as pino.DestinationStream;\n pinoLogger = pino({ name, level }, transport);\n }\n\n return wrapPino(pinoLogger);\n}\n\n/**\n * Build logger config from process.env (SWE_* vars). Caller loads .env if desired (e.g. dotenv or `node --env-file=.env`).\n *\n * Env vars (all optional):\n * - SWE_LOG_ENABLED: 1|true|yes (default) = on; 0|false|no|disabled = off (no-op logger).\n * - SWE_LOG_LEVEL: debug|info|warn|error (default: info).\n * - SWE_LOG_STREAM: stdout|stderr; default stderr when SWE_LOG_PRETTY is true, else stdout.\n * - SWE_LOG_PRETTY: 1|true|yes = human-readable (pino-pretty); 0|false (default) = JSON.\n * - SWE_LOG_FILE: path to also write JSON logs to a file.\n * - SWE_LOG_NAME: logger name in output.\n *\n * For interactive CLIs (e.g. inquirer), use pretty and stderr so logs do not mix with stdout prompts.\n */\nexport function loggerConfigFromEnv(overrides: Partial<LoggerConfig> = {}): LoggerConfig {\n const raw = process.env;\n const enabledRaw = (raw.SWE_LOG_ENABLED ?? 'true').trim().toLowerCase();\n const enabled =\n enabledRaw !== '0' &&\n enabledRaw !== 'false' &&\n enabledRaw !== 'no' &&\n enabledRaw !== 'disabled';\n\n const levelRaw = (raw.SWE_LOG_LEVEL ?? 'info').trim().toLowerCase();\n const level: LogLevel =\n levelRaw === 'debug' || levelRaw === 'info' || levelRaw === 'warn' || levelRaw === 'error'\n ? levelRaw\n : 'info';\n\n const streamRaw = (raw.SWE_LOG_STREAM ?? '').trim().toLowerCase();\n const prettyRaw = (raw.SWE_LOG_PRETTY ?? '0').trim().toLowerCase();\n const pretty = prettyRaw === '1' || prettyRaw === 'true' || prettyRaw === 'yes';\n const stream: 'stdout' | 'stderr' =\n streamRaw === 'stdout'\n ? 'stdout'\n : streamRaw === 'stderr'\n ? 'stderr'\n : pretty\n ? 'stderr'\n : 'stdout';\n\n const file = raw.SWE_LOG_FILE?.trim() || undefined;\n const name = raw.SWE_LOG_NAME?.trim() || undefined;\n\n return {\n enabled,\n level,\n stream,\n pretty,\n ...(file && { file }),\n ...(name && { name }),\n ...overrides,\n };\n}\n\nfunction wrapPino(p: pino.Logger): Logger {\n return {\n debug: (msg, data) => {\n p.debug(data ?? {}, msg);\n },\n info: (msg, data) => {\n p.info(data ?? {}, msg);\n },\n warn: (msg, data) => {\n p.warn(data ?? {}, msg);\n },\n error: (msg, err) => {\n if (err instanceof Error) {\n p.error({ err }, msg);\n } else {\n p.error(err ?? {}, msg);\n }\n },\n child: (bindings: Record<string, unknown>) => wrapPino(p.child(bindings as pino.Bindings)),\n };\n}\n","/**\n * Utility functions\n */\n\nimport type { LanguageModelUsage } from '../types/ai-types';\n\nconst emptyDetails = {\n noCacheTokens: undefined as number | undefined,\n cacheReadTokens: undefined as number | undefined,\n cacheWriteTokens: undefined as number | undefined,\n};\nconst emptyOutputDetails = {\n textTokens: undefined as number | undefined,\n reasoningTokens: undefined as number | undefined,\n};\n\n/**\n * Sum token usage from multiple steps (AI SDK LanguageModelUsage)\n */\nexport function sumTokenUsage(usages: (LanguageModelUsage | undefined)[]): LanguageModelUsage {\n let inputTokens = 0;\n let outputTokens = 0;\n let totalTokens = 0;\n\n for (const usage of usages) {\n if (usage) {\n inputTokens += usage.inputTokens ?? 0;\n outputTokens += usage.outputTokens ?? 0;\n totalTokens += usage.totalTokens ?? 0;\n }\n }\n\n return {\n inputTokens,\n outputTokens,\n totalTokens,\n inputTokenDetails: emptyDetails,\n outputTokenDetails: emptyOutputDetails,\n };\n}\n","/**\n * Notify agent observers (step, tool, error, budget).\n */\n\nimport type { AgentObserver, AgentStep } from '../types/agent';\nimport type { LanguageModelUsage } from '../types/model';\n\nexport function notifyObserversStep(\n observers: AgentObserver[] | undefined,\n step: AgentStep,\n cumulativeUsage?: LanguageModelUsage\n): void {\n observers?.forEach(o => o.onStep?.(step, cumulativeUsage));\n}\n\nexport function notifyObserversTool(\n observers: AgentObserver[] | undefined,\n toolName: string,\n result: unknown\n): void {\n observers?.forEach(o => o.onToolExecution?.(toolName, result));\n}\n\nexport function notifyObserversError(observers: AgentObserver[] | undefined, error: Error): void {\n observers?.forEach(o => o.onError?.(error));\n}\n\nexport function notifyObserversBudgetWarning(\n observers: AgentObserver[] | undefined,\n used: number,\n budget: number\n): void {\n observers?.forEach(o => o.onTokenBudgetWarning?.(used, budget));\n}\n","/**\n * Tool-related types and helpers\n * Exports Tool, tool(), jsonSchema, ToolExecutionOptions; keeps ToolConfig and ToolContext for defineTool\n */\n\nimport { z } from 'zod';\nimport type { Tool as ToolType, ToolConfigInput } from './ai-types';\n\nexport type { Tool, ToolExecutionOptions } from './ai-types';\n\nfunction toJsonSchema(schema: z.ZodType): Record<string, unknown> {\n const result = z.toJSONSchema(schema) as Record<string, unknown> & {\n $schema?: string;\n definitions?: unknown;\n };\n const { $schema: _s, definitions: _d, ...rest } = result;\n return rest as Record<string, unknown>;\n}\n\n/**\n * Create a tool from description, inputSchema (Zod), and optional execute.\n * Used by defineTool; adapters use description + parameters (JSON Schema) for provider APIs.\n */\nexport function tool<TInput = unknown, TOutput = unknown>(\n config: ToolConfigInput & { inputSchema: z.ZodType<TInput> }\n): ToolType<TInput, TOutput> {\n const { description, inputSchema, execute } = config;\n const parameters = toJsonSchema(inputSchema);\n return {\n description,\n inputSchema,\n parameters,\n execute: execute as ToolType<TInput, TOutput>['execute'],\n };\n}\n\n/**\n * Wrap a Zod schema for structured output (e.g. invokeObject).\n * Returns an object adapters can use to request JSON matching the schema.\n */\nexport function jsonSchema<T>(schema: z.ZodType<T>): {\n schema: z.ZodType<T>;\n jsonSchema: Record<string, unknown>;\n} {\n return {\n schema,\n jsonSchema: toJsonSchema(schema),\n };\n}\n\n/**\n * Configuration for defining a tool (input to defineTool)\n */\nexport interface ToolConfig<TInput extends z.ZodType = z.ZodType, TOutput = unknown> {\n /** Unique name for the tool */\n name: string;\n /** Description of what the tool does */\n description: string;\n /** Zod schema for input validation */\n input: TInput;\n /** The handler function that executes the tool */\n handler: (input: z.infer<TInput>, context?: ToolContext) => Promise<TOutput>;\n}\n\n/**\n * Logger interface for tool context\n */\nexport interface ToolLogger {\n debug(message: string, data?: Record<string, unknown>): void;\n info(message: string, data?: Record<string, unknown>): void;\n warn(message: string, data?: Record<string, unknown>): void;\n error(message: string, error?: Error | Record<string, unknown>): void;\n}\n\n/**\n * Context passed to tool handlers\n */\nexport interface ToolContext {\n /** Optional model for tools that need AI capabilities */\n model?: { invoke: (...args: unknown[]) => Promise<unknown> };\n /** Optional logger */\n logger?: ToolLogger;\n /** Additional custom context */\n [key: string]: unknown;\n}\n\n/**\n * Result of tool execution (for executeTool / executeToolByName)\n */\nexport interface ToolExecutionResult<T = unknown> {\n success: boolean;\n output?: T;\n error?: string;\n}\n","/**\n * Tools: defineTool, createToolSet, execute, zodToJsonSchema\n */\n\nimport { z } from 'zod';\nimport { tool } from '../types/tool';\nimport type { Tool, ToolExecutionOptions } from '../types/tool';\nimport type { Logger } from '../types/common';\nimport type { ToolConfig, ToolContext, ToolExecutionResult } from '../types/tool';\nimport { ToolError } from '../utils/errors';\n\n/** Tool has description (and optional title) in config; name is the key in createToolSet. */\nexport function defineTool<TInput extends z.ZodType, TOutput>(\n config: ToolConfig<TInput, TOutput>\n): Tool {\n const { name, description, input: inputSchema, handler } = config;\n return tool({\n description,\n inputSchema,\n execute: async (args: unknown): Promise<TOutput> => {\n const parsed = inputSchema.safeParse(args);\n if (!parsed.success)\n throw new ToolError(`Invalid input: ${parsed.error.message}`, name, parsed.error);\n try {\n return await handler(parsed.data as z.infer<TInput>, undefined as ToolContext | undefined);\n } catch (e) {\n if (e instanceof ToolError) throw e;\n throw new ToolError(\n `Tool \"${name}\" failed: ${e instanceof Error ? e.message : String(e)}`,\n name,\n e instanceof Error ? e : undefined\n );\n }\n },\n });\n}\n\nexport type ToolSet = Record<string, Tool>;\n\n/** Pass a record: key = tool name (same as in defineTool config). */\nexport function createToolSet(tools: ToolSet): ToolSet {\n return tools;\n}\n\nexport function getTools(toolSet: ToolSet): Tool[] {\n return Object.values(toolSet);\n}\n\nexport function getTool(toolSet: ToolSet, name: string): Tool | undefined {\n return toolSet[name];\n}\n\nexport interface ExecuteToolOptions {\n toolCallId?: string;\n abortSignal?: AbortSignal;\n logger?: Logger;\n}\n\nexport async function executeTool<TInput, TOutput>(\n toolImpl: Tool<TInput, TOutput>,\n input: TInput,\n options?: ExecuteToolOptions & { toolName?: string }\n): Promise<ToolExecutionResult<TOutput>> {\n const { logger } = options ?? {};\n const toolName =\n options?.toolName ??\n ('name' in toolImpl && typeof toolImpl.name === 'string' ? toolImpl.name : 'unknown');\n\n if (!toolImpl.execute) {\n logger?.error('Tool has no execute function', { toolName });\n return { success: false, error: 'Tool has no execute function' };\n }\n logger?.debug('Executing tool', { toolName, toolCallId: options?.toolCallId });\n try {\n const out = await toolImpl.execute(input, {\n toolCallId: options?.toolCallId ?? '',\n messages: [],\n abortSignal: options?.abortSignal,\n } as ToolExecutionOptions);\n logger?.info('Tool completed', { toolName, toolCallId: options?.toolCallId });\n return { success: true, output: out as TOutput };\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n logger?.error('Tool failed', {\n toolName,\n toolCallId: options?.toolCallId,\n error: msg,\n });\n return { success: false, error: msg };\n }\n}\n\nexport async function executeToolByName(\n tools: ToolSet,\n name: string,\n input: unknown,\n options?: ExecuteToolOptions\n): Promise<ToolExecutionResult> {\n const toolImpl = tools[name];\n if (!toolImpl) {\n options?.logger?.error('Tool not found', {\n name,\n availableTools: Object.keys(tools),\n });\n throw new ToolError(`Tool not found: ${name}`);\n }\n return executeTool(toolImpl, input, { ...options, toolName: name });\n}\n\nexport type JsonSchemaObject = Record<string, unknown>;\n\nexport function zodToJsonSchema(schema: z.ZodType): JsonSchemaObject {\n const result = z.toJSONSchema(schema) as JsonSchemaObject & {\n $schema?: string;\n definitions?: unknown;\n };\n const { $schema: _s, definitions: _d, ...rest } = result;\n return rest as JsonSchemaObject;\n}\n","/**\n * Shared validation tool factory - generates a validate_* tool from a Zod schema.\n * Eliminates boilerplate across modules that all follow the same pattern.\n */\n\nimport { z } from 'zod';\nimport type { Tool } from '../types/tool';\nimport { defineTool } from './tools';\n\nexport interface ValidationResult {\n valid: boolean;\n errors?: string[];\n}\n\n/**\n * Create a validation tool that parses JSON input against a Zod schema.\n * Every module can replace its hand-written validate_* tool with this one-liner.\n *\n * @param name - Tool name (e.g. 'validate_schema', 'validate_api')\n * @param schema - Zod schema to validate against\n * @param description - Tool description for the agent\n * @param inputParamName - Name of the input parameter (default: 'json')\n */\nexport function createValidationTool(\n name: string,\n schema: z.ZodType,\n description: string,\n inputParamName = 'json'\n): Tool {\n return defineTool({\n name,\n description,\n input: z.object({\n [inputParamName]: z.string().describe('JSON string to validate'),\n }),\n handler: async (args: Record<string, string>): Promise<ValidationResult> => {\n const raw = args[inputParamName] ?? '';\n try {\n const parsed = JSON.parse(raw) as unknown;\n schema.parse(parsed);\n return { valid: true };\n } catch (err) {\n if (err instanceof z.ZodError) {\n return {\n valid: false,\n errors: err.issues.map(e => `${e.path.join('.')}: ${e.message}`),\n };\n }\n if (err instanceof SyntaxError) {\n return { valid: false, errors: [`Invalid JSON: ${err.message}`] };\n }\n return { valid: false, errors: [String(err)] };\n }\n },\n });\n}\n","/**\n * In-memory store for proposed outputs before finalization.\n * Adapted from redxpilot's proposed-content-store.\n *\n * Keyed by runId + artifact name so multiple proposals can coexist.\n * Consumers call propose() to store a draft, then finalize() to commit it.\n */\n\nexport interface ProposedEntry<T = unknown> {\n artifact: string;\n data: T;\n proposedAt: number;\n}\n\nconst store = new Map<string, Map<string, ProposedEntry>>();\n\nfunction key(runId: string): Map<string, ProposedEntry> {\n let entries = store.get(runId);\n if (!entries) {\n entries = new Map();\n store.set(runId, entries);\n }\n return entries;\n}\n\n/**\n * Store a proposed artifact for later review/finalization.\n */\nexport function propose<T>(runId: string, artifact: string, data: T): ProposedEntry<T> {\n const entry: ProposedEntry<T> = { artifact, data, proposedAt: Date.now() };\n key(runId).set(artifact, entry as ProposedEntry);\n return entry;\n}\n\n/**\n * Retrieve a proposed artifact (returns undefined if not found).\n */\nexport function getProposed<T = unknown>(\n runId: string,\n artifact: string\n): ProposedEntry<T> | undefined {\n return key(runId).get(artifact) as ProposedEntry<T> | undefined;\n}\n\n/**\n * List all proposed artifacts for a run.\n */\nexport function listProposed(runId: string): ProposedEntry[] {\n return Array.from(key(runId).values());\n}\n\n/**\n * Finalize: remove from proposed store and return the data.\n * Returns undefined if not found.\n */\nexport function finalize(runId: string, artifact: string): unknown | undefined {\n const entries = key(runId);\n const entry = entries.get(artifact);\n if (entry) entries.delete(artifact);\n return entry?.data;\n}\n\n/**\n * Discard a proposal without finalizing.\n */\nexport function discard(runId: string, artifact: string): boolean {\n return key(runId).delete(artifact);\n}\n\n/**\n * Clear all proposals for a run (cleanup after run completes).\n */\nexport function clearRun(runId: string): void {\n store.delete(runId);\n}\n","/**\n * Propose-before-finalize tools: propose_output and finalize_output.\n * Adapted from redxpilot's propose_str_replace / propose_write_file pattern.\n *\n * Agents produce a proposed artifact, review it, then finalize.\n */\n\nimport { z } from 'zod';\nimport type { Tool } from '../types/tool';\nimport { defineTool } from './tools';\nimport { propose, finalize, getProposed, listProposed } from '../stores/proposed-store';\n\n/**\n * Create the propose/finalize tool pair for a given run.\n * Returns a record with `propose_output`, `finalize_output`, and `list_proposals`.\n */\nexport function createProposalTools(runId: string): Record<string, Tool> {\n const proposeOutputTool = defineTool({\n name: 'propose_output',\n description: 'Propose an output artifact for review before finalizing. Returns the proposal.',\n input: z.object({\n artifact: z.string().describe('Name/key for this artifact (e.g. \"data-model\", \"api-spec\")'),\n data: z.any().describe('The proposed content (JSON, string, etc.)'),\n }),\n handler: async ({ artifact, data }) => {\n const entry = propose(runId, artifact, data);\n return {\n status: 'proposed',\n artifact: entry.artifact,\n proposedAt: entry.proposedAt,\n preview: typeof data === 'string' ? data.slice(0, 500) : JSON.stringify(data).slice(0, 500),\n };\n },\n });\n\n const finalizeOutputTool = defineTool({\n name: 'finalize_output',\n description: 'Finalize a previously proposed artifact, committing it as the final output.',\n input: z.object({\n artifact: z.string().describe('The artifact name to finalize'),\n }),\n handler: async ({ artifact }) => {\n const data = finalize(runId, artifact);\n if (data === undefined) {\n return { status: 'error', message: `No proposal found for \"${artifact}\"` };\n }\n return { status: 'finalized', artifact, data };\n },\n });\n\n const listProposalsTool = defineTool({\n name: 'list_proposals',\n description: 'List all pending proposed artifacts for the current run.',\n input: z.object({}),\n handler: async () => {\n const proposals = listProposed(runId);\n return proposals.map(p => ({\n artifact: p.artifact,\n proposedAt: p.proposedAt,\n preview:\n typeof p.data === 'string' ? p.data.slice(0, 200) : JSON.stringify(p.data).slice(0, 200),\n }));\n },\n });\n\n const reviewProposalTool = defineTool({\n name: 'review_proposal',\n description: 'View the full content of a proposed artifact for review.',\n input: z.object({\n artifact: z.string().describe('The artifact name to review'),\n }),\n handler: async ({ artifact }) => {\n const entry = getProposed(runId, artifact);\n if (!entry) {\n return { status: 'error', message: `No proposal found for \"${artifact}\"` };\n }\n return { status: 'found', artifact: entry.artifact, data: entry.data };\n },\n });\n\n return {\n propose_output: proposeOutputTool,\n finalize_output: finalizeOutputTool,\n list_proposals: listProposalsTool,\n review_proposal: reviewProposalTool,\n };\n}\n","/**\n * Execute tool calls from a model response and build AI SDK messages.\n * Extracted from agent.ts to keep files under 150 lines.\n */\n\nimport type { AgentToolResult } from '../types/agent';\nimport type { ModelMessage } from '../types/common';\nimport type { ModelToolCall } from '../types/model';\nimport type { Logger } from '../types/common';\nimport type { ToolSet } from '../tools';\nimport { executeToolByName } from '../tools';\n\nexport interface ToolExecutionContext {\n tools: ToolSet;\n toolCalls: ModelToolCall[];\n messages: ModelMessage[];\n logger?: Logger;\n onToolResult?: (toolName: string, output: unknown) => void;\n /** Optional text from the same model response, merged into the assistant message */\n responseText?: string;\n}\n\n/**\n * Execute all tool calls, push assistant + tool messages, and return results.\n */\nexport async function executeToolCalls(ctx: ToolExecutionContext): Promise<AgentToolResult[]> {\n const { tools, toolCalls, messages, logger, onToolResult, responseText } = ctx;\n\n const assistantContent = [\n ...(responseText ? [{ type: 'text' as const, text: responseText }] : []),\n ...toolCalls.map((tc: ModelToolCall) => ({\n type: 'tool-call' as const,\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n input: tc.input,\n })),\n ];\n messages.push({ role: 'assistant', content: assistantContent });\n\n const results: AgentToolResult[] = [];\n\n for (const tc of toolCalls) {\n const exec = await executeToolByName(tools, tc.toolName, tc.input, {\n toolCallId: tc.toolCallId,\n logger,\n });\n\n const result: AgentToolResult = {\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n output: exec.success ? exec.output : exec.error,\n isError: !exec.success,\n };\n results.push(result);\n onToolResult?.(tc.toolName, result.output);\n\n const outputVal = result.isError\n ? { type: 'error-text' as const, value: String(result.output) }\n : {\n type: 'text' as const,\n value: typeof result.output === 'string' ? result.output : JSON.stringify(result.output),\n };\n\n messages.push({\n role: 'tool',\n content: [\n {\n type: 'tool-result' as const,\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n output: outputVal,\n },\n ],\n });\n }\n\n return results;\n}\n","/**\n * Token estimation utilities.\n * Adapted from redxpilot's context-pruner: approximate token count\n * from JSON-serialized length (1 token ≈ 3 characters).\n */\n\nconst CHARS_PER_TOKEN = 3;\n\n/**\n * Estimate the number of tokens in an arbitrary value by serializing to JSON.\n * Useful for budget checks without calling a tokenizer.\n */\nexport function estimateTokens(value: unknown): number {\n if (value === undefined || value === null) return 0;\n const serialized = typeof value === 'string' ? value : JSON.stringify(value);\n return Math.ceil(serialized.length / CHARS_PER_TOKEN);\n}\n\n/**\n * Estimate total tokens in a message array (the main context window).\n */\nexport function estimateMessagesTokens(messages: unknown[]): number {\n let total = 0;\n for (const msg of messages) {\n total += estimateTokens(msg);\n }\n return total;\n}\n","/**\n * Text truncation utilities.\n * Adapted from redxpilot's context-pruner: 80/20 truncation preserves\n * the beginning (most context) and end (most recent) of long text.\n */\n\nconst TRUNCATION_OVERHEAD = 50;\nconst PREFIX_RATIO = 0.8;\n\n/**\n * Truncate text that exceeds `limit` characters.\n * Keeps 80% from the start and 20% from the end, with a marker in between.\n */\nexport function truncateText(text: string, limit: number): string {\n if (text.length <= limit) return text;\n\n const available = limit - TRUNCATION_OVERHEAD;\n if (available <= 0) return text.slice(0, limit);\n\n const prefixLen = Math.floor(available * PREFIX_RATIO);\n const suffixLen = available - prefixLen;\n const prefix = text.slice(0, prefixLen);\n const suffix = text.slice(-suffixLen);\n const omitted = text.length - prefixLen - suffixLen;\n\n return `${prefix}\\n\\n[...truncated ${omitted} chars...]\\n\\n${suffix}`;\n}\n\n/**\n * Truncate text to a target token count (approximate).\n * Converts token limit to a character limit and delegates to truncateText.\n */\nexport function truncateToTokens(text: string, maxTokens: number): string {\n const charLimit = maxTokens * 3;\n return truncateText(text, charLimit);\n}\n","/**\n * Rule-based message summarization.\n * Adapted from redxpilot's context-pruner: deterministic summarization\n * per message role, keeping errors and key tool results.\n */\n\nimport type { ModelMessage } from '../types/common';\nimport { truncateText } from './text-truncator';\n\nconst USER_TEXT_LIMIT = 15_000;\nconst ASSISTANT_TEXT_LIMIT = 4_000;\nconst TOOL_ERROR_LIMIT = 200;\nconst TOOL_RESULT_LIMIT = 2_000;\n\ninterface ContentPart {\n type: string;\n text?: string;\n toolName?: string;\n toolCallId?: string;\n input?: unknown;\n output?: { type?: string; value?: string };\n}\n\n/**\n * Summarize a single message based on its role.\n * Returns a plain-text summary string.\n */\nexport function summarizeMessage(message: ModelMessage): string {\n const role = (message as { role: string }).role;\n const content = (message as { content: unknown }).content;\n\n switch (role) {\n case 'system':\n return '[SYSTEM] (preserved)';\n case 'user':\n return summarizeUserMessage(content);\n case 'assistant':\n return summarizeAssistantMessage(content);\n case 'tool':\n return summarizeToolMessage(content);\n default:\n return `[${role.toUpperCase()}]`;\n }\n}\n\nfunction summarizeUserMessage(content: unknown): string {\n const text = extractText(content);\n return `[USER] ${truncateText(text, USER_TEXT_LIMIT)}`;\n}\n\nfunction summarizeAssistantMessage(content: unknown): string {\n if (typeof content === 'string') {\n return `[ASSISTANT] ${truncateText(content, ASSISTANT_TEXT_LIMIT)}`;\n }\n if (!Array.isArray(content)) return '[ASSISTANT]';\n\n const parts: string[] = [];\n const toolCalls: string[] = [];\n\n for (const part of content as ContentPart[]) {\n if (part.type === 'text' && part.text) {\n parts.push(truncateText(part.text, ASSISTANT_TEXT_LIMIT));\n } else if (part.type === 'tool-call' && part.toolName) {\n toolCalls.push(part.toolName);\n }\n }\n\n const text = parts.join(' ');\n const tools = toolCalls.length ? ` | Tools: ${toolCalls.join(', ')}` : '';\n return `[ASSISTANT] ${text}${tools}`;\n}\n\nfunction summarizeToolMessage(content: unknown): string {\n if (!Array.isArray(content)) return '[TOOL]';\n\n const summaries: string[] = [];\n for (const part of content as ContentPart[]) {\n if (part.type !== 'tool-result') continue;\n\n const name = part.toolName ?? 'unknown';\n const outputType = part.output?.type;\n const value = part.output?.value ?? '';\n\n if (outputType === 'error-text') {\n summaries.push(`[TOOL:${name}] ERROR: ${truncateText(value, TOOL_ERROR_LIMIT)}`);\n } else {\n summaries.push(`[TOOL:${name}] ${truncateText(value, TOOL_RESULT_LIMIT)}`);\n }\n }\n\n return summaries.join('\\n') || '[TOOL]';\n}\n\nfunction extractText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n return (content as ContentPart[])\n .filter(\n (p): p is ContentPart & { text: string } => p.type === 'text' && typeof p.text === 'string'\n )\n .map(p => p.text)\n .join(' ');\n }\n if (content == null) return '';\n return JSON.stringify(content);\n}\n\n/**\n * Summarize an array of messages into a single conversation summary string.\n * Preserves the most recent `keepRecentCount` messages verbatim.\n */\nexport function summarizeMessages(\n messages: ModelMessage[],\n keepRecentCount = 4\n): { summary: string; kept: ModelMessage[] } {\n if (messages.length <= keepRecentCount) {\n return { summary: '', kept: messages };\n }\n\n const toSummarize = messages.slice(0, -keepRecentCount);\n const kept = messages.slice(-keepRecentCount);\n\n const lines = toSummarize.map(summarizeMessage);\n const summary = lines.join('\\n');\n\n return { summary, kept };\n}\n","/**\n * Context pruner: automatic context window management.\n * Adapted from redxpilot's context-pruner. Deterministic (no LLM call).\n *\n * When estimated tokens exceed the budget, older messages are replaced\n * with a compact summary, keeping recent messages and the system prompt intact.\n */\n\nimport type { ModelMessage } from '../types/common';\nimport type { Logger } from '../types/common';\nimport { estimateMessagesTokens } from './token-estimator';\nimport { summarizeMessages } from './message-summarizer';\nimport { truncateText } from './text-truncator';\n\nconst TOKEN_FUDGE_FACTOR = 1_000;\nconst DEFAULT_MAX_CONTEXT_TOKENS = 200_000;\nconst TARGET_SUMMARY_RATIO = 0.1;\nconst KEEP_RECENT_COUNT = 4;\n\nexport interface PruneOptions {\n maxContextTokens?: number;\n keepRecentCount?: number;\n logger?: Logger;\n}\n\nexport interface PruneResult {\n pruned: boolean;\n beforeTokens: number;\n afterTokens: number;\n}\n\n/**\n * Prune a message array in-place when it exceeds the token budget.\n *\n * Strategy:\n * 1. Estimate token count of all messages.\n * 2. If under budget, return immediately (no-op).\n * 3. Otherwise, summarize older messages into a compact summary.\n * 4. Replace the messages array contents with [system, summary, ...recent].\n */\nexport function pruneContext(messages: ModelMessage[], options?: PruneOptions): PruneResult {\n const maxTokens = options?.maxContextTokens ?? DEFAULT_MAX_CONTEXT_TOKENS;\n const keepRecent = options?.keepRecentCount ?? KEEP_RECENT_COUNT;\n const logger = options?.logger;\n\n const beforeTokens = estimateMessagesTokens(messages);\n\n if (beforeTokens + TOKEN_FUDGE_FACTOR <= maxTokens) {\n return { pruned: false, beforeTokens, afterTokens: beforeTokens };\n }\n\n logger?.info('Context pruning triggered', { beforeTokens, maxTokens });\n\n const systemMsg = messages[0];\n if (!systemMsg) return { pruned: false, beforeTokens, afterTokens: beforeTokens };\n const conversationMsgs = messages.slice(1);\n\n const { summary, kept } = summarizeMessages(conversationMsgs, keepRecent);\n\n const maxSummaryTokens = Math.floor(maxTokens * TARGET_SUMMARY_RATIO);\n const maxSummaryChars = maxSummaryTokens * 3;\n const truncatedSummary = truncateText(summary, maxSummaryChars);\n\n const summaryMessage: ModelMessage = {\n role: 'user',\n content: buildSummaryContent(truncatedSummary),\n } as ModelMessage;\n\n const newMessages: ModelMessage[] = [systemMsg, summaryMessage, ...kept];\n const afterTokens = estimateMessagesTokens(newMessages);\n\n messages.length = 0;\n messages.push(...newMessages);\n\n logger?.info('Context pruned', {\n beforeTokens,\n afterTokens,\n summarizedCount: conversationMsgs.length - kept.length,\n keptCount: kept.length,\n });\n\n return { pruned: true, beforeTokens, afterTokens };\n}\n\nfunction buildSummaryContent(summaryText: string): string {\n return [\n '<conversation_summary>',\n 'This is a summary of the conversation so far.',\n 'The original messages have been condensed to save context space.',\n '',\n summaryText,\n '</conversation_summary>',\n '',\n 'Please continue from here.',\n 'You may need to re-gather context before proceeding.',\n ].join('\\n');\n}\n","/**\n * Agent loop: model + tools, AI SDK message shapes\n */\n\nimport type { AgentConfig, AgentResult, AgentStep } from '../types/agent';\nimport type { ModelMessage } from '../types/common';\nimport type { ModelToolCall } from '../types/model';\nimport { AgentError } from '../utils/errors';\nimport { sumTokenUsage } from '../utils/utils';\nimport {\n notifyObserversStep,\n notifyObserversTool,\n notifyObserversError,\n notifyObserversBudgetWarning,\n} from './agent-observers';\nimport { executeToolCalls } from './agent-tool-executor';\nimport { pruneContext } from '../context';\n\n/**\n * Run an agent loop: invoke model, execute tools, repeat until done.\n * Supports context pruning (maxContextTokens) and token budgets.\n */\nexport async function runAgent(config: AgentConfig): Promise<AgentResult> {\n const {\n model,\n tools,\n systemPrompt,\n input,\n maxIterations = 10,\n onStep,\n observers,\n logger,\n maxContextTokens,\n tokenBudget,\n } = config;\n\n logger?.info('Starting agent', { maxIterations });\n\n const messages: ModelMessage[] = [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: input },\n ];\n\n const steps: AgentStep[] = [];\n\n for (let iteration = 0; iteration < maxIterations; iteration++) {\n if (iteration > 0 && iteration >= maxIterations - 2) {\n logger?.warn('Approaching max iterations', { iteration, maxIterations });\n }\n\n if (maxContextTokens && iteration > 0) {\n pruneContext(messages, { maxContextTokens, logger });\n }\n\n const cumulative = sumTokenUsage(steps.map(s => s.usage));\n const used = cumulative.totalTokens ?? 0;\n if (tokenBudget) {\n if (used >= tokenBudget) {\n logger?.warn('Token budget exhausted', { used, tokenBudget });\n notifyObserversBudgetWarning(observers, used, tokenBudget);\n return { output: steps.at(-1)?.content ?? '', steps, totalUsage: cumulative, messages };\n }\n if (used >= tokenBudget * 0.8) {\n notifyObserversBudgetWarning(observers, used, tokenBudget);\n }\n }\n\n logger?.debug('Agent iteration', { iteration });\n const response = await model.invoke(messages, { tools });\n\n const step: AgentStep = {\n iteration,\n content: response.text,\n toolCalls: response.toolCalls,\n usage: response.usage,\n };\n\n if (!response.toolCalls?.length) {\n step.cumulativeUsage = sumTokenUsage(steps.map(s => s.usage).concat(step.usage));\n steps.push(step);\n onStep?.(step);\n notifyObserversStep(observers, step, step.cumulativeUsage);\n const totalUsage = step.cumulativeUsage;\n logger?.info('Agent completed', { steps: steps.length, totalUsage });\n return { output: response.text, steps, totalUsage, messages };\n }\n\n logger?.debug('Tool calls', {\n iteration,\n toolCalls: response.toolCalls.map((tc: ModelToolCall) => ({\n name: tc.toolName,\n toolCallId: tc.toolCallId,\n })),\n });\n\n const toolResults = await executeToolCalls({\n tools,\n toolCalls: response.toolCalls,\n messages,\n logger,\n responseText: response.text || undefined,\n onToolResult: (name, output) => {\n notifyObserversTool(observers, name, output);\n },\n });\n\n step.toolResults = toolResults;\n step.cumulativeUsage = sumTokenUsage(steps.map(s => s.usage).concat(step.usage));\n steps.push(step);\n onStep?.(step);\n notifyObserversStep(observers, step, step.cumulativeUsage);\n }\n\n const err = new AgentError(\n `Agent reached maximum iterations (${maxIterations}) without completing`,\n maxIterations - 1\n );\n notifyObserversError(observers, err);\n logger?.error('Agent failed: max iterations reached', { maxIterations, error: err });\n throw err;\n}\n","/**\n * Programmatic step engine for the handleSteps generator pattern.\n * Adapted from redxpilot's run-programmatic-step.ts.\n *\n * Executes yields from a HandleStepsGenerator:\n * - Tool calls → execute programmatically, resume generator with result\n * - 'STEP' → signal caller to run one LLM step\n * - 'STEP_ALL' → signal caller to run LLM until it ends\n * - GENERATE_N → signal caller to produce N responses\n */\n\nimport type {\n HandleStepsGenerator,\n HandleStepsResume,\n ProgrammaticToolCall,\n} from '../types/handle-steps';\nimport type { AgentStep } from '../types/agent';\nimport type { ModelMessage } from '../types/common';\nimport type { Logger } from '../types/common';\nimport type { ToolSet } from '../tools';\nimport { executeToolByName } from '../tools';\n\nexport type ProgrammaticAction =\n | { type: 'step' }\n | { type: 'step_all' }\n | { type: 'generate_n'; n: number }\n | { type: 'done' };\n\nexport interface RunProgrammaticStepOptions {\n generator: HandleStepsGenerator;\n tools: ToolSet;\n messages: ModelMessage[];\n steps: AgentStep[];\n logger?: Logger;\n lastToolResult?: unknown;\n stepsComplete?: boolean;\n nResponses?: string[];\n}\n\n/**\n * Advance the generator until it yields a control signal (STEP/STEP_ALL/GENERATE_N)\n * or completes. Tool call yields are executed inline.\n */\nexport async function runProgrammaticStep(\n opts: RunProgrammaticStepOptions\n): Promise<ProgrammaticAction> {\n const { generator, tools, messages, steps, logger } = opts;\n\n const resumeData: HandleStepsResume = {\n messages,\n toolResult: opts.lastToolResult,\n stepsComplete: opts.stepsComplete ?? false,\n nResponses: opts.nResponses,\n steps,\n };\n\n let result = generator.next(resumeData);\n\n while (!result.done) {\n const yielded = result.value;\n\n if (yielded === 'STEP') return { type: 'step' };\n if (yielded === 'STEP_ALL') return { type: 'step_all' };\n\n if (typeof yielded === 'object' && 'type' in yielded && yielded.type === 'GENERATE_N') {\n return { type: 'generate_n', n: (yielded as { type: string; n: number }).n };\n }\n\n const toolCall = yielded as ProgrammaticToolCall;\n logger?.debug('Programmatic tool call', { toolName: toolCall.toolName });\n\n const exec = await executeToolByName(tools, toolCall.toolName, toolCall.input, { logger });\n const toolResult = exec.success ? exec.output : exec.error;\n\n result = generator.next({\n messages,\n toolResult,\n stepsComplete: false,\n steps,\n });\n }\n\n return { type: 'done' };\n}\n","/**\n * Best-of-N generation: produce multiple LLM responses and select the best.\n * Adapted from redxpilot's GENERATE_N pattern.\n */\n\nimport type { Model } from '../types/model';\nimport type { ModelMessage } from '../types/common';\nimport type { InvokeOptions, ModelResponse } from '../types/model';\nimport type { Logger } from '../types/common';\n\nexport interface GenerateNOptions {\n model: Model;\n messages: ModelMessage[];\n n: number;\n invokeOptions?: InvokeOptions;\n logger?: Logger;\n}\n\nexport interface GenerateNResult {\n responses: ModelResponse[];\n texts: string[];\n}\n\n/**\n * Generate N independent responses from the model for the same message context.\n * Returns all responses so a selector can choose the best one.\n */\nexport async function generateNResponses(options: GenerateNOptions): Promise<GenerateNResult> {\n const { model, messages, n, invokeOptions, logger } = options;\n logger?.info('Generating N responses', { n });\n\n const promises = Array.from({ length: n }, () => model.invoke(messages, invokeOptions));\n const responses = await Promise.all(promises);\n const texts = responses.map(r => r.text);\n\n logger?.info('Generated N responses', { n, lengths: texts.map(t => t.length) });\n return { responses, texts };\n}\n","/**\n * Agent loop with handleSteps generator support.\n * Alternates between programmatic steps and LLM steps.\n */\n\nimport type { AgentConfig, AgentResult, AgentStep } from '../types/agent';\nimport type { ModelMessage } from '../types/common';\nimport { AgentError } from '../utils/errors';\nimport { sumTokenUsage } from '../utils/utils';\nimport {\n notifyObserversStep,\n notifyObserversTool,\n notifyObserversError,\n notifyObserversBudgetWarning,\n} from './agent-observers';\nimport { executeToolCalls } from './agent-tool-executor';\nimport { runProgrammaticStep } from './programmatic-step';\nimport { generateNResponses } from './best-of-n';\nimport { pruneContext } from '../context';\n\n/**\n * Run an agent that uses handleSteps for hybrid programmatic+LLM control.\n * The generator decides when to execute tools and when to hand off to the LLM.\n */\nexport async function runAgentWithSteps(config: AgentConfig): Promise<AgentResult> {\n const {\n model,\n tools,\n systemPrompt,\n input,\n maxIterations = 10,\n observers,\n logger,\n maxContextTokens,\n tokenBudget,\n handleSteps,\n stepPrompt,\n } = config;\n\n if (!handleSteps) {\n throw new AgentError('runAgentWithSteps requires handleSteps in config');\n }\n\n logger?.info('Starting agent with handleSteps', { maxIterations });\n\n const messages: ModelMessage[] = [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: input },\n ];\n const steps: AgentStep[] = [];\n const generator = handleSteps({ input, logger });\n\n let lastToolResult: unknown;\n let stepsComplete = false;\n let nResponses: string[] | undefined;\n\n for (let iteration = 0; iteration < maxIterations; iteration++) {\n if (maxContextTokens && iteration > 0) {\n pruneContext(messages, { maxContextTokens, logger });\n }\n const cumulative = sumTokenUsage(steps.map(s => s.usage));\n const used = cumulative.totalTokens ?? 0;\n if (tokenBudget) {\n if (used >= tokenBudget) {\n logger?.warn('Token budget exhausted', { used, tokenBudget });\n notifyObserversBudgetWarning(observers, used, tokenBudget);\n return { output: steps.at(-1)?.content ?? '', steps, totalUsage: cumulative, messages };\n }\n if (used >= tokenBudget * 0.8) {\n notifyObserversBudgetWarning(observers, used, tokenBudget);\n }\n }\n\n const action = await runProgrammaticStep({\n generator,\n tools,\n messages,\n steps,\n logger,\n lastToolResult,\n stepsComplete,\n nResponses,\n });\n\n if (action.type === 'done') {\n const totalUsage = sumTokenUsage(steps.map(s => s.usage));\n return { output: steps.at(-1)?.content ?? '', steps, totalUsage, messages };\n }\n\n if (action.type === 'generate_n') {\n const genResult = await generateNResponses({\n model,\n messages,\n n: action.n,\n invokeOptions: { tools },\n logger,\n });\n nResponses = genResult.texts;\n lastToolResult = undefined;\n stepsComplete = false;\n continue;\n }\n\n const stepAll = action.type === 'step_all';\n const result = await runLlmStep(config, messages, steps, stepAll, iteration, stepPrompt);\n lastToolResult = undefined;\n stepsComplete = result.stepsComplete;\n nResponses = undefined;\n }\n\n const err = new AgentError(\n `Agent reached maximum iterations (${maxIterations})`,\n maxIterations - 1\n );\n notifyObserversError(observers, err);\n throw err;\n}\n\nasync function runLlmStep(\n config: AgentConfig,\n messages: ModelMessage[],\n steps: AgentStep[],\n stepAll: boolean,\n iteration: number,\n stepPrompt?: string\n): Promise<{ stepsComplete: boolean }> {\n const { model, tools, onStep, observers, logger } = config;\n\n if (stepPrompt) {\n messages.push({ role: 'user', content: stepPrompt } as ModelMessage);\n }\n\n const response = await model.invoke(messages, { tools });\n const step: AgentStep = {\n iteration,\n content: response.text,\n toolCalls: response.toolCalls,\n usage: response.usage,\n };\n\n if (!response.toolCalls?.length) {\n steps.push(step);\n onStep?.(step);\n notifyObserversStep(observers, step);\n return { stepsComplete: true };\n }\n\n const toolResults = await executeToolCalls({\n tools,\n toolCalls: response.toolCalls,\n messages,\n logger,\n onToolResult: (name, output) => {\n notifyObserversTool(observers, name, output);\n },\n });\n step.toolResults = toolResults;\n steps.push(step);\n onStep?.(step);\n notifyObserversStep(observers, step);\n\n return { stepsComplete: !stepAll };\n}\n","/**\n * Response selection strategies for best-of-N generation.\n * Supports heuristic (length-based) and LLM-as-judge selection.\n */\n\nimport type { Model } from '../types/model';\nimport type { ModelMessage } from '../types/common';\nimport type { Logger } from '../types/common';\n\nexport interface SelectionResult {\n selectedIndex: number;\n selectedText: string;\n reason?: string;\n}\n\n/**\n * Select the longest response (simple heuristic: more detail = better).\n */\nexport function selectByLength(responses: string[]): SelectionResult {\n if (responses.length === 0) {\n return { selectedIndex: 0, selectedText: '', reason: 'no responses' };\n }\n let bestIdx = 0;\n for (let i = 1; i < responses.length; i++) {\n if ((responses[i]?.length ?? 0) > (responses[bestIdx]?.length ?? 0)) bestIdx = i;\n }\n return {\n selectedIndex: bestIdx,\n selectedText: responses[bestIdx] ?? '',\n reason: 'longest response',\n };\n}\n\nexport interface JudgeOptions {\n model: Model;\n responses: string[];\n criteria: string;\n logger?: Logger;\n}\n\n/**\n * Use an LLM as a judge to pick the best response based on criteria.\n * The judge sees all candidates and returns the index of the best one.\n */\nexport async function selectByJudge(options: JudgeOptions): Promise<SelectionResult> {\n const { model, responses, criteria, logger } = options;\n\n const candidateList = responses.map((r, i) => `--- Candidate ${i} ---\\n${r}`).join('\\n\\n');\n\n const messages: ModelMessage[] = [\n {\n role: 'system',\n content: [\n 'You are a judge selecting the best response.',\n `Criteria: ${criteria}`,\n 'Reply with ONLY the candidate number (0-indexed) of the best response.',\n ].join('\\n'),\n } as ModelMessage,\n {\n role: 'user',\n content: `Select the best candidate:\\n\\n${candidateList}`,\n } as ModelMessage,\n ];\n\n logger?.debug('Running LLM judge', { candidateCount: responses.length });\n const result = await model.invoke(messages, {});\n const idx = parseInt(result.text.trim(), 10);\n const selectedIndex = isNaN(idx) || idx < 0 || idx >= responses.length ? 0 : idx;\n\n return {\n selectedIndex,\n selectedText: responses[selectedIndex] ?? '',\n reason: `judge selected candidate ${selectedIndex}`,\n };\n}\n","/**\n * OpenAI model adapter using the official openai npm package.\n * Implements Model (invoke, generateVision, invokeObject) without the Vercel AI SDK.\n */\n\nimport OpenAI from 'openai';\nimport type { z } from 'zod';\nimport type { ModelMessage, ContentPart } from '../../types/ai-types';\nimport type {\n Model,\n ModelResponse,\n InvokeOptions,\n InvokeObjectOptions,\n InvokeObjectResult,\n VisionOptions,\n ModelToolCall,\n ModelTool,\n} from '../../types/model';\nimport type { ImageInput } from '../../types/common';\nimport type { LanguageModelUsage, FinishReason } from '../../types/ai-types';\nimport { ModelError } from '../../utils/errors';\nimport { zodToJsonSchema } from '../../tools/tools';\n\ntype ChatMessage = OpenAI.Chat.ChatCompletionMessageParam;\ntype ToolChoice = OpenAI.Chat.ChatCompletionToolChoiceOption;\n\nfunction messageToOpenAI(m: ModelMessage): ChatMessage {\n if (m.role === 'system') {\n return { role: 'system', content: m.content };\n }\n if (m.role === 'user') {\n const content = m.content;\n if (typeof content === 'string') return { role: 'user', content };\n const parts: OpenAI.Chat.ChatCompletionContentPart[] = [];\n for (const p of content) {\n if (p.type === 'text') parts.push({ type: 'text', text: p.text });\n if (p.type === 'image')\n parts.push({\n type: 'image_url',\n image_url: {\n url: p.image.startsWith('data:')\n ? p.image\n : `data:${p.mimeType ?? 'image/png'};base64,${p.image}`,\n },\n });\n }\n return { role: 'user', content: parts };\n }\n if (m.role === 'assistant') {\n const content = m.content;\n if (typeof content === 'string') return { role: 'assistant', content };\n const textParts: string[] = [];\n const toolCalls: OpenAI.Chat.ChatCompletionMessageToolCall[] = [];\n for (const p of content) {\n if (p.type === 'text') textParts.push(p.text);\n if (p.type === 'tool-call')\n toolCalls.push({\n id: p.toolCallId,\n type: 'function',\n function: { name: p.toolName, arguments: JSON.stringify(p.input ?? {}) },\n });\n }\n if (toolCalls.length > 0)\n return { role: 'assistant', content: textParts.join('') || null, tool_calls: toolCalls };\n return { role: 'assistant', content: textParts.join('') || '' };\n }\n if (m.role === 'tool') {\n const first = m.content[0];\n if (first && 'type' in first && first.type === 'tool-result')\n return {\n role: 'tool',\n tool_call_id: first.toolCallId,\n content: first.output.type === 'text' ? first.output.value : first.output.value,\n };\n }\n return { role: 'user', content: '' };\n}\n\nfunction toolsToOpenAI(tools: Record<string, ModelTool>): OpenAI.Chat.ChatCompletionTool[] {\n return Object.entries(tools).map(([name, t]) => {\n const params =\n t.parameters ??\n (t.inputSchema ? zodToJsonSchema(t.inputSchema) : { type: 'object', properties: {} });\n return {\n type: 'function',\n function: {\n name,\n description: t.description,\n parameters: params,\n },\n };\n });\n}\n\nfunction usageFromOpenAI(u: OpenAI.CompletionUsage | undefined): LanguageModelUsage {\n if (!u) return { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n return {\n inputTokens: u.prompt_tokens,\n outputTokens: u.completion_tokens,\n totalTokens: u.total_tokens ?? u.prompt_tokens + u.completion_tokens,\n };\n}\n\nfunction finishReasonFromOpenAI(r: string | null | undefined): FinishReason {\n if (r === 'stop' || r === 'length' || r === 'tool_calls' || r === 'content_filter')\n return r === 'tool_calls' ? 'tool-calls' : r;\n return r ?? 'stop';\n}\n\nexport function createOpenAIModel(config: {\n model: string;\n apiKey?: string;\n baseUrl?: string;\n}): Model {\n const { model: modelName, apiKey, baseUrl } = config;\n const client = new OpenAI({\n apiKey: apiKey ?? process.env.OPENAI_API_KEY,\n baseURL: baseUrl,\n });\n\n return {\n provider: 'openai',\n modelName,\n\n async invoke(messages: ModelMessage[], options?: InvokeOptions): Promise<ModelResponse> {\n try {\n const openaiMessages: ChatMessage[] = messages.map(messageToOpenAI);\n const tools = options?.tools ? toolsToOpenAI(options.tools) : undefined;\n const completion = await client.chat.completions.create({\n model: modelName,\n messages: openaiMessages,\n tools: tools?.length ? tools : undefined,\n tool_choice: tools?.length ? ('auto' as ToolChoice) : undefined,\n max_tokens: options?.maxOutputTokens,\n temperature: options?.temperature,\n stop: options?.stop?.length ? options.stop : undefined,\n });\n\n const choice = completion.choices?.[0];\n const msg = choice?.message;\n const text = typeof msg?.content === 'string' ? msg.content : '';\n const rawToolCalls = msg?.tool_calls ?? [];\n const toolCalls: ModelToolCall[] = rawToolCalls.map(\n (tc: { id: string; function?: { name?: string; arguments?: string } }) => {\n let input: unknown = {};\n try {\n input = JSON.parse(tc.function?.arguments ?? '{}');\n } catch {\n // leave input as {}\n }\n return {\n toolCallId: tc.id,\n toolName: tc.function?.name ?? '',\n input,\n };\n }\n );\n\n return {\n text,\n toolCalls,\n usage: usageFromOpenAI(completion.usage),\n finishReason: finishReasonFromOpenAI(choice?.finish_reason),\n };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n throw new ModelError('Failed to invoke OpenAI model', 'openai', err);\n }\n },\n\n async generateVision(\n prompt: string,\n images: ImageInput[],\n options?: VisionOptions\n ): Promise<ModelResponse> {\n const content: ContentPart[] = images.map(img => ({\n type: 'image',\n image: `data:${img.mimeType};base64,${img.base64}`,\n mimeType: img.mimeType,\n }));\n content.push({ type: 'text', text: prompt });\n const messages: ModelMessage[] = [];\n if (options?.systemPrompt) messages.push({ role: 'system', content: options.systemPrompt });\n messages.push({ role: 'user', content });\n return this.invoke(messages, {\n maxOutputTokens: options?.maxOutputTokens,\n temperature: options?.temperature,\n });\n },\n\n async invokeObject<T>(\n messages: ModelMessage[],\n schema: unknown,\n options?: InvokeObjectOptions\n ): Promise<InvokeObjectResult<T>> {\n try {\n const zodSchema = schema as z.ZodType<T>;\n const openaiMessages = messages.map(messageToOpenAI);\n const completion = await client.chat.completions.create({\n model: modelName,\n messages: [\n ...openaiMessages,\n {\n role: 'system' as const,\n content:\n 'Respond with a single valid JSON object only. No markdown, no explanation, no code block.',\n },\n ],\n max_tokens: options?.maxOutputTokens,\n temperature: options?.temperature ?? 0,\n });\n\n const raw = completion.choices?.[0]?.message?.content;\n if (typeof raw !== 'string') throw new Error('No content in response');\n const trimmed = raw.replace(/^```(?:json)?\\s*|\\s*```$/g, '').trim();\n const parsed: unknown = JSON.parse(trimmed);\n const data = zodSchema.parse(parsed);\n return {\n data,\n usage: usageFromOpenAI(completion.usage),\n };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n throw new ModelError('Failed to invokeObject OpenAI model', 'openai', err);\n }\n },\n };\n}\n","/**\n * OpenAI model provider using the official openai package\n */\n\nimport type { Model, ModelConfig } from '../../types/model';\nimport { createOpenAIModel as createOpenAIAdapter } from './openai-adapter';\n\n/**\n * Create an OpenAI model instance\n */\nexport function createOpenAIModel(config: ModelConfig): Model {\n return createOpenAIAdapter({\n model: config.model,\n apiKey: config.apiKey,\n baseUrl: config.baseUrl,\n });\n}\n","/**\n * Anthropic model adapter using the official @anthropic-ai/sdk package.\n * Implements Model (invoke, generateVision, invokeObject) without the Vercel AI SDK.\n */\n\nimport Anthropic from '@anthropic-ai/sdk';\nimport type { z } from 'zod';\nimport type { ModelMessage, ContentPart } from '../../types/ai-types';\nimport type {\n Model,\n ModelResponse,\n InvokeOptions,\n InvokeObjectOptions,\n InvokeObjectResult,\n VisionOptions,\n ModelToolCall,\n ModelTool,\n} from '../../types/model';\nimport type { ImageInput } from '../../types/common';\nimport type { LanguageModelUsage, FinishReason } from '../../types/ai-types';\nimport { ModelError } from '../../utils/errors';\nimport { zodToJsonSchema } from '../../tools/tools';\n\ntype AnthropicMessageParam = Anthropic.MessageParam;\ntype AnthropicContentBlock =\n | Anthropic.TextBlockParam\n | Anthropic.ImageBlockParam\n | { type: 'tool_use'; id: string; name: string; input: Record<string, unknown> }\n | { type: 'tool_result'; tool_use_id: string; content: string };\n\nfunction messageToAnthropic(m: ModelMessage): AnthropicMessageParam | { system: string } | null {\n if (m.role === 'system') return { system: m.content };\n if (m.role === 'user') {\n const content = m.content;\n const blocks: AnthropicContentBlock[] = [];\n if (typeof content === 'string') {\n blocks.push({ type: 'text', text: content });\n } else {\n for (const p of content) {\n if (p.type === 'text') blocks.push({ type: 'text', text: p.text });\n if (p.type === 'image')\n blocks.push({\n type: 'image',\n source: {\n type: 'base64',\n media_type: (p.mimeType ?? 'image/png') as\n | 'image/png'\n | 'image/jpeg'\n | 'image/gif'\n | 'image/webp',\n data: p.image.replace(/^data:[^;]+;base64,/, ''),\n },\n });\n if (p.type === 'tool-result')\n blocks.push({\n type: 'tool_result',\n tool_use_id: p.toolCallId,\n content: p.output.type === 'text' ? p.output.value : p.output.value,\n });\n }\n }\n if (blocks.length) return { role: 'user', content: blocks };\n return null;\n }\n if (m.role === 'assistant') {\n const content = m.content;\n const blocks: AnthropicContentBlock[] = [];\n if (typeof content === 'string') {\n blocks.push({ type: 'text', text: content });\n } else {\n for (const p of content) {\n if (p.type === 'text') blocks.push({ type: 'text', text: p.text });\n if (p.type === 'tool-call')\n blocks.push({\n type: 'tool_use',\n id: p.toolCallId,\n name: p.toolName,\n input: (p.input as Record<string, unknown>) ?? {},\n });\n }\n }\n if (blocks.length) return { role: 'assistant', content: blocks };\n return null;\n }\n if (m.role === 'tool') {\n const blocks: AnthropicContentBlock[] = [];\n for (const p of m.content) {\n if (p.type === 'tool-result')\n blocks.push({\n type: 'tool_result',\n tool_use_id: p.toolCallId,\n content: p.output.type === 'text' ? p.output.value : p.output.value,\n });\n }\n if (blocks.length) return { role: 'user', content: blocks };\n return null;\n }\n return null;\n}\n\nfunction buildAnthropicMessages(messages: ModelMessage[]): {\n system?: string;\n messages: AnthropicMessageParam[];\n} {\n let system: string | undefined;\n const out: AnthropicMessageParam[] = [];\n for (const m of messages) {\n const converted = messageToAnthropic(m);\n if (!converted) continue;\n if ('system' in converted) {\n system = system ? `${system}\\n\\n${converted.system}` : converted.system;\n } else {\n out.push(converted);\n }\n }\n return { system, messages: out };\n}\n\nfunction toolsToAnthropic(tools: Record<string, ModelTool>): Anthropic.Tool[] {\n return Object.entries(tools).map(([name, t]) => {\n const params =\n t.parameters ??\n (t.inputSchema ? zodToJsonSchema(t.inputSchema) : { type: 'object', properties: {} });\n return {\n name,\n description: t.description,\n input_schema: { type: 'object' as const, properties: params.properties ?? {}, ...params },\n };\n });\n}\n\nfunction usageFromAnthropic(inputTokens: number, outputTokens: number): LanguageModelUsage {\n return {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n };\n}\n\nfunction finishReasonFromAnthropic(r: string | null | undefined): FinishReason {\n if (\n r === 'end_turn' ||\n r === 'max_tokens' ||\n r === 'tool_use' ||\n r === 'stop_sequence' ||\n r === 'content_block_stop'\n ) {\n return r === 'tool_use' ? 'tool-calls' : r === 'max_tokens' ? 'length' : 'stop';\n }\n return r ?? 'stop';\n}\n\nexport function createAnthropicModel(config: { model: string; apiKey?: string }): Model {\n const { model: modelName, apiKey } = config;\n const client = new Anthropic({\n apiKey: apiKey ?? process.env.ANTHROPIC_API_KEY,\n });\n\n return {\n provider: 'anthropic',\n modelName,\n\n async invoke(messages: ModelMessage[], options?: InvokeOptions): Promise<ModelResponse> {\n try {\n const { system, messages: anthropicMessages } = buildAnthropicMessages(messages);\n const tools = options?.tools ? toolsToAnthropic(options.tools) : undefined;\n const response = await client.messages.create({\n model: modelName,\n max_tokens: options?.maxOutputTokens ?? 4096,\n system,\n messages: anthropicMessages,\n tools: tools?.length ? tools : undefined,\n temperature: options?.temperature,\n stop_sequences: options?.stop?.length ? options.stop : undefined,\n });\n\n const textBlock = response.content?.find(\n (b): b is { type: 'text'; text: string } => b.type === 'text'\n );\n const text = textBlock?.text ?? '';\n const toolCalls: ModelToolCall[] = (response.content ?? [])\n .filter(\n (b): b is { type: 'tool_use'; id: string; name: string; input: unknown } =>\n b.type === 'tool_use'\n )\n .map(b => ({\n toolCallId: b.id,\n toolName: b.name,\n input: b.input ?? {},\n }));\n\n return {\n text,\n toolCalls,\n usage: usageFromAnthropic(response.usage.input_tokens, response.usage.output_tokens),\n finishReason: finishReasonFromAnthropic(response.stop_reason),\n };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n throw new ModelError('Failed to invoke Anthropic model', 'anthropic', err);\n }\n },\n\n async generateVision(\n prompt: string,\n images: ImageInput[],\n options?: VisionOptions\n ): Promise<ModelResponse> {\n const content: ContentPart[] = images.map(img => ({\n type: 'image',\n image: img.base64,\n mimeType: img.mimeType,\n }));\n content.push({ type: 'text', text: prompt });\n const messages: ModelMessage[] = [];\n if (options?.systemPrompt) messages.push({ role: 'system', content: options.systemPrompt });\n messages.push({ role: 'user', content });\n return this.invoke(messages, {\n maxOutputTokens: options?.maxOutputTokens,\n temperature: options?.temperature,\n });\n },\n\n async invokeObject<T>(\n messages: ModelMessage[],\n schema: unknown,\n options?: InvokeObjectOptions\n ): Promise<InvokeObjectResult<T>> {\n try {\n const zodSchema = schema as z.ZodType<T>;\n const { system, messages: anthropicMessages } = buildAnthropicMessages(messages);\n const response = await client.messages.create({\n model: modelName,\n max_tokens: options?.maxOutputTokens ?? 4096,\n system: system\n ? `${system}\\n\\nRespond with a single valid JSON object only. No markdown, no explanation, no code block.`\n : 'Respond with a single valid JSON object only. No markdown, no explanation, no code block.',\n messages: anthropicMessages,\n temperature: options?.temperature ?? 0,\n });\n\n const textBlock = response.content?.find(\n (b): b is { type: 'text'; text: string } => b.type === 'text'\n );\n const raw = textBlock?.text ?? '';\n const trimmed = raw.replace(/^```(?:json)?\\s*|\\s*```$/g, '').trim();\n const parsed: unknown = JSON.parse(trimmed);\n const data = zodSchema.parse(parsed);\n return {\n data,\n usage: usageFromAnthropic(response.usage.input_tokens, response.usage.output_tokens),\n };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n throw new ModelError('Failed to invokeObject Anthropic model', 'anthropic', err);\n }\n },\n };\n}\n","/**\n * Anthropic model provider using the official @anthropic-ai/sdk package\n */\n\nimport type { Model, ModelConfig } from '../../types/model';\nimport { createAnthropicModel as createAnthropicAdapter } from './anthropic-adapter';\n\n/**\n * Create an Anthropic model instance\n */\nexport function createAnthropicModel(config: ModelConfig): Model {\n return createAnthropicAdapter({\n model: config.model,\n apiKey: config.apiKey,\n });\n}\n","/**\n * Google (Gemini) model adapter using the official @google/genai package.\n * Implements Model (invoke, generateVision, invokeObject) without the Vercel AI SDK.\n */\n\nimport { GoogleGenAI } from '@google/genai';\nimport type { z } from 'zod';\nimport type { ModelMessage } from '../../types/ai-types';\nimport type {\n Model,\n ModelResponse,\n InvokeOptions,\n InvokeObjectOptions,\n InvokeObjectResult,\n VisionOptions,\n ModelToolCall,\n ModelTool,\n} from '../../types/model';\nimport type { ImageInput } from '../../types/common';\nimport type { LanguageModelUsage, FinishReason } from '../../types/ai-types';\nimport { ModelError } from '../../utils/errors';\nimport { zodToJsonSchema } from '../../tools/tools';\n\ninterface Content {\n role: 'user' | 'model';\n parts: Record<string, unknown>[];\n}\n\nfunction messageToGeminiParts(m: ModelMessage): Content | { system?: string } | null {\n if (m.role === 'system') return { system: m.content };\n if (m.role === 'user') {\n const content = m.content;\n const parts: Record<string, unknown>[] = [];\n if (typeof content === 'string') {\n parts.push({ text: content });\n } else {\n for (const p of content) {\n if (p.type === 'text') parts.push({ text: p.text });\n if (p.type === 'image')\n parts.push({\n inlineData: {\n mimeType: p.mimeType ?? 'image/png',\n data: p.image.replace(/^data:[^;]+;base64,/, ''),\n },\n });\n if (p.type === 'tool-result')\n parts.push({\n functionResponse: {\n name: p.toolName,\n response: p.output.type === 'text' ? p.output.value : p.output.value,\n },\n });\n }\n }\n if (parts.length) return { role: 'user', parts };\n return null;\n }\n if (m.role === 'assistant') {\n const content = m.content;\n const parts: Record<string, unknown>[] = [];\n if (typeof content === 'string') {\n parts.push({ text: content });\n } else {\n for (const p of content) {\n if (p.type === 'text') parts.push({ text: p.text });\n if (p.type === 'tool-call')\n parts.push({\n functionCall: {\n name: p.toolName,\n args: (p.input as Record<string, unknown>) ?? {},\n },\n });\n }\n }\n if (parts.length) return { role: 'model', parts };\n return null;\n }\n if (m.role === 'tool') {\n const parts: Record<string, unknown>[] = [];\n for (const p of m.content) {\n if (p.type === 'tool-result')\n parts.push({\n functionResponse: {\n name: p.toolName,\n response: p.output.type === 'text' ? p.output.value : p.output.value,\n },\n });\n }\n if (parts.length) return { role: 'user', parts };\n return null;\n }\n return null;\n}\n\nfunction buildGeminiContents(messages: ModelMessage[]): {\n systemInstruction?: string;\n contents: Content[];\n} {\n let systemInstruction: string | undefined;\n const contents: Content[] = [];\n for (const m of messages) {\n const converted = messageToGeminiParts(m);\n if (!converted) continue;\n if ('system' in converted && converted.system !== undefined) {\n systemInstruction = systemInstruction\n ? `${systemInstruction}\\n\\n${converted.system}`\n : converted.system;\n } else if ('role' in converted && 'parts' in converted) {\n contents.push(converted);\n }\n }\n return { systemInstruction, contents };\n}\n\nfunction toolsToGemini(\n tools: Record<string, ModelTool>\n): { functionDeclarations: Record<string, unknown>[] }[] {\n const declarations = Object.entries(tools).map(([name, t]) => {\n const params =\n t.parameters ??\n (t.inputSchema ? zodToJsonSchema(t.inputSchema) : { type: 'object', properties: {} });\n return {\n name,\n description: t.description,\n parameters: params,\n };\n });\n return [{ functionDeclarations: declarations }];\n}\n\nfunction finishReasonFromGemini(r: string | null | undefined): FinishReason {\n if (r === 'STOP' || r === 'MAX_TOKENS' || r === 'SAFETY' || r === 'RECITATION' || r === 'OTHER') {\n return r === 'MAX_TOKENS'\n ? 'length'\n : r === 'STOP'\n ? 'stop'\n : r === 'SAFETY'\n ? 'content-filter'\n : 'stop';\n }\n return r ?? 'stop';\n}\n\nexport function createGoogleModel(config: { model: string; apiKey?: string }): Model {\n const { model: modelName, apiKey } = config;\n const client = new GoogleGenAI({\n apiKey: apiKey ?? process.env.GOOGLE_GENERATIVE_AI_API_KEY ?? process.env.GOOGLE_API_KEY,\n });\n\n return {\n provider: 'google',\n modelName,\n\n async invoke(messages: ModelMessage[], options?: InvokeOptions): Promise<ModelResponse> {\n try {\n const { systemInstruction, contents } = buildGeminiContents(messages);\n const tools = options?.tools ? toolsToGemini(options.tools) : undefined;\n const response = await client.models.generateContent({\n model: modelName,\n contents: contents.length ? contents : [{ role: 'user', parts: [{ text: '' }] }],\n config: {\n systemInstruction,\n maxOutputTokens: options?.maxOutputTokens,\n temperature: options?.temperature,\n stopSequences: options?.stop,\n tools,\n },\n });\n\n const text = response.text ?? '';\n const functionCalls =\n (response.functionCalls as { name?: string; args?: unknown }[] | undefined) ?? [];\n const toolCalls: ModelToolCall[] = functionCalls.map((fc, i) => ({\n toolCallId: `call_${i}_${fc.name ?? ''}`,\n toolName: fc.name ?? '',\n input: fc.args ?? {},\n }));\n\n const usage = response.usageMetadata as\n | { promptTokenCount?: number; candidatesTokenCount?: number; totalTokenCount?: number }\n | undefined;\n const usageResult: LanguageModelUsage = {\n inputTokens: usage?.promptTokenCount ?? 0,\n outputTokens: usage?.candidatesTokenCount ?? usage?.totalTokenCount ?? 0,\n totalTokens: usage?.totalTokenCount ?? 0,\n };\n\n return {\n text,\n toolCalls,\n usage: usageResult,\n finishReason: finishReasonFromGemini(\n (response as { finishReason?: string }).finishReason\n ),\n };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n throw new ModelError('Failed to invoke Google model', 'google', err);\n }\n },\n\n async generateVision(\n prompt: string,\n images: ImageInput[],\n options?: VisionOptions\n ): Promise<ModelResponse> {\n const parts: Record<string, unknown>[] = images.map(img => ({\n inlineData: {\n mimeType: img.mimeType,\n data: img.base64,\n },\n }));\n parts.push({ text: prompt });\n const messages: ModelMessage[] = [];\n if (options?.systemPrompt) messages.push({ role: 'system', content: options.systemPrompt });\n messages.push({\n role: 'user',\n content: [\n { type: 'text', text: prompt },\n ...images.map(img => ({\n type: 'image' as const,\n image: img.base64,\n mimeType: img.mimeType,\n })),\n ],\n });\n return this.invoke(messages, {\n maxOutputTokens: options?.maxOutputTokens,\n temperature: options?.temperature,\n });\n },\n\n async invokeObject<T>(\n messages: ModelMessage[],\n schema: unknown,\n options?: InvokeObjectOptions\n ): Promise<InvokeObjectResult<T>> {\n try {\n const zodSchema = schema as z.ZodType<T>;\n const { systemInstruction, contents } = buildGeminiContents(messages);\n const system = systemInstruction\n ? `${systemInstruction}\\n\\nRespond with a single valid JSON object only. No markdown, no explanation, no code block.`\n : 'Respond with a single valid JSON object only. No markdown, no explanation, no code block.';\n const response = await client.models.generateContent({\n model: modelName,\n contents: contents.length ? contents : [{ role: 'user', parts: [{ text: '' }] }],\n config: {\n systemInstruction: system,\n maxOutputTokens: options?.maxOutputTokens,\n temperature: options?.temperature ?? 0,\n },\n });\n\n const raw = response.text ?? '';\n const trimmed = raw.replace(/^```(?:json)?\\s*|\\s*```$/g, '').trim();\n const parsed: unknown = JSON.parse(trimmed);\n const data = zodSchema.parse(parsed);\n const usage = response.usageMetadata as\n | { promptTokenCount?: number; candidatesTokenCount?: number; totalTokenCount?: number }\n | undefined;\n return {\n data,\n usage: {\n inputTokens: usage?.promptTokenCount ?? 0,\n outputTokens: usage?.candidatesTokenCount ?? 0,\n totalTokens: usage?.totalTokenCount ?? 0,\n },\n };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n throw new ModelError('Failed to invokeObject Google model', 'google', err);\n }\n },\n };\n}\n","/**\n * Google (Gemini) model provider using the official @google/genai package\n */\n\nimport type { Model, ModelConfig } from '../../types/model';\nimport { createGoogleModel as createGoogleAdapter } from './google-adapter';\n\n/**\n * Create a Google (Gemini) model instance\n */\nexport function createGoogleModel(config: ModelConfig): Model {\n return createGoogleAdapter({\n model: config.model,\n apiKey: config.apiKey,\n });\n}\n","/**\n * Create a model instance based on provider\n */\n\nimport type { Model, ModelConfig } from '../types/model';\nimport { ModelError } from '../utils/errors';\nimport { createOpenAIModel } from './providers/openai';\nimport { createAnthropicModel } from './providers/anthropic';\nimport { createGoogleModel } from './providers/google';\n\n/**\n * Create a model instance for the given provider\n *\n * @example\n * ```typescript\n * const model = createModel({\n * provider: 'openai',\n * model: 'gpt-4o',\n * temperature: 0.7\n * });\n *\n * const response = await model.invoke([\n * { role: 'user', content: 'Hello!' }\n * ]);\n * ```\n */\nexport function createModel(config: ModelConfig): Model {\n const { provider } = config;\n\n switch (provider) {\n case 'openai':\n return createOpenAIModel(config);\n case 'anthropic':\n return createAnthropicModel(config);\n case 'google':\n return createGoogleModel(config);\n default:\n throw new ModelError(\n `Unsupported provider: ${provider}. Supported providers: openai, anthropic, google`\n );\n }\n}\n","/**\n * Subagents: define, run, and expose as tools to a parent agent\n */\n\nimport { z } from 'zod';\nimport type { SubagentConfig, SubagentDefinition, SubagentResult } from '../types/subagent';\nimport type { AgentTool } from '../types/agent';\nimport type { Model } from '../types/model';\nimport { runAgent, runAgentWithSteps } from '../agents';\nimport { createModel } from '../models/create-model';\nimport { defineTool } from '../tools';\nimport type { ToolSet } from '../tools';\nimport { SubagentError, ValidationError } from '../utils/errors';\n\nconst NAME_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;\n\n/**\n * Validates and creates a subagent definition.\n */\nexport function defineSubagent(config: SubagentConfig): SubagentDefinition {\n if (!config.name.trim()) {\n throw new SubagentError('Subagent name is required', undefined);\n }\n if (!NAME_REGEX.test(config.name)) {\n throw new SubagentError(`Subagent name must be kebab-case: ${config.name}`, config.name);\n }\n return { ...config };\n}\n\nexport interface RunSubagentOptions {\n parentTools?: Record<string, AgentTool>;\n parentModel?: Model;\n /** Parent's system prompt; used when inheritParentSystemPrompt is true */\n parentSystemPrompt?: string;\n}\n\nfunction resolveTools(\n definition: SubagentDefinition,\n parentTools?: Record<string, AgentTool>\n): Record<string, AgentTool> {\n if (definition.tools != null && Object.keys(definition.tools).length > 0) {\n return definition.tools;\n }\n const base = parentTools ?? {};\n const disallowed = new Set(definition.disallowedTools ?? []);\n const filtered: Record<string, AgentTool> = {};\n for (const [key, t] of Object.entries(base)) {\n if (key.startsWith('subagent_')) continue;\n if (!disallowed.has(key)) filtered[key] = t;\n }\n return filtered;\n}\n\nfunction resolveSystemPrompt(def: SubagentDefinition, parentPrompt?: string): string {\n if (def.inheritParentSystemPrompt && parentPrompt) {\n return `${parentPrompt}\\n\\n${def.systemPrompt}`;\n }\n return def.systemPrompt;\n}\n\n/**\n * Run a subagent. Supports handleSteps, outputSchema validation,\n * inherited system prompts, stepPrompt, and token budgets.\n */\nexport async function runSubagent(\n definition: SubagentDefinition,\n input: string,\n options?: RunSubagentOptions\n): Promise<SubagentResult> {\n const { parentTools, parentModel, parentSystemPrompt } = options ?? {};\n const tools = resolveTools(definition, parentTools);\n const model = definition.model == null ? parentModel : createModel(definition.model);\n if (!model) {\n throw new SubagentError(\n 'Subagent has no model: set definition.model or pass parentModel in options',\n definition.name\n );\n }\n\n const systemPrompt = resolveSystemPrompt(definition, parentSystemPrompt);\n const agentConfig = {\n model,\n tools,\n systemPrompt,\n input,\n maxIterations: definition.maxIterations ?? 10,\n onStep: definition.onStep,\n observers: definition.observers,\n stepPrompt: definition.stepPrompt,\n maxContextTokens: definition.maxContextTokens,\n tokenBudget: definition.tokenBudget,\n handleSteps: definition.handleSteps,\n };\n\n const result = definition.handleSteps\n ? await runAgentWithSteps(agentConfig)\n : await runAgent(agentConfig);\n\n if (definition.outputSchema) {\n const parsed = definition.outputSchema.safeParse(result.output);\n if (!parsed.success) {\n throw new ValidationError(\n `Subagent \"${definition.name}\" output schema validation failed: ${parsed.error.message}`,\n parsed.error.issues\n );\n }\n }\n\n return { ...result, subagentName: definition.name };\n}\n\nexport interface CreateSubagentToolOptions {\n parentTools?: Record<string, AgentTool>;\n parentModel?: Model;\n parentSystemPrompt?: string;\n}\n\nexport function createSubagentTool(\n definition: SubagentDefinition,\n options?: CreateSubagentToolOptions\n): AgentTool {\n const toolDesc = definition.spawnerPrompt ?? definition.description;\n return defineTool({\n name: `subagent_${definition.name}`,\n description: toolDesc,\n input: z.object({\n prompt: z.string().describe('The task or question to delegate to this subagent'),\n }),\n handler: async ({ prompt }) => {\n const result = await runSubagent(definition, prompt, {\n parentTools: options?.parentTools,\n parentModel: options?.parentModel,\n parentSystemPrompt: options?.parentSystemPrompt,\n });\n return result.output;\n },\n });\n}\n\nexport function createSubagentToolSet(\n definitions: SubagentDefinition[],\n options?: CreateSubagentToolOptions\n): ToolSet {\n const out: ToolSet = {};\n for (const def of definitions) {\n out[`subagent_${def.name}`] = createSubagentTool(def, options);\n }\n return out;\n}\n","/**\n * Handlebars template compiler - reads .hbs files, compiles with context, writes output\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport Handlebars from 'handlebars';\nimport type { TemplateContext, ScaffoldConfig, ScaffoldResult, ScaffoldError } from './types';\n\n/** Compile a single Handlebars template string with context */\nexport function compileTemplate(template: string, context: TemplateContext): string {\n const compiled = Handlebars.compile(template, { noEscape: true });\n return compiled(context);\n}\n\n/** Recursively find all .hbs files in a directory */\nfunction findHbsFiles(dir: string, base: string = dir): string[] {\n const results: string[] = [];\n if (!fs.existsSync(dir)) return results;\n\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n results.push(...findHbsFiles(fullPath, base));\n } else if (entry.name.endsWith('.hbs')) {\n results.push(path.relative(base, fullPath));\n }\n }\n return results;\n}\n\n/** Convert a .hbs relative path to the output file path (strip .hbs extension) */\nfunction toOutputPath(hbsRelPath: string): string {\n return hbsRelPath.replace(/\\.hbs$/, '');\n}\n\n/** Check if a path matches any skip pattern (simple glob: * matches any segment) */\nfunction shouldSkip(relativePath: string, skipPatterns: string[]): boolean {\n for (const pattern of skipPatterns) {\n const regex = new RegExp(\n '^' +\n pattern\n .replace(/\\./g, '\\\\.')\n .replace(/\\*\\*/g, '<<GLOBSTAR>>')\n .replace(/\\*/g, '[^/]*')\n .replace(/<<GLOBSTAR>>/g, '.*') +\n '$'\n );\n if (regex.test(relativePath)) return true;\n }\n return false;\n}\n\n/**\n * Scaffold a project: compile all .hbs templates in templateDir with context,\n * write results to outputDir, return summary.\n */\nexport async function scaffoldProject(config: ScaffoldConfig): Promise<ScaffoldResult> {\n const { templateDir, outputDir, context, skipPatterns = [] } = config;\n const hbsFiles = findHbsFiles(templateDir);\n const files: string[] = [];\n const errors: ScaffoldError[] = [];\n\n for (const hbsFile of hbsFiles) {\n if (shouldSkip(hbsFile, skipPatterns)) continue;\n\n const outputRelPath = toOutputPath(hbsFile);\n const inputPath = path.join(templateDir, hbsFile);\n const outputPath = path.join(outputDir, outputRelPath);\n\n try {\n const templateSource = fs.readFileSync(inputPath, 'utf-8');\n const compiled = compileTemplate(templateSource, context);\n\n fs.mkdirSync(path.dirname(outputPath), { recursive: true });\n fs.writeFileSync(outputPath, compiled, 'utf-8');\n files.push(outputRelPath);\n } catch (err) {\n errors.push({\n file: hbsFile,\n message: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n return { fileCount: files.length, files, errors };\n}\n\n/** Register common Handlebars helpers */\nexport function registerHelpers(): void {\n Handlebars.registerHelper('eq', (a, b) => a === b);\n Handlebars.registerHelper('neq', (a, b) => a !== b);\n Handlebars.registerHelper('json', obj => JSON.stringify(obj, null, 2));\n Handlebars.registerHelper('uppercase', (str: string) =>\n typeof str === 'string' ? str.toUpperCase() : ''\n );\n Handlebars.registerHelper('lowercase', (str: string) =>\n typeof str === 'string' ? str.toLowerCase() : ''\n );\n Handlebars.registerHelper('capitalize', (str: string) =>\n typeof str === 'string' ? str.charAt(0).toUpperCase() + str.slice(1) : ''\n );\n Handlebars.registerHelper('camelCase', (str: string) => {\n if (typeof str !== 'string') return '';\n return str\n .replace(/[-_\\s]+(.)?/g, (_, c: string) => (c ? c.toUpperCase() : ''))\n .replace(/^(.)/, c => c.toLowerCase());\n });\n Handlebars.registerHelper('pascalCase', (str: string) => {\n if (typeof str !== 'string') return '';\n return str\n .replace(/[-_\\s]+(.)?/g, (_, c: string) => (c ? c.toUpperCase() : ''))\n .replace(/^(.)/, c => c.toUpperCase());\n });\n}\n\n// Register helpers on module load\nregisterHelpers();\n","/**\n * MCP SDK transport creation and result parsing. Isolates SDK path and dynamic imports.\n */\n\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { McpTransport, McpToolContent } from './types';\n\nfunction getSdkRoot(): string {\n const require = createRequire(import.meta.url);\n const entry = require.resolve('@modelcontextprotocol/sdk/client');\n return path.dirname(path.dirname(path.dirname(path.dirname(entry))));\n}\n\nconst sdkRoot = getSdkRoot();\n\n/** Parse first text content block of an MCP tool result to JSON or { text } / { raw }. */\nexport function parseToolResult(result: { content?: McpToolContent[] }): unknown {\n const content = result.content;\n if (!content?.length) return {};\n const first = content[0];\n if (first?.type === 'text' && typeof first.text === 'string') {\n const text = first.text.trim();\n if (text.startsWith('{') || text.startsWith('[')) {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return { raw: text };\n }\n }\n return { text };\n }\n return result;\n}\n\n/** Build StreamableHTTPClientTransport from the MCP SDK. */\nexport async function createHttpTransport(\n url: string,\n headers?: Record<string, string>\n): Promise<McpTransport> {\n const modPath = path.join(sdkRoot, 'dist', 'esm', 'client', 'streamableHttp.js');\n const mod = (await import(pathToFileURL(modPath).href)) as {\n StreamableHTTPClientTransport: new (\n url: URL,\n opts?: { requestInit?: RequestInit }\n ) => McpTransport;\n };\n const requestInit: RequestInit | undefined = headers\n ? { headers: new Headers(headers) }\n : undefined;\n return new mod.StreamableHTTPClientTransport(\n new URL(url),\n requestInit ? { requestInit } : undefined\n );\n}\n\n/** Build StdioClientTransport from the MCP SDK. */\nexport async function createStdioTransport(command: string, args: string[]): Promise<McpTransport> {\n const modPath = path.join(sdkRoot, 'dist', 'esm', 'client', 'stdio.js');\n const mod = (await import(pathToFileURL(modPath).href)) as {\n StdioClientTransport: new (params: { command: string; args: string[] }) => McpTransport;\n };\n return new mod.StdioClientTransport({ command, args });\n}\n","/**\n * BaseMcpClient - reusable MCP client with lazy connection and typed tool invocation.\n * Extend and add domain methods that call this.callTool(name, args).\n */\n\nimport { Client } from '@modelcontextprotocol/sdk/client';\nimport { ToolError } from '../utils/errors';\nimport { createHttpTransport, createStdioTransport, parseToolResult } from './transports';\nimport type {\n McpClientConfig,\n McpClientInfo,\n McpToolContent,\n McpTransport,\n McpResolveOptions,\n} from './types';\n\nexport class BaseMcpClient {\n private readonly info: McpClientInfo;\n private readonly config: McpClientConfig;\n private client: Client | null = null;\n private transport: McpTransport | null = null;\n private connectPromise: Promise<void> | null = null;\n\n constructor(info: McpClientInfo, config: McpClientConfig) {\n this.info = info;\n this.config = config;\n }\n\n /** Build config from options + env (<PREFIX>_URL, _API_KEY, _COMMAND, _ARGS). */\n static resolveConfig(\n options?: McpClientConfig,\n resolveOpts: McpResolveOptions = { envPrefix: 'MCP' }\n ): McpClientConfig {\n const { envPrefix, serverLabel, apiKeyHeader } = resolveOpts;\n const url = options?.url ?? process.env[`${envPrefix}_URL`];\n const apiKey = process.env[`${envPrefix}_API_KEY`];\n const command = options?.command ?? process.env[`${envPrefix}_COMMAND`];\n const argsEnv = process.env[`${envPrefix}_ARGS`];\n const args = options?.args ?? (argsEnv ? argsEnv.split(',').map(a => a.trim()) : undefined);\n\n let headers = options?.headers ? { ...options.headers } : undefined;\n if (apiKey) {\n const name = apiKeyHeader ?? 'Authorization';\n\n headers = headers ?? {};\n\n headers[name] = name === 'Authorization' ? `Bearer ${apiKey}` : apiKey;\n }\n\n if (url) return { url, headers };\n if (command) return { command, args: args?.length ? args : [] };\n throw new ToolError(\n `${serverLabel ?? envPrefix} uses MCP only. Set ${envPrefix}_URL or ${envPrefix}_COMMAND (and optionally ${envPrefix}_ARGS).`,\n 'mcp_client'\n );\n }\n\n private async ensureConnected(): Promise<Client> {\n if (this.client) return this.client;\n if (this.connectPromise) {\n await this.connectPromise;\n if (!this.client) throw new ToolError('MCP connection failed.', 'mcp_client');\n return this.client;\n }\n this.connectPromise = this.doConnect();\n await this.connectPromise;\n this.connectPromise = null;\n if (!this.client) throw new ToolError('MCP connection failed.', 'mcp_client');\n return this.client;\n }\n\n private async doConnect(): Promise<void> {\n const client = new Client(\n { name: this.info.name, version: this.info.version },\n { capabilities: {} }\n );\n if (this.config.url) {\n this.transport = await createHttpTransport(this.config.url, this.config.headers);\n } else if (this.config.command) {\n this.transport = await createStdioTransport(this.config.command, this.config.args ?? []);\n } else {\n throw new ToolError('MCP config missing: provide url or command.', 'mcp_client');\n }\n await client.connect(this.transport as Parameters<Client['connect']>[0]);\n this.client = client;\n }\n\n /** Call MCP tool and parse result. Subclasses use this for typed domain methods. */\n protected async callTool<T>(name: string, args: Record<string, unknown> = {}): Promise<T> {\n const client = await this.ensureConnected();\n const result = await client.callTool({ name, arguments: args });\n if (result && typeof result === 'object' && 'content' in result) {\n return parseToolResult(result as { content?: McpToolContent[] }) as T;\n }\n return result as T;\n }\n\n async close(): Promise<void> {\n if (this.transport) {\n await this.transport.close();\n this.transport = null;\n }\n this.client = null;\n this.connectPromise = null;\n }\n}\n","/**\n * Context management for planning chat\n */\n\nimport type { PlanningContext, PlanStageResult, PlanSections, Stage, ChatEntry } from './types';\n\nconst EMPTY_SECTIONS: PlanSections = {\n overview: null,\n techStack: null,\n featureDecisions: null,\n dataModels: null,\n pagesAndRoutes: null,\n authFlow: null,\n apiRoutes: null,\n implementation: null,\n executionPlan: null,\n edgeCases: null,\n testingChecklist: null,\n};\n\nexport function createInitialContext(): PlanningContext {\n return {\n stage: 'discovery',\n projectDescription: null,\n sections: { ...EMPTY_SECTIONS },\n history: [],\n pendingQuestions: [],\n };\n}\n\nexport function mergeStageResult(\n context: PlanningContext,\n result: PlanStageResult\n): PlanningContext {\n const { sections: newSections, projectDescription, pendingQuestions } = result;\n const sections: PlanSections = { ...context.sections };\n if (newSections) {\n for (const key of Object.keys(newSections) as (keyof PlanSections)[]) {\n const v = newSections[key];\n if (v !== undefined && v !== null) sections[key] = v;\n }\n }\n return {\n ...context,\n ...(projectDescription !== undefined && { projectDescription }),\n sections,\n ...(pendingQuestions !== undefined && { pendingQuestions }),\n };\n}\n\nexport function addChatEntry(\n context: PlanningContext,\n role: 'user' | 'assistant',\n content: string\n): PlanningContext {\n const entry: ChatEntry = { role, content };\n return {\n ...context,\n history: [...context.history, entry],\n };\n}\n\nexport function advanceStage(context: PlanningContext): PlanningContext {\n const order: Stage[] = ['discovery', 'requirements', 'design', 'complete'];\n const idx = order.indexOf(context.stage);\n const nextStage = idx >= 0 && idx < order.length - 1 ? order[idx + 1] : undefined;\n const next: Stage = nextStage ?? context.stage;\n return { ...context, stage: next };\n}\n","/**\n * Shared utilities for planning stages - no JSON extraction or parsing\n */\n\nimport type { PlanningContext } from '../types';\n\n/** Whether the user message is a confirmation (continue / yes / looks good) */\nexport function isConfirmation(message: string): boolean {\n const normalized = message.trim().toLowerCase();\n const confirmations = [\n 'continue',\n 'yes',\n 'yeah',\n 'yep',\n 'looks good',\n 'good',\n 'ok',\n 'okay',\n 'next',\n 'proceed',\n 'sure',\n ];\n return confirmations.some(c => normalized === c || normalized.startsWith(c + ' '));\n}\n\n/** Build a short text summary of context for logging */\nexport function buildContextSummary(ctx: PlanningContext): string {\n const parts: string[] = [];\n if (ctx.projectDescription) parts.push('Project description set');\n const sections = Object.entries(ctx.sections).filter(\n (entry): entry is [string, string] => typeof entry[1] === 'string' && entry[1].length > 0\n );\n if (sections.length) parts.push(`Sections: ${sections.map(([k]) => k).join(', ')}`);\n return parts.join('. ') || 'No context yet';\n}\n","/**\n * System prompt for planning module - markdown-only, pro-level output\n */\n\nexport const PLANNING_SYSTEM_PROMPT = `You are a senior software architect creating a single, implementation-ready plan that a developer can follow without ambiguity.\n\nCRITICAL RULES:\n- 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.\n- 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**).\n- 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.`;\n","/**\n * Discovery stage prompt - understand project, ask questions; pro format when ready\n */\n\nexport const DISCOVERY_SYSTEM_FRAGMENT = `You are in the discovery stage. Your goal is to understand what the user wants to build.\n\nRespond in natural language only. Do NOT output JSON.\n\n- 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.\n- When you have enough to proceed: output the project overview in this exact pro format so it matches the rest of the plan:\n - **## Overview** — One paragraph (2–4 sentences) summarizing the project and its purpose.\n - **## Core Features** — Numbered list: 1. **Feature Name** - Short description. (one line per feature)\n - **## Tech Stack** — Bullet list with category labels: - **Frontend**: ... (versions if known), - **Database**: ..., - **Authentication**: ..., - **API**: ..., - **Backend**: ... Include versions and key libraries where relevant.\n\nWhen 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.`;\n\nexport const DISCOVERY_USER_PROMPT = `## Current user message:\n{userMessage}\n\n## Prior conversation (if any):\n{history}\n\nRespond 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.`;\n\nexport function buildDiscoveryPrompt(userMessage: string, history: string): string {\n return DISCOVERY_USER_PROMPT.replace('{userMessage}', userMessage).replace(\n '{history}',\n history || '(No prior messages)'\n );\n}\n","/**\n * Requirements stage prompts - pro-level markdown sections\n */\n\nconst CONTEXT_BLOCK = `## Project description / context:\n{context}`;\n\nexport const REQUIREMENTS_OVERVIEW_PROMPT = `${CONTEXT_BLOCK}\n\nUsing the project description above, write two markdown sections in this exact format:\n\n1. **## Overview** — One paragraph only (2–4 sentences) summarizing the project and its purpose.\n2. **## Tech Stack** — 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.\n\nOutput only these two sections in markdown. Do NOT output JSON.`;\n\nexport const REQUIREMENTS_FEATURE_DATA_PROMPT = `${CONTEXT_BLOCK}\n\n## Already written (Overview + Tech Stack):\n{overviewAndTechStack}\n\nWrite the next two markdown sections in this exact format:\n\n1. **## Feature Decisions** — 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).\n2. **## Data Models** — 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.\n\nOutput only markdown. Do NOT output JSON.`;\n\nexport const REQUIREMENTS_PAGES_PROMPT = `${CONTEXT_BLOCK}\n\n## Already written:\n{priorSections}\n\nWrite the next markdown section in this exact format:\n\n**## Pages and Routes**\n- **### Public Pages (No Authentication Required)** and **### Protected Pages (Authentication Required)**.\n- For each page use: #### \\`/path\\` - Page Title\n- Under each page, include bullets for: purpose, form fields and validation (e.g. \"Form validation: Required fields, valid email format\"), buttons/actions, empty states, redirects on success/error (e.g. \"On success: Redirect to /dashboard\"), key UI (cards, sidebar, charts). Match the depth of a pro implementation spec so a developer can build the page from this alone.\n\nOutput only markdown. Do NOT output JSON.`;\n\nexport const REQUIREMENTS_AUTH_PROMPT = `${CONTEXT_BLOCK}\n\n## Already written:\n{priorSections}\n\nWrite the next markdown section in this exact format:\n\n**## Authentication Flow** — Use these subsections: ### Sign Up Flow, ### Login Flow, ### Logout Flow, ### Protected Route Middleware, ### API Authentication Middleware.\n- Use **numbered steps** in each flow. Include both frontend and backend steps (e.g. \"4. Frontend sends POST to /api/auth/signup with { name, email, password }\", \"5. Backend validates input\", \"6. Backend hashes password with bcrypt (10 rounds)\", \"7. Backend sets JWT in HTTP-only cookie (name, maxAge, httpOnly, secure, sameSite)\").\n- For middleware: steps for cookie check, JWT verify, attach userId to request, return 401 when invalid.\n\nOutput only markdown. Do NOT output JSON.`;\n\nexport function buildRequirementsOverviewPrompt(context: string): string {\n return REQUIREMENTS_OVERVIEW_PROMPT.replace('{context}', context);\n}\n\nexport function buildRequirementsFeatureDataPrompt(\n context: string,\n overviewAndTechStack: string\n): string {\n return REQUIREMENTS_FEATURE_DATA_PROMPT.replace('{context}', context).replace(\n '{overviewAndTechStack}',\n overviewAndTechStack\n );\n}\n\nexport function buildRequirementsPagesPrompt(context: string, priorSections: string): string {\n return REQUIREMENTS_PAGES_PROMPT.replace('{context}', context).replace(\n '{priorSections}',\n priorSections\n );\n}\n\nexport function buildRequirementsAuthPrompt(context: string, priorSections: string): string {\n return REQUIREMENTS_AUTH_PROMPT.replace('{context}', context).replace(\n '{priorSections}',\n priorSections\n );\n}\n","/**\n * Design stage prompts - pro-level API routes and implementation details\n */\n\nconst DESIGN_CONTEXT = `## Project context (all sections so far):\n{priorSections}`;\n\nexport const DESIGN_API_ROUTES_PROMPT = `${DESIGN_CONTEXT}\n\nWrite the next markdown section in this exact format:\n\n**## API Routes**\n- Group by domain: ### Authentication Endpoints, ### Exercise Endpoints, ### Workout Endpoints, etc.\n- For each endpoint use: #### METHOD \\`/path\\` (e.g. #### POST \\`/api/auth/signup\\`)\n- Under each endpoint include:\n - **Purpose**: one line\n - **Request Body** or **Query Parameters** (and **Validation** bullets: required, format, lengths)\n - **Response on Success (status)**: code block with example JSON (e.g. 200, 201)\n - **Response on Error**: bullets (e.g. 400 validation, 401, 403, 404, 500 with message)\n - **Side Effects** or **Implementation** where relevant (e.g. \"Creates User and UserProfile; sets auth cookie\")\n- Use code blocks ONLY for request/response JSON examples. No JSON elsewhere.\n\nOutput only markdown. Do NOT output JSON except inside code blocks.`;\n\nexport const DESIGN_IMPLEMENTATION_PROMPT = `${DESIGN_CONTEXT}\n\n## API Routes (already written):\n{apiRoutes}\n\nWrite the next markdown section in this exact format:\n\n**## Implementation Details**\n- **### File Structure** — 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.\n- **### Environment Variables** — List with comments (e.g. MONGODB_URI=... # connection string, JWT_SECRET=... # change in production).\n- **### Dependencies to Install** — npm install line and short explanation per dependency (e.g. mongoose: MongoDB ODM; bcryptjs: password hashing; jsonwebtoken: JWT; cookie: cookie parsing).\n- **### Key Setup** — One subsection per concern: **MongoDB connection** (file path, purpose, 3–5 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).\n- 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).\n\nOutput only markdown. Do NOT output JSON.`;\n\nexport function buildDesignApiRoutesPrompt(priorSections: string): string {\n return DESIGN_API_ROUTES_PROMPT.replace('{priorSections}', priorSections);\n}\n\nexport function buildDesignImplementationPrompt(priorSections: string, apiRoutes: string): string {\n return DESIGN_IMPLEMENTATION_PROMPT.replace('{priorSections}', priorSections).replace(\n '{apiRoutes}',\n apiRoutes\n );\n}\n","/**\n * Synthesis stage prompt - pro-level final sections (order matters for splitting)\n */\n\nconst SYNTHESIS_CONTEXT = `## Full plan so far (all sections):\n{priorSections}`;\n\nexport const SYNTHESIS_SYSTEM_FRAGMENT = `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.`;\n\nexport const SYNTHESIS_USER_PROMPT = `${SYNTHESIS_CONTEXT}\n\nWrite the following sections in this exact order. Output only markdown. Do NOT output JSON.\n\n**Block 1 — Implementation Order, Current State, Desired End State**\n\n1. **## Implementation Order** — 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.\n\n2. **## Current State Analysis** — 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.).\n\n3. **## Desired End State** — 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.\n\n**Block 2 — Edge Cases, Security, Performance, Future Enhancements**\n\n4. **## Edge Cases and Considerations** — ### 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\").\n\n5. **## Security Considerations** — 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).\n\n6. **## Performance Considerations** — 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.\n\n7. **## Future Enhancements (Not in Current Scope)** — Short grouped list (e.g. Social, Analytics, Integrations, Mobile, Premium) so scope is clear. One line per group is enough.\n\n**Block 3 — Manual Testing Checklist**\n\n8. **## Manual Testing Checklist** — ### 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\").\n\nOutput all eight sections in the order above. Do NOT output JSON.`;\n\nexport function buildSynthesisPrompt(priorSections: string): string {\n return SYNTHESIS_USER_PROMPT.replace('{priorSections}', priorSections);\n}\n","/**\n * System prompt for the edit-plan pipeline.\n * Instructs the LLM to revise an existing plan based on feedback.\n */\n\nexport const EDIT_PLAN_SYSTEM_PROMPT = `You are a senior software architect revising an existing implementation plan.\n\nCRITICAL RULES:\n- You will receive the FULL existing plan and the user's feedback or edit instructions.\n- Output ONLY the complete revised plan in markdown. Do NOT output partial plans, explanations, or commentary.\n- Preserve the same section structure (## headings) as the original plan.\n- Only modify sections that are affected by the feedback. Leave unrelated sections intact.\n- Use code blocks ONLY for: request/response JSON examples, file/directory trees, and env or config snippets.\n- Be concrete and actionable: include validation rules, HTTP status codes, redirects, field-level data model descriptions, and step-by-step auth flows.\n- 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).`;\n\nexport function buildEditPlanPrompt(existingPlan: string, feedback: string): string {\n return `## Existing Plan\\n\\n${existingPlan}\\n\\n---\\n\\n## Edit Instructions\\n\\n${feedback}`;\n}\n","/**\n * Discovery stage - understand project, optional questions; output is raw markdown\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { PlanningContext, PlanStageResult } from '../types';\nimport {\n PLANNING_SYSTEM_PROMPT,\n DISCOVERY_SYSTEM_FRAGMENT,\n buildDiscoveryPrompt,\n} from '../prompts';\nimport { isConfirmation } from './base';\n\n/** Heuristic: response contains project overview (markdown headers we expect when ready to advance) */\nfunction hasProjectOverview(text: string): boolean {\n const t = text.trim();\n if (t.length < 100) return false;\n // Primary: exact markdown headers\n if (t.includes('## Overview') || t.includes('## Core Features')) return true;\n // Secondary: bold-label or h1 variants the LLM might use\n const lower = t.toLowerCase();\n if (\n (lower.includes('overview') || lower.includes('core features')) &&\n (lower.includes('tech stack') || lower.includes('technology'))\n ) {\n return true;\n }\n return false;\n}\n\nexport async function runDiscoveryStage(\n userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<PlanStageResult> {\n logger?.debug('Discovery stage started', { historyLength: context.history.length });\n\n // Exclude the last entry from history if it duplicates the current userMessage\n // (processPlanningChat calls addChatEntry before runStage)\n const historyEntries = context.history.slice(0, -1);\n const history = historyEntries\n .map(e => `${e.role}: ${e.content}`)\n .slice(-10)\n .join('\\n');\n const prompt = buildDiscoveryPrompt(userMessage, history);\n const systemContent = `${PLANNING_SYSTEM_PROMPT}\\n\\n${DISCOVERY_SYSTEM_FRAGMENT}`;\n const messages = [\n { role: 'system' as const, content: systemContent },\n { role: 'user' as const, content: prompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 4096 });\n const message = response.text?.trim() ?? '';\n\n const hasOverview = hasProjectOverview(message);\n const userConfirmed = isConfirmation(userMessage);\n // Safety net: after enough discovery turns with confirmations, force advance\n const forceAdvance = userConfirmed && context.history.length >= 7 && message.length > 50;\n // Advance when: (1) we got overview, (2) user confirmed & description exists, or (3) safety net\n const advance =\n (hasOverview && (context.projectDescription == null || userConfirmed)) ||\n (userConfirmed && context.projectDescription != null) ||\n forceAdvance;\n const storeDescription = hasOverview || (forceAdvance && message.length > 50);\n\n logger?.debug('Discovery stage complete', {\n advance,\n hasOverview,\n userConfirmed,\n forceAdvance,\n });\n\n return {\n message,\n advance,\n sections: {},\n ...(storeDescription && { projectDescription: message }),\n };\n}\n","/**\n * Discovery state - placeholder until discovery.stage is implemented\n */\n\nimport type { PlanningContext, PlanStageResult, StageInput } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { runDiscoveryStage } from './discovery.stage';\n\nexport class DiscoveryState implements PlanningStageState {\n readonly stageName = 'discovery' as const;\n\n async process(context: PlanningContext, input: StageInput): Promise<PlanStageResult> {\n return runDiscoveryStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: PlanStageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): 'requirements' | null {\n return 'requirements';\n }\n}\n","/**\n * entity-analyzer subagent - extracts entities, fields, and relationships from requirements\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ENTITY_ANALYZER_SYSTEM_PROMPT = `You are an expert database entity analyst. Your job is to extract data model signals from requirements.\n\nPerform these analyses:\n\n## Entity Discovery\n- List every entity implied by the requirements (users, domain objects, settings, logs).\n- For each entity: name, purpose, key fields (with types), and which user type owns it.\n- Identify status enums from flow transitions (e.g. pending -> active -> completed).\n\n## Field Analysis\n- For each entity, list fields with: name, likely type, required/optional, unique constraints.\n- Identify computed vs stored fields.\n- Note fields that need indexing (lookups, sorting, filtering).\n\n## Relationship Signals\n- List entity pairs that reference each other.\n- Note ownership direction (which entity \"belongs to\" which).\n- Identify potential M:N relationships that may need join tables.\n\nRespond with a clear, structured analysis using headings and bullet points. Do NOT return JSON.`;\n\nexport const entityAnalyzerSubagent = defineSubagent({\n name: 'entity-analyzer',\n description:\n 'Analyzes requirements to extract entities, fields, relationships, and data model signals. Use when you need to understand the data before designing the schema.',\n systemPrompt: ENTITY_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * relationship-mapper subagent - maps cardinality, foreign keys, indexes\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst RELATIONSHIP_MAPPER_SYSTEM_PROMPT = `You are a database relationship specialist. Given a list of entities and their fields, you determine:\n\n## Cardinality Analysis\n- For every entity pair that references each other, classify: 1:1, 1:N, or M:N.\n- Explain the reasoning (e.g. \"A User has many Orders, but an Order belongs to one User -> 1:N\").\n\n## Foreign Key / Reference Strategy\n- For MongoDB: recommend ObjectId references vs embedding. Embed when: data is small, always read together, rarely updated independently.\n- For PostgreSQL: define foreign key columns, ON DELETE behavior (CASCADE, SET NULL, RESTRICT).\n\n## Join Table Design (M:N)\n- When M:N is detected, design the join table with: both foreign keys, any extra fields (e.g. role in a membership), indexes.\n\n## Index Recommendations\n- Suggest compound indexes for common query patterns.\n- Suggest unique indexes for natural keys (email, slug, etc.).\n- Note partial indexes where applicable (e.g. only active records).\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const relationshipMapperSubagent = defineSubagent({\n name: 'relationship-mapper',\n description:\n 'Maps cardinality (1:1, 1:N, M:N), foreign keys, join tables, and index recommendations for entity relationships. Use after entity analysis.',\n systemPrompt: RELATIONSHIP_MAPPER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * schema-refiner subagent - reviews schema for completeness and performance\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst SCHEMA_REFINER_SYSTEM_PROMPT = `You are an expert database schema reviewer. Your job is to:\n\n1. Validate the schema structure: every entity has fields, indexes, and relations properly defined.\n2. Check completeness: all entities from requirements are present, all relationships are bidirectional where needed.\n3. Check normalization: no redundant data, proper use of references vs embedding.\n4. Check performance: indexes cover common query patterns, no missing indexes on foreign keys.\n5. Check security: passwords are marked as hashed, sensitive fields noted, no plaintext secrets.\n6. Check conventions: consistent naming (camelCase or snake_case), timestamps on all entities.\n\nIf you have access to the validate_schema tool, use it first. Then provide a detailed review with:\n- Issues found (with severity: critical, warning, suggestion)\n- Specific fixes for each issue\n- Overall assessment (ready / needs work)\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport function createSchemaRefinerSubagent() {\n return defineSubagent({\n name: 'schema-refiner',\n description:\n 'Reviews a data model schema for completeness, normalization, performance, and security. Has access to validate_schema tool.',\n systemPrompt: SCHEMA_REFINER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 3,\n });\n}\n","/**\n * page-planner subagent - designs page structure, routes, and layouts\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst PAGE_PLANNER_SYSTEM_PROMPT = `You are a UX-focused frontend architect. You design detailed page specifications.\n\n## Page Planning\nFor each page in the application:\n\n### Route Definition\n- Path (e.g. /login, /dashboard, /workouts/:id)\n- Access level: public (no auth) or protected (requires auth)\n- Page name and purpose (one sentence)\n\n### Page Detail\n- **Form fields**: name, type (text, email, password, number, select, textarea, date, checkbox), required flag, validation rule.\n- **Actions**: buttons and what they do (e.g. \"Submit form\", \"Delete item\", \"Export CSV\").\n- **Empty state**: what to show when there's no data (e.g. \"No workouts yet. Click + to add one.\").\n- **Error state**: how to handle errors (e.g. \"Show inline validation errors\", \"Toast notification\").\n- **Redirect on success**: where to go after successful action (e.g. \"/dashboard\").\n- **Key UI elements**: cards, tables, charts, sidebar, modals, tabs.\n\n### Page Grouping\n- Group by access: public pages first, then protected.\n- Order by user flow: signup -> login -> dashboard -> feature pages -> settings -> admin.\n\nRespond with structured page specs. Do NOT return JSON.`;\n\nexport const pagePlannerSubagent = defineSubagent({\n name: 'page-planner',\n description:\n 'Designs detailed page specifications with routes, form fields, actions, states, and UI elements. Use for frontend page design.',\n systemPrompt: PAGE_PLANNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * component-analyzer subagent - identifies reusable components and shared layouts\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst COMPONENT_ANALYZER_SYSTEM_PROMPT = `You are a component design specialist. Given page specifications, you identify reusable components and shared patterns.\n\n## Component Identification\n- **Layout components**: main layout (with nav, sidebar, content area), auth layout (centered form), admin layout.\n- **Navigation components**: navbar, sidebar, breadcrumbs, mobile menu.\n- **Form components**: reusable form inputs, form wrappers, validation display.\n- **Display components**: cards, tables, lists, stat widgets, charts, badges.\n- **Shared components**: modals, toasts, loading spinners, empty state illustrations, error boundaries.\n\n## Component Analysis\nFor each component:\n- Name (PascalCase)\n- Type: layout, shared, form, display, navigation\n- Purpose (one sentence)\n- Props it accepts (e.g. \"user\", \"items\", \"onSubmit\", \"isLoading\")\n- Which pages use it\n\n## State Management\n- Identify which state is per-page (form state, UI state) vs global (auth state, user preferences).\n- Recommend server vs client state strategy.\n- Identify data fetching patterns (on mount, on action, real-time).\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const componentAnalyzerSubagent = defineSubagent({\n name: 'component-analyzer',\n description:\n 'Identifies reusable components, shared layouts, and state management patterns from page specifications. Use after page planning.',\n systemPrompt: COMPONENT_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * framework-selector subagent - recommends React/Vite or Next.js\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst FRAMEWORK_SELECTOR_SYSTEM_PROMPT = `You are a frontend technology advisor. Given project requirements, you recommend the best frontend framework.\n\n## Decision Criteria\n\n### Choose \"react-vite\" (Vite + React SPA) when:\n- The app is a single-page application (SPA) behind authentication\n- No SEO requirements (admin dashboards, internal tools, B2B apps)\n- Backend is a separate API (GraphQL or REST) already built\n- Simple routing with client-side navigation\n- Team prefers traditional React patterns (hooks, context)\n\n### Choose \"nextjs\" (Next.js App Router) when:\n- SEO is important (marketing pages, blogs, e-commerce storefronts)\n- Need server-side rendering (SSR) or static site generation (SSG)\n- Want unified frontend + API in one project (server actions, API routes)\n- Need streaming and progressive rendering\n- Complex data fetching with caching requirements\n- Mix of public and authenticated pages\n\n## Output Format\nState your recommendation clearly:\n- Framework: react-vite | nextjs\n- Reasoning: 2-3 sentences explaining why\n- Trade-offs: what you would lose with the alternative\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const frameworkSelectorSubagent = defineSubagent({\n name: 'framework-selector',\n description:\n 'Analyzes project requirements and recommends React/Vite SPA or Next.js. Use to determine the frontend framework before delegating to a builder.',\n systemPrompt: FRAMEWORK_SELECTOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * security-analyzer subagent - analyzes security requirements and threat vectors\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst SECURITY_ANALYZER_SYSTEM_PROMPT = `You are a web security specialist. You analyze project requirements for security concerns and design security policies.\n\n## Authentication Analysis\n- Determine the best auth strategy (JWT, session, OAuth) based on requirements.\n- JWT: token expiry, refresh strategy, cookie vs header, httpOnly/secure/sameSite flags.\n- Session: session store (memory, Redis, DB), cookie config, session expiry.\n- OAuth: which providers, callback flow, token exchange, account linking.\n\n## Password Security\n- Hashing algorithm (bcrypt recommended), cost factor (10+ rounds).\n- Password requirements: minimum length, complexity rules.\n- Password reset flow: token generation, expiry, one-time use.\n\n## Authorization Analysis\n- Identify role hierarchy (e.g. admin > moderator > user).\n- Map roles to permissions per resource (CRUD matrix).\n- Resource ownership checks (users can only modify their own data).\n\n## Threat Analysis\n- Rate limiting: login attempts, API calls, password reset requests.\n- CORS: allowed origins, methods, headers.\n- Input sanitization: XSS prevention, SQL injection prevention.\n- Brute force protection: account lockout, exponential backoff.\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const securityAnalyzerSubagent = defineSubagent({\n name: 'security-analyzer',\n description:\n 'Analyzes security requirements, threat vectors, and designs security policies. Use to understand auth needs before designing flows.',\n systemPrompt: SECURITY_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * flow-designer subagent - designs step-by-step auth flows\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst FLOW_DESIGNER_SYSTEM_PROMPT = `You are an authentication flow architect. You design detailed, numbered step-by-step auth flows.\n\nFor each flow (signup, login, logout, password reset, protected route middleware, API auth middleware):\n\n## Flow Design Pattern\n1. Number each step sequentially.\n2. Mark each step as \"frontend\" or \"backend\".\n3. Describe the action clearly (e.g. \"Frontend sends POST to /api/auth/signup with { name, email, password }\").\n4. Include implementation details (e.g. \"Backend hashes password with bcrypt (10 rounds)\").\n\n## Signup Flow\n- Frontend: form validation, submit request.\n- Backend: validate input, check existing user, hash password, create user + profile, generate token, set cookie.\n- Frontend: redirect to dashboard.\n\n## Login Flow\n- Frontend: form validation, submit credentials.\n- Backend: find user, compare password hash, generate token, set cookie.\n- Frontend: redirect to dashboard.\n\n## Password Reset Flow\n- Frontend: request reset (email).\n- Backend: generate reset token, send email.\n- Frontend: enter new password with token.\n- Backend: validate token, hash new password, update user, invalidate token.\n\n## Middleware Flows\n- Protected route: check cookie/header, verify token, attach user to request, reject if invalid.\n- API auth: same as above but for API routes, return 401 JSON.\n\nRespond with structured numbered flows. Do NOT return JSON.`;\n\nexport const flowDesignerSubagent = defineSubagent({\n name: 'flow-designer',\n description:\n 'Designs detailed step-by-step authentication flows (signup, login, logout, password reset, middleware). Use after security analysis.',\n systemPrompt: FLOW_DESIGNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * Requirements stage - delegates to specialist agents:\n * data-modeler (data models), auth-designer (auth flow), frontend-architect (pages/routes)\n * Overview, tech stack, and feature decisions use direct LLM calls for markdown output.\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { PlanningContext, PlanStageResult } from '../types';\nimport { PLANNING_SYSTEM_PROMPT } from '../prompts';\nimport { buildRequirementsOverviewPrompt, buildRequirementsFeatureDataPrompt } from '../prompts';\nimport { runSubagent } from '../../../lib/subagents';\nimport { entityAnalyzerSubagent } from '../../data-modeler/subagents';\nimport { pagePlannerSubagent } from '../../frontend-architect/subagents';\nimport { flowDesignerSubagent } from '../../auth-designer/subagents';\n\nfunction invokeMarkdown(model: Model, systemPrompt: string, userPrompt: string): Promise<string> {\n const messages = [\n { role: 'system' as const, content: systemPrompt },\n { role: 'user' as const, content: userPrompt },\n ];\n return model\n .invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 })\n .then(r => r.text?.trim() ?? '');\n}\n\nfunction splitOverviewAndTechStack(text: string): { overview: string; techStack: string } {\n const idx = text.indexOf('## Tech Stack');\n if (idx < 0) return { overview: text, techStack: '' };\n return { overview: text.slice(0, idx).trim(), techStack: text.slice(idx).trim() };\n}\n\nfunction splitFeatureDecisionsAndDataModels(text: string): {\n featureDecisions: string;\n dataModels: string;\n} {\n const idx = text.indexOf('## Data Models');\n if (idx < 0) return { featureDecisions: text, dataModels: '' };\n return { featureDecisions: text.slice(0, idx).trim(), dataModels: text.slice(idx).trim() };\n}\n\nexport async function runRequirementsStage(\n _userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<PlanStageResult> {\n logger?.debug('Requirements stage started (specialist agents)');\n\n const ctx = context.projectDescription ?? '';\n if (!ctx) {\n return {\n message: 'No project description yet. Complete discovery first.',\n advance: false,\n sections: {},\n };\n }\n\n const systemPrompt = `${PLANNING_SYSTEM_PROMPT}\\n\\nOutput only markdown. Do NOT output JSON.`;\n\n // Part 1: Overview + Tech Stack (direct LLM call)\n const part1 = await invokeMarkdown(model, systemPrompt, buildRequirementsOverviewPrompt(ctx));\n const { overview, techStack } = splitOverviewAndTechStack(part1);\n\n // Part 2: Feature Decisions + Data Models via entity-analyzer specialist\n const part2 = await invokeMarkdown(\n model,\n systemPrompt,\n buildRequirementsFeatureDataPrompt(ctx, part1)\n );\n const { featureDecisions } = splitFeatureDecisionsAndDataModels(part2);\n\n logger?.info('Delegating to data-modeler specialist');\n const dataModelResult = await runSubagent(\n entityAnalyzerSubagent,\n `Analyze the data model for this project:\\n\\n${ctx}\\n\\nFeatures:\\n${featureDecisions}`,\n { parentModel: model }\n );\n const dataModels = dataModelResult.output;\n\n // Part 3: Pages and Routes via frontend-architect specialist\n logger?.info('Delegating to frontend-architect specialist');\n const priorContext = [part1, featureDecisions, dataModels].join('\\n\\n---\\n\\n');\n const pagesResult = await runSubagent(\n pagePlannerSubagent,\n `Design the pages and routes for this project:\\n\\n${ctx}\\n\\nContext:\\n${priorContext}`,\n { parentModel: model }\n );\n const pagesAndRoutes = pagesResult.output;\n\n // Part 4: Auth Flow via auth-designer specialist\n logger?.info('Delegating to auth-designer specialist');\n const fullContext = [priorContext, pagesAndRoutes].join('\\n\\n---\\n\\n');\n const authResult = await runSubagent(\n flowDesignerSubagent,\n `Design the authentication flows for this project:\\n\\n${ctx}\\n\\nContext:\\n${fullContext}`,\n { parentModel: model }\n );\n const authFlow = authResult.output;\n\n logger?.info('Requirements stage complete (specialist agents)');\n return {\n message:\n 'Requirements generated via specialist agents (Data Modeler, Frontend Architect, Auth Designer).',\n advance: true,\n sections: { overview, techStack, featureDecisions, dataModels, pagesAndRoutes, authFlow },\n };\n}\n","/**\n * Requirements state - delegates to requirements stage\n */\n\nimport type { PlanningContext, PlanStageResult, StageInput } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { runRequirementsStage } from './requirements.stage';\n\nexport class RequirementsState implements PlanningStageState {\n readonly stageName = 'requirements' as const;\n\n async process(context: PlanningContext, input: StageInput): Promise<PlanStageResult> {\n return runRequirementsStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: PlanStageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): 'design' | null {\n return 'design';\n }\n}\n","/**\n * endpoint-analyzer subagent - derives API endpoints from data model and requirements\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ENDPOINT_ANALYZER_SYSTEM_PROMPT = `You are an API endpoint analyst. Given a data model and requirements, you derive the complete API surface.\n\n## Endpoint Discovery\n- For each entity in the data model, determine CRUD operations: create, read (by ID), list (with filters/pagination), update, delete.\n- From user stories/flows, identify custom operations beyond CRUD (e.g. searchUsers, bulkImport, exportCsv, toggleStatus).\n- Group endpoints by resource name (pluralized entity name).\n\n## Route Design\n- Design RESTful routes: POST /resource, GET /resource/:id, GET /resource, PUT /resource/:id, DELETE /resource/:id.\n- For nested resources: GET /users/:userId/orders, POST /users/:userId/orders.\n- For custom operations: POST /resource/:id/actions/activate, GET /resource/search.\n\n## Auth Annotations\n- Mark which endpoints require authentication.\n- Mark which endpoints require specific roles (admin, owner).\n- Identify resource-ownership checks (user can only access their own data).\n\nRespond with structured analysis using headings and bullet points. Do NOT return JSON.`;\n\nexport const endpointAnalyzerSubagent = defineSubagent({\n name: 'endpoint-analyzer',\n description:\n 'Analyzes data model and requirements to derive API endpoints, routes, and auth annotations. Use before generating the API design.',\n systemPrompt: ENDPOINT_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * contract-designer subagent - designs request/response contracts per endpoint\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst CONTRACT_DESIGNER_SYSTEM_PROMPT = `You are an API contract specialist. Given endpoints and a data model, you design detailed request/response contracts.\n\n## Request Design\n- For each endpoint, define: required fields, optional fields, field types, validation rules.\n- Validation rules: required, min/max length, email format, enum values, numeric ranges.\n- For list endpoints: pagination (page, limit, offset), sorting (sortBy, order), filtering (query params).\n\n## Response Design\n- Success responses: HTTP status (200, 201, 204), response body shape.\n- For list endpoints: { items: T[], total: number, page: number, limit: number }.\n- For single item: the entity shape with all fields.\n\n## Error Responses\n- 400: validation errors with field-level messages.\n- 401: unauthenticated (missing or invalid token).\n- 403: forbidden (insufficient role or not resource owner).\n- 404: resource not found.\n- 409: conflict (duplicate unique field).\n- 500: internal server error.\n\n## Naming Conventions\n- Use consistent field naming (camelCase for JSON, snake_case for query params if preferred).\n- Use ISO 8601 for dates in responses.\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const contractDesignerSubagent = defineSubagent({\n name: 'contract-designer',\n description:\n 'Designs detailed request/response contracts, validation rules, and error responses per API endpoint. Use after endpoint analysis.',\n systemPrompt: CONTRACT_DESIGNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * Design stage - delegates to api-designer specialists:\n * endpoint-analyzer (API routes), contract-designer (implementation details)\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { PlanningContext, PlanStageResult } from '../types';\nimport { PLANNING_SYSTEM_PROMPT } from '../prompts';\nimport { buildDesignImplementationPrompt } from '../prompts';\nimport { runSubagent } from '../../../lib/subagents';\nimport { endpointAnalyzerSubagent, contractDesignerSubagent } from '../../api-designer/subagents';\n\nfunction gatherPriorSections(ctx: PlanningContext): string {\n const parts: string[] = [];\n if (ctx.projectDescription) parts.push(ctx.projectDescription);\n const s = ctx.sections;\n if (s.overview) parts.push(s.overview);\n if (s.techStack) parts.push(s.techStack);\n if (s.featureDecisions) parts.push(s.featureDecisions);\n if (s.dataModels) parts.push(s.dataModels);\n if (s.pagesAndRoutes) parts.push(s.pagesAndRoutes);\n if (s.authFlow) parts.push(s.authFlow);\n return parts.join('\\n\\n---\\n\\n');\n}\n\nexport async function runDesignStage(\n _userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<PlanStageResult> {\n logger?.debug('Design stage started (specialist agents)');\n\n const priorSections = gatherPriorSections(context);\n if (!priorSections) {\n return {\n message: 'No prior sections. Complete discovery and requirements first.',\n advance: false,\n sections: {},\n };\n }\n\n // API Routes via endpoint-analyzer specialist\n logger?.info('Delegating to api-designer endpoint-analyzer specialist');\n const apiResult = await runSubagent(\n endpointAnalyzerSubagent,\n `Design the API routes for this project:\\n\\n${priorSections}`,\n { parentModel: model }\n );\n const apiRoutes = apiResult.output;\n\n // Implementation Details via contract-designer specialist + direct LLM call\n logger?.info('Delegating to api-designer contract-designer specialist');\n const contractResult = await runSubagent(\n contractDesignerSubagent,\n `Design detailed request/response contracts for these API endpoints:\\n\\n${apiRoutes}\\n\\nProject context:\\n${priorSections}`,\n { parentModel: model }\n );\n\n const systemPrompt = `${PLANNING_SYSTEM_PROMPT}\\n\\nOutput only markdown. Do NOT output JSON.`;\n const implementation = await model\n .invoke(\n [\n { role: 'system' as const, content: systemPrompt },\n {\n role: 'user' as const,\n content: buildDesignImplementationPrompt(\n priorSections,\n apiRoutes + '\\n\\n' + contractResult.output\n ),\n },\n ],\n { temperature: 0.3, maxOutputTokens: 8192 }\n )\n .then(r => r.text?.trim() ?? '');\n\n logger?.info('Design stage complete (specialist agents)');\n return {\n message: 'Design generated via specialist agents (Endpoint Analyzer, Contract Designer).',\n advance: true,\n sections: { apiRoutes, implementation },\n };\n}\n","/**\n * Design state - delegates to design stage\n */\n\nimport type { PlanningContext, PlanStageResult, StageInput } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { runDesignStage } from './design.stage';\n\nexport class DesignState implements PlanningStageState {\n readonly stageName = 'design' as const;\n\n async process(context: PlanningContext, input: StageInput): Promise<PlanStageResult> {\n return runDesignStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: PlanStageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): 'complete' | null {\n return 'complete';\n }\n}\n","/**\n * Assemble plan sections into markdown and write to file\n */\n\nimport { writeFile } from 'fs/promises';\nimport type { PlanSections } from './types';\n\nexport function assemblePlan(projectName: string, sections: PlanSections): string {\n const parts: (string | null)[] = [\n `# ${projectName} Implementation Plan\\n`,\n sections.overview,\n sections.techStack,\n sections.featureDecisions,\n '---',\n sections.dataModels,\n '---',\n sections.pagesAndRoutes,\n '---',\n sections.authFlow,\n '---',\n sections.apiRoutes,\n '---',\n sections.implementation,\n '---',\n sections.executionPlan,\n '---',\n sections.edgeCases,\n '---',\n sections.testingChecklist,\n ];\n return parts.filter(Boolean).join('\\n\\n');\n}\n\nexport async function writePlanToFile(markdown: string, outputPath: string): Promise<void> {\n await writeFile(outputPath, markdown, 'utf-8');\n}\n","/**\n * edge-case-analyzer subagent - identifies edge cases per domain area\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst EDGE_CASE_ANALYZER_SYSTEM_PROMPT = `You are a QA-minded tech lead. You identify edge cases that developers often miss.\n\nFor each domain area (Authentication, Data, API, Frontend, Integrations):\n\n## Edge Case Analysis\n- **Scenario**: Describe the edge case concretely (e.g. \"User submits signup form with email that already exists\").\n- **Handling**: How to handle it (e.g. \"Return 400 with message 'Email already in use'\").\n- **Severity**: critical (must handle or app breaks), warning (should handle for good UX), info (nice to have).\n\n## Common Areas to Check\n- **Authentication**: duplicate email, invalid credentials, expired token, concurrent sessions, password reset with invalid token.\n- **Data**: empty collections, max field lengths, special characters in input, date timezone issues, null references.\n- **API**: missing required fields, invalid field types, unauthorized access, rate limiting, pagination edge (page 0, negative page).\n- **Frontend**: empty states, loading states, network errors, form resubmission, back button behavior.\n- **Integrations**: external API down, timeout, rate limited, invalid response format.\n\nRespond with structured edge cases grouped by area. Do NOT return JSON.`;\n\nexport const edgeCaseAnalyzerSubagent = defineSubagent({\n name: 'edge-case-analyzer',\n description:\n 'Identifies edge cases per domain area with scenarios, handling strategies, and severity levels. Use for comprehensive edge case analysis.',\n systemPrompt: EDGE_CASE_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * testing-strategist subagent - designs manual testing checklists\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst TESTING_STRATEGIST_SYSTEM_PROMPT = `You are a testing strategy specialist. You design comprehensive manual testing checklists.\n\n## Testing Checklist Design\nGroup test items by flow (Authentication, CRUD operations, Edge cases, etc.).\n\nFor each test item:\n- **Flow name**: which feature flow this tests (e.g. \"Authentication Flow\", \"Workout CRUD Flow\").\n- **Test item**: what to verify (e.g. \"Sign up with valid credentials creates account\").\n- **Expected result**: what should happen (e.g. \"User created in DB, JWT cookie set, redirected to /dashboard\").\n\n## Coverage Areas\n- **Happy paths**: normal user flows work end-to-end.\n- **Validation**: invalid inputs are rejected with clear messages.\n- **Authorization**: users can only access what they should.\n- **Error handling**: errors are caught and displayed properly.\n- **Data integrity**: data is saved correctly, relationships maintained.\n- **UI states**: loading, empty, error, success states display correctly.\n\n## Checklist Format\nPresent as grouped checklist items using markdown checkboxes:\n### Flow Name\n- [ ] Test item description -> Expected result\n\nRespond with structured checklist. Do NOT return JSON.`;\n\nexport const testingStrategistSubagent = defineSubagent({\n name: 'testing-strategist',\n description:\n 'Designs comprehensive manual testing checklists grouped by feature flow. Use for testing strategy and QA planning.',\n systemPrompt: TESTING_STRATEGIST_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * Synthesis stage - delegates to execution-planner specialists:\n * edge-case-analyzer (edge cases), testing-strategist (testing checklist)\n * Then assembles plan.md from all sections.\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { PlanningContext, PlanStageResult } from '../types';\nimport { PLANNING_SYSTEM_PROMPT } from '../prompts';\nimport { SYNTHESIS_SYSTEM_FRAGMENT, buildSynthesisPrompt } from '../prompts';\nimport { assemblePlan } from '../writer';\nimport { runSubagent } from '../../../lib/subagents';\nimport {\n edgeCaseAnalyzerSubagent,\n testingStrategistSubagent,\n} from '../../execution-planner/subagents';\n\nfunction gatherAllSections(ctx: PlanningContext): string {\n const parts: string[] = [];\n if (ctx.projectDescription) parts.push(ctx.projectDescription);\n const s = ctx.sections;\n [\n s.overview,\n s.techStack,\n s.featureDecisions,\n s.dataModels,\n s.pagesAndRoutes,\n s.authFlow,\n s.apiRoutes,\n s.implementation,\n ].forEach(p => {\n if (p) parts.push(p);\n });\n return parts.join('\\n\\n---\\n\\n');\n}\n\nfunction extractProjectName(ctx: PlanningContext): string {\n const raw = ctx.sections.overview ?? ctx.projectDescription ?? '';\n const firstLine = raw.split('\\n')[0]?.trim() ?? '';\n const regex = /^#+\\s*(.+?)(?:\\s+Implementation Plan)?$/i;\n const match = regex.exec(firstLine);\n if (match?.[1]) return match[1].trim();\n if (firstLine.length > 0 && firstLine.length < 80) return firstLine.replace(/^#+\\s*/, '').trim();\n return 'Project Implementation Plan';\n}\n\nexport async function runSynthesisStage(\n _userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<PlanStageResult> {\n logger?.debug('Synthesis stage started (specialist agents)');\n\n const priorSections = gatherAllSections(context);\n if (!priorSections) {\n return {\n message: 'No prior sections. Complete earlier stages first.',\n advance: false,\n sections: {},\n };\n }\n\n // Execution plan via direct LLM call (phased implementation order)\n const systemPrompt = `${PLANNING_SYSTEM_PROMPT}\\n\\n${SYNTHESIS_SYSTEM_FRAGMENT}\\n\\nOutput only markdown. Do NOT output JSON.`;\n const executionPlan = await model\n .invoke(\n [\n { role: 'system' as const, content: systemPrompt },\n { role: 'user' as const, content: buildSynthesisPrompt(priorSections) },\n ],\n { temperature: 0.3, maxOutputTokens: 8192 }\n )\n .then(r => r.text?.trim() ?? '');\n\n // Edge cases via edge-case-analyzer specialist\n logger?.info('Delegating to execution-planner edge-case-analyzer specialist');\n const edgeCaseResult = await runSubagent(\n edgeCaseAnalyzerSubagent,\n `Identify edge cases for this project:\\n\\n${priorSections}`,\n { parentModel: model }\n );\n const edgeCases = edgeCaseResult.output;\n\n // Testing checklist via testing-strategist specialist\n logger?.info('Delegating to execution-planner testing-strategist specialist');\n const testingResult = await runSubagent(\n testingStrategistSubagent,\n `Design the manual testing checklist for this project:\\n\\n${priorSections}`,\n { parentModel: model }\n );\n const testingChecklist = testingResult.output;\n\n const projectName = extractProjectName(context);\n const fullSections = {\n ...context.sections,\n executionPlan: executionPlan || null,\n edgeCases: edgeCases || null,\n testingChecklist: testingChecklist || null,\n };\n const fullMarkdown = assemblePlan(projectName, fullSections);\n\n logger?.info('Synthesis stage complete (specialist agents)', { projectName });\n return {\n message: `Plan complete: ${projectName}. Generated via specialist agents.`,\n advance: true,\n sections: { executionPlan, edgeCases, testingChecklist },\n planMarkdown: fullMarkdown,\n };\n}\n","/**\n * Synthesis state - delegates to synthesis stage\n */\n\nimport type { PlanningContext, PlanStageResult, StageInput } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { runSynthesisStage } from './synthesis.stage';\n\nexport class SynthesisState implements PlanningStageState {\n readonly stageName = 'complete' as const;\n\n async process(context: PlanningContext, input: StageInput): Promise<PlanStageResult> {\n return runSynthesisStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: PlanStageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): null {\n return null;\n }\n}\n","/**\n * Registry: map Stage to State instance for State pattern routing\n */\n\nimport type { Stage } from '../types';\nimport type { PlanningStageState } from './state-types';\nimport { DiscoveryState } from './discovery.state';\nimport { RequirementsState } from './requirements.state';\nimport { DesignState } from './design.state';\nimport { SynthesisState } from './synthesis.state';\n\nconst states: Record<Stage, PlanningStageState> = {\n discovery: new DiscoveryState(),\n requirements: new RequirementsState(),\n design: new DesignState(),\n complete: new SynthesisState(),\n};\n\nexport function getStateForStage(stage: Stage): PlanningStageState {\n return states[stage];\n}\n","/**\n * Stage routing and auto-advance logic (State pattern)\n */\n\nimport type { Logger } from '../../lib/types/common';\nimport type { Model } from '../../lib/types/model';\nimport type { PlanningContext, Stage } from './types';\nimport { getStateForStage } from './stages';\nimport { isConfirmation } from './stages/base';\nimport { advanceStage, mergeStageResult, addChatEntry } from './context';\n\nexport function getStageForTurn(context: PlanningContext, _userMessage: string): Stage {\n return context.stage;\n}\n\n/**\n * Run the current stage via State pattern; merge result into context.\n * Returns planMarkdown when synthesis stage completes.\n */\nexport async function runStage(\n stage: Stage,\n userMessage: string,\n context: PlanningContext,\n model: Model,\n logger?: Logger\n): Promise<{\n message: string;\n pendingQuestions: string[];\n advance: boolean;\n data: PlanningContext;\n planMarkdown?: string;\n}> {\n logger?.debug('Stage processor invoked', { stage });\n const state = getStateForStage(stage);\n const result = await state.process(context, { userMessage, model, logger });\n const merged = mergeStageResult(context, result);\n const data: PlanningContext = {\n ...merged,\n pendingQuestions: result.pendingQuestions ?? merged.pendingQuestions,\n };\n logger?.debug('Stage result', {\n stage,\n advance: result.advance,\n hasPlanMarkdown: !!result.planMarkdown,\n });\n return {\n message: result.message,\n pendingQuestions: result.pendingQuestions ?? merged.pendingQuestions,\n advance: result.advance,\n data,\n planMarkdown: result.planMarkdown,\n };\n}\n\nexport { isConfirmation, advanceStage, addChatEntry };\n","/**\n * processPlanningChat - main entry point for chat-based planning\n */\n\nimport { createModel } from '../../lib/models/create-model';\nimport type { PlanningContext, PlanChatTurnResult, PlanningChatConfig, Stage } from './types';\nimport { createInitialContext, addChatEntry, advanceStage } from './context';\nimport { runStage } from './router';\n\nconst STAGE_ORDER: Stage[] = ['discovery', 'requirements', 'design', 'complete'];\n\nexport async function processPlanningChat(\n userMessage: string,\n context: PlanningContext | null,\n config: PlanningChatConfig\n): Promise<PlanChatTurnResult> {\n const { logger } = config;\n\n const modelConfig = config.model ?? { provider: 'openai', model: 'gpt-4o-mini' };\n const model = createModel(modelConfig);\n\n let ctx: PlanningContext = context ?? createInitialContext();\n ctx = addChatEntry(ctx, 'user', userMessage);\n\n logger?.info('Planning chat turn', { stage: ctx.stage, messageLength: userMessage.length });\n\n let message = '';\n let pendingQuestions: string[] = [];\n let planMarkdown: string | null = null;\n\n const runOne = async (stage: Stage): Promise<{ advance: boolean; planMarkdown?: string }> => {\n const result = await runStage(stage, userMessage, ctx, model, logger);\n message = result.message;\n pendingQuestions = result.pendingQuestions;\n ctx = result.data;\n if (result.planMarkdown) planMarkdown = result.planMarkdown;\n return { advance: result.advance, planMarkdown: result.planMarkdown };\n };\n\n let stage = ctx.stage;\n logger?.info('Stage', { stage });\n let runResult = await runOne(stage);\n\n while (runResult.advance && !planMarkdown) {\n const idx = STAGE_ORDER.indexOf(stage);\n const nextStage = idx >= 0 && idx < STAGE_ORDER.length - 1 ? STAGE_ORDER[idx + 1] : undefined;\n if (nextStage === undefined) break;\n logger?.info('Stage transition', { from: stage, to: nextStage });\n stage = nextStage;\n ctx = advanceStage(ctx);\n ctx = { ...ctx, stage };\n logger?.info('Stage', { stage });\n runResult = await runOne(stage);\n }\n\n ctx = addChatEntry(ctx, 'assistant', message);\n\n logger?.info('Planning chat turn done', { stage, hasPlanMarkdown: !!planMarkdown });\n return {\n message,\n context: ctx,\n pendingQuestions,\n planMarkdown,\n };\n}\n","/**\n * runPlanningAgent - one-shot wrapper around processPlanningChat\n * Auto-advances with \"continue\"; returns plan markdown. Does not write to file.\n */\n\nimport type { PlanningAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\nimport { processPlanningChat } from './chat';\n\nconst MAX_TURNS = 10;\n\n/**\n * Run the planning agent in one-shot mode: single input, auto-advance through stages,\n * return plan markdown as AgentResult. Does not write to file.\n */\nexport async function runPlanningAgent(config: PlanningAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, onStep, logger } = config;\n logger?.info('Starting planning agent', { maxTurns: MAX_TURNS });\n\n let context = null;\n let lastResult = await processPlanningChat(input, context, {\n model: modelConfig,\n onStep,\n logger,\n });\n context = lastResult.context;\n let turns = 1;\n while (!lastResult.planMarkdown && turns < MAX_TURNS) {\n logger?.debug('Planning agent turn', { turn: turns });\n const continueMsg =\n `continue - proceed with the project: \"${input}\". ` +\n 'Make reasonable assumptions for any unresolved details and produce the required output format.';\n lastResult = await processPlanningChat(continueMsg, context, {\n model: modelConfig,\n onStep,\n logger,\n });\n context = lastResult.context;\n turns++;\n }\n const output = lastResult.planMarkdown ?? lastResult.message;\n const messages = context.history.map(e => ({\n role: e.role as 'user' | 'system' | 'assistant',\n content: e.content,\n }));\n\n logger?.info('Planning agent completed', {\n turns,\n hasPlanMarkdown: !!lastResult.planMarkdown,\n });\n return {\n output,\n steps: [],\n totalUsage: undefined,\n messages,\n };\n}\n","/**\n * editPlan - single LLM call to revise an existing plan based on feedback.\n * Takes existing plan markdown + edit instructions, returns updated markdown.\n */\n\nimport type { EditPlanConfig } from './types';\nimport { createModel } from '../../lib/models/create-model';\nimport { EDIT_PLAN_SYSTEM_PROMPT, buildEditPlanPrompt } from './prompts';\n\n/**\n * Edit an existing plan based on feedback or additional context.\n * Single focused LLM call -- no multi-stage pipeline needed.\n * Returns the full revised plan as a markdown string.\n */\nexport async function editPlan(config: EditPlanConfig): Promise<string> {\n const { existingPlan, feedback, logger } = config;\n logger?.info('Editing plan', { feedbackLength: feedback.length });\n\n if (!existingPlan || existingPlan.trim().length < 50) {\n throw new Error('existingPlan is too short or empty. Provide a valid plan to edit.');\n }\n if (!feedback || feedback.trim().length === 0) {\n throw new Error('feedback is empty. Provide edit instructions.');\n }\n\n const modelConfig = config.model ?? { provider: 'openai' as const, model: 'gpt-4o-mini' };\n const model = createModel(modelConfig);\n\n const response = await model.invoke(\n [\n { role: 'system' as const, content: EDIT_PLAN_SYSTEM_PROMPT },\n { role: 'user' as const, content: buildEditPlanPrompt(existingPlan, feedback) },\n ],\n { temperature: 0.3, maxOutputTokens: 16384 }\n );\n\n const revised = response.text?.trim() ?? '';\n if (!revised) {\n throw new Error('Model returned empty response when editing plan.');\n }\n\n logger?.info('Plan edited successfully', { outputLength: revised.length });\n return revised;\n}\n","/**\n * Wire requirement-gatherer output into the planning module.\n * Converts a FinalRequirement into a pre-filled PlanningContext at the design stage,\n * skipping the redundant discovery + requirements stages.\n */\n\nimport type { AgentResult } from '../../lib/types/agent';\nimport type { PlanningContext, PlanSections } from './types';\nimport type { PlanFromRequirementsConfig } from './from-requirements.types';\nimport type {\n FinalRequirement,\n DatabaseDesign,\n DatabaseEntity,\n Module,\n Actor,\n Flow,\n Story,\n} from '../requirement-gatherer/types';\nimport { processPlanningChat } from './chat';\n\n/* ── Markdown formatters ─────────────────────────────────── */\n\nfunction formatEntityFields(entity: DatabaseEntity): string {\n if (!entity.fields.length) return '';\n const rows = entity.fields.map(f => {\n const flags = [f.required ? 'required' : '', f.unique ? 'unique' : '']\n .filter(Boolean)\n .join(', ');\n return `| ${f.name} | ${f.type} | ${flags || '-'} | ${f.description} |`;\n });\n return `| Field | Type | Constraints | Description |\\n| --- | --- | --- | --- |\\n${rows.join('\\n')}`;\n}\n\nfunction formatDatabaseAsMarkdown(db: DatabaseDesign): string {\n const header = `## Data Models\\n\\n**Database:** ${db.type}\\n**Reasoning:** ${db.reasoning}\\n`;\n const entities = db.entities\n .map(e => {\n const fields = formatEntityFields(e);\n const relParts = e.relations.map(\n r => r.field + ' → ' + r.references + ' (' + r.description + ')'\n );\n const relations = relParts.length ? '\\n**Relations:** ' + relParts.join('; ') : '';\n const idxParts = e.indexes.map(\n i => i.name + ' [' + i.fields.join(', ') + ']' + (i.unique ? ' (unique)' : '')\n );\n const indexes = idxParts.length ? '\\n**Indexes:** ' + idxParts.join('; ') : '';\n return `### ${e.name}\\n\\n${e.description}\\n\\n${fields}${relations}${indexes}`;\n })\n .join('\\n\\n');\n return `${header}\\n${entities}`;\n}\n\nfunction formatModulesAsMarkdown(modules: Module[]): string {\n const items = modules\n .map(m => {\n const apis = m.apis.map(a => ` - \\`${a.operation}\\` ${a.name}: ${a.description}`).join('\\n');\n return `### ${m.name}\\n\\n${m.description} (entity: ${m.entity})\\n\\n**APIs:**\\n${apis}`;\n })\n .join('\\n\\n');\n return `## Feature Decisions\\n\\n${items}`;\n}\n\nfunction formatProjectOverview(req: FinalRequirement): string {\n const p = req.project;\n const features = p.features.map(f => `- ${f}`).join('\\n');\n return `# ${p.name}\\n\\n**Goal:** ${p.goal}\\n**Domain:** ${p.domain}\\n\\n${req.summary.overview}\\n\\n**Key Features:**\\n${features}`;\n}\n\nfunction formatTechStack(req: FinalRequirement): string {\n const p = req.project;\n return [\n '## Tech Stack',\n '',\n `- **Database:** ${p.database}`,\n `- **Backend Runtime:** ${p.backendRuntime}`,\n `- **API Style:** ${p.apiStyle}`,\n ].join('\\n');\n}\n\nfunction formatActorsContext(actors: Actor[], flows: Flow[], stories: Story[]): string {\n const parts: string[] = ['## Actors and Flows'];\n for (const actor of actors) {\n parts.push(`\\n### ${actor.name}\\n${actor.description}`);\n const actorFlows = flows.filter(f => f.actorId === actor.id);\n if (actorFlows.length) {\n parts.push('**Flows:**');\n for (const f of actorFlows) {\n parts.push(`- ${f.name}: ${f.description} (trigger: ${f.trigger}, outcome: ${f.outcome})`);\n }\n }\n }\n if (stories.length) {\n parts.push('\\n### Key User Stories');\n for (const s of stories.slice(0, 10)) {\n parts.push(`- As **${s.actor}**, I want to **${s.action}**, so that **${s.benefit}**`);\n }\n if (stories.length > 10) parts.push(`- ... and ${stories.length - 10} more stories`);\n }\n return parts.join('\\n');\n}\n\n/* ── Converter ───────────────────────────────────────────── */\n\n/**\n * Convert a FinalRequirement (from requirement-gatherer) into a PlanningContext\n * pre-filled at the design stage, skipping discovery + requirements.\n */\nexport function convertRequirementToContext(req: FinalRequirement): PlanningContext {\n const sections: PlanSections = {\n overview: `## Overview\\n\\n${req.summary.overview}`,\n techStack: formatTechStack(req),\n featureDecisions: formatModulesAsMarkdown(req.modules),\n dataModels: formatDatabaseAsMarkdown(req.database),\n pagesAndRoutes: null,\n authFlow: null,\n apiRoutes: null,\n implementation: null,\n executionPlan: null,\n edgeCases: null,\n testingChecklist: null,\n };\n\n return {\n stage: 'design',\n projectDescription:\n formatProjectOverview(req) + '\\n\\n' + formatActorsContext(req.actors, req.flows, req.stories),\n sections,\n history: [],\n pendingQuestions: [],\n };\n}\n\n/* ── Runner ──────────────────────────────────────────────── */\n\nconst MAX_TURNS = 8;\n\n/**\n * Run the planning pipeline starting from a FinalRequirement.\n * Skips discovery + requirements stages; begins at design.\n */\nexport async function runPlanningFromRequirements(\n config: PlanFromRequirementsConfig\n): Promise<AgentResult> {\n const { requirement, model: modelConfig, onStep, logger } = config;\n\n logger?.info('Starting planning from requirements (fast path)', {\n project: requirement.project.name,\n });\n\n const context = convertRequirementToContext(requirement);\n\n const triggerMsg =\n `Generate the implementation plan for \"${requirement.project.name}\". ` +\n 'The project description, tech stack, features, and data models are already provided in context. ' +\n 'Proceed with API routes, implementation details, execution plan, edge cases, and testing checklist.';\n\n let lastResult = await processPlanningChat(triggerMsg, context, {\n model: modelConfig,\n onStep,\n logger,\n });\n let turns = 1;\n\n while (!lastResult.planMarkdown && turns < MAX_TURNS) {\n logger?.debug('Planning from requirements turn', { turn: turns });\n lastResult = await processPlanningChat(\n 'continue - produce the complete implementation plan.',\n lastResult.context,\n { model: modelConfig, onStep, logger }\n );\n turns++;\n }\n\n const output = lastResult.planMarkdown ?? lastResult.message;\n const messages = lastResult.context.history.map(e => ({\n role: e.role as 'user' | 'system' | 'assistant',\n content: e.content,\n }));\n\n logger?.info('Planning from requirements completed', {\n turns,\n hasPlanMarkdown: !!lastResult.planMarkdown,\n });\n\n return { output, steps: [], totalUsage: undefined, messages };\n}\n","/**\n * Builder for PlanningContext - fluent API\n */\n\nimport type { PlanningContext, Stage, PlanSections, ChatEntry } from './types';\n\nconst DEFAULT_STAGE: Stage = 'discovery';\n\nconst EMPTY_SECTIONS: PlanSections = {\n overview: null,\n techStack: null,\n featureDecisions: null,\n dataModels: null,\n pagesAndRoutes: null,\n authFlow: null,\n apiRoutes: null,\n implementation: null,\n executionPlan: null,\n edgeCases: null,\n testingChecklist: null,\n};\n\nexport class PlanningContextBuilder {\n private data: Partial<PlanningContext> = {};\n\n withStage(stage: Stage): this {\n this.data.stage = stage;\n return this;\n }\n\n withProjectDescription(projectDescription: string | null): this {\n this.data.projectDescription = projectDescription;\n return this;\n }\n\n withSections(sections: Partial<PlanSections>): this {\n this.data.sections = { ...(this.data.sections ?? EMPTY_SECTIONS), ...sections };\n return this;\n }\n\n withHistory(history: ChatEntry[]): this {\n this.data.history = history;\n return this;\n }\n\n withPendingQuestions(pendingQuestions: string[]): this {\n this.data.pendingQuestions = pendingQuestions;\n return this;\n }\n\n reset(): this {\n this.data = {};\n return this;\n }\n\n build(): PlanningContext {\n return {\n stage: this.data.stage ?? DEFAULT_STAGE,\n projectDescription: this.data.projectDescription ?? null,\n sections: this.data.sections ?? { ...EMPTY_SECTIONS },\n history: this.data.history ?? [],\n pendingQuestions: this.data.pendingQuestions ?? [],\n };\n }\n}\n\nexport function createPlanningContextBuilder(): PlanningContextBuilder {\n return new PlanningContextBuilder();\n}\n","/**\n * Zod schema for extract_actors tool output\n */\n\nimport { z } from 'zod';\n\nexport const actorSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n goals: z.array(z.string()),\n});\n\nexport const actorsResultSchema = z.object({\n actors: z.array(actorSchema),\n message: z.string(),\n});\n\nexport type ActorResult = z.infer<typeof actorsResultSchema>;\n","/**\n * Zod schema for generate_flows tool output\n */\n\nimport { z } from 'zod';\n\nexport const flowSchema = z.object({\n id: z.string(),\n actorId: z.string(),\n name: z.string(),\n description: z.string(),\n trigger: z.string(),\n outcome: z.string(),\n});\n\nexport const flowsResultSchema = z.object({\n flows: z.array(flowSchema),\n message: z.string(),\n});\n\nexport type FlowsResult = z.infer<typeof flowsResultSchema>;\n","/**\n * Zod schema for generate_stories tool output\n */\n\nimport { z } from 'zod';\n\nexport const storySchema = z.object({\n id: z.string(),\n flowId: z.string(),\n actor: z.string(),\n action: z.string(),\n benefit: z.string(),\n preconditions: z.array(z.string()),\n postconditions: z.array(z.string()),\n dataInvolved: z.array(z.string()),\n});\n\nexport const storiesResultSchema = z.object({\n stories: z.array(storySchema),\n message: z.string(),\n});\n\nexport type StoriesResult = z.infer<typeof storiesResultSchema>;\n","/**\n * Zod schema for extract_modules tool output\n */\n\nimport { z } from 'zod';\n\nexport const crudApiSchema = z.object({\n id: z.string(),\n name: z.string(),\n operation: z.enum(['create', 'read', 'readAll', 'update', 'delete']),\n description: z.string(),\n inputs: z.array(z.string()),\n outputs: z.array(z.string()),\n});\n\nexport const extractedModuleSchema = z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n entity: z.string(),\n apis: z.array(crudApiSchema),\n});\n\nexport const modulesResultSchema = z.object({\n modules: z.array(extractedModuleSchema),\n summary: z.object({\n totalModules: z.number(),\n totalApis: z.number(),\n }),\n message: z.string(),\n});\n\nexport type ModulesResult = z.infer<typeof modulesResultSchema>;\n","/**\n * Zod schemas for DatabaseDesign, DatabaseEntity, EntityField, EntityIndex, EntityRelation\n */\n\nimport { z } from 'zod';\n\nexport const entityFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.boolean(),\n unique: z.boolean(),\n description: z.string(),\n default: z.string().optional(),\n});\n\nexport const entityIndexSchema = z.object({\n name: z.string(),\n fields: z.array(z.string()),\n unique: z.boolean(),\n});\n\nexport const entityRelationSchema = z.object({\n field: z.string(),\n references: z.string(),\n description: z.string(),\n});\n\nexport const databaseEntitySchema = z.object({\n name: z.string(),\n description: z.string(),\n fields: z.array(entityFieldSchema),\n indexes: z.array(entityIndexSchema),\n relations: z.array(entityRelationSchema),\n});\n\nexport const databaseDesignSchema = z.object({\n type: z.enum(['mongodb', 'postgresql']),\n reasoning: z.string(),\n entities: z.array(databaseEntitySchema),\n});\n\nexport type EntityField = z.infer<typeof entityFieldSchema>;\nexport type EntityIndex = z.infer<typeof entityIndexSchema>;\nexport type EntityRelation = z.infer<typeof entityRelationSchema>;\nexport type DatabaseEntity = z.infer<typeof databaseEntitySchema>;\nexport type DatabaseDesign = z.infer<typeof databaseDesignSchema>;\n","/**\n * Zod schemas for RequirementContext, ProjectBrief, Question, ChatEntry\n * Note: apiDesign removed -- API design is delegated to the api-designer module.\n */\n\nimport { z } from 'zod';\nimport { actorSchema } from './actor.schema';\nimport { flowSchema } from './flow.schema';\nimport { storySchema } from './story.schema';\nimport { extractedModuleSchema } from './module.schema';\nimport { databaseDesignSchema } from './database.schema';\n\nexport const projectBriefSchema = z.object({\n name: z.string(),\n goal: z.string(),\n features: z.array(z.string()),\n domain: z.string(),\n database: z.enum(['mongodb', 'postgresql']),\n backendRuntime: z.literal('nodejs'),\n apiStyle: z.enum(['rest', 'graphql']),\n});\n\nexport const questionSchema = z.object({\n id: z.string(),\n question: z.string(),\n context: z.string(),\n suggestions: z.array(z.string()),\n multiSelect: z.boolean(),\n required: z.boolean(),\n});\n\nexport const chatEntrySchema = z.object({\n role: z.enum(['user', 'assistant']),\n content: z.string(),\n});\n\nexport const requirementContextSchema = z.object({\n stage: z.enum(['discovery', 'requirements', 'design', 'complete']),\n projectBrief: projectBriefSchema.nullable(),\n actors: z.array(actorSchema),\n flows: z.array(flowSchema),\n stories: z.array(storySchema),\n modules: z.array(extractedModuleSchema),\n database: databaseDesignSchema.nullable(),\n history: z.array(chatEntrySchema),\n pendingQuestions: z.array(questionSchema),\n});\n\nexport type ProjectBrief = z.infer<typeof projectBriefSchema>;\nexport type Question = z.infer<typeof questionSchema>;\nexport type ChatEntry = z.infer<typeof chatEntrySchema>;\nexport type RequirementContext = z.infer<typeof requirementContextSchema>;\n","/**\n * Zod schemas for FinalRequirement, RequirementSummary\n * Note: apiDesign removed -- API design is delegated to the api-designer module.\n */\n\nimport { z } from 'zod';\nimport { projectBriefSchema } from './context.schema';\nimport { actorSchema } from './actor.schema';\nimport { flowSchema } from './flow.schema';\nimport { storySchema } from './story.schema';\nimport { extractedModuleSchema } from './module.schema';\nimport { databaseDesignSchema } from './database.schema';\n\nexport const requirementSummarySchema = z.object({\n totalActors: z.number(),\n totalFlows: z.number(),\n totalStories: z.number(),\n totalModules: z.number(),\n totalEntities: z.number(),\n overview: z.string(),\n});\n\nexport const finalRequirementSchema = z.object({\n project: projectBriefSchema,\n actors: z.array(actorSchema),\n flows: z.array(flowSchema),\n stories: z.array(storySchema),\n modules: z.array(extractedModuleSchema),\n database: databaseDesignSchema,\n summary: requirementSummarySchema,\n});\n\nexport type RequirementSummary = z.infer<typeof requirementSummarySchema>;\nexport type FinalRequirement = z.infer<typeof finalRequirementSchema>;\n","/**\n * System prompt for chat-based requirement gathering\n */\n\nexport const REQUIREMENT_GATHERER_SYSTEM_PROMPT = `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.\n\nYou work in stages: discovery (understand the project and tech preferences), requirements (actors, flows, stories, modules), design (database + APIs), and complete (final document).\n\nThink 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.\n\nGuidelines:\n- For tech choices (API style: REST vs GraphQL; database: MongoDB vs PostgreSQL), offer predefined options and ask what the user is comfortable with.\n- For everything else, ask open-ended, context-specific questions based on what the user described. Leave suggestions empty for those.\n- Never repeat a question already answered in the conversation history.\n- When the user says \"continue\", \"yes\", \"looks good\", or similar, treat it as confirmation and advance.\n- Return valid JSON only when the prompt asks for JSON (no markdown code fences unless specified).\n- Backend is Node.js only; database is MongoDB or PostgreSQL per user preference.`;\n","/**\n * Discovery stage prompt - understand project and optionally ask questions\n */\n\nexport const DISCOVERY_SYSTEM_FRAGMENT = `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.\n\nDetermine from the user's words:\n- Project name and goal\n- Key features (array of strings)\n- Domain (e.g. e-commerce, healthcare, saas)\n- API style: \"rest\" | \"graphql\" — infer from context or ask with predefined options\n- Database: \"mongodb\" | \"postgresql\" — ask which they are comfortable with, with predefined options\n- Backend is always \"nodejs\"\n\nQuestion rules:\n- Tech stack (API style, database): Always provide \"suggestions\" with predefined options (e.g. [\"REST\", \"GraphQL\"], [\"MongoDB\", \"PostgreSQL\"]). Frame as \"which are you comfortable with?\"\n- 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).\n- Never ask: scale, \"how many users?\", \"what's the complexity?\", or generic intake-form questions.\n- Before asking, check conversation history — never repeat something already answered.\n- 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.`;\n\nexport const DISCOVERY_USER_PROMPT = `## Current user message:\n{userMessage}\n\n## Prior conversation (if any):\n{history}\n\nAnalyze 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.\n\nReturn ONLY valid JSON (no markdown, no explanation) in this shape:\n{\n \"needsClarification\": boolean,\n \"questions\": [\n {\n \"id\": \"q1\",\n \"question\": \"Question text\",\n \"context\": \"Why this helps\",\n \"suggestions\": [],\n \"multiSelect\": false,\n \"required\": true\n }\n ],\n \"conversationalMessage\": \"Brief friendly message to the user\",\n \"projectBrief\": {\n \"name\": \"string\",\n \"goal\": \"string\",\n \"features\": [\"string\"],\n \"domain\": \"string\",\n \"database\": \"mongodb\" | \"postgresql\",\n \"backendRuntime\": \"nodejs\",\n \"apiStyle\": \"rest\" | \"graphql\"\n }\n}\n\nFor tech choices (API style, database), populate \"suggestions\" with the predefined options. For all other questions, use \"suggestions\": [].\nIf needsClarification is true, projectBrief can have empty/default values. If false, projectBrief must be complete.`;\n\nexport function buildDiscoveryPrompt(userMessage: string, history: string): string {\n return DISCOVERY_USER_PROMPT.replace('{userMessage}', userMessage).replace(\n '{history}',\n history || '(No prior messages)'\n );\n}\n","/**\n * Requirements stage prompts - actors, flows, stories, modules (chained)\n */\n\nconst PROJECT_BLOCK = `## Project:\n- **Name**: {projectName}\n- **Goal**: {projectGoal}\n- **Features**: {projectFeatures}`;\n\nexport const EXTRACT_ACTORS_PROMPT = `${PROJECT_BLOCK}\n\nIdentify ALL distinct user types (actors) who will use this system. 2-5 actors. Include unauthenticated and admin roles if applicable.\n\nReturn ONLY valid JSON:\n{\n \"actors\": [\n { \"id\": \"actor-1\", \"name\": \"Name\", \"description\": \"Who they are\", \"goals\": [\"goal1\", \"goal2\"] }\n ],\n \"message\": \"Brief explanation\"\n}`;\n\nexport const GENERATE_FLOWS_PROMPT = `${PROJECT_BLOCK}\n\n## Actors (JSON):\n{actors}\n\nFor EACH actor, identify 2-5 key user journeys (flows). Each flow: id, actorId, name, description, trigger, outcome.\n\nReturn ONLY valid JSON:\n{\n \"flows\": [\n { \"id\": \"flow-1\", \"actorId\": \"actor-1\", \"name\": \"Flow Name\", \"description\": \"...\", \"trigger\": \"...\", \"outcome\": \"...\" }\n ],\n \"message\": \"Brief explanation\"\n}`;\n\nexport const GENERATE_STORIES_PROMPT = `${PROJECT_BLOCK}\n\n## Actors: {actors}\n\n## Flows (JSON):\n{flows}\n\nFor EACH flow, generate 2-5 user stories. Each story MUST include dataInvolved (entity.field names) for DB design. Include preconditions, postconditions.\n\nReturn ONLY valid JSON:\n{\n \"stories\": [\n { \"id\": \"story-1\", \"flowId\": \"flow-1\", \"actor\": \"ActorName\", \"action\": \"...\", \"benefit\": \"...\", \"preconditions\": [], \"postconditions\": [], \"dataInvolved\": [\"User.email\", \"Order.total\"] }\n ],\n \"message\": \"Brief explanation\"\n}`;\n\nexport const EXTRACT_MODULES_PROMPT = `${PROJECT_BLOCK}\n\n## Actors: {actors}\n## Flows: {flows}\n## Stories (JSON):\n{stories}\n\nExtract 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.\n\nReturn ONLY valid JSON:\n{\n \"modules\": [\n { \"id\": \"module-1\", \"name\": \"User\", \"description\": \"...\", \"entity\": \"User\", \"apis\": [ { \"id\": \"api-1-1\", \"name\": \"createUser\", \"operation\": \"create\", \"description\": \"...\", \"inputs\": [], \"outputs\": [] } ] }\n ],\n \"summary\": { \"totalModules\": 0, \"totalApis\": 0 },\n \"message\": \"Brief explanation\"\n}`;\n\nexport function buildExtractActorsPrompt(\n projectName: string,\n projectGoal: string,\n projectFeatures: string\n): string {\n return EXTRACT_ACTORS_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{projectFeatures}', projectFeatures);\n}\n\nexport function buildGenerateFlowsPrompt(\n projectName: string,\n projectGoal: string,\n projectFeatures: string,\n actorsJson: string\n): string {\n return GENERATE_FLOWS_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{projectFeatures}', projectFeatures)\n .replace('{actors}', actorsJson);\n}\n\nexport function buildGenerateStoriesPrompt(\n projectName: string,\n projectGoal: string,\n projectFeatures: string,\n actorsJson: string,\n flowsJson: string\n): string {\n return GENERATE_STORIES_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{projectFeatures}', projectFeatures)\n .replace('{actors}', actorsJson)\n .replace('{flows}', flowsJson);\n}\n\nexport function buildExtractModulesPrompt(\n projectName: string,\n projectGoal: string,\n projectFeatures: string,\n actorsJson: string,\n flowsJson: string,\n storiesJson: string\n): string {\n return EXTRACT_MODULES_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{projectFeatures}', projectFeatures)\n .replace('{actors}', actorsJson)\n .replace('{flows}', flowsJson)\n .replace('{stories}', storiesJson);\n}\n","/**\n * Design stage prompts - direct LLM invocation for database and API design\n */\n\nconst DESIGN_DB_PROMPT = `You are a database architect. The project brief includes a \"database\" field (mongodb or postgresql)—use that database. Do not choose a different one. Output a single JSON object.\n\n## Project brief (includes database: \"mongodb\" | \"postgresql\"):\n{projectBrief}\n\n## Modules (entities and CRUD):\n{modules}\n\n## User stories (data involved):\n{stories}\n\nDesign 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.\n\nReturn ONLY valid JSON (no markdown) in this exact shape. Set \"type\" to the database from the project brief.\n{\n \"type\": \"mongodb\" | \"postgresql\",\n \"reasoning\": \"2-4 sentences on how the schema fits the project\",\n \"entities\": [\n {\n \"name\": \"EntityName\",\n \"description\": \"Brief description\",\n \"fields\": [\n { \"name\": \"fieldName\", \"type\": \"DB-native type\", \"required\": true, \"unique\": false, \"description\": \"...\" }\n ],\n \"indexes\": [ { \"name\": \"index_name\", \"fields\": [\"field1\"], \"unique\": false } ],\n \"relations\": [ { \"field\": \"refField\", \"references\": \"OtherEntity\", \"description\": \"...\" } ]\n }\n ]\n}`;\n\nconst DESIGN_APIS_PROMPT = `You are an API architect for Node.js backends. Design the API according to apiStyle in the project brief.\n\n## Project brief (includes apiStyle: \"rest\" | \"graphql\"):\n{projectBrief}\n\n## Modules:\n{modules}\n\n## Actors:\n{actors}\n\n## Stories:\n{stories}\n\n## Database design (entities and fields):\n{database}\n\nProduce an API design:\n- 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—even for list endpoints use a single object describing the shape (e.g. for GET /users use \"responseBody\": { \"items\": \"array of user objects\", \"total\": \"number\" }).\n- 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.\n\nReturn ONLY valid JSON (no markdown, no code fences). Required shape:\n{\n \"style\": \"rest\" or \"graphql\",\n \"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\": {} } ] },\n \"graphql\": { \"types\": [], \"queries\": [], \"mutations\": [] }\n}\n- Use lowercase \"rest\" or \"graphql\" for style. Omit the branch not used (omit \"graphql\" when style is \"rest\", omit \"rest\" when style is \"graphql\").`;\n\nexport const DESIGN_DATABASE_SYSTEM_PROMPT =\n 'You output only valid JSON. No markdown, no explanation.';\n\nexport const DESIGN_APIS_SYSTEM_PROMPT = 'You output only valid JSON. No markdown, no explanation.';\n\nexport function buildDesignDatabasePrompt(\n projectBrief: string,\n modules: string,\n stories: string\n): string {\n return DESIGN_DB_PROMPT.replace('{projectBrief}', projectBrief)\n .replace('{modules}', modules)\n .replace('{stories}', stories);\n}\n\nexport function buildDesignApisPrompt(\n projectBrief: string,\n modules: string,\n actors: string,\n stories: string,\n database: string\n): string {\n return DESIGN_APIS_PROMPT.replace('{projectBrief}', projectBrief)\n .replace('{modules}', modules)\n .replace('{actors}', actors)\n .replace('{stories}', stories)\n .replace('{database}', database);\n}\n","/**\n * Synthesis stage prompt - compile FinalRequirement document\n * Note: apiDesign removed; API design is delegated to the api-designer module.\n */\n\nexport const SYNTHESIS_SYSTEM_FRAGMENT = `You are in the complete stage. You have the full context: project brief, actors, flows, stories, modules, and database design. Your job is to produce a single final requirement document (JSON) that matches the FinalRequirement schema, with a summary that includes totalActors, totalFlows, totalStories, totalModules, totalEntities, and a short overview paragraph.`;\n\nexport const SYNTHESIS_USER_PROMPT = `## Project brief (JSON):\n{projectBrief}\n\n## Actors (JSON):\n{actors}\n\n## Flows (JSON):\n{flows}\n\n## Stories (JSON):\n{stories}\n\n## Modules (JSON):\n{modules}\n\n## Database design (JSON):\n{database}\n\nCompile the above into one FinalRequirement JSON. Include a \"summary\" object with: totalActors, totalFlows, totalStories, totalModules, totalEntities (from database.entities.length), and \"overview\" (2-4 sentence paragraph summarizing the project and tech choices).\n\nReturn ONLY valid JSON in this shape (no markdown, no extra text):\n{\n \"project\": { ... },\n \"actors\": [ ... ],\n \"flows\": [ ... ],\n \"stories\": [ ... ],\n \"modules\": [ ... ],\n \"database\": { ... },\n \"summary\": {\n \"totalActors\": 0,\n \"totalFlows\": 0,\n \"totalStories\": 0,\n \"totalModules\": 0,\n \"totalEntities\": 0,\n \"overview\": \"string\"\n }\n}`;\n\nexport function buildSynthesisPrompt(\n projectBrief: string,\n actors: string,\n flows: string,\n stories: string,\n modules: string,\n database: string\n): string {\n return SYNTHESIS_USER_PROMPT.replace('{projectBrief}', projectBrief)\n .replace('{actors}', actors)\n .replace('{flows}', flows)\n .replace('{stories}', stories)\n .replace('{modules}', modules)\n .replace('{database}', database);\n}\n","/**\n * Context management for requirement chat\n */\n\nimport type { RequirementContext, StageResult, Stage, ChatEntry } from './types';\n\nexport function createInitialContext(): RequirementContext {\n return {\n stage: 'discovery',\n projectBrief: null,\n actors: [],\n flows: [],\n stories: [],\n modules: [],\n database: null,\n history: [],\n pendingQuestions: [],\n };\n}\n\nexport function mergeStageResult(\n context: RequirementContext,\n result: StageResult\n): RequirementContext {\n const data = result.data;\n return {\n ...context,\n ...(data.stage !== undefined && { stage: data.stage }),\n ...(data.projectBrief !== undefined && { projectBrief: data.projectBrief }),\n ...(data.actors !== undefined && { actors: data.actors }),\n ...(data.flows !== undefined && { flows: data.flows }),\n ...(data.stories !== undefined && { stories: data.stories }),\n ...(data.modules !== undefined && { modules: data.modules }),\n ...(data.database !== undefined && { database: data.database }),\n ...(data.pendingQuestions !== undefined && { pendingQuestions: data.pendingQuestions }),\n };\n}\n\nexport function addChatEntry(\n context: RequirementContext,\n role: 'user' | 'assistant',\n content: string\n): RequirementContext {\n const entry: ChatEntry = { role, content };\n return {\n ...context,\n history: [...context.history, entry],\n };\n}\n\nexport function advanceStage(context: RequirementContext): RequirementContext {\n const order: Stage[] = ['discovery', 'requirements', 'design', 'complete'];\n const idx = order.indexOf(context.stage);\n const nextStage = idx >= 0 && idx < order.length - 1 ? order[idx + 1] : undefined;\n const next: Stage = nextStage ?? context.stage;\n return { ...context, stage: next };\n}\n","/**\n * Stage processor interface and shared helpers\n */\n\nimport type { RequirementContext, Module, Story } from '../types';\n\nexport type { StageProcessor } from '../types';\n\n/** Summarize modules for token-efficient prompts (name, entity, API count) */\nexport function summarizeModules(modules: Module[]): string {\n return modules.map(m => `${m.name}: ${m.entity} (${m.apis.length} APIs)`).join('\\n');\n}\n\n/** Summarize stories for token-efficient prompts (actor + action) */\nexport function summarizeStories(stories: Story[]): string {\n return stories.map(s => `- ${s.actor}: ${s.action}`).join('\\n');\n}\n\nexport function extractJson(text: string): string {\n const trimmed = text.trim();\n const codeBlock = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n if (codeBlock?.[1]) return codeBlock[1].trim();\n return trimmed;\n}\n\nexport function safeParseJson(\n text: string\n): { success: true; data: unknown } | { success: false; error: string } {\n try {\n return { success: true, data: JSON.parse(text) };\n } catch (e) {\n return {\n success: false,\n error: e instanceof Error ? e.message : String(e),\n };\n }\n}\n\n/** Build a short text summary of context for inclusion in prompts */\nexport function buildContextSummary(ctx: RequirementContext): string {\n const parts: string[] = [];\n if (ctx.projectBrief) {\n parts.push(\n `Project: ${ctx.projectBrief.name}, Goal: ${ctx.projectBrief.goal}, API: ${ctx.projectBrief.apiStyle}`\n );\n }\n if (ctx.actors.length) parts.push(`Actors: ${ctx.actors.length}`);\n if (ctx.flows.length) parts.push(`Flows: ${ctx.flows.length}`);\n if (ctx.stories.length) parts.push(`Stories: ${ctx.stories.length}`);\n if (ctx.modules.length) parts.push(`Modules: ${ctx.modules.length}`);\n if (ctx.database) parts.push(`Database: ${ctx.database.type}`);\n return parts.join('. ') || 'No context yet';\n}\n\nexport function isConfirmation(message: string): boolean {\n const normalized = message.trim().toLowerCase();\n const confirmations = [\n 'continue',\n 'yes',\n 'yeah',\n 'yep',\n 'looks good',\n 'good',\n 'ok',\n 'okay',\n 'next',\n 'proceed',\n 'sure',\n ];\n return confirmations.some(c => normalized === c || normalized.startsWith(c + ' '));\n}\n","/**\n * Discovery stage - understand project, optional clarifying questions\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { RequirementContext, StageResult } from '../types';\nimport { projectBriefSchema, questionSchema } from '../schemas';\nimport { REQUIREMENT_GATHERER_SYSTEM_PROMPT } from '../prompts';\nimport { DISCOVERY_SYSTEM_FRAGMENT, buildDiscoveryPrompt } from '../prompts';\nimport { extractJson, safeParseJson } from './base';\n\nexport async function runDiscoveryStage(\n userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<StageResult> {\n logger?.debug('Discovery stage started', { historyLength: context.history.length });\n\n const history = context.history\n .map(e => `${e.role}: ${e.content}`)\n .slice(-10)\n .join('\\n');\n const prompt = buildDiscoveryPrompt(userMessage, history);\n const systemContent = `${REQUIREMENT_GATHERER_SYSTEM_PROMPT}\\n\\n${DISCOVERY_SYSTEM_FRAGMENT}`;\n const messages = [\n { role: 'system' as const, content: systemContent },\n { role: 'user' as const, content: prompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 4096 });\n const jsonStr = extractJson(response.text);\n const parsed = safeParseJson(jsonStr);\n if (!parsed.success) {\n logger?.warn('Discovery response was not valid JSON', { error: parsed.error });\n return {\n message: \"I couldn't parse that. Could you describe your project in a few sentences?\",\n advance: false,\n data: {},\n };\n }\n const data = parsed.data as {\n needsClarification?: boolean;\n questions?: unknown[];\n conversationalMessage?: string;\n projectBrief?: unknown;\n };\n const message =\n data.conversationalMessage ?? response.text?.slice(0, 500) ?? 'Thanks for the details.';\n const needsClarification = data.needsClarification === true;\n const questions: RequirementContext['pendingQuestions'] = [];\n if (Array.isArray(data.questions)) {\n for (const q of data.questions) {\n const validated = questionSchema.safeParse(q);\n if (validated.success) questions.push(validated.data);\n }\n }\n let projectBrief: RequirementContext['projectBrief'] = null;\n if (data.projectBrief && !needsClarification) {\n const pb = projectBriefSchema.safeParse(data.projectBrief);\n if (pb.success) projectBrief = pb.data;\n }\n logger?.debug('Discovery stage complete', {\n advance: !needsClarification && projectBrief !== null,\n hasProjectBrief: !!projectBrief,\n questionsCount: questions.length,\n });\n return {\n message,\n questions: questions.length ? questions : undefined,\n advance: !needsClarification && projectBrief !== null,\n data: {\n ...(projectBrief && { projectBrief }),\n pendingQuestions: questions,\n },\n };\n}\n","/**\n * Requirements stage: structured output via invokeObject, or invoke + parse\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { ModelMessage } from '../../../lib/types/common';\nimport type { ActorResult, FlowsResult, StoriesResult, ModulesResult } from '../schemas';\nimport {\n actorsResultSchema,\n flowsResultSchema,\n storiesResultSchema,\n modulesResultSchema,\n} from '../schemas';\nimport { extractJson, safeParseJson } from './base';\n\nexport async function getActors(\n model: Model,\n messages: ModelMessage[],\n _logger?: Logger\n): Promise<ActorResult> {\n if (model.invokeObject) {\n const result = await model.invokeObject<ActorResult>(messages, actorsResultSchema, {\n temperature: 0.4,\n maxOutputTokens: 4096,\n });\n return result.data;\n }\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 4096 });\n const parsed = safeParseJson(extractJson(response.text));\n if (!parsed.success) throw new Error(`Actors: ${parsed.error}`);\n const validated = actorsResultSchema.safeParse(parsed.data);\n if (!validated.success) throw new Error(`Actors schema: ${validated.error.message}`);\n return validated.data;\n}\n\nexport async function getFlows(\n model: Model,\n messages: ModelMessage[],\n _actors: ActorResult['actors'],\n _logger?: Logger\n): Promise<FlowsResult> {\n if (model.invokeObject) {\n const result = await model.invokeObject<FlowsResult>(messages, flowsResultSchema, {\n temperature: 0.4,\n maxOutputTokens: 8192,\n });\n return result.data;\n }\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 8192 });\n const parsed = safeParseJson(extractJson(response.text));\n if (!parsed.success) throw new Error(`Flows: ${parsed.error}`);\n const validated = flowsResultSchema.safeParse(parsed.data);\n if (!validated.success) throw new Error(`Flows schema: ${validated.error.message}`);\n return validated.data;\n}\n\nexport async function getStories(\n model: Model,\n messages: ModelMessage[],\n _actors: ActorResult['actors'],\n _flows: FlowsResult['flows'],\n _logger?: Logger\n): Promise<StoriesResult> {\n if (model.invokeObject) {\n const result = await model.invokeObject<StoriesResult>(messages, storiesResultSchema, {\n temperature: 0.4,\n maxOutputTokens: 16384,\n });\n return result.data;\n }\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 16384 });\n const parsed = safeParseJson(extractJson(response.text));\n if (!parsed.success) throw new Error(`Stories: ${parsed.error}`);\n const validated = storiesResultSchema.safeParse(parsed.data);\n if (!validated.success) throw new Error(`Stories schema: ${validated.error.message}`);\n return validated.data;\n}\n\nexport async function getModules(\n model: Model,\n messages: ModelMessage[],\n _actors: ActorResult['actors'],\n _flows: FlowsResult['flows'],\n _stories: StoriesResult['stories'],\n _logger?: Logger\n): Promise<ModulesResult> {\n if (model.invokeObject) {\n const result = await model.invokeObject<ModulesResult>(messages, modulesResultSchema, {\n temperature: 0.4,\n maxOutputTokens: 16384,\n });\n return result.data;\n }\n const response = await model.invoke(messages, { temperature: 0.4, maxOutputTokens: 16384 });\n const parsed = safeParseJson(extractJson(response.text));\n if (!parsed.success) throw new Error(`Modules: ${parsed.error}`);\n const validated = modulesResultSchema.safeParse(parsed.data);\n if (!validated.success) throw new Error(`Modules schema: ${validated.error.message}`);\n return validated.data;\n}\n","/**\n * Requirements stage - chain actors -> flows -> stories -> modules\n * Uses AI SDK structured output (invokeObject); no fallback data.\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { ModelMessage } from '../../../lib/types/common';\nimport type { RequirementContext, StageResult } from '../types';\nimport { REQUIREMENT_GATHERER_SYSTEM_PROMPT } from '../prompts';\nimport {\n buildExtractActorsPrompt,\n buildGenerateFlowsPrompt,\n buildGenerateStoriesPrompt,\n buildExtractModulesPrompt,\n} from '../prompts';\nimport { getActors, getFlows, getStories, getModules } from './requirements-invoke';\n\nexport async function runRequirementsStage(\n _userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<StageResult> {\n logger?.debug('Requirements stage started');\n\n const brief = context.projectBrief;\n if (!brief) {\n return {\n message: 'Project brief is missing. Complete discovery first.',\n advance: false,\n data: {},\n };\n }\n const projectName = brief.name;\n const projectGoal = brief.goal;\n const projectFeatures = brief.features.join('. ');\n\n const messages: ModelMessage[] = [\n { role: 'system', content: REQUIREMENT_GATHERER_SYSTEM_PROMPT },\n ];\n\n try {\n messages.push({\n role: 'user',\n content: buildExtractActorsPrompt(projectName, projectGoal, projectFeatures),\n });\n const actorsResult = await getActors(model, messages, logger);\n const actors = actorsResult.actors;\n logger?.debug('Requirements: actors', { count: actors.length });\n\n messages.push({\n role: 'assistant',\n content: `[Extracted ${actors.length} actors]`,\n });\n messages.push({\n role: 'user',\n content: buildGenerateFlowsPrompt(\n projectName,\n projectGoal,\n projectFeatures,\n JSON.stringify(actors)\n ),\n });\n const flowsResult = await getFlows(model, messages, actors, logger);\n const flows = flowsResult.flows;\n logger?.debug('Requirements: flows', { count: flows.length });\n\n messages.push({\n role: 'assistant',\n content: `[Generated ${flows.length} flows]`,\n });\n messages.push({\n role: 'user',\n content: buildGenerateStoriesPrompt(\n projectName,\n projectGoal,\n projectFeatures,\n JSON.stringify(actors),\n JSON.stringify(flows)\n ),\n });\n const storiesResult = await getStories(model, messages, actors, flows, logger);\n const stories = storiesResult.stories;\n logger?.debug('Requirements: stories', { count: stories.length });\n\n messages.push({\n role: 'assistant',\n content: `[Generated ${stories.length} stories]`,\n });\n messages.push({\n role: 'user',\n content: buildExtractModulesPrompt(\n projectName,\n projectGoal,\n projectFeatures,\n JSON.stringify(actors),\n JSON.stringify(flows),\n JSON.stringify(stories)\n ),\n });\n const modulesResult = await getModules(model, messages, actors, flows, stories, logger);\n const modules = modulesResult.modules;\n logger?.debug('Requirements stage complete', {\n actors: actors.length,\n flows: flows.length,\n stories: stories.length,\n modules: modules.length,\n });\n\n return {\n message: `I've identified ${actors.length} actors, ${flows.length} flows, ${stories.length} stories, and ${modules.length} modules. Proceeding to technical design.`,\n advance: true,\n data: { actors, flows, stories, modules, pendingQuestions: [] },\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n logger?.warn('Requirements stage failed', { error: message });\n return {\n message: `Requirements step failed: ${message}. Please try again.`,\n advance: false,\n data: {},\n };\n }\n}\n","/**\n * Design stage - direct LLM call for database design (prompt chaining)\n * Note: API design removed; delegated to the api-designer module downstream.\n */\n\nimport { z } from 'zod';\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { RequirementContext, StageResult } from '../types';\nimport { databaseDesignSchema } from '../schemas';\nimport { extractJson, safeParseJson, summarizeModules, summarizeStories } from './base';\nimport { DESIGN_DATABASE_SYSTEM_PROMPT, buildDesignDatabasePrompt } from '../prompts';\n\nexport async function runDesignStage(\n _userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<StageResult> {\n const brief = context.projectBrief;\n if (!brief) {\n return { message: 'Project brief is missing.', advance: false, data: {} };\n }\n if (!context.modules.length || !context.stories.length) {\n return {\n message: 'Requirements (modules and stories) are missing. Run requirements stage first.',\n advance: false,\n data: {},\n };\n }\n\n logger?.info('Design stage: database design', {\n modules: context.modules.length,\n stories: context.stories.length,\n });\n\n const projectBriefStr = JSON.stringify(brief);\n const modulesSummary = summarizeModules(context.modules);\n const storiesSummary = summarizeStories(context.stories);\n\n const dbPrompt = buildDesignDatabasePrompt(projectBriefStr, modulesSummary, storiesSummary);\n const dbMessages = [\n { role: 'system' as const, content: DESIGN_DATABASE_SYSTEM_PROMPT },\n { role: 'user' as const, content: dbPrompt },\n ];\n const dbResponse = await model.invoke(dbMessages, {\n temperature: 0.3,\n maxOutputTokens: 8192,\n });\n const dbJsonStr = extractJson(dbResponse.text);\n const dbParsed = safeParseJson(dbJsonStr);\n if (!dbParsed.success) {\n logger?.warn('Database design response was not valid JSON', { error: dbParsed.error });\n return {\n message: 'Failed to parse database design response. Please try again.',\n advance: false,\n data: {},\n };\n }\n const databaseResult = databaseDesignSchema.safeParse(dbParsed.data);\n if (!databaseResult.success) {\n const err = databaseResult.error;\n logger?.warn('Database design schema validation failed', { error: z.treeifyError(err) });\n return {\n message: 'Failed to produce database design. Please try again.',\n advance: false,\n data: {},\n };\n }\n const database = databaseResult.data;\n\n return {\n message: `Database design complete: ${database.type}. API design will be handled by the api-designer module.`,\n advance: true,\n data: { database, pendingQuestions: [] },\n };\n}\n","/**\n * Synthesis stage - compile FinalRequirement document\n */\n\nimport type { Logger } from '../../../lib/types/common';\nimport type { Model } from '../../../lib/types/model';\nimport type { RequirementContext, StageResult } from '../types';\nimport type { FinalRequirement } from '../types';\nimport { finalRequirementSchema } from '../schemas';\nimport { REQUIREMENT_GATHERER_SYSTEM_PROMPT } from '../prompts';\nimport { SYNTHESIS_SYSTEM_FRAGMENT, buildSynthesisPrompt } from '../prompts';\nimport { extractJson, safeParseJson } from './base';\n\nexport async function runSynthesisStage(\n _userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<StageResult> {\n logger?.debug('Synthesis stage started');\n\n const brief = context.projectBrief;\n if (!brief || !context.database) {\n return {\n message: 'Missing project brief or database design. Complete earlier stages first.',\n advance: false,\n data: {},\n };\n }\n const prompt = buildSynthesisPrompt(\n JSON.stringify(brief),\n JSON.stringify(context.actors),\n JSON.stringify(context.flows),\n JSON.stringify(context.stories),\n JSON.stringify(context.modules),\n JSON.stringify(context.database)\n );\n const systemContent = `${REQUIREMENT_GATHERER_SYSTEM_PROMPT}\\n\\n${SYNTHESIS_SYSTEM_FRAGMENT}`;\n const messages = [\n { role: 'system' as const, content: systemContent },\n { role: 'user' as const, content: prompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 16384 });\n const jsonStr = extractJson(response.text);\n const parsed = safeParseJson(jsonStr);\n if (!parsed.success) {\n logger?.warn('Synthesis response was not valid JSON', { error: parsed.error });\n return {\n message: 'Failed to compile final requirement document. Please try again.',\n advance: false,\n data: {},\n };\n }\n const validated = finalRequirementSchema.safeParse(parsed.data);\n if (!validated.success) {\n logger?.warn('Synthesis: final requirement schema validation failed', {\n error: validated.error.message,\n });\n return {\n message: 'Final document did not match schema. ' + (response.text?.slice(0, 300) ?? ''),\n advance: false,\n data: {},\n };\n }\n const finalRequirement: FinalRequirement = validated.data;\n logger?.info('Synthesis stage complete', { overview: finalRequirement.summary?.overview });\n return {\n message: `Requirement document ready. ${finalRequirement.summary.overview}`,\n advance: true,\n data: { finalRequirement },\n };\n}\n","/**\n * Discovery stage - State pattern wrapper\n */\n\nimport type { RequirementContext, Stage, StageResult } from '../types';\nimport type { RequirementStageState, StageInput } from './state-types';\nimport { runDiscoveryStage } from './discovery.stage';\n\nexport class DiscoveryState implements RequirementStageState {\n readonly stageName: Stage = 'discovery';\n\n async process(context: RequirementContext, input: StageInput): Promise<StageResult> {\n return runDiscoveryStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: StageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): Stage | null {\n return 'requirements';\n }\n}\n","/**\n * Requirements stage - State pattern wrapper\n */\n\nimport type { RequirementContext, Stage, StageResult } from '../types';\nimport type { RequirementStageState, StageInput } from './state-types';\nimport { runRequirementsStage } from './requirements.stage';\n\nexport class RequirementsState implements RequirementStageState {\n readonly stageName: Stage = 'requirements';\n\n async process(context: RequirementContext, input: StageInput): Promise<StageResult> {\n return runRequirementsStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: StageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): Stage | null {\n return 'design';\n }\n}\n","/**\n * Design stage - State pattern wrapper\n */\n\nimport type { RequirementContext, Stage, StageResult } from '../types';\nimport type { RequirementStageState, StageInput } from './state-types';\nimport { runDesignStage } from './design.stage';\n\nexport class DesignState implements RequirementStageState {\n readonly stageName: Stage = 'design';\n\n async process(context: RequirementContext, input: StageInput): Promise<StageResult> {\n return runDesignStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: StageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): Stage | null {\n return 'complete';\n }\n}\n","/**\n * Synthesis (complete) stage - State pattern wrapper\n */\n\nimport type { RequirementContext, Stage, StageResult } from '../types';\nimport type { RequirementStageState, StageInput } from './state-types';\nimport { runSynthesisStage } from './synthesis.stage';\n\nexport class SynthesisState implements RequirementStageState {\n readonly stageName: Stage = 'complete';\n\n async process(context: RequirementContext, input: StageInput): Promise<StageResult> {\n return runSynthesisStage(input.userMessage, context, input.model, input.logger);\n }\n\n canAdvance(result: StageResult): boolean {\n return result.advance;\n }\n\n getNextStageName(): Stage | null {\n return null;\n }\n}\n","/**\n * Registry: map Stage (string) to State instance for State pattern routing.\n */\n\nimport type { Stage } from '../types';\nimport type { RequirementStageState } from './state-types';\nimport { DiscoveryState } from './discovery.state';\nimport { RequirementsState } from './requirements.state';\nimport { DesignState } from './design.state';\nimport { SynthesisState } from './synthesis.state';\n\nconst states: Record<Stage, RequirementStageState> = {\n discovery: new DiscoveryState(),\n requirements: new RequirementsState(),\n design: new DesignState(),\n complete: new SynthesisState(),\n};\n\nexport function getStateForStage(stage: Stage): RequirementStageState {\n return states[stage];\n}\n","/**\n * Stage routing and auto-advance logic (State pattern)\n */\n\nimport type { Logger } from '../../lib/types/common';\nimport type { Model } from '../../lib/types/model';\nimport type { RequirementContext, Stage, FinalRequirement } from './types';\nimport { getStateForStage } from './stages';\nimport { isConfirmation } from './stages/base';\nimport { advanceStage, mergeStageResult, addChatEntry } from './context';\n\n/**\n * Determine which stage to run for this turn.\n */\nexport function getStageForTurn(context: RequirementContext, _userMessage: string): Stage {\n return context.stage;\n}\n\n/**\n * Run the current stage via State pattern: get state for context.stage, process, merge result.\n * If result.advance, context.stage is advanced to the next state's stage name.\n */\nexport async function runStage(\n stage: Stage,\n userMessage: string,\n context: RequirementContext,\n model: Model,\n logger?: Logger\n): Promise<{\n message: string;\n questions: RequirementContext['pendingQuestions'];\n advance: boolean;\n data: RequirementContext;\n finalRequirement?: FinalRequirement;\n}> {\n logger?.debug('Stage processor invoked', { stage });\n const state = getStateForStage(stage);\n const result = await state.process(context, { userMessage, model, logger });\n const merged = mergeStageResult(context, result);\n const finalReq = 'finalRequirement' in result.data ? result.data.finalRequirement : undefined;\n logger?.debug('Stage result', {\n stage,\n advance: result.advance,\n hasFinalRequirement: !!finalReq,\n });\n const data: RequirementContext = {\n ...merged,\n pendingQuestions: result.questions ?? merged.pendingQuestions,\n };\n return {\n message: result.message,\n questions: result.questions ?? merged.pendingQuestions,\n advance: result.advance,\n data,\n finalRequirement: finalReq,\n };\n}\n\n/**\n * Whether the user message is a confirmation (continue / yes / looks good)\n */\nexport { isConfirmation };\n\n/**\n * Advance context to next stage\n */\nexport { advanceStage };\n\n/**\n * Add a chat entry to context history\n */\nexport { addChatEntry };\n","/**\n * processRequirementChat - main entry point for chat-based requirement gathering\n */\n\nimport { createModel } from '../../lib/models/create-model';\nimport type { RequirementContext, ChatTurnResult, RequirementChatConfig, Stage } from './types';\nimport { createInitialContext, addChatEntry, advanceStage } from './context';\nimport { runStage } from './router';\n\nconst STAGE_ORDER: Stage[] = ['discovery', 'requirements', 'design', 'complete'];\n\nexport async function processRequirementChat(\n userMessage: string,\n context: RequirementContext | null,\n config: RequirementChatConfig\n): Promise<ChatTurnResult> {\n const { logger } = config;\n\n const modelConfig = config.model ?? { provider: 'openai', model: 'gpt-4o-mini' };\n const model = createModel(modelConfig);\n\n let ctx: RequirementContext = context ?? createInitialContext();\n ctx = addChatEntry(ctx, 'user', userMessage);\n\n logger?.info('Chat turn', { stage: ctx.stage, messageLength: userMessage.length });\n\n let message = '';\n let questions: RequirementContext['pendingQuestions'] = [];\n let finalRequirement: ChatTurnResult['finalRequirement'] = null;\n\n const runOne = async (\n stage: Stage\n ): Promise<{ advance: boolean; finalReq?: ChatTurnResult['finalRequirement'] }> => {\n const result = await runStage(stage, userMessage, ctx, model, logger);\n message = result.message;\n questions = result.questions;\n ctx = result.data;\n if (result.finalRequirement) finalRequirement = result.finalRequirement;\n return { advance: result.advance, finalReq: result.finalRequirement };\n };\n\n let stage = ctx.stage;\n logger?.info('Stage', { stage });\n let runResult = await runOne(stage);\n ctx = { ...ctx, pendingQuestions: questions };\n\n while (runResult.advance && !finalRequirement) {\n const idx = STAGE_ORDER.indexOf(stage);\n const nextStage = idx >= 0 && idx < STAGE_ORDER.length - 1 ? STAGE_ORDER[idx + 1] : undefined;\n if (nextStage === undefined) break;\n logger?.info('Stage transition', { from: stage, to: nextStage });\n stage = nextStage;\n ctx = advanceStage(ctx);\n ctx = { ...ctx, stage };\n logger?.info('Stage', { stage });\n runResult = await runOne(stage);\n ctx = { ...ctx, pendingQuestions: questions };\n }\n\n ctx = addChatEntry(ctx, 'assistant', message);\n\n logger?.info('Chat turn done', { stage, hasFinalRequirement: !!finalRequirement });\n return {\n message,\n context: ctx,\n questions,\n finalRequirement,\n };\n}\n","/**\n * runRequirementGathererAgent - one-shot wrapper around processRequirementChat\n * Runs the full chat flow non-interactively, auto-advancing with \"continue\" when questions are asked.\n */\n\nimport type { RequirementGathererAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\nimport { processRequirementChat } from './chat';\n\nconst MAX_TURNS = 10;\n\n/**\n * Run the requirement gatherer in one-shot mode: single input, auto-advance through stages,\n * return final requirement document or last message as AgentResult.\n */\nexport async function runRequirementGathererAgent(\n config: RequirementGathererAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, onStep, logger } = config;\n logger?.info('Starting requirement gatherer agent', { maxTurns: MAX_TURNS });\n\n let context = null;\n let lastResult = await processRequirementChat(input, context, {\n model: modelConfig,\n onStep,\n logger,\n });\n context = lastResult.context;\n let turns = 1;\n while (!lastResult.finalRequirement && turns < MAX_TURNS) {\n logger?.debug('Requirement gatherer turn', { turn: turns });\n lastResult = await processRequirementChat('continue', context, {\n model: modelConfig,\n onStep,\n logger,\n });\n context = lastResult.context;\n turns++;\n }\n const output = lastResult.finalRequirement\n ? JSON.stringify(lastResult.finalRequirement, null, 2)\n : lastResult.message;\n const messages = context.history.map(e => ({\n role: e.role as 'user' | 'system' | 'assistant',\n content: e.content,\n }));\n\n logger?.info('Requirement gatherer agent completed', {\n turns,\n hasFinalRequirement: !!lastResult.finalRequirement,\n });\n return {\n output,\n steps: [],\n totalUsage: undefined,\n messages,\n };\n}\n","/**\n * Builder for RequirementContext - fluent API, max 150 lines.\n */\n\nimport type {\n RequirementContext,\n Stage,\n ProjectBrief,\n Actor,\n Flow,\n Story,\n Module,\n DatabaseDesign,\n ChatEntry,\n Question,\n} from './types';\n\nconst DEFAULT_STAGE: Stage = 'discovery';\n\nexport class RequirementContextBuilder {\n private data: Partial<RequirementContext> = {};\n\n withStage(stage: Stage): this {\n this.data.stage = stage;\n return this;\n }\n\n withProjectBrief(projectBrief: ProjectBrief | null): this {\n this.data.projectBrief = projectBrief;\n return this;\n }\n\n withActors(actors: Actor[]): this {\n this.data.actors = actors;\n return this;\n }\n\n withFlows(flows: Flow[]): this {\n this.data.flows = flows;\n return this;\n }\n\n withStories(stories: Story[]): this {\n this.data.stories = stories;\n return this;\n }\n\n withModules(modules: Module[]): this {\n this.data.modules = modules;\n return this;\n }\n\n withDatabase(database: DatabaseDesign | null): this {\n this.data.database = database;\n return this;\n }\n\n withHistory(history: ChatEntry[]): this {\n this.data.history = history;\n return this;\n }\n\n withPendingQuestions(pendingQuestions: Question[]): this {\n this.data.pendingQuestions = pendingQuestions;\n return this;\n }\n\n reset(): this {\n this.data = {};\n return this;\n }\n\n build(): RequirementContext {\n return {\n stage: this.data.stage ?? DEFAULT_STAGE,\n projectBrief: this.data.projectBrief ?? null,\n actors: this.data.actors ?? [],\n flows: this.data.flows ?? [],\n stories: this.data.stories ?? [],\n modules: this.data.modules ?? [],\n database: this.data.database ?? null,\n history: this.data.history ?? [],\n pendingQuestions: this.data.pendingQuestions ?? [],\n };\n }\n}\n\nexport function createRequirementContextBuilder(): RequirementContextBuilder {\n return new RequirementContextBuilder();\n}\n","/**\n * Zod schemas for DataModelDesign\n */\n\nimport { z } from 'zod';\n\nexport const entityFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean().default(false),\n unique: z.coerce.boolean().default(false),\n description: z.string().default(''),\n default: z.string().optional(),\n});\n\nexport const entityIndexSchema = z.object({\n name: z.string().default(''),\n fields: z.array(z.string()).default([]),\n unique: z.coerce.boolean().default(false),\n});\n\n/** Normalize common relation type variants to canonical form. */\nconst relationTypeSchema = z\n .string()\n .transform(s => {\n const n = s.toLowerCase().replace(/[\\s_-]+/g, '');\n if (['1:1', 'onetoone'].includes(n)) return '1:1' as const;\n if (['1:n', '1:m', 'n:1', 'onetomany', 'manytoone'].includes(n)) return '1:N' as const;\n if (['m:n', 'n:m', 'manytomany'].includes(n)) return 'M:N' as const;\n return s;\n })\n .pipe(z.enum(['1:1', '1:N', 'M:N']));\n\nexport const entityRelationSchema = z.object({\n field: z.string(),\n references: z.string(),\n type: relationTypeSchema,\n description: z.string().default(''),\n});\n\nexport const dataEntitySchema = z.object({\n name: z.string(),\n description: z.string().default(''),\n fields: z\n .union([z.array(entityFieldSchema), z.record(z.string(), z.unknown())])\n .transform((v, ctx) => {\n if (Array.isArray(v)) return v;\n const results: z.infer<typeof entityFieldSchema>[] = [];\n for (const [key, raw] of Object.entries(v)) {\n const obj =\n typeof raw === 'object' && raw !== null ? { ...(raw as Record<string, unknown>) } : {};\n if (!obj.name) obj.name = key;\n const result = entityFieldSchema.safeParse(obj);\n if (result.success) {\n results.push(result.data);\n } else {\n for (const issue of result.error.issues) {\n ctx.addIssue({ ...issue, path: [key, ...issue.path] });\n }\n }\n }\n return results;\n }),\n indexes: z.array(entityIndexSchema).default([]),\n relations: z.array(entityRelationSchema).default([]),\n});\n\n/** Case-insensitive database type */\nconst dbTypeSchema = z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(['mongodb', 'postgresql']));\n\nexport const dataModelDesignSchema = z.object({\n type: dbTypeSchema,\n reasoning: z.string().default(''),\n entities: z.array(dataEntitySchema).default([]),\n});\n\nexport type TDataModelDesign = z.infer<typeof dataModelDesignSchema>;\n","/**\n * MongoDB field-level schema (merged from db-designer)\n */\n\nimport { z } from 'zod';\n\nexport const mongoFieldSchema = z.object({\n fieldName: z.string().describe('fieldName must be in camelCase'),\n fieldType: z\n .string()\n .default('string')\n .transform(s => {\n const n = s.toLowerCase().trim();\n if (['string', 'text', 'varchar'].includes(n)) return 'string' as const;\n if (['number', 'int', 'integer', 'float', 'double', 'decimal'].includes(n))\n return 'number' as const;\n if (['boolean', 'bool'].includes(n)) return 'boolean' as const;\n if (['types.objectid', 'objectid', 'ref', 'reference'].includes(n))\n return 'Types.ObjectId' as const;\n if (['date', 'datetime', 'timestamp'].includes(n)) return 'Date' as const;\n if (['object', 'json', 'mixed'].includes(n)) return 'object' as const;\n if (['email'].includes(n)) return 'email' as const;\n if (['password', 'hash'].includes(n)) return 'password' as const;\n if (['enum', 'select'].includes(n)) return 'enum' as const;\n if (['array'].includes(n)) return 'string' as const;\n return 'string' as const;\n })\n .pipe(\n z.enum([\n 'string',\n 'number',\n 'boolean',\n 'Types.ObjectId',\n 'Date',\n 'object',\n 'email',\n 'password',\n 'enum',\n ])\n ),\n isArray: z.coerce.boolean().default(false),\n isRequired: z.coerce.boolean().default(true),\n isUnique: z.coerce.boolean().default(false),\n values: z\n .array(z.string())\n .default([])\n .describe('Enum values if fieldType is enum, else empty array'),\n defaultVal: z.union([z.string(), z.boolean(), z.number(), z.null()]).optional(),\n relationTo: z.string().optional().describe('Module name for relations'),\n relationType: z\n .string()\n .transform(s => {\n const n = s.toLowerCase().replace(/[\\s_]+/g, '-');\n if (['one-to-one', '1:1', '1-to-1'].includes(n)) return 'one-to-one' as const;\n if (['many-to-one', 'n:1', 'n-to-1', 'many-to-1', '*:1'].includes(n))\n return 'many-to-one' as const;\n return '' as const;\n })\n .pipe(z.enum(['one-to-one', 'many-to-one', '']))\n .optional(),\n isPrivate: z.coerce.boolean().default(false).describe('True if password field, else false'),\n});\n\nexport type TMongoFieldSchema = z.infer<typeof mongoFieldSchema>;\n","/**\n * MongoDB module (collection) schema with RBAC (merged from db-designer)\n */\n\nimport { z } from 'zod';\nimport { mongoFieldSchema } from './mongodb-field.schema';\n\nexport const mongoModuleSchema = z.object({\n moduleName: z.string().describe('camelCase, single word, never auth/authentication'),\n isUserModule: z.coerce.boolean().default(false),\n authMethod: z\n .string()\n .transform(s => {\n const n = s.toUpperCase().replace(/[\\s-]+/g, '_');\n if (['EMAIL_AND_PASSWORD', 'EMAIL_PASSWORD', 'EMAIL'].includes(n))\n return 'EMAIL_AND_PASSWORD' as const;\n if (['PHONE_AND_OTP', 'PHONE_OTP', 'PHONE', 'SMS'].includes(n))\n return 'PHONE_AND_OTP' as const;\n return '' as const;\n })\n .pipe(z.enum(['EMAIL_AND_PASSWORD', 'PHONE_AND_OTP', '']))\n .optional(),\n emailField: z.string().optional(),\n passwordField: z.string().optional(),\n phoneField: z.string().optional(),\n roleField: z.string().optional(),\n permissions: z\n .record(z.string(), z.array(z.enum(['CREATE', 'READ', 'UPDATE', 'DELETE'])))\n .optional()\n .describe('Permissions per role'),\n fields: z\n .union([z.array(mongoFieldSchema), z.record(z.string(), z.unknown())])\n .transform((v, ctx) => {\n if (Array.isArray(v)) return v;\n const results: z.infer<typeof mongoFieldSchema>[] = [];\n for (const [key, raw] of Object.entries(v)) {\n const obj =\n typeof raw === 'object' && raw !== null ? { ...(raw as Record<string, unknown>) } : {};\n if (!obj.fieldName) obj.fieldName = key;\n const result = mongoFieldSchema.safeParse(obj);\n if (result.success) {\n results.push(result.data);\n } else {\n for (const issue of result.error.issues) {\n ctx.addIssue({ ...issue, path: [key, ...issue.path] });\n }\n }\n }\n return results;\n }),\n});\n\nexport type TMongoModuleSchema = z.infer<typeof mongoModuleSchema>;\n","/**\n * MongoDB root project schema with RBAC (merged from db-designer)\n */\n\nimport { z } from 'zod';\nimport { mongoModuleSchema } from './mongodb-module.schema';\n\nexport const mongoProjectSchema = z.object({\n projectName: z.string().default('project').describe('projectName must be in kebab-case'),\n projectDescription: z.string().default(''),\n modules: z\n .union([z.array(mongoModuleSchema), z.record(z.string(), z.unknown())])\n .transform((v, ctx) => {\n if (Array.isArray(v)) return v;\n const results: z.infer<typeof mongoModuleSchema>[] = [];\n for (const [key, raw] of Object.entries(v)) {\n const obj =\n typeof raw === 'object' && raw !== null ? { ...(raw as Record<string, unknown>) } : {};\n if (!obj.moduleName) obj.moduleName = key;\n const result = mongoModuleSchema.safeParse(obj);\n if (result.success) {\n results.push(result.data);\n } else {\n for (const issue of result.error.issues) {\n ctx.addIssue({ ...issue, path: [key, ...issue.path] });\n }\n }\n }\n return results;\n }),\n author: z.string().default('sijeeshmiziha'),\n});\n\nexport type TMongoProjectSchema = z.infer<typeof mongoProjectSchema>;\n","/**\n * System prompt for data-modeler orchestrator\n */\n\nexport const DATA_MODELER_SYSTEM_PROMPT = `You are a senior database architect specializing in both MongoDB and PostgreSQL schema design.\n\nYou analyze requirements and produce enterprise-quality data models with:\n- Properly typed fields (MongoDB: ObjectId, string, number, date, array; PostgreSQL: uuid, varchar, text, integer, timestamp, jsonb)\n- Indexes optimized for query patterns\n- Relationships with correct cardinality (1:1, 1:N, M:N)\n- Validation constraints and default values\n- Security considerations (hashed passwords, encrypted fields)\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for data-modeler\n */\n\nexport const DESIGN_SCHEMA_PROMPT = `## Requirements:\n{requirement}\n\nDesign the database schema. Determine the best database type (mongodb or postgresql) based on the requirements, or use the one specified.\n\nFor MongoDB use types: ObjectId, string, number, boolean, date, array, mixed.\nFor PostgreSQL use types: uuid, varchar(n), text, integer, bigint, boolean, timestamp, jsonb, and proper foreign key relations.\n\nReturn ONLY valid JSON:\n{\n \"type\": \"mongodb\" | \"postgresql\",\n \"reasoning\": \"2-4 sentences explaining the choice and design approach\",\n \"entities\": [\n {\n \"name\": \"EntityName\",\n \"description\": \"Brief description\",\n \"fields\": [\n { \"name\": \"fieldName\", \"type\": \"DB-native type\", \"required\": true, \"unique\": false, \"description\": \"...\" }\n ],\n \"indexes\": [ { \"name\": \"idx_name\", \"fields\": [\"field1\"], \"unique\": false } ],\n \"relations\": [ { \"field\": \"refField\", \"references\": \"OtherEntity\", \"type\": \"1:N\", \"description\": \"...\" } ]\n }\n ]\n}`;\n\nexport const REFINE_SCHEMA_PROMPT = `## Current Schema (JSON):\n{existingSchema}\n\n## Feedback:\n{feedback}\n\nUpdate the schema based on the feedback. Return the complete updated schema as valid JSON in the same format.`;\n\nexport function buildDesignSchemaPrompt(requirement: string): string {\n return DESIGN_SCHEMA_PROMPT.replace('{requirement}', requirement);\n}\n\nexport function buildRefineSchemaPrompt(existingSchema: string, feedback: string): string {\n return REFINE_SCHEMA_PROMPT.replace('{existingSchema}', existingSchema).replace(\n '{feedback}',\n feedback\n );\n}\n","/**\n * Pro-level 5-phase data modeling prompt\n */\n\nexport const PRO_DESIGN_PROMPT = `## Project: {projectName}\n## Goal: {projectGoal}\n## Database: {databaseType}\n\n## Context:\n{context}\n\nApply the 5-phase enterprise data modeling process:\n\n### Phase 1: Entity Discovery\n- Extract every entity from the context (user types, domain objects, settings, logs).\n- Identify status enums from flow transitions.\n\n### Phase 2: Relationship Mapping\n- For each entity pair, determine ownership and cardinality (1:1, 1:N, M:N).\n- Note bidirectional references and join tables (PostgreSQL) or embedded arrays (MongoDB).\n\n### Phase 3: Permission Derivation\n- Map actor types to role names.\n- From actions, derive which role can CRUD which entity.\n\n### Phase 4: Schema Generation\n- Generate fields with DB-native types, required/unique flags, defaults.\n- Add indexes for common queries (user lookups, date ranges, foreign keys).\n- Include timestamps (createdAt, updatedAt) on all entities.\n\n### Phase 5: Validation\n- Verify every entity referenced in relations exists.\n- Verify no orphan fields or missing indexes.\n\nReturn ONLY valid JSON in the DataModelDesign format.`;\n\nexport function buildProDesignPrompt(\n projectName: string,\n projectGoal: string,\n databaseType: string,\n context: string\n): string {\n return PRO_DESIGN_PROMPT.replace('{projectName}', projectName)\n .replace('{projectGoal}', projectGoal)\n .replace('{databaseType}', databaseType)\n .replace('{context}', context);\n}\n","/**\n * MongoDB 5-phase system prompt (merged from db-designer)\n */\n\nexport const MONGODB_SYSTEM_PROMPT = `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.\n\n## ANALYSIS FRAMEWORK\n\nYou MUST follow this 5-phase analysis process before generating the schema:\n\n### PHASE 1: Entity Discovery\nSystematically extract all entities from the provided requirements:\n\n1. **From dataInvolved fields**: Every item in user stories' dataInvolved[] array indicates a potential entity or field\n2. **From User Types (Actors)**: Each actor type may indicate a User variant or role\n3. **From User Flow Actions**: Action verbs reveal implicit entities\n4. **From Flow States**: Transitions reveal status enums\n\n### PHASE 2: Relationship Mapping\nFor each entity pair, determine relationships based on:\n\n1. **Ownership Patterns** (from actor actions)\n2. **Cardinality from Flow Context** (one-to-one, many-to-one)\n3. **Shared Entities** (referenced across flows)\n4. **Bidirectional References** (for one-to-one)\n\n### PHASE 3: Permission Derivation\nMap actors to RBAC permissions:\n\n1. **Role Extraction**: Each actor type becomes a role value\n2. **Permission Mining from User Stories**: Map actions to CRUD per role\n3. **Data Visibility Rules**: \"view own\" vs \"view all\" vs \"manage\"\n\n### PHASE 4: Query Pattern Inference\nAnalyze flows to predict database access patterns:\n\n1. **Read Patterns** (suggest indexes)\n2. **Write Patterns** (affect schema design)\n3. **Aggregation Needs** (from reporting flows)\n\n### PHASE 5: Schema Construction\nSynthesize all analyses into the final schema:\n\n1. **Module Definition**: One module per core entity, camelCase names\n2. **Field Completeness**: All fields from dataInvolved, relationships, status enums, timestamps\n3. **Validation Constraints**: isRequired, isUnique, enum values\n4. **Security Fields**: password fields with isPrivate: true\n\n## CORE CONSTRAINTS (MUST FOLLOW)\n\n1. **Primary Key**: _id with Types.ObjectId (auto-generated, do not include in fields)\n2. **Relationships**: One-to-One: reference in BOTH collections; Many-to-One: reference in \"many\" side; One-to-Many: FORBIDDEN - invert to many-to-one\n3. **Data Types**: NO arrays of ObjectIds; Timestamps: createdAt, updatedAt in EVERY collection; Enums: fieldType: 'enum' with values array\n4. **Security**: NO separate \"Auth\" collection; NO token storage; Password fields: isPrivate: true\n5. **Authorization (RBAC)**: Define permissions per role on user modules`;\n","/**\n * MongoDB prompt formatters - format structured requirements for prompts\n * (merged from db-designer)\n */\n\nimport type {\n MongoActor,\n MongoExtractedFlow,\n MongoExtractedStory,\n MongoTechnicalRequirements,\n MongoStructuredInput,\n} from '../types';\n\nexport function formatUserTypes(actors: MongoActor[]): string {\n if (!actors || actors.length === 0) {\n return 'No specific user types defined. Assume a general \"User\" role.';\n }\n return actors\n .map((actor, i) => {\n const goals = actor.goals.filter(g => g.trim()).join('\\n - ');\n return `### ${i + 1}. ${actor.name}\\n**Description:** ${actor.description}\\n**Goals:**\\n - ${goals || 'No specific goals defined'}`;\n })\n .join('\\n\\n');\n}\n\nexport function formatUserFlows(flows: MongoExtractedFlow[], actors: MongoActor[]): string {\n if (!flows || flows.length === 0) return 'No specific user flows defined.';\n return flows\n .map((flow, i) => {\n const actor = actors.find(a => a.id === flow.actorId);\n return `### ${i + 1}. ${flow.name}\\n**Actor:** ${actor?.name || 'User'}\\n**Description:** ${flow.description}\\n**Trigger:** ${flow.trigger || 'User initiates action'}\\n**Outcome:** ${flow.outcome || 'Action completed'}`;\n })\n .join('\\n\\n');\n}\n\nexport function formatUserStories(\n stories: MongoExtractedStory[],\n flows: MongoExtractedFlow[]\n): string {\n if (!stories || stories.length === 0) return 'No specific user stories defined.';\n const byFlow = new Map<string, MongoExtractedStory[]>();\n for (const s of stories) {\n const arr = byFlow.get(s.flowId) || [];\n arr.push(s);\n byFlow.set(s.flowId, arr);\n }\n const sections: string[] = [];\n for (const flow of flows) {\n const flowStories = byFlow.get(flow.id) || [];\n if (flowStories.length === 0) continue;\n sections.push(`### Flow: ${flow.name}\\n`);\n for (const story of flowStories) {\n const pre = story.preconditions.filter(p => p.trim());\n const post = story.postconditions.filter(p => p.trim());\n const data = story.dataInvolved.filter(d => d.trim());\n let t = `**As a** ${story.actor}, **I want to** ${story.action}, **so that** ${story.benefit}\\n`;\n if (pre.length) t += `\\n**Preconditions:**\\n${pre.map(p => `- ${p}`).join('\\n')}\\n`;\n if (post.length) t += `\\n**Postconditions:**\\n${post.map(p => `- ${p}`).join('\\n')}\\n`;\n if (data.length)\n t += `\\n**Data Involved (IMPORTANT):**\\n${data.map(d => `- ${d}`).join('\\n')}\\n`;\n sections.push(t);\n }\n }\n const orphans = stories.filter(s => !flows.some(f => f.id === s.flowId));\n if (orphans.length) {\n sections.push(`### Other Stories\\n`);\n for (const s of orphans) {\n const data = s.dataInvolved.filter(d => d.trim());\n let t = `**As a** ${s.actor}, **I want to** ${s.action}, **so that** ${s.benefit}\\n`;\n if (data.length) t += `\\n**Data Involved:** ${data.join(', ')}\\n`;\n sections.push(t);\n }\n }\n return sections.join('\\n');\n}\n\nexport function formatTechnicalRequirements(tech?: MongoTechnicalRequirements): string {\n if (!tech) return 'No specific technical requirements. Use defaults.';\n const lines: string[] = [`**Authentication:** ${tech.authentication || 'none'}`];\n if (tech.authorization) {\n lines.push('**Authorization (RBAC):** Enabled');\n if (tech.roles?.length) lines.push(`**Defined Roles:** ${tech.roles.join(', ')}`);\n } else {\n lines.push('**Authorization:** Disabled');\n }\n if (tech.realtime) lines.push('**Realtime Features:** Required');\n if (tech.fileUpload) lines.push('**File Upload:** Required');\n if (tech.search) lines.push('**Search Functionality:** Required');\n if (tech.integrations?.length) lines.push(`**Integrations:** ${tech.integrations.join(', ')}`);\n return lines.join('\\n');\n}\n\nexport function extractDataEntities(stories: MongoExtractedStory[]): string[] {\n const entities = new Set<string>();\n for (const s of stories) for (const d of s.dataInvolved) if (d.trim()) entities.add(d.trim());\n return Array.from(entities);\n}\n\nexport function extractRoles(actors: MongoActor[]): string[] {\n return actors.map(a => a.name.toLowerCase().replaceAll(/\\s+/g, '_'));\n}\n\nexport function buildPromptVariables(input: MongoStructuredInput): Record<string, string> {\n return {\n projectName: input.projectName,\n projectGoal: input.projectGoal,\n projectDescription: input.projectDescription || input.projectGoal,\n userTypes: formatUserTypes(input.actors),\n userFlows: formatUserFlows(input.flows, input.actors),\n userStories: formatUserStories(input.stories, input.flows),\n technicalRequirements: formatTechnicalRequirements(input.technicalRequirements),\n };\n}\n","/**\n * MongoDB design prompt builders (merged from db-designer)\n */\n\nimport type { MongoStructuredInput } from '../types';\nimport { MONGODB_SYSTEM_PROMPT } from './mongodb-system.prompt';\nimport { buildPromptVariables } from './mongodb-formatters';\n\n/**\n * Legacy: build design prompt from plain requirement string\n */\nexport function createMongoDesignPrompt(requirement: string): string {\n return `${MONGODB_SYSTEM_PROMPT}\n\nDesign a robust and efficient MongoDB database schema based on the following requirements:\n\n## Requirements\n${requirement}\n\n## Guidelines\n1. Use camelCase for module names and field names\n2. Include createdAt and updatedAt Date fields in every module\n3. Define proper relationships between modules\n4. Set appropriate permissions for user modules\n\nReturn ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`;\n}\n\n/**\n * Pro-level MongoDB design prompt from structured requirements\n */\nexport function createMongoProDesignPrompt(input: MongoStructuredInput): string {\n const vars = buildPromptVariables(input);\n return `${MONGODB_SYSTEM_PROMPT}\n\n---\n\n## PROJECT CONTEXT\n\n**Project Name:** ${vars.projectName}\n**Project Goal:** ${vars.projectGoal}\n**Description:** ${vars.projectDescription}\n\n---\n\n## USER TYPES (ACTORS)\n\n${vars.userTypes}\n\n---\n\n## USER FLOWS\n\n${vars.userFlows}\n\n---\n\n## USER STORIES WITH DATA REQUIREMENTS\n\n${vars.userStories}\n\n---\n\n## TECHNICAL REQUIREMENTS\n\n${vars.technicalRequirements}\n\n---\n\n## YOUR TASK\n\nFollow the 5-phase analysis framework:\n\n### Step 1: Entity Discovery\n- List ALL entities extracted from dataInvolved fields\n- Identify implicit entities from user flow actions\n- Map user types to User collection roles\n- Extract status enums from flow transitions\n\n### Step 2: Relationship Mapping\n- Define ownership: which actor creates/owns each entity\n- Determine cardinality from flow context\n\n### Step 3: Permission Derivation\n- Map each actor to a role\n- Extract CRUD permissions from user story actions\n\n### Step 4: Query Pattern Inference\n- Identify likely query patterns from flows\n\n### Step 5: Schema Construction\nGenerate the final schema with complete module definitions, fields, relationships, RBAC permissions, and timestamps.\n\nReturn ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`;\n}\n","/**\n * MongoDB redesign prompt - update existing schema based on feedback\n * (merged from db-designer)\n */\n\nimport { MONGODB_SYSTEM_PROMPT } from './mongodb-system.prompt';\n\nexport function createMongoRedesignPrompt(existingSchema: string, feedback: string): string {\n return `${MONGODB_SYSTEM_PROMPT}\n\nUpdate the existing MongoDB schema based on user feedback.\n\n## Steps\n1. Analyze the existing MongoDB schema provided\n2. Review the user feedback to understand the required updates\n3. Update the schema to incorporate the requested changes while adhering to best practices\n\n## Existing Schema\n${existingSchema}\n\n## User Feedback\n${feedback}\n\nReturn the updated schema as a valid JSON object matching the original schema format.\nIMPORTANT: Return ONLY the JSON object, no markdown code blocks, no explanations.`;\n}\n","/**\n * validate_schema tool - validates JSON against dataModelDesignSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { dataModelDesignSchema } from '../schemas';\n\nexport const validateSchemaTool = createValidationTool(\n 'validate_data_model',\n dataModelDesignSchema,\n 'Validates a data model JSON string against the DataModelDesign schema. Returns valid: true or valid: false with errors.',\n 'schema'\n);\n","/**\n * design_schema tool - generates data model from plain text requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { dataModelDesignSchema, type TDataModelDesign } from '../schemas';\nimport { buildDesignSchemaPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_schema tool. Requires a model for generation.\n */\nexport function createDesignSchemaTool(model: Model) {\n return defineTool({\n name: 'design_schema',\n description:\n 'Generate a database schema (MongoDB or PostgreSQL) from plain text requirements. Returns the full data model as JSON.',\n input: z.object({\n requirement: z.string().describe('Plain text description of the data modeling requirements'),\n }),\n handler: async ({ requirement }): Promise<TDataModelDesign> => {\n const userPrompt = buildDesignSchemaPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a database schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, dataModelDesignSchema);\n },\n });\n}\n","/**\n * design_schema_pro tool - 5-phase structured data modeling (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { dataModelDesignSchema, type TDataModelDesign } from '../schemas';\nimport { buildProDesignPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_schema_pro tool for structured 5-phase data modeling.\n */\nexport function createDesignSchemaProTool(model: Model) {\n return defineTool({\n name: 'design_schema_pro',\n description:\n '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.',\n input: z.object({\n projectName: z.string().describe('Project name'),\n projectGoal: z.string().describe('Project goal / purpose'),\n databaseType: z.enum(['mongodb', 'postgresql']).describe('Target database type'),\n context: z.string().describe('Full project context: features, actors, flows, stories'),\n }),\n handler: async ({\n projectName,\n projectGoal,\n databaseType,\n context,\n }): Promise<TDataModelDesign> => {\n const userPrompt = buildProDesignPrompt(projectName, projectGoal, databaseType, context);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a database schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.2, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, dataModelDesignSchema);\n },\n });\n}\n","/**\n * refine_schema tool - updates existing schema based on feedback (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { dataModelDesignSchema, type TDataModelDesign } from '../schemas';\nimport { buildRefineSchemaPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the refine_schema tool for iterating on an existing data model.\n */\nexport function createRefineSchemaTools(model: Model) {\n return defineTool({\n name: 'refine_schema',\n description:\n 'Update an existing data model schema based on user feedback. Provide the current schema JSON and feedback describing desired changes.',\n input: z.object({\n existingSchema: z.string().describe('Current data model schema as JSON string'),\n feedback: z.string().describe('Feedback describing desired changes'),\n }),\n handler: async ({ existingSchema, feedback }): Promise<TDataModelDesign> => {\n const userPrompt = buildRefineSchemaPrompt(existingSchema, feedback);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a database schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, dataModelDesignSchema);\n },\n });\n}\n","/**\n * validate_schema tool - validates JSON against mongoProjectSchema (merged from db-designer)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { mongoProjectSchema } from '../schemas';\n\nexport const validateMongoSchemaTool = createValidationTool(\n 'validate_schema',\n mongoProjectSchema,\n 'Validates a MongoDB project schema JSON string against the expected schema. Returns valid: true or valid: false with errors.',\n 'schema'\n);\n","/**\n * design_database tool - generates MongoDB schema from plain text (merged from db-designer)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { mongoProjectSchema, type TMongoProjectSchema } from '../schemas';\nimport { createMongoDesignPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_database tool for MongoDB schema generation.\n */\nexport function createDesignDatabaseTool(model: Model) {\n return defineTool({\n name: 'design_database',\n description:\n 'Generate a MongoDB database schema from plain text requirements. Returns the full project schema as JSON.',\n input: z.object({\n requirement: z.string().describe('Plain text description of the database requirements'),\n }),\n handler: async ({ requirement }): Promise<TMongoProjectSchema> => {\n const userPrompt = createMongoDesignPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a MongoDB schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, mongoProjectSchema);\n },\n });\n}\n","/**\n * design_database_pro tool - MongoDB schema from structured requirements (merged from db-designer)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { mongoProjectSchema, type TMongoProjectSchema } from '../schemas';\nimport { createMongoProDesignPrompt, extractDataEntities, extractRoles } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\nconst structuredInputSchema = z.object({\n projectName: z.string(),\n projectGoal: z.string(),\n projectDescription: z.string().optional(),\n actors: z.array(\n z.object({\n id: z.string(),\n name: z.string(),\n description: z.string(),\n goals: z.array(z.string()),\n })\n ),\n flows: z.array(\n z.object({\n id: z.string(),\n actorId: z.string(),\n name: z.string(),\n description: z.string(),\n trigger: z.string(),\n outcome: z.string(),\n })\n ),\n stories: z.array(\n z.object({\n id: z.string(),\n flowId: z.string(),\n actor: z.string(),\n action: z.string(),\n benefit: z.string(),\n preconditions: z.array(z.string()),\n postconditions: z.array(z.string()),\n dataInvolved: z.array(z.string()),\n })\n ),\n technicalRequirements: z\n .object({\n authentication: z\n .string()\n .transform(s => {\n const n = s.toLowerCase().replace(/[\\s_-]+/g, '');\n if (['none', 'no', ''].includes(n)) return 'none' as const;\n if (['email', 'emailpassword', 'emailandpassword'].includes(n)) return 'email' as const;\n if (['oauth', 'oauth2', 'social'].includes(n)) return 'oauth' as const;\n if (['phone', 'phoneotp', 'sms'].includes(n)) return 'phone' as const;\n if (['emailandphone', 'emailphone', 'both'].includes(n))\n return 'email_and_phone' as const;\n return 'email' as const;\n })\n .pipe(z.enum(['none', 'email', 'oauth', 'phone', 'email_and_phone'])),\n authorization: z.coerce.boolean().default(false),\n roles: z.array(z.string()).optional(),\n integrations: z.array(z.string()).optional(),\n realtime: z.boolean().optional(),\n fileUpload: z.boolean().optional(),\n search: z.boolean().optional(),\n })\n .optional(),\n});\n\n/**\n * Creates the design_database_pro tool for structured 5-phase MongoDB analysis.\n */\nexport function createDesignDatabaseProTool(model: Model) {\n return defineTool({\n name: 'design_database_pro',\n description:\n 'Generate a MongoDB schema from structured requirements (actors, flows, stories, technical requirements). Returns dbDesign and metadata.',\n input: structuredInputSchema,\n handler: async (\n input\n ): Promise<{\n dbDesign: TMongoProjectSchema;\n metadata: { entitiesDetected: string[]; rolesExtracted: string[] };\n }> => {\n const userPrompt = createMongoProDesignPrompt(input);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a MongoDB schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.2, maxOutputTokens: 16384 });\n const dbDesign = parseModelJsonResponse(response.text, mongoProjectSchema);\n const metadata = {\n entitiesDetected: extractDataEntities(input.stories),\n rolesExtracted: extractRoles(input.actors),\n };\n return { dbDesign, metadata };\n },\n });\n}\n","/**\n * redesign_database tool - updates existing MongoDB schema from feedback (merged from db-designer)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { mongoProjectSchema, type TMongoProjectSchema } from '../schemas';\nimport { createMongoRedesignPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the redesign_database tool for iterating on MongoDB schemas.\n */\nexport function createRedesignDatabaseTool(model: Model) {\n return defineTool({\n name: 'redesign_database',\n description:\n 'Update an existing MongoDB project schema based on user feedback. Provide the current schema JSON string and the feedback.',\n input: z.object({\n existingSchema: z.string().describe('Current project schema as JSON string'),\n feedback: z.string().describe('User feedback describing desired changes'),\n }),\n handler: async ({ existingSchema, feedback }): Promise<TMongoProjectSchema> => {\n const userPrompt = createMongoRedesignPrompt(existingSchema, feedback);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a MongoDB schema expert. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, mongoProjectSchema);\n },\n });\n}\n","/**\n * data-modeler tools (generic + MongoDB)\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateSchemaTool } from './validate-schema';\nimport { createDesignSchemaTool } from './design-schema';\nimport { createDesignSchemaProTool } from './design-schema-pro';\nimport { createRefineSchemaTools } from './refine-schema';\nimport { validateMongoSchemaTool } from './validate-mongodb';\nimport { createDesignDatabaseTool } from './design-mongodb';\nimport { createDesignDatabaseProTool } from './design-mongodb-pro';\nimport { createRedesignDatabaseTool } from './redesign-mongodb';\n\nexport { validateSchemaTool } from './validate-schema';\nexport { createDesignSchemaTool } from './design-schema';\nexport { createDesignSchemaProTool } from './design-schema-pro';\nexport { createRefineSchemaTools } from './refine-schema';\n\n/* MongoDB-specific tools (merged from db-designer) */\nexport { validateMongoSchemaTool } from './validate-mongodb';\nexport { createDesignDatabaseTool } from './design-mongodb';\nexport { createDesignDatabaseProTool } from './design-mongodb-pro';\nexport { createRedesignDatabaseTool } from './redesign-mongodb';\n\n/**\n * Create all generic data-modeler tools. Pass the model for AI-backed tools.\n */\nexport function createDataModelerTools(model: Model) {\n return createToolSet({\n validate_data_model: validateSchemaTool,\n design_schema: createDesignSchemaTool(model),\n design_schema_pro: createDesignSchemaProTool(model),\n refine_schema: createRefineSchemaTools(model),\n });\n}\n\n/**\n * Create all MongoDB-specific tools (merged from db-designer).\n */\nexport function createDbDesignerTools(model: Model) {\n return createToolSet({\n validate_schema: validateMongoSchemaTool,\n design_database: createDesignDatabaseTool(model),\n design_database_pro: createDesignDatabaseProTool(model),\n redesign_database: createRedesignDatabaseTool(model),\n });\n}\n","/**\n * runDataModelerAgent - orchestrator for data model design\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { DATA_MODELER_SYSTEM_PROMPT } from './prompts';\nimport { createDataModelerTools } from './tools';\nimport {\n entityAnalyzerSubagent,\n relationshipMapperSubagent,\n createSchemaRefinerSubagent,\n} from './subagents';\nimport type { DataModelerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${DATA_MODELER_SYSTEM_PROMPT}\n\nYou are the data modeling orchestrator. When the user asks for a data model:\n\n1. **Analyze first**: Use subagent_entity-analyzer to extract entities, fields, and relationships from the requirements.\n2. **Map relationships**: Use subagent_relationship-mapper with the entity analysis to determine cardinality, foreign keys, and indexes.\n3. **Generate schema**: Use design_schema (plain text) or design_schema_pro (when structured context is available) to produce the data model.\n4. **Refine (optional)**: Use subagent_schema-refiner to validate and suggest improvements to the generated schema.\n5. **Validate**: Use validate_data_model to check the final schema JSON before returning.\n\nRespond with the final data model schema as JSON.`;\n\n/**\n * Run the data-modeler orchestrator agent with all tools and subagents.\n */\nexport async function runDataModelerAgent(config: DataModelerAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createDataModelerTools(model);\n const schemaRefiner = createSchemaRefinerSubagent();\n const subagentTools = createSubagentToolSet(\n [entityAnalyzerSubagent, relationshipMapperSubagent, schemaRefiner],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * runDbDesignerAgent - MongoDB-specific orchestrator (merged from db-designer)\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { MONGODB_SYSTEM_PROMPT } from './prompts';\nimport { createDbDesignerTools } from './tools';\nimport { entityAnalyzerSubagent, createSchemaRefinerSubagent } from './subagents';\nimport type { MongoDbDesignerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${MONGODB_SYSTEM_PROMPT}\n\nYou are the MongoDB database design orchestrator. When the user asks for a database design:\n\n1. **Analyze first**: Use subagent_entity-analyzer to extract entities, relationships, and roles.\n2. **Generate schema**: Use design_database (plain text) or design_database_pro (structured requirements) to produce the MongoDB schema.\n3. **Refine (optional)**: Use subagent_schema-refiner to validate and suggest improvements.\n4. **Validate**: Use validate_schema to check the final schema JSON.\n5. **Redesign**: If changes are requested, use redesign_database with existing schema and feedback.\n\nRespond with the final schema as JSON.`;\n\n/**\n * Run the MongoDB db-designer orchestrator agent with all tools and subagents.\n */\nexport async function runDbDesignerAgent(config: MongoDbDesignerAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const dbTools = createDbDesignerTools(model);\n const schemaRefiner = createSchemaRefinerSubagent();\n const subagentTools = createSubagentToolSet([entityAnalyzerSubagent, schemaRefiner], {\n parentModel: model,\n });\n const tools = createToolSet({ ...dbTools, ...subagentTools });\n\n return runAgent({\n model,\n tools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for ApiDesign\n */\n\nimport { z } from 'zod';\n\nconst httpMethodSchema = z\n .union([z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']), z.string()])\n .transform(s => (typeof s === 'string' ? s.toUpperCase() : s))\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nconst stringRecordSchema = z\n .record(z.string(), z.unknown())\n .optional()\n .default({})\n .transform(m =>\n Object.fromEntries(\n Object.entries(m ?? {}).map(([k, v]) => [k, typeof v === 'string' ? v : String(v)])\n )\n );\n\n/** Coerce arrays of mixed strings/objects to string arrays (models often return objects). */\nconst stringOrObjectArraySchema = z\n .array(z.unknown())\n .default([])\n .transform(arr => arr.map(v => (typeof v === 'string' ? v : JSON.stringify(v))));\n\nexport const restEndpointSchema = z.object({\n id: z.string(),\n resource: z.string(),\n method: httpMethodSchema,\n path: z.string(),\n description: z.string(),\n auth: z.coerce.boolean(),\n roles: z.array(z.string()).default([]),\n requestBody: stringRecordSchema,\n responseBody: stringRecordSchema,\n queryParams: stringRecordSchema,\n validation: stringOrObjectArraySchema,\n errorResponses: stringOrObjectArraySchema,\n});\n\nexport const graphqlOperationSchema = z.object({\n name: z.string(),\n type: z.enum(['query', 'mutation', 'subscription']),\n description: z.string(),\n auth: z.coerce.boolean(),\n roles: z.array(z.string()).default([]),\n args: z.array(\n z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean(),\n })\n ),\n returnType: z.string(),\n});\n\nconst apiStyleSchema = z.unknown().transform(v => {\n const s = typeof v === 'string' ? v.toLowerCase().trim() : 'rest';\n if (s.includes('graphql')) return 'graphql' as const;\n return 'rest' as const;\n});\n\nexport const apiDesignSchema = z\n .object({\n style: apiStyleSchema,\n baseUrl: z.string().default('/api/v1'),\n endpoints: z.array(restEndpointSchema).optional().default([]),\n graphqlOperations: z.array(graphqlOperationSchema).optional().default([]),\n })\n .refine(data => data.endpoints.length > 0 || data.graphqlOperations.length > 0, {\n message:\n 'API design must include at least one REST endpoint or GraphQL operation. ' +\n 'The endpoints array and graphqlOperations array cannot both be empty.',\n });\n\nexport type TApiDesign = z.infer<typeof apiDesignSchema>;\n","/**\n * System prompt for api-designer orchestrator\n */\n\nexport const API_DESIGNER_SYSTEM_PROMPT = `You are a senior API architect specializing in REST and GraphQL API design.\n\nYou analyze data models and requirements to produce enterprise-quality API designs with:\n- RESTful endpoints grouped by resource with proper HTTP methods\n- Request/response contracts with field types and validation rules\n- Error responses with appropriate HTTP status codes (400, 401, 403, 404, 500)\n- Pagination, filtering, and sorting patterns\n- Authentication and authorization annotations per endpoint\n- GraphQL types, queries, mutations, and subscriptions when applicable\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for api-designer\n */\n\nexport const DESIGN_API_PROMPT = `## Requirements:\n{requirement}\n\nDesign the API. Determine the best API style (\"rest\" or \"graphql\") based on the requirements, or use the one specified.\n\nIMPORTANT: You MUST generate ALL CRUD endpoints (Create, Read, List, Update, Delete) for EVERY resource identified in the requirements. The \"endpoints\" array MUST NOT be empty for REST APIs.\n\nFor REST: group endpoints by resource. Each endpoint needs: id, resource, method, path, description, auth, roles, requestBody, responseBody, queryParams, validation, and errorResponses.\nFor GraphQL: define operations (queries, mutations, subscriptions) with args and return types.\n\nReturn ONLY valid JSON matching this exact structure:\n{\n \"style\": \"rest\",\n \"baseUrl\": \"/api/v1\",\n \"endpoints\": [\n {\n \"id\": \"ep-1\",\n \"resource\": \"users\",\n \"method\": \"POST\",\n \"path\": \"/api/v1/users\",\n \"description\": \"Register a new user\",\n \"auth\": false,\n \"roles\": [],\n \"requestBody\": { \"name\": \"string\", \"email\": \"string\", \"password\": \"string\" },\n \"responseBody\": { \"id\": \"string\", \"name\": \"string\", \"email\": \"string\" },\n \"queryParams\": {},\n \"validation\": [\"name is required\", \"email must be valid format\"],\n \"errorResponses\": [\"400 Validation error\", \"409 Email already exists\"]\n },\n {\n \"id\": \"ep-2\",\n \"resource\": \"users\",\n \"method\": \"GET\",\n \"path\": \"/api/v1/users/:id\",\n \"description\": \"Get user by ID\",\n \"auth\": true,\n \"roles\": [\"user\", \"admin\"],\n \"requestBody\": {},\n \"responseBody\": { \"id\": \"string\", \"name\": \"string\", \"email\": \"string\" },\n \"queryParams\": {},\n \"validation\": [],\n \"errorResponses\": [\"401 Unauthenticated\", \"404 User not found\"]\n }\n ],\n \"graphqlOperations\": []\n}\n\nGenerate endpoints for ALL resources. Do NOT return an empty endpoints array.`;\n\nexport const PRO_DESIGN_API_PROMPT = `## Project: {projectName}\n## API Style: {apiStyle}\n## Data Model:\n{dataModel}\n## Requirements:\n{context}\n\nDesign a comprehensive API surface from the data model and requirements. For EVERY entity in the data model, generate CRUD endpoints (Create, Read by ID, List with pagination, Update, Delete) plus any custom operations implied by the requirements.\n\nIMPORTANT: The \"endpoints\" array MUST NOT be empty. You MUST include endpoints for ALL entities.\n\nInclude per-endpoint: id (unique like \"ep-1\"), resource, method, path, description, auth flag, roles array, requestBody (field-to-type map), responseBody (field-to-type map), queryParams (field-to-type map), validation rules (string array), and error responses (string array with status codes like \"400 Validation error\", \"401 Unauthenticated\", \"404 Not found\").\n\nReturn ONLY valid JSON in the ApiDesign format.`;\n\nexport function buildDesignApiPrompt(requirement: string): string {\n return DESIGN_API_PROMPT.replace('{requirement}', requirement);\n}\n\nexport function buildProDesignApiPrompt(\n projectName: string,\n apiStyle: string,\n dataModel: string,\n context: string\n): string {\n return PRO_DESIGN_API_PROMPT.replace('{projectName}', projectName)\n .replace('{apiStyle}', apiStyle)\n .replace('{dataModel}', dataModel)\n .replace('{context}', context);\n}\n","/**\n * validate_api tool - validates JSON against apiDesignSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { apiDesignSchema } from '../schemas';\n\nexport const validateApiTool = createValidationTool(\n 'validate_api',\n apiDesignSchema,\n 'Validates an API design JSON string against the ApiDesign schema. Returns valid: true or valid: false with errors.',\n 'design'\n);\n","/**\n * design_api tool - generates API design from plain text requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { apiDesignSchema, type TApiDesign } from '../schemas';\nimport { buildDesignApiPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_api tool for plain text requirements.\n */\nexport function createDesignApiTool(model: Model) {\n return defineTool({\n name: 'design_api',\n description:\n 'Generate an API design (REST or GraphQL) from plain text requirements. Returns the full API design as JSON.',\n input: z.object({\n requirement: z.string().describe('Plain text description of the API requirements'),\n }),\n handler: async ({ requirement }): Promise<TApiDesign> => {\n const userPrompt = buildDesignApiPrompt(requirement);\n const messages = [\n { role: 'system' as const, content: 'You are an API architect. Return only valid JSON.' },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, apiDesignSchema);\n },\n });\n}\n","/**\n * design_api_pro tool - structured API design from data model + context (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { apiDesignSchema, type TApiDesign } from '../schemas';\nimport { buildProDesignApiPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_api_pro tool for structured API design.\n */\nexport function createDesignApiProTool(model: Model) {\n return defineTool({\n name: 'design_api_pro',\n description:\n 'Generate a comprehensive API design from a data model and project context. Produces detailed endpoints with validation, error responses, and auth annotations.',\n input: z.object({\n projectName: z.string().describe('Project name'),\n apiStyle: z.enum(['rest', 'graphql']).describe('Target API style'),\n dataModel: z.string().describe('Data model JSON or description'),\n context: z.string().describe('Project context: features, actors, stories'),\n }),\n handler: async ({ projectName, apiStyle, dataModel, context }): Promise<TApiDesign> => {\n const userPrompt = buildProDesignApiPrompt(projectName, apiStyle, dataModel, context);\n const messages = [\n { role: 'system' as const, content: 'You are an API architect. Return only valid JSON.' },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.2, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, apiDesignSchema);\n },\n });\n}\n","/**\n * api-designer tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateApiTool } from './validate-api';\nimport { createDesignApiTool } from './design-api';\nimport { createDesignApiProTool } from './design-api-pro';\n\nexport { validateApiTool } from './validate-api';\nexport { createDesignApiTool } from './design-api';\nexport { createDesignApiProTool } from './design-api-pro';\n\n/**\n * Create all api-designer tools. Pass the model for AI-backed tools.\n */\nexport function createApiDesignerTools(model: Model) {\n return createToolSet({\n validate_api: validateApiTool,\n design_api: createDesignApiTool(model),\n design_api_pro: createDesignApiProTool(model),\n });\n}\n","/**\n * runApiDesignerAgent - orchestrator for API design\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { API_DESIGNER_SYSTEM_PROMPT } from './prompts';\nimport { createApiDesignerTools } from './tools';\nimport { endpointAnalyzerSubagent, contractDesignerSubagent } from './subagents';\nimport type { ApiDesignerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${API_DESIGNER_SYSTEM_PROMPT}\n\nYou are the API design orchestrator. You MUST use tools to generate the API design. Do NOT respond with a text-only answer or skip tool calls.\n\nFollow these steps:\n\n1. **Analyze endpoints**: Use subagent_endpoint-analyzer to derive endpoints from the data model and requirements.\n2. **Design contracts**: Use subagent_contract-designer to design request/response contracts, validation rules, and error responses.\n3. **Generate design**: You MUST call design_api (for plain text requirements) or design_api_pro (when data model and structured context are available) to produce the API design. This step is mandatory — never skip it.\n4. **Validate**: Use validate_api to check the final API design JSON before returning.\n\nCRITICAL: You MUST always call the design_api or design_api_pro tool. If a tool call fails, retry with adjusted input. Never fall back to a text-only response. The final output must be valid API design JSON with a non-empty endpoints array.`;\n\n/**\n * Run the api-designer orchestrator agent with all tools and subagents.\n */\nexport async function runApiDesignerAgent(config: ApiDesignerAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createApiDesignerTools(model);\n const subagentTools = createSubagentToolSet(\n [endpointAnalyzerSubagent, contractDesignerSubagent],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for AuthDesign\n */\n\nimport { z } from 'zod';\n\nexport const authFlowStepSchema = z.object({\n order: z.number(),\n side: z.enum(['frontend', 'backend']),\n action: z.string(),\n details: z.string(),\n});\n\nexport const authFlowSchema = z.object({\n name: z.string(),\n description: z.string(),\n steps: z.array(authFlowStepSchema),\n});\n\nexport const authMiddlewareSchema = z.object({\n name: z.string(),\n purpose: z.string(),\n behavior: z.array(z.string()),\n});\n\nexport const roleDefinitionSchema = z.object({\n name: z.string(),\n description: z.string(),\n permissions: z.array(z.string()),\n});\n\nexport const securityPolicySchema = z.object({\n area: z.string(),\n rules: z.array(z.string()),\n});\n\nexport const authDesignSchema = z.object({\n strategy: z.enum(['jwt', 'session', 'oauth']),\n flows: z.array(authFlowSchema),\n middleware: z.array(authMiddlewareSchema),\n roles: z.array(roleDefinitionSchema),\n policies: z.array(securityPolicySchema),\n});\n\nexport type TAuthDesign = z.infer<typeof authDesignSchema>;\n","/**\n * System prompt for auth-designer orchestrator\n */\n\nexport const AUTH_DESIGNER_SYSTEM_PROMPT = `You are a senior security engineer specializing in authentication, authorization, and web security.\n\nYou design enterprise-quality auth systems with:\n- Step-by-step auth flows (signup, login, logout, password reset) with both frontend and backend steps\n- JWT or session strategy with proper cookie configuration (httpOnly, secure, sameSite, maxAge)\n- Role-based access control (RBAC) with permission matrices\n- Middleware chains for route protection and API authentication\n- Security policies: password hashing (bcrypt), rate limiting, CORS, input sanitization, brute force protection\n- OAuth integration patterns when needed\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for auth-designer\n */\n\nexport const DESIGN_AUTH_PROMPT = `## Requirements:\n{requirement}\n\nDesign the authentication and authorization system. Include:\n\n1. Strategy: jwt, session, or oauth (choose based on requirements).\n2. Flows: signup, login, logout, password reset (if applicable). Each flow with numbered steps, frontend/backend side, action, and details.\n3. Middleware: route protection middleware, API auth middleware. Each with name, purpose, and behavior list.\n4. Roles: role definitions with name, description, and permissions list.\n5. Policies: security policies grouped by area (passwords, tokens, CORS, rate limiting, etc.).\n\nReturn ONLY valid JSON:\n{\n \"strategy\": \"jwt\" | \"session\" | \"oauth\",\n \"flows\": [{ \"name\": \"signup\", \"description\": \"...\", \"steps\": [{ \"order\": 1, \"side\": \"frontend\", \"action\": \"...\", \"details\": \"...\" }] }],\n \"middleware\": [{ \"name\": \"authenticateRequest\", \"purpose\": \"...\", \"behavior\": [\"...\"] }],\n \"roles\": [{ \"name\": \"user\", \"description\": \"...\", \"permissions\": [\"...\"] }],\n \"policies\": [{ \"area\": \"passwords\", \"rules\": [\"...\"] }]\n}`;\n\nexport function buildDesignAuthPrompt(requirement: string): string {\n return DESIGN_AUTH_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_auth tool - validates JSON against authDesignSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { authDesignSchema } from '../schemas';\n\nexport const validateAuthTool = createValidationTool(\n 'validate_auth',\n authDesignSchema,\n 'Validates an auth design JSON string against the AuthDesign schema. Returns valid: true or valid: false with errors.',\n 'design'\n);\n","/**\n * design_auth tool - generates auth design from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { authDesignSchema, type TAuthDesign } from '../schemas';\nimport { buildDesignAuthPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_auth tool for auth flow generation.\n */\nexport function createDesignAuthTool(model: Model) {\n return defineTool({\n name: 'design_auth',\n description:\n 'Generate a complete authentication and authorization design from project requirements. Returns auth flows, middleware, roles, and security policies as JSON.',\n input: z.object({\n requirement: z.string().describe('Project context and auth requirements'),\n }),\n handler: async ({ requirement }): Promise<TAuthDesign> => {\n const userPrompt = buildDesignAuthPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a security engineer. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 8192 });\n return parseModelJsonResponse(response.text, authDesignSchema);\n },\n });\n}\n","/**\n * auth-designer tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateAuthTool } from './validate-auth';\nimport { createDesignAuthTool } from './design-auth';\n\nexport { validateAuthTool } from './validate-auth';\nexport { createDesignAuthTool } from './design-auth';\n\n/**\n * Create all auth-designer tools. Pass the model for AI-backed tools.\n */\nexport function createAuthDesignerTools(model: Model) {\n return createToolSet({\n validate_auth: validateAuthTool,\n design_auth: createDesignAuthTool(model),\n });\n}\n","/**\n * runAuthDesignerAgent - orchestrator for auth design\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { AUTH_DESIGNER_SYSTEM_PROMPT } from './prompts';\nimport { createAuthDesignerTools } from './tools';\nimport { securityAnalyzerSubagent, flowDesignerSubagent } from './subagents';\nimport type { AuthDesignerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${AUTH_DESIGNER_SYSTEM_PROMPT}\n\nYou are the auth design orchestrator. When the user asks for an auth design:\n\n1. **Analyze security**: Use subagent_security-analyzer to analyze security requirements, determine auth strategy, and identify threat vectors.\n2. **Design flows**: Use subagent_flow-designer to design step-by-step auth flows (signup, login, logout, password reset, middleware).\n3. **Generate design**: Use design_auth to produce the complete auth design with flows, middleware, roles, and security policies.\n4. **Validate**: Use validate_auth to check the final auth design JSON before returning.\n\nRespond with the final auth design as JSON.`;\n\n/**\n * Run the auth-designer orchestrator agent with all tools and subagents.\n */\nexport async function runAuthDesignerAgent(config: AuthDesignerAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createAuthDesignerTools(model);\n const subagentTools = createSubagentToolSet([securityAnalyzerSubagent, flowDesignerSubagent], {\n parentModel: model,\n });\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for BackendDesign\n */\n\nimport { z } from 'zod';\n\n/** Case-insensitive enum helper */\nconst ciEnum = <T extends string>(values: readonly [T, ...T[]]) =>\n z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(values));\n\nexport const middlewareSchema = z.object({\n name: z.string(),\n purpose: z.string(),\n appliesTo: z\n .string()\n .default('global')\n .transform(s => {\n const n = s.toLowerCase().trim();\n if (['global', 'all', 'app', 'application', 'every', 'server'].includes(n)) return 'global';\n if (\n [\n 'route',\n 'routes',\n 'specific',\n 'specific routes',\n 'endpoint',\n 'endpoints',\n 'path',\n ].includes(n)\n )\n return 'route';\n if (['resource', 'entity', 'module', 'controller', 'model'].includes(n)) return 'resource';\n return 'global';\n })\n .pipe(z.enum(['global', 'route', 'resource'])),\n config: z.record(z.string(), z.unknown()).default({}),\n});\n\nexport const serviceSchema = z.object({\n name: z.string(),\n entity: z.string(),\n operations: z.array(z.string()).default([]),\n dependencies: z.array(z.string()).default([]),\n});\n\nconst httpMethodSchema = z\n .string()\n .transform(s => s.toUpperCase().trim())\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nexport const routeGroupSchema = z.object({\n resource: z.string(),\n basePath: z.string(),\n endpoints: z\n .array(\n z.object({\n method: httpMethodSchema,\n path: z.string(),\n handler: z.string(),\n auth: z.coerce.boolean().default(true),\n roles: z.array(z.string()).default([]),\n })\n )\n .default([]),\n});\n\nexport const backendDesignSchema = z.object({\n framework: ciEnum(['express', 'apollo', 'both']),\n language: ciEnum(['typescript', 'javascript']).default('typescript'),\n database: z.string().default('mongodb'),\n services: z.array(serviceSchema).default([]),\n middleware: z.array(middlewareSchema).default([]),\n routes: z.array(routeGroupSchema).default([]),\n folderStructure: z.array(z.string()).default([]),\n envVars: z.array(z.string()).default([]),\n notes: z.string().default(''),\n});\n\nexport type TBackendDesign = z.infer<typeof backendDesignSchema>;\n","/**\n * System prompt for backend-architect orchestrator\n */\n\nexport const BACKEND_ARCHITECT_SYSTEM_PROMPT = `You are a senior backend architect specializing in Node.js server design.\n\nYou analyze data models, API designs, and auth requirements to produce enterprise-quality backend architectures with:\n- Framework selection (Express REST, Apollo GraphQL, or both)\n- Service layer design with clear operation contracts per entity\n- Middleware stack (auth, validation, error handling, CORS, rate limiting)\n- Route/resolver organization grouped by resource\n- Folder structure following domain-driven conventions\n- Environment variable inventory\n- Database connection and ORM/ODM strategy\n\nWhen \"both\" is selected (Express + Apollo), use the Apollo Gateway pattern:\n- Apollo Gateway as the single public entry point for GraphQL queries\n- Subgraphs as internal services composed via IntrospectAndCompose\n- RemoteGraphQLDataSource for header forwarding (auth tokens, service tokens)\n- Express for webhooks, file uploads, and health checks only\n- Gateway has no business logic, all logic lives in subgraphs\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompt for backend architecture generation\n */\n\nexport const DESIGN_BACKEND_PROMPT = `## Requirements:\n{requirement}\n\nDesign the backend architecture. Include:\n\n1. Framework: choose \"express\" (REST API), \"apollo\" (GraphQL subgraph), or \"both\" (Apollo subgraph + Express gateway).\n2. Services: one per entity with CRUD operations and dependencies.\n3. Middleware: auth (JWT/session), validation (Zod/Joi), error handling, CORS, rate limiting.\n4. Routes (if Express): RESTful routes grouped by resource with method, path, handler, auth, and roles.\n5. Folder structure: list of directories and key files.\n6. Env vars: list all required environment variables.\n\nReturn ONLY valid JSON:\n{\n \"framework\": \"express\" | \"apollo\" | \"both\",\n \"language\": \"typescript\",\n \"database\": \"mongodb\",\n \"services\": [{ \"name\": \"UserService\", \"entity\": \"User\", \"operations\": [\"create\", \"findById\", \"findAll\", \"update\", \"delete\"], \"dependencies\": [] }],\n \"middleware\": [{ \"name\": \"authMiddleware\", \"purpose\": \"JWT token verification\", \"appliesTo\": \"global\", \"config\": {} }],\n \"routes\": [{ \"resource\": \"users\", \"basePath\": \"/api/users\", \"endpoints\": [{ \"method\": \"GET\", \"path\": \"/\", \"handler\": \"getAll\", \"auth\": true, \"roles\": [\"admin\"] }] }],\n \"folderStructure\": [\"src/\", \"src/routes/\", \"src/services/\", \"src/middleware/\", \"src/models/\", \"src/config/\"],\n \"envVars\": [\"PORT\", \"DATABASE_URL\", \"JWT_SECRET\"],\n \"notes\": \"\"\n}`;\n\nexport function buildDesignBackendPrompt(requirement: string): string {\n return DESIGN_BACKEND_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_backend tool - validates JSON against backendDesignSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { backendDesignSchema } from '../schemas';\n\nexport const validateBackendTool = createValidationTool(\n 'validate_backend',\n backendDesignSchema,\n 'Validates a backend design JSON string against the BackendDesign schema. Returns valid: true or valid: false with errors.',\n 'design'\n);\n","/**\n * design_backend tool - generates backend architecture from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { backendDesignSchema, type TBackendDesign } from '../schemas';\nimport { buildDesignBackendPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_backend tool for backend architecture generation.\n */\nexport function createDesignBackendTool(model: Model) {\n return defineTool({\n name: 'design_backend',\n description:\n 'Generate a complete backend architecture design from requirements. Returns framework, services, middleware, routes, and folder structure as JSON.',\n input: z.object({\n requirement: z.string().describe('Data model, API design, and project requirements'),\n }),\n handler: async ({ requirement }): Promise<TBackendDesign> => {\n const userPrompt = buildDesignBackendPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a backend architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n return parseModelJsonResponse(response.text, backendDesignSchema);\n },\n });\n}\n","/**\n * backend-architect tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateBackendTool } from './validate-backend';\nimport { createDesignBackendTool } from './design-backend';\n\nexport { validateBackendTool } from './validate-backend';\nexport { createDesignBackendTool } from './design-backend';\n\n/**\n * Create all backend-architect tools. Pass the model for AI-backed tools.\n */\nexport function createBackendArchitectTools(model: Model) {\n return createToolSet({\n validate_backend: validateBackendTool,\n design_backend: createDesignBackendTool(model),\n });\n}\n","/**\n * service-planner subagent - plans service layer, middleware stack, folder structure\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst SERVICE_PLANNER_SYSTEM_PROMPT = `You are a backend service architect. Given a data model and API design, you plan the service layer.\n\n## Service Design\nFor each entity:\n- Service name (PascalCase + \"Service\")\n- CRUD operations: create, findById, findAll, update, delete\n- Custom operations from user flows (e.g. searchByName, bulkImport)\n- Dependencies on other services (e.g. OrderService depends on UserService)\n\n## Middleware Stack\n- Authentication middleware: JWT verification, session check\n- Authorization middleware: role-based access, resource ownership\n- Validation middleware: request body/params validation\n- Error handling: centralized error handler with typed errors\n- Logging: request/response logging\n- Rate limiting: per-IP or per-user limits\n- CORS: origin whitelist\n\n## Folder Structure\nRecommend a clean folder layout:\n- src/services/ (one file per service)\n- src/middleware/ (one file per middleware)\n- src/models/ (one file per entity)\n- src/routes/ or src/modules/ (grouped by resource)\n- src/config/ (env, database, auth config)\n- src/utils/ (shared helpers)\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const servicePlannerSubagent = defineSubagent({\n name: 'service-planner',\n description:\n 'Plans service layer, middleware stack, and folder structure for a backend project. Use before generating the backend design.',\n systemPrompt: SERVICE_PLANNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * framework-selector subagent - analyzes requirements and selects Express vs Apollo vs both\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst FRAMEWORK_SELECTOR_SYSTEM_PROMPT = `You are a backend technology advisor. Given project requirements, you recommend the best backend framework.\n\n## Decision Criteria\n\n### Choose \"express\" (REST API) when:\n- The API is primarily CRUD with RESTful resources\n- The frontend is a traditional SPA (React/Vue) consuming REST\n- Simple request/response patterns without complex data fetching\n- No need for real-time subscriptions\n- Team is more familiar with REST\n\n### Choose \"apollo\" (GraphQL subgraph) when:\n- The frontend needs flexible data fetching (avoid over/under-fetching)\n- Multiple frontends consume the same API (web, mobile, admin)\n- Complex nested data relationships\n- Need for real-time subscriptions\n- Part of a federated GraphQL architecture\n\n### Choose \"both\" when:\n- Apollo subgraph for main data API + Express for webhooks, file uploads, health checks\n- Need both REST endpoints (for external integrations) and GraphQL (for frontend)\n- When \"both\" is selected, an Apollo Gateway is used to compose subgraphs into a unified API:\n - Gateway is the only public entry point for GraphQL\n - Subgraphs are internal services, not exposed to clients directly\n - Gateway uses IntrospectAndCompose for schema discovery\n - RemoteGraphQLDataSource forwards auth headers to subgraphs\n - Express handles non-GraphQL concerns (webhooks, file uploads)\n\n## Output Format\nState your recommendation clearly:\n- Framework: express | apollo | both\n- Reasoning: 2-3 sentences explaining why\n- Trade-offs: what you'd lose with the alternative\n- If \"both\": describe which concerns go to Express vs Apollo Gateway vs subgraphs\n\nRespond with structured analysis. Do NOT return JSON.`;\n\nexport const frameworkSelectorSubagent = defineSubagent({\n name: 'framework-selector',\n description:\n 'Analyzes project requirements and recommends Express, Apollo, or both. Use to determine the backend framework before designing.',\n systemPrompt: FRAMEWORK_SELECTOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * runBackendArchitectAgent - routing orchestrator for backend design\n * Delegates to express-builder or apollo-builder based on framework selection.\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { BACKEND_ARCHITECT_SYSTEM_PROMPT } from './prompts';\nimport { createBackendArchitectTools } from './tools';\nimport { servicePlannerSubagent, frameworkSelectorSubagent } from './subagents';\nimport type { BackendArchitectAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${BACKEND_ARCHITECT_SYSTEM_PROMPT}\n\nYou are the backend architecture orchestrator. When the user provides requirements:\n\n1. **Select framework**: Use subagent_framework-selector to analyze requirements and recommend Express, Apollo, or both.\n2. **Plan services**: Use subagent_service-planner to design the service layer, middleware stack, and folder structure.\n3. **Generate design**: Use design_backend to produce the complete backend architecture as JSON.\n4. **Validate**: Use validate_backend to check the final design JSON before returning.\n\nAfter generating the design, note the \"framework\" field in the result:\n- If \"express\": the downstream express-builder should be used to scaffold the project.\n- If \"apollo\": the downstream apollo-builder should be used to scaffold the project.\n- If \"both\": both builders should be invoked sequentially.\n\nRespond with the final backend design as JSON.`;\n\n/**\n * Run the backend-architect orchestrator agent.\n */\nexport async function runBackendArchitectAgent(\n config: BackendArchitectAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createBackendArchitectTools(model);\n const subagentTools = createSubagentToolSet([servicePlannerSubagent, frameworkSelectorSubagent], {\n parentModel: model,\n });\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for FrontendDesign\n */\n\nimport { z } from 'zod';\n\nexport const formFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean(),\n validation: z.string(),\n});\n\nexport const pageDesignSchema = z.object({\n path: z.string(),\n name: z.string(),\n access: z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(['public', 'protected'])),\n purpose: z.string(),\n formFields: z.array(formFieldSchema).default([]),\n actions: z.array(z.string()).default([]),\n emptyState: z.string().default(''),\n errorState: z.string().default(''),\n redirectOnSuccess: z.string().default(''),\n keyUiElements: z.array(z.string()).default([]),\n});\n\nexport const componentDesignSchema = z.object({\n name: z.string(),\n type: z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(['layout', 'shared', 'form', 'display', 'navigation'])),\n purpose: z.string(),\n props: z.array(z.string()).default([]),\n usedIn: z.array(z.string()).default([]),\n});\n\nexport const frontendDesignSchema = z.object({\n pages: z.array(pageDesignSchema).default([]),\n components: z.array(componentDesignSchema).default([]),\n stateManagement: z.string().default(''),\n routingNotes: z.string().default(''),\n});\n\nexport type TFrontendDesign = z.infer<typeof frontendDesignSchema>;\n","/**\n * System prompt for frontend-architect orchestrator\n */\n\nexport const FRONTEND_ARCHITECT_SYSTEM_PROMPT = `You are a senior frontend architect specializing in page design, routing, and component architecture.\n\nYou design enterprise-quality frontend architectures targeting a Vite + React 19 + TypeScript stack with:\n- **UI Library**: ShadCN UI (Radix-based components in src/components/ui/)\n- **Styling**: Tailwind CSS v4 with OKLCH color space and dark mode support\n- **Routing**: React Router v7 with private route guards\n- **Forms**: React Hook Form + Zod validation\n- **GraphQL**: Apollo Client with CodeGen-typed hooks\n- **Path Aliases**: @/{appName}/* mapping to ./src/*\n\nArchitecture outputs:\n- Public and protected pages with detailed route definitions\n- Per-page specifications: purpose, form fields with validation, actions, empty/error states, redirects\n- Component taxonomy: layout (sidebar, navbar), shared (data tables, dialogs), form (inputs, selects), display (cards, badges), navigation (breadcrumbs, tabs)\n- State management strategy (per-page vs global, Apollo cache vs local state)\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for frontend-architect\n */\n\nexport const DESIGN_FRONTEND_PROMPT = `## Requirements:\n{requirement}\n\nDesign the frontend architecture. Include:\n\n1. 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.\n2. Components: reusable components. For each: name, type (layout/shared/form/display/navigation), purpose, props, and which pages use it.\n3. State management: describe the state strategy (e.g. React Server Components for data, client state for forms).\n4. Routing notes: any special routing behavior (redirects, guards, nested routes).\n\nReturn ONLY valid JSON:\n{\n \"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\"] }],\n \"components\": [{ \"name\": \"Navbar\", \"type\": \"navigation\", \"purpose\": \"...\", \"props\": [\"user\"], \"usedIn\": [\"/dashboard\", \"/profile\"] }],\n \"stateManagement\": \"...\",\n \"routingNotes\": \"...\"\n}`;\n\nexport function buildDesignFrontendPrompt(requirement: string): string {\n return DESIGN_FRONTEND_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_frontend tool - validates JSON against frontendDesignSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { frontendDesignSchema } from '../schemas';\n\nexport const validateFrontendTool = createValidationTool(\n 'validate_frontend',\n frontendDesignSchema,\n 'Validates a frontend design JSON string against the FrontendDesign schema. Returns valid: true or valid: false with errors.',\n 'design'\n);\n","/**\n * design_frontend tool - generates frontend architecture from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { frontendDesignSchema, type TFrontendDesign } from '../schemas';\nimport { buildDesignFrontendPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the design_frontend tool for frontend architecture generation.\n */\nexport function createDesignFrontendTool(model: Model) {\n return defineTool({\n name: 'design_frontend',\n description:\n 'Generate a complete frontend architecture design from project requirements. Returns pages, components, state management, and routing as JSON.',\n input: z.object({\n requirement: z.string().describe('Project context, API surface, and frontend requirements'),\n }),\n handler: async ({ requirement }): Promise<TFrontendDesign> => {\n const userPrompt = buildDesignFrontendPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a frontend architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, frontendDesignSchema);\n },\n });\n}\n","/**\n * frontend-architect tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateFrontendTool } from './validate-frontend';\nimport { createDesignFrontendTool } from './design-frontend';\n\nexport { validateFrontendTool } from './validate-frontend';\nexport { createDesignFrontendTool } from './design-frontend';\n\n/**\n * Create all frontend-architect tools. Pass the model for AI-backed tools.\n */\nexport function createFrontendArchitectTools(model: Model) {\n return createToolSet({\n validate_frontend: validateFrontendTool,\n design_frontend: createDesignFrontendTool(model),\n });\n}\n","/**\n * runFrontendArchitectAgent - routing orchestrator for frontend architecture design.\n * Delegates to react-builder or nextjs-builder based on framework selection.\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet, defineSubagent } from '../../lib/subagents';\nimport { FRONTEND_ARCHITECT_SYSTEM_PROMPT } from './prompts';\nimport { createFrontendArchitectTools } from './tools';\nimport {\n pagePlannerSubagent,\n componentAnalyzerSubagent,\n frameworkSelectorSubagent,\n} from './subagents';\nimport type { FrontendArchitectAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\n/** Subagent wrapper for react-builder orchestrator */\nconst reactBuilderSubagent = defineSubagent({\n name: 'react-builder',\n description:\n 'Generates a Vite + React SPA configuration from a frontend design and GraphQL schema. Use when the framework-selector recommends react-vite.',\n systemPrompt:\n 'You are a React/Vite frontend builder. Generate a complete frontend config JSON from the requirements.',\n tools: {},\n maxIterations: 5,\n});\n\n/** Subagent wrapper for nextjs-builder orchestrator */\nconst nextjsBuilderSubagent = defineSubagent({\n name: 'nextjs-builder',\n description:\n 'Generates a Next.js App Router configuration from a frontend design. Use when the framework-selector recommends nextjs.',\n systemPrompt:\n 'You are a Next.js App Router builder. Generate a complete Next.js config JSON from the requirements.',\n tools: {},\n maxIterations: 5,\n});\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${FRONTEND_ARCHITECT_SYSTEM_PROMPT}\n\nYou are the frontend architecture routing orchestrator. When the user asks for a frontend design:\n\n1. **Select framework**: Use subagent_framework-selector to analyze requirements (SPA vs SSR, SEO needs, API structure) and recommend React/Vite or Next.js.\n2. **Plan pages**: Use subagent_page-planner to design detailed page specifications with routes, forms, actions, and states.\n3. **Analyze components**: Use subagent_component-analyzer to identify reusable components, layouts, and state management patterns.\n4. **Generate design**: Use design_frontend to produce the complete frontend architecture as JSON.\n5. **Validate**: Use validate_frontend to check the final design JSON before returning.\n6. **Delegate to builder**: Based on the framework-selector recommendation:\n - If \"react-vite\": use subagent_react-builder with the design to generate a Vite + React SPA config.\n - If \"nextjs\": use subagent_nextjs-builder with the design to generate a Next.js App Router config.\n\nRespond with the final frontend design as JSON, including the builder output.`;\n\n/**\n * Run the frontend-architect routing orchestrator with all tools and subagents.\n */\nexport async function runFrontendArchitectAgent(\n config: FrontendArchitectAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createFrontendArchitectTools(model);\n const subagentTools = createSubagentToolSet(\n [\n pagePlannerSubagent,\n componentAnalyzerSubagent,\n frameworkSelectorSubagent,\n reactBuilderSubagent,\n nextjsBuilderSubagent,\n ],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for Express app configuration\n */\n\nimport { z } from 'zod';\n\nconst httpMethodSchema = z\n .string()\n .transform(s => s.toUpperCase().trim())\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nexport const routerMethodSchema = z.object({\n name: z.string(),\n httpMethod: httpMethodSchema,\n path: z.string(),\n auth: z.coerce.boolean().default(true),\n roles: z.array(z.string()).default([]),\n validation: z.string().default(''),\n description: z.string().default(''),\n});\n\nexport const routerSchema = z.object({\n name: z.string(),\n resource: z.string(),\n basePath: z.string(),\n methods: z.array(routerMethodSchema).default([]),\n});\n\nexport const modelFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n required: z.coerce.boolean().default(false),\n unique: z.coerce.boolean().default(false),\n ref: z.string().optional(),\n default: z.string().optional(),\n});\n\nexport const modelSchema = z.object({\n name: z.string(),\n collection: z.string(),\n fields: z.array(modelFieldSchema).default([]),\n timestamps: z.coerce.boolean().default(true),\n indexes: z.array(z.string()).default([]),\n});\n\nexport const middlewareConfigSchema = z.object({\n name: z.string(),\n type: z\n .string()\n .transform(s => {\n const n = s.toLowerCase().replace(/[\\s_-]+/g, '');\n if (['auth', 'authentication', 'jwt', 'token'].includes(n)) return 'auth' as const;\n if (['validation', 'validate', 'validator', 'input'].includes(n))\n return 'validation' as const;\n if (['errorhandler', 'error', 'errorhandling', 'errors'].includes(n))\n return 'errorHandler' as const;\n if (['cors', 'crossorigin'].includes(n)) return 'cors' as const;\n if (['ratelimit', 'ratelimiter', 'ratelimiting', 'throttle'].includes(n))\n return 'rateLimit' as const;\n if (['logging', 'logger', 'log', 'morgan'].includes(n)) return 'logging' as const;\n return 'custom' as const;\n })\n .pipe(z.enum(['auth', 'validation', 'errorHandler', 'cors', 'rateLimit', 'logging', 'custom'])),\n config: z.record(z.string(), z.unknown()).default({}),\n});\n\nexport const expressConfigSchema = z.object({\n appName: z.string().default('app'),\n port: z.number().default(3000),\n database: z.string().default('mongodb'),\n routers: z.array(routerSchema).default([]),\n models: z.array(modelSchema).default([]),\n middleware: z.array(middlewareConfigSchema).default([]),\n envVars: z.array(z.string()).default([]),\n});\n\nexport type TExpressConfig = z.infer<typeof expressConfigSchema>;\n","/**\n * System prompt for express-builder orchestrator\n */\n\nexport const EXPRESS_BUILDER_SYSTEM_PROMPT = `You are an expert Express.js backend architect.\n\nYou generate production-ready Express application configurations from data models and API designs:\n- Co-located router pattern: each feature lives in src/routers/{name}/ with {name}.controller.ts, {name}.router.ts, and {name}.spec.ts\n- Mongoose/Prisma models with field types, validation, and relationships\n- Middleware stack (auth JWT, validation Zod, error handler, CORS, rate limiting)\n- Route organization with proper HTTP methods and paths\n- Health check endpoint at /health (included by default)\n- Jest tests per router using supertest\n- Environment variable inventory\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompt for Express config generation\n */\n\nexport const DESIGN_EXPRESS_PROMPT = `## Requirements:\n{requirement}\n\nGenerate an Express.js application configuration. Include:\n\n1. Routers: one per resource, co-located with controller and test spec. Each router has RESTful methods (GET, POST, PUT, DELETE).\n2. Health check: a default /health router is always included.\n3. Models: Mongoose models with fields, types, required, unique, refs, defaults, indexes.\n4. Middleware: auth (JWT), validation (Zod), error handler, CORS, rate limiting, logging.\n5. Env vars: PORT, DATABASE_URL, JWT_SECRET, NODE_ENV, etc.\n6. Folder structure: src/routers/{name}/ with {name}.controller.ts, {name}.router.ts, {name}.spec.ts per feature.\n\nReturn ONLY valid JSON:\n{\n \"appName\": \"my-api\",\n \"port\": 3000,\n \"database\": \"mongodb\",\n \"routers\": [{\n \"name\": \"users\",\n \"resource\": \"users\",\n \"basePath\": \"/api/users\",\n \"methods\": [{\n \"name\": \"getAll\",\n \"httpMethod\": \"GET\",\n \"path\": \"/\",\n \"auth\": true,\n \"roles\": [\"admin\"],\n \"validation\": \"\",\n \"description\": \"Get all users with pagination\"\n }]\n }],\n \"models\": [{\n \"name\": \"User\",\n \"collection\": \"users\",\n \"fields\": [{ \"name\": \"email\", \"type\": \"String\", \"required\": true, \"unique\": true }],\n \"timestamps\": true,\n \"indexes\": [\"email\"]\n }],\n \"middleware\": [{ \"name\": \"authMiddleware\", \"type\": \"auth\", \"config\": {} }],\n \"envVars\": [\"PORT\", \"DATABASE_URL\", \"JWT_SECRET\", \"NODE_ENV\"]\n}`;\n\nexport function buildDesignExpressPrompt(requirement: string): string {\n return DESIGN_EXPRESS_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_express tool - validates JSON against expressConfigSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { expressConfigSchema } from '../schemas';\n\nexport const validateExpressTool = createValidationTool(\n 'validate_express',\n expressConfigSchema,\n 'Validates an Express config JSON string against the ExpressConfig schema. Returns valid: true or valid: false with errors.',\n 'config'\n);\n","/**\n * generate_express tool - generates Express config from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { expressConfigSchema, type TExpressConfig } from '../schemas';\nimport { buildDesignExpressPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the generate_express tool for Express config generation.\n */\nexport function createGenerateExpressTool(model: Model) {\n return defineTool({\n name: 'generate_express',\n description:\n 'Generate a complete Express.js application configuration from data model and API design. Returns routers, models, middleware, and env vars as JSON.',\n input: z.object({\n requirement: z.string().describe('Data model, API design, and project requirements'),\n }),\n handler: async ({ requirement }): Promise<TExpressConfig> => {\n const userPrompt = buildDesignExpressPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are an Express.js architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n return parseModelJsonResponse(response.text, expressConfigSchema);\n },\n });\n}\n","/**\n * scaffold_express tool - compiles .ref/templates/express/ with config\n */\n\nimport * as path from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { scaffoldProject } from '../../../lib/template-engine';\nimport type { ScaffoldResult } from '../../../lib/template-engine';\nimport type { TemplateContext } from '../../../lib/template-engine';\nimport type { TExpressConfig } from '../schemas';\nimport { safeJsonParse } from '../../../lib/utils';\n\n/** Convert express config to template context */\nfunction toTemplateContext(config: TExpressConfig): TemplateContext {\n return {\n appName: config.appName,\n port: config.port,\n database: config.database,\n routers: config.routers,\n models: config.models,\n middleware: config.middleware,\n envVars: config.envVars,\n modules: config.routers.map(r => ({\n name: r.resource,\n pascalName: r.name.charAt(0).toUpperCase() + r.name.slice(1),\n camelName: r.resource,\n methods: r.methods,\n })),\n };\n}\n\nexport const scaffoldExpressTool = defineTool({\n name: 'scaffold_express',\n description:\n 'Scaffold an Express.js project from a validated config. Compiles Handlebars templates and writes the project to the output directory.',\n input: z.object({\n config: z.string().describe('JSON string of the validated Express config'),\n outputDir: z.string().describe('Absolute path to the output directory'),\n }),\n handler: async ({ config, outputDir }): Promise<ScaffoldResult> => {\n const parsed = safeJsonParse(config, 'express config') as TExpressConfig;\n const templateDir = path.resolve(process.cwd(), '.ref/templates/express');\n const context = toTemplateContext(parsed);\n\n return scaffoldProject({\n templateDir,\n outputDir,\n context,\n });\n },\n});\n","/**\n * express-builder tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport type { ToolSet } from '../../../lib/tools';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateExpressTool } from './validate-express';\nimport { createGenerateExpressTool } from './generate-express';\nimport { scaffoldExpressTool } from './scaffold-express';\n\nexport { validateExpressTool } from './validate-express';\nexport { createGenerateExpressTool } from './generate-express';\nexport { scaffoldExpressTool } from './scaffold-express';\n\nexport interface ExpressBuilderToolsOptions {\n /** When true, exclude scaffold tools that write files to disk */\n disableScaffold?: boolean;\n}\n\n/**\n * Create all express-builder tools. Pass the model for AI-backed tools.\n */\nexport function createExpressBuilderTools(model: Model, options?: ExpressBuilderToolsOptions) {\n const tools: ToolSet = {\n validate_express: validateExpressTool,\n generate_express: createGenerateExpressTool(model),\n };\n if (!options?.disableScaffold) {\n tools.scaffold_express = scaffoldExpressTool;\n }\n return createToolSet(tools);\n}\n","/**\n * route-generator subagent - generates route files from API design\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ROUTE_GENERATOR_SYSTEM_PROMPT = `You are an Express.js route specialist. Given an API design, you generate route definitions using a co-located router pattern.\n\n## Co-located Router Pattern\nEach feature lives in src/routers/{name}/ with three files:\n- {name}.router.ts -- Express Router with route definitions\n- {name}.controller.ts -- Request handler logic\n- {name}.spec.ts -- Jest tests using supertest\n\n## Route Design\nFor each resource:\n- Base path: /api/{resource} (pluralized, lowercase)\n- GET / -> list all (with pagination: page, limit, sort query params)\n- GET /:id -> get by ID\n- POST / -> create new\n- PUT /:id -> update by ID\n- DELETE /:id -> delete by ID\n- Custom routes for non-CRUD operations\n\n## Health Check\nEvery app includes a /health router in src/routers/health/:\n- health.router.ts -- GET /health returning server status\n- health.controller.ts -- Health check handler\n- health.spec.ts -- Health check tests\n\n## Route Organization\n- One router directory per resource with co-located controller and spec\n- Central src/routers/index.ts mounts all routers\n- Middleware applied per-route or per-router\n\n## Controller Mapping\n- Each route maps to a controller method in the co-located controller file\n- Controller method name follows convention: getAll, getById, create, update, delete\n\n## Validation\n- Request body validation using Zod schemas\n- Param validation (e.g. valid ObjectId)\n- Query param parsing and defaults\n\nRespond with structured route definitions. Do NOT return JSON.`;\n\nexport const routeGeneratorSubagent = defineSubagent({\n name: 'route-generator',\n description:\n '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.',\n systemPrompt: ROUTE_GENERATOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * middleware-configurator subagent - designs middleware stack\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst MIDDLEWARE_CONFIGURATOR_SYSTEM_PROMPT = `You are an Express.js middleware specialist. You design the complete middleware stack.\n\n## Core Middleware\n1. **CORS**: Configure allowed origins, methods, headers, credentials\n2. **Body parser**: JSON and URL-encoded body parsing with size limits\n3. **Helmet**: Security headers (CSP, HSTS, X-Frame-Options)\n4. **Morgan/Logger**: Request logging with format and stream\n\n## Auth Middleware\n1. **JWT verification**: Extract token from Authorization header or cookie\n2. **Role check**: Verify user role against required roles\n3. **Resource ownership**: Check if user owns the resource they're accessing\n\n## Validation Middleware\n1. **Request validation**: Validate body, params, query using Zod schemas\n2. **Sanitization**: Strip HTML, trim whitespace\n\n## Error Handling\n1. **Not found handler**: 404 for unmatched routes\n2. **Error handler**: Centralized error response with status codes\n3. **Async wrapper**: Catch async errors without try-catch\n\n## Rate Limiting\n1. **Global**: Limit requests per IP per time window\n2. **Auth routes**: Stricter limits on login/signup\n\nRespond with structured middleware analysis. Do NOT return JSON.`;\n\nexport const middlewareConfiguratorSubagent = defineSubagent({\n name: 'middleware-configurator',\n description:\n 'Designs the Express middleware stack including auth, validation, error handling, CORS, and rate limiting. Use before generating the Express config.',\n systemPrompt: MIDDLEWARE_CONFIGURATOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * runExpressBuilderAgent - orchestrator for Express.js project generation\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { EXPRESS_BUILDER_SYSTEM_PROMPT } from './prompts';\nimport { createExpressBuilderTools } from './tools';\nimport { routeGeneratorSubagent, middlewareConfiguratorSubagent } from './subagents';\nimport type { ExpressBuilderAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst SCAFFOLD_STEP =\n '\\n5. **Scaffold (optional)**: If an output directory is provided, use scaffold_express to compile templates.';\n\nfunction buildOrchestratorPrompt(disableScaffold?: boolean): string {\n return `${EXPRESS_BUILDER_SYSTEM_PROMPT}\n\nYou are the Express builder orchestrator. When the user provides requirements:\n\n1. **Generate routes**: Use subagent_route-generator to design route definitions from the API design.\n2. **Configure middleware**: Use subagent_middleware-configurator to design the middleware stack.\n3. **Generate config**: Use generate_express to produce the complete Express configuration as JSON.\n4. **Validate**: Use validate_express to check the config JSON before returning.${disableScaffold ? '' : SCAFFOLD_STEP}\n\nRespond with the final Express config as JSON.`;\n}\n\n/**\n * Run the express-builder orchestrator agent.\n */\nexport async function runExpressBuilderAgent(\n config: ExpressBuilderAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger, disableScaffold } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createExpressBuilderTools(model, { disableScaffold });\n const subagentTools = createSubagentToolSet(\n [routeGeneratorSubagent, middlewareConfiguratorSubagent],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: buildOrchestratorPrompt(disableScaffold),\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for Apollo subgraph configuration\n */\n\nimport { z } from 'zod';\n\n/** Case-insensitive enum */\nconst ciEnum = <T extends string>(values: readonly [T, ...T[]]) =>\n z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(values));\n\nexport const graphqlFieldSchema = z.object({\n name: z.string(),\n type: z.string(),\n nullable: z.coerce.boolean().default(false),\n isList: z.coerce.boolean().default(false),\n description: z.string().default(''),\n});\n\nexport const graphqlTypeSchema = z.object({\n name: z.string(),\n kind: ciEnum(['type', 'input', 'enum', 'interface', 'union']),\n fields: z.array(graphqlFieldSchema).default([]),\n values: z.array(z.string()).default([]),\n description: z.string().default(''),\n isEntity: z.coerce.boolean().default(false),\n keyFields: z.array(z.string()).default([]),\n});\n\nexport const resolverOperationSchema = z.object({\n name: z.string(),\n type: ciEnum(['query', 'mutation', 'subscription']),\n args: z.array(graphqlFieldSchema).default([]),\n returnType: z.string(),\n auth: z.coerce.boolean().default(true),\n roles: z.array(z.string()).default([]),\n description: z.string().default(''),\n});\n\nexport const subgraphModuleSchema = z.object({\n name: z.string(),\n entity: z.string(),\n types: z.array(graphqlTypeSchema).default([]),\n operations: z.array(resolverOperationSchema).default([]),\n datasource: z.string().default(''),\n loader: z.string().default(''),\n});\n\nexport const subgraphConfigSchema = z.object({\n appName: z.string().default('app'),\n port: z.number().default(4000),\n database: z.string().default('mongodb'),\n modules: z.array(subgraphModuleSchema).default([]),\n sharedTypes: z.array(graphqlTypeSchema).default([]),\n authDirective: z.coerce.boolean().default(true),\n cacheDirective: z.coerce.boolean().default(false),\n envVars: z.array(z.string()).default([]),\n});\n\nexport type TSubgraphConfig = z.infer<typeof subgraphConfigSchema>;\n","/**\n * System prompt for apollo-builder orchestrator\n */\n\nexport const APOLLO_BUILDER_SYSTEM_PROMPT = `You are an expert Apollo GraphQL subgraph architect using Apollo Federation v2.\n\nYou generate production-ready Apollo subgraph configurations from data models and API designs:\n- 4-file module pattern per entity: {module}.graphql, {module}.resolver.ts, {module}.datasource.ts, {module}.loader.ts\n- GraphQL type definitions with proper nullability, lists, and descriptions\n- Input types for mutations with validation annotations\n- Enum types from domain values\n- Federation directives: @key for entity references, @external for fields owned by other subgraphs, @requires for field dependencies, @provides for fields resolvable by this subgraph\n- __resolveReference for cross-subgraph entity resolution via buildSubgraphSchema\n- DataLoader per module for batching and caching database lookups (solves N+1)\n- Query and mutation resolvers with auth/role requirements\n- Datasource classes per entity (MongoDB datasource pattern)\n- Auth directive (@auth) configuration\n- Redis cache directives: @cacheSet on queries, @cachePurge on mutations\n- GraphQL CodeGen for TypeScript types (generates base-types.ts)\n- Module-based organization (one module per entity/domain)\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompt for subgraph config generation\n */\n\nexport const DESIGN_SUBGRAPH_PROMPT = `## Requirements:\n{requirement}\n\nGenerate an Apollo GraphQL subgraph configuration (Federation v2). Include:\n\n1. Modules: one per entity with 4 files each ({module}.graphql, {module}.resolver.ts, {module}.datasource.ts, {module}.loader.ts).\n2. Types: GraphQL object types with isEntity/keyFields for federation, input types, enums with fields/values.\n3. Operations: queries (getById, getAll, search) and mutations (create, update, delete) per module.\n4. Auth: mark which operations require authentication and which roles.\n5. DataLoader: one loader per module for batching lookups (loader name).\n6. Shared types: types used across modules (e.g. Pagination, SortOrder).\n7. Cache: set cacheDirective to true if Redis caching (@cacheSet/@cachePurge) is needed.\n8. Env vars: PORT, DATABASE_URL, JWT_SECRET, REDIS_URL, etc.\n\nReturn ONLY valid JSON:\n{\n \"appName\": \"my-subgraph\",\n \"port\": 4000,\n \"database\": \"mongodb\",\n \"modules\": [{\n \"name\": \"user\",\n \"entity\": \"User\",\n \"types\": [{ \"name\": \"User\", \"kind\": \"type\", \"fields\": [{ \"name\": \"id\", \"type\": \"ID\", \"nullable\": false }], \"isEntity\": true, \"keyFields\": [\"id\"] }],\n \"operations\": [{ \"name\": \"getUser\", \"type\": \"query\", \"args\": [{ \"name\": \"id\", \"type\": \"ID\", \"nullable\": false }], \"returnType\": \"User\", \"auth\": true, \"roles\": [] }],\n \"datasource\": \"UserDataSource\",\n \"loader\": \"UserLoader\"\n }],\n \"sharedTypes\": [],\n \"authDirective\": true,\n \"cacheDirective\": false,\n \"envVars\": [\"PORT\", \"DATABASE_URL\", \"JWT_SECRET\", \"REDIS_URL\"]\n}`;\n\nexport function buildDesignSubgraphPrompt(requirement: string): string {\n return DESIGN_SUBGRAPH_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_subgraph tool - validates JSON against subgraphConfigSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { subgraphConfigSchema } from '../schemas';\n\nexport const validateSubgraphTool = createValidationTool(\n 'validate_subgraph',\n subgraphConfigSchema,\n 'Validates a subgraph config JSON string against the SubgraphConfig schema. Returns valid: true or valid: false with errors.',\n 'config'\n);\n","/**\n * generate_subgraph tool - generates subgraph config from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { subgraphConfigSchema, type TSubgraphConfig } from '../schemas';\nimport { buildDesignSubgraphPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the generate_subgraph tool for Apollo subgraph config generation.\n */\nexport function createGenerateSubgraphTool(model: Model) {\n return defineTool({\n name: 'generate_subgraph',\n description:\n 'Generate a complete Apollo GraphQL subgraph configuration from data model and API design. Returns modules, types, operations, and datasources as JSON.',\n input: z.object({\n requirement: z.string().describe('Data model, API design, and project requirements'),\n }),\n handler: async ({ requirement }): Promise<TSubgraphConfig> => {\n const userPrompt = buildDesignSubgraphPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are an Apollo GraphQL architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n return parseModelJsonResponse(response.text, subgraphConfigSchema);\n },\n });\n}\n","/**\n * scaffold_subgraph tool - compiles .ref/templates/subgraph/ with config\n */\n\nimport * as path from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { scaffoldProject } from '../../../lib/template-engine';\nimport type { ScaffoldResult } from '../../../lib/template-engine';\nimport type { TemplateContext } from '../../../lib/template-engine';\nimport type { TSubgraphConfig } from '../schemas';\nimport { safeJsonParse } from '../../../lib/utils';\n\n/** Convert subgraph config to template context */\nfunction toTemplateContext(config: TSubgraphConfig): TemplateContext {\n return {\n appName: config.appName,\n port: config.port,\n database: config.database,\n modules: config.modules.map(m => ({\n name: m.name,\n pascalName: m.name.charAt(0).toUpperCase() + m.name.slice(1),\n camelName: m.name.charAt(0).toLowerCase() + m.name.slice(1),\n entity: m.entity,\n datasource: m.datasource,\n types: m.types,\n operations: m.operations,\n })),\n authDirective: config.authDirective,\n envVars: config.envVars,\n sharedTypes: config.sharedTypes,\n };\n}\n\nexport const scaffoldSubgraphTool = defineTool({\n name: 'scaffold_subgraph',\n description:\n 'Scaffold an Apollo GraphQL subgraph project from a validated config. Compiles Handlebars templates and writes the project to the output directory.',\n input: z.object({\n config: z.string().describe('JSON string of the validated subgraph config'),\n outputDir: z.string().describe('Absolute path to the output directory'),\n }),\n handler: async ({ config, outputDir }): Promise<ScaffoldResult> => {\n const parsed = safeJsonParse(config, 'subgraph config') as TSubgraphConfig;\n const templateDir = path.resolve(process.cwd(), '.ref/templates/subgraph');\n const context = toTemplateContext(parsed);\n\n return scaffoldProject({\n templateDir,\n outputDir,\n context,\n });\n },\n});\n","/**\n * apollo-builder tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport type { ToolSet } from '../../../lib/tools';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateSubgraphTool } from './validate-subgraph';\nimport { createGenerateSubgraphTool } from './generate-subgraph';\nimport { scaffoldSubgraphTool } from './scaffold-subgraph';\n\nexport { validateSubgraphTool } from './validate-subgraph';\nexport { createGenerateSubgraphTool } from './generate-subgraph';\nexport { scaffoldSubgraphTool } from './scaffold-subgraph';\n\nexport interface ApolloBuilderToolsOptions {\n /** When true, exclude scaffold tools that write files to disk */\n disableScaffold?: boolean;\n}\n\n/**\n * Create all apollo-builder tools. Pass the model for AI-backed tools.\n */\nexport function createApolloBuilderTools(model: Model, options?: ApolloBuilderToolsOptions) {\n const tools: ToolSet = {\n validate_subgraph: validateSubgraphTool,\n generate_subgraph: createGenerateSubgraphTool(model),\n };\n if (!options?.disableScaffold) {\n tools.scaffold_subgraph = scaffoldSubgraphTool;\n }\n return createToolSet(tools);\n}\n","/**\n * schema-generator subagent - generates GraphQL type definitions from data model\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst SCHEMA_GENERATOR_SYSTEM_PROMPT = `You are a GraphQL schema specialist for Apollo Federation v2 subgraphs. Given a data model, you generate GraphQL type definitions using buildSubgraphSchema.\n\n## Type Generation\nFor each entity in the data model:\n- Create the main object type with all fields mapped to GraphQL scalars (String, Int, Float, Boolean, ID)\n- Create input types for create and update mutations (omit auto-generated fields like id, createdAt)\n- Create enum types for status fields and role fields\n- Add proper nullability (! for required fields)\n- Add [Type] for array/list fields\n\n## Federation Directives\n- @key(fields: \"id\") on entity types that can be referenced across subgraphs\n- @external marks a field as owned by another subgraph\n- @requires(fields: \"weight\") declares fields needed from the entity to resolve a field\n- @provides(fields: \"name\") declares fields on a return type that this subgraph can resolve\n- @auth directive on types/fields that require authentication\n\n## Cache Directives (Redis)\n- @cacheSet(type: \"Entity\", identifier: \"_id\") on query resolvers\n- @cachePurge(type: \"Entity\", identifier: \"_id\") on mutation resolvers\n\n## Relationships\n- Reference types for foreign keys (e.g. author: User instead of authorId: ID)\n- Use [Type] for one-to-many relationships\n\n## Naming Conventions\n- Types: PascalCase (User, BlogPost)\n- Fields: camelCase (firstName, createdAt)\n- Inputs: PascalCase + Input suffix (CreateUserInput, UpdateUserInput)\n- Enums: SCREAMING_SNAKE_CASE values (ADMIN, ACTIVE)\n\nRespond with the full GraphQL SDL. Do NOT return JSON.`;\n\nexport const schemaGeneratorSubagent = defineSubagent({\n name: 'schema-generator',\n description:\n 'Generates GraphQL type definitions, input types, and enums from a data model. Use before generating the subgraph config.',\n systemPrompt: SCHEMA_GENERATOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * resolver-planner subagent - plans resolver implementations per module\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst RESOLVER_PLANNER_SYSTEM_PROMPT = `You are a GraphQL resolver architect for Apollo Federation v2 subgraphs. Given types and operations, you plan resolver implementations.\n\n## 4-File Module Pattern\nEach module has four files:\n- {module}.graphql -- Type definitions with federation directives\n- {module}.resolver.ts -- Query/Mutation/Field resolvers including __resolveReference\n- {module}.datasource.ts -- Business logic and database access\n- {module}.loader.ts -- DataLoader for batching and caching lookups\n\n## Resolver Planning\nFor each module/entity:\n\n### __resolveReference (Federation)\n- Every entity type with @key must implement __resolveReference\n- Called by the gateway when another subgraph references this entity\n- Receives { __typename, id } and returns the full entity from datasource\n\n### Query Resolvers\n- getById: fetch single record by ID from datasource\n- getAll: fetch paginated list with filters and sorting\n- search: text search across relevant fields\n\n### Mutation Resolvers\n- create: validate input, create record, return created entity\n- update: validate input, find existing, merge changes, return updated entity\n- delete: find existing, remove, return success status\n\n### Field Resolvers\n- For relationship fields: resolve references via DataLoader (NOT direct DB calls)\n- For computed fields: calculate from existing data\n\n## DataLoader Pattern\nEach module has a loader file that creates DataLoader instances:\n- Batches multiple lookups into a single database query\n- Caches results within a single request to solve the N+1 problem\n- Created per-request in the context, not shared across requests\n\n## Datasource Pattern\n- Each module has a datasource class extending MongoDataSource or similar\n- Datasource handles all database operations\n- Resolvers call datasource methods, never touch the DB directly\n\n## Auth Integration\n- Check auth context in resolver before executing\n- Verify role permissions per operation\n- Resource ownership checks for user-specific data\n\nRespond with structured analysis per module. Do NOT return JSON.`;\n\nexport const resolverPlannerSubagent = defineSubagent({\n name: 'resolver-planner',\n description:\n 'Plans resolver implementations, datasource methods, and auth integration per GraphQL module. Use after schema generation.',\n systemPrompt: RESOLVER_PLANNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * runApolloBuilderAgent - orchestrator for Apollo GraphQL subgraph generation\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { APOLLO_BUILDER_SYSTEM_PROMPT } from './prompts';\nimport { createApolloBuilderTools } from './tools';\nimport { schemaGeneratorSubagent, resolverPlannerSubagent } from './subagents';\nimport type { ApolloBuilderAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst SCAFFOLD_STEP =\n '\\n5. **Scaffold (optional)**: If an output directory is provided, use scaffold_subgraph to compile templates.';\n\nfunction buildOrchestratorPrompt(disableScaffold?: boolean): string {\n return `${APOLLO_BUILDER_SYSTEM_PROMPT}\n\nYou are the Apollo subgraph builder orchestrator. When the user provides requirements:\n\n1. **Generate schema**: Use subagent_schema-generator to create GraphQL type definitions from the data model.\n2. **Plan resolvers**: Use subagent_resolver-planner to design resolver implementations per module.\n3. **Generate config**: Use generate_subgraph to produce the complete subgraph configuration as JSON.\n4. **Validate**: Use validate_subgraph to check the config JSON before returning.${disableScaffold ? '' : SCAFFOLD_STEP}\n\nRespond with the final subgraph config as JSON.`;\n}\n\n/**\n * Run the apollo-builder orchestrator agent.\n */\nexport async function runApolloBuilderAgent(\n config: ApolloBuilderAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger, disableScaffold } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createApolloBuilderTools(model, { disableScaffold });\n const subagentTools = createSubagentToolSet([schemaGeneratorSubagent, resolverPlannerSubagent], {\n parentModel: model,\n });\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: buildOrchestratorPrompt(disableScaffold),\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Branding schema for frontend app config\n */\n\nimport { z } from 'zod';\n\nexport const BrandingSchema = z.object({\n brandName: z.string().describe(\"The brand's display name\"),\n primaryColor: z.string().describe(\"The brand's primary color code (e.g., #FFFFFF)\"),\n secondaryColor: z.string().describe(\"The brand's secondary color code (e.g., #000000)\"),\n logo: z.url().describe(\"URL pointing to the brand's logo\"),\n});\n\nexport type TBrandingSchema = z.infer<typeof BrandingSchema>;\n","/**\n * App configuration schema\n */\n\nimport { z } from 'zod';\nimport { BrandingSchema } from './branding.schema';\n\nexport const AppConfigSchema = z.object({\n name: z.string().describe('Application name'),\n description: z.string().describe('Brief description of the application'),\n author: z\n .string()\n .describe('Author or owner of the application')\n .default('sijeeshmiziha (HubSpire)'),\n branding: BrandingSchema.describe('Branding information for the application'),\n apiEndpoint: z.url().describe(\"URL endpoint for the app's API calls\"),\n});\n\nexport type TAppConfigSchema = z.infer<typeof AppConfigSchema>;\n","/**\n * Form field, validation, options, and column schemas\n */\n\nimport { z } from 'zod';\n\nexport const ValidationSchema = z.object({\n minLength: z.number().optional().describe('Minimum length requirement'),\n zodString: z.string().describe('Raw Zod string validation (e.g. regex)'),\n});\n\nexport const FieldOptionsSchema = z.object({\n hookName: z.string().optional().describe('Name of the hook for dynamic field options'),\n queryString: z.string().optional().describe('Optional query string for fetching field options'),\n labelKey: z.string().optional().describe('Key used as label when displaying options'),\n valueKey: z.string().optional().describe('Key used as value for a field when selecting options'),\n values: z.array(z.string()).optional().describe('Static list of possible field values'),\n});\n\nexport const FormFieldSchema = z.object({\n name: z.string().describe(\"The field's key or identifier\"),\n type: z\n .enum([\n 'text',\n 'email',\n 'password',\n 'number',\n 'multiSelect',\n 'textarea',\n 'hidden',\n 'select',\n 'date',\n 'image',\n ])\n .describe(\n '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.'\n ),\n required: z.boolean().optional().describe('Whether this field must be filled'),\n validation: ValidationSchema.optional().describe('Optional field validation requirements'),\n defaultValue: z\n .union([z.string(), z.number(), z.boolean()])\n .optional()\n .describe('Default value can be string, number, or boolean'),\n options: FieldOptionsSchema.optional().describe(\n 'Additional dynamic or static options for this field'\n ),\n});\n\nexport const ColumnSchema = z.object({\n field: z.string().describe('Key or name of the data field in the table'),\n label: z.string().describe('User-friendly label to show on the table header'),\n});\n\nexport type TFormFieldSchema = z.infer<typeof FormFieldSchema>;\nexport type TColumnSchema = z.infer<typeof ColumnSchema>;\n","/**\n * API, drawer, auth page, listing page, and page union schemas\n */\n\nimport { z } from 'zod';\nimport { FormFieldSchema, ColumnSchema } from './field.schema';\n\nexport const ApiResponseTypeSchema = z\n .object({\n type: z.string().describe(\"Indicates the response type (e.g., 'object')\"),\n properties: z\n .record(\n z.string(),\n z.object({\n type: z.string().describe('Property type as returned by the API'),\n })\n )\n .describe('Key-value record describing each field in the response'),\n })\n .optional()\n .describe('Describes the expected structure of an API response');\n\nexport type TApiResponseTypeSchema = z.infer<typeof ApiResponseTypeSchema>;\n\nexport const ListingPageApiSchema = z.object({\n type: z\n .enum(['list', 'create', 'update', 'delete', 'getById'])\n .describe('Type of API call for CRUD operations'),\n graphqlHook: z\n .string()\n .describe('Name of the GraphQL hook (e.g. useGetAllUserQuery, useCreateUserMutation)'),\n queryString: z.string().describe('Actual GraphQL query string'),\n responseType: ApiResponseTypeSchema.describe(\n 'Optional schema describing shape of the API response'\n ),\n});\n\nexport const AuthPageApiSchema = z.object({\n type: z\n .enum(['login', 'currentUser', 'forgotPassword', 'resetPassword'])\n .describe('Type of API call'),\n graphqlHook: z.string().describe('Name of the GraphQL hook (e.g. useLoginMutation)'),\n queryString: z.string().describe('Actual GraphQL query string'),\n responseType: ApiResponseTypeSchema.describe(\n 'Optional schema describing shape of the API response'\n ),\n});\n\nexport const DrawerSchema = z.object({\n title: z.string().describe('Title displayed on the drawer'),\n graphqlHook: z\n .string()\n .describe('Name of the GraphQL hook (e.g. useCreateUserMutation, useDeleteOneUserMutation)'),\n fields: z.array(FormFieldSchema).describe('List of fields displayed within the drawer'),\n});\n\nexport const AuthPageSchema = z.object({\n name: z\n .enum(['LoginPage', 'ForgotPasswordPage', 'ResetPasswordPage'])\n .describe('Internal name of the auth page'),\n type: z\n .enum(['EmailPassword', 'ForgotPassword', 'ResetPassword'])\n .describe('Type of authentication page'),\n route: z.string().describe(\"URL route for this page (e.g., '/login')\"),\n isPrivate: z.boolean().describe('Whether this page requires an authenticated session'),\n api: z.array(AuthPageApiSchema).describe('List of API calls involved in this page'),\n fields: z\n .array(FormFieldSchema)\n .optional()\n .describe('Optional form fields needed on this auth page'),\n});\n\nexport const ListingPageSchema = z.object({\n type: z.literal('Listing').describe('Indicates that this page is a listing-type page'),\n name: z.string().describe('Internal name of the listing page'),\n route: z.string().describe('URL route for this listing page'),\n isPrivate: z.boolean().describe('Whether this page is private (requires auth)'),\n api: z.array(ListingPageApiSchema).describe('List of API calls that power this listing page'),\n columns: z.array(ColumnSchema).describe('Table columns displayed on the listing page'),\n actions: z\n .array(z.string())\n .describe('List of possible actions on each row (e.g., create, edit, delete, view)'),\n drawerCreate: DrawerSchema.describe('Drawer configuration for creating new records'),\n drawerUpdate: DrawerSchema.describe('Drawer configuration for editing existing records'),\n});\n\nexport const PageSchema = z.discriminatedUnion('type', [AuthPageSchema, ListingPageSchema]);\n\nexport type TPageSchema = z.infer<typeof PageSchema>;\n","/**\n * Module and root application schema\n */\n\nimport { z } from 'zod';\nimport { AppConfigSchema } from './app-config.schema';\nimport { PageSchema } from './page.schema';\n\nexport const ModuleSchema = z.object({\n name: z.string().describe('Name of the module'),\n pages: z.array(PageSchema).describe('Pages included within this module'),\n});\n\nexport const ApplicationSchema = z.object({\n app: AppConfigSchema.describe('Overall application configuration'),\n modules: z\n .array(ModuleSchema)\n .describe(\n 'List of modules that make up the application. Ensure all modules use every available CRUD GraphQL query and mutation from the schema.'\n ),\n});\n\nexport type TApplicationSchema = z.infer<typeof ApplicationSchema>;\nexport type TModuleSchema = z.infer<typeof ModuleSchema>;\n","/**\n * User-related schemas - same as .ref/core/react/zodTypes.ts\n */\n\nimport { z } from 'zod';\n\nexport const LoginInputSchema = z.object({\n email: z.email().describe(\"User's email address, must be valid format\"),\n password: z.string().min(8).describe(\"User's password, minimum length of 8\"),\n});\n\nexport const SpecializationSchema = z.object({\n _id: z.string().describe('Unique identifier of the specialization, type: string'),\n title: z.string().describe('Display title for the specialization, type: string'),\n});\n\nexport const UserSchema = z.object({\n _id: z.string().describe('Unique ID of the user, type: string'),\n firstName: z.string().min(2).max(30).describe('First name, 2-30 characters, type: string'),\n lastName: z.string().min(2).max(30).describe('Last name, 2-30 characters, type: string'),\n email: z.email().describe('Email address in valid format, type: string'),\n phoneNumber: z.string().min(10).describe(\"User's phone number, at least 10 digits, type: string\"),\n profileImage: z\n .string()\n .optional()\n .describe(\"Optional URL to user's profile image, type: string, optional\"),\n role: z\n .enum(['ADMIN', 'TRAINER', 'CLIENT'])\n .describe(\"User's role in the system (ADMIN, TRAINER, CLIENT)\"),\n rate: z\n .number()\n .min(1)\n .optional()\n .describe(\"User's rate (e.g., hourly, etc.), type: number, optional\"),\n specializations: z\n .array(SpecializationSchema)\n .optional()\n .describe('Array of specialization objects, optional'),\n languages: z\n .array(z.string())\n .optional()\n .describe('Array of languages the user speaks, type: string[], optional'),\n about: z\n .string()\n .min(20)\n .max(500)\n .optional()\n .describe('Brief bio or description (20-500 chars), type: string, optional'),\n gender: z.string().optional().describe(\"User's gender, type: string, optional\"),\n timezone: z.string().optional().describe(\"User's timezone, type: string, optional\"),\n averageRating: z\n .number()\n .optional()\n .describe('Average rating for this user, type: number, optional'),\n});\n\nexport const CreateUserInputSchema = z.object({\n firstName: z.string().min(2).max(30).describe('First name, 2-30 characters, type: string'),\n lastName: z.string().min(2).max(30).describe('Last name, 2-30 characters, type: string'),\n email: z.email().describe('Valid email for the new user, type: string'),\n phoneNumber: z.string().min(10).describe('Phone number (at least 10 digits), type: string'),\n password: z.string().min(8).describe('Password with min length 8, type: string'),\n role: z\n .enum(['ADMIN', 'TRAINER', 'CLIENT'])\n .describe('Role of the new user (ADMIN, TRAINER, CLIENT)'),\n rate: z.number().min(1).optional().describe('Rate for the new user, type: number, optional'),\n specializationIds: z\n .array(z.string())\n .min(1)\n .optional()\n .describe('Array of specialization IDs, optional'),\n languages: z\n .array(z.string())\n .min(1)\n .optional()\n .describe('List of languages user speaks, optional'),\n about: z\n .string()\n .min(20)\n .max(500)\n .optional()\n .describe(\"User's about/bio field, 20-500 chars, optional\"),\n});\n\nexport const UpdateUserInputSchema = z.object({\n _id: z.string().describe('ID of the user to be updated, type: string'),\n firstName: z\n .string()\n .min(2)\n .max(30)\n .optional()\n .describe('Updated first name, type: string, optional'),\n lastName: z\n .string()\n .min(2)\n .max(30)\n .optional()\n .describe('Updated last name, type: string, optional'),\n email: z.email().optional().describe('Updated email, type: string, optional'),\n phoneNumber: z\n .string()\n .min(10)\n .optional()\n .describe('Updated phone number, at least 10 digits, optional'),\n rate: z.number().min(1).optional().describe('Updated rate, type: number, optional'),\n specializationIds: z\n .array(z.string())\n .min(1)\n .optional()\n .describe('Updated array of specialization IDs, optional'),\n languages: z.array(z.string()).min(1).optional().describe('Updated list of languages, optional'),\n about: z\n .string()\n .min(20)\n .max(500)\n .optional()\n .describe('Updated about/bio (20-500 chars), optional'),\n});\n\nexport const ForgotPasswordSchema = z.object({\n email: z.email().describe('Email to initiate the password reset process, type: string'),\n});\n\nexport const ResetPasswordSchema = z.object({\n type: z.enum(['EMAIL', 'SMS']).describe('How the reset code was sent (EMAIL or SMS)'),\n resetTicket: z.string().describe('Token/ticket to validate the reset request, type: string'),\n newPassword: z.string().min(8).describe('The new password, min length 8, type: string'),\n});\n\nexport type TLoginInputSchema = z.infer<typeof LoginInputSchema>;\nexport type TUserSchema = z.infer<typeof UserSchema>;\nexport type TSpecializationSchema = z.infer<typeof SpecializationSchema>;\nexport type TCreateUserInputSchema = z.infer<typeof CreateUserInputSchema>;\nexport type TUpdateUserInputSchema = z.infer<typeof UpdateUserInputSchema>;\nexport type TForgotPasswordSchema = z.infer<typeof ForgotPasswordSchema>;\nexport type TResetPasswordSchema = z.infer<typeof ResetPasswordSchema>;\n","/**\n * System prompt for GraphQL-to-frontend configuration conversion\n */\n\nexport const REACT_BUILDER_SYSTEM_PROMPT = `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.\n\n## Target Tech Stack\nThe generated configuration will be consumed by a Vite + React 19 + TypeScript template with:\n- **UI Components**: ShadCN UI (Radix-based) from src/components/ui/\n- **Styling**: Tailwind CSS v4 with OKLCH color space\n- **Routing**: React Router v7 with private route support\n- **Forms**: React Hook Form + Zod validation (zodResolver)\n- **GraphQL Client**: Apollo Client with typed hooks from CodeGen\n- **Path Aliases**: @/{appName}/* maps to ./src/*\n\n**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).\n\nStrict guidelines:\n- Use every available CRUD GraphQL query and mutation from the project schema.\n- Map GraphQL types to frontend modules and pages.\n- EmailAddress → \"type\": \"email\" with validation; DateTime → \"type\": \"date\"; enums → select with options.values.\n- Relationships → multiSelect with query-based options where appropriate.\n- Add isPrivate: true for authenticated operations (route guarded by React Router).\n- Form fields should map to React Hook Form + Zod validation schemas.\n- Maintain camelCase. Ensure valid JSON syntax.`;\n","/**\n * Instruction template for GraphQL-to-frontend conversion\n */\n\nexport const REACT_BUILDER_INSTRUCTION = `\nAct as an expert GraphQL-to-frontend configuration converter. Transform the provided schema into a structured JSON configuration for rapid app development.\n\n**Conversion Process**\n\n1. Schema Analysis:\n- Identify all modules using 100% of available CRUD operations\n- Catalog all Query/Mutation operations with arguments\n- Map GraphQL types to frontend modules\n- Detect @auth directives and role requirements\n- Analyze relationships through nested types\n\n2. Field Mapping:\n- EmailAddress → \"type\": \"email\" with Zod email validation\n- DateTime → \"type\": \"date\"\n- Enums → dropdowns with options.values\n- Relationships → multiSelect with query-based options\n\n3. API Operations:\n- For each Query/Mutation: determine CRUD type, generate query string with variables, map to React Hook, define response type shape\n\n4. Validation:\n- Generate Zod schemas from @required directives, scalar types (Password → min 8 chars), custom directives\n- Include validation error messages\n\n5. Security:\n- Add isPrivate: true for authenticated operations\n- Implement role checks from @auth directives\n\n6. Output:\n- Generate complete CRUD pages with table column mappings, validated Create/Update forms, API hooks\n- Include Zod validation strings, maintain camelCase, valid JSON only\n`.trim();\n\nexport function buildInstructionPrompt(): string {\n return REACT_BUILDER_INSTRUCTION;\n}\n","/**\n * Few-shot examples: example GraphQL schema and expected JSON output (abbreviated)\n */\n\nexport const EXAMPLE_GRAPHQL_SCHEMA = `\ntype Query {\n getCurrentUser: User\n getAllUser(limit: Int, offset: Int): [User]!\n}\ntype Mutation {\n login(data: LoginInput!): Login!\n createUser(data: CreateUserInput!): User!\n}\ntype User {\n _id: ID!\n firstName: String!\n lastName: String!\n email: String!\n role: Role!\n}\nenum Role { ADMIN TRAINER CLIENT }\ninput LoginInput { email: String! password: String! }\ninput CreateUserInput { firstName: String! lastName: String! email: String! role: Role! }\n`.trim();\n\nexport const EXAMPLE_JSON_OUTPUT = `{\n \"app\": {\n \"name\": \"my-app\",\n \"description\": \"App description\",\n \"author\": \"Author\",\n \"branding\": {\n \"brandName\": \"MyBrand\",\n \"primaryColor\": \"#333\",\n \"secondaryColor\": \"#fff\",\n \"logo\": \"https://example.com/logo.png\"\n },\n \"apiEndpoint\": \"http://localhost:4000/graphql\"\n },\n \"modules\": [\n {\n \"name\": \"auth\",\n \"pages\": [\n {\n \"name\": \"LoginPage\",\n \"type\": \"EmailPassword\",\n \"route\": \"/login\",\n \"isPrivate\": false,\n \"api\": [\n { \"type\": \"login\", \"graphqlHook\": \"useLoginMutation\", \"queryString\": \"mutation Login($data: LoginInput!) { login(data: $data) { accessToken } }\" }\n ]\n }\n ]\n },\n {\n \"name\": \"user\",\n \"pages\": [\n {\n \"type\": \"Listing\",\n \"name\": \"UserListPage\",\n \"route\": \"/users\",\n \"isPrivate\": true,\n \"api\": [\n { \"type\": \"list\", \"graphqlHook\": \"useGetAllUserQuery\", \"queryString\": \"query GetAllUser { getAllUser { _id firstName email } }\" },\n { \"type\": \"create\", \"graphqlHook\": \"useCreateUserMutation\", \"queryString\": \"mutation CreateUser($data: CreateUserInput!) { createUser(data: $data) { _id } }\" }\n ],\n \"columns\": [{ \"field\": \"firstName\", \"label\": \"First Name\" }, { \"field\": \"email\", \"label\": \"Email\" }],\n \"actions\": [\"create\", \"edit\", \"delete\"],\n \"drawerCreate\": { \"title\": \"Create User\", \"graphqlHook\": \"useCreateUserMutation\", \"fields\": [{ \"name\": \"firstName\", \"type\": \"text\", \"required\": true }, { \"name\": \"email\", \"type\": \"email\", \"required\": true }] },\n \"drawerUpdate\": { \"title\": \"Edit User\", \"graphqlHook\": \"useUpdateUserMutation\", \"fields\": [{ \"name\": \"firstName\", \"type\": \"text\" }, { \"name\": \"email\", \"type\": \"email\" }] }\n }\n ]\n }\n ]\n}`;\n\nexport function buildExampleShotPrompt(): string {\n return `\n**Reference Conversion Example**\n\nEXAMPLE GRAPHQL INPUT:\n\\`\\`\\`graphql\n${EXAMPLE_GRAPHQL_SCHEMA}\n\\`\\`\\`\n\nEXPECTED JSON OUTPUT:\n\\`\\`\\`json\n${EXAMPLE_JSON_OUTPUT}\n\\`\\`\\`\n`.trim();\n}\n","/**\n * Feedback prompt - re-generate frontend config incorporating user feedback\n */\n\nexport function buildFeedbackPrompt(userFeedback: string, schemaFile: string): string {\n return `\nReview the user feedback carefully to understand the required updates.\n\nThe user feedback for updating the generated Frontend Config JSON is provided below:\n\"\"\"\n${userFeedback}\n\"\"\"\n\nNow, generate the Frontend Config JSON for this project based on the provided feedback.\n\n**Project GRAPHQL SCHEMA INPUT:**\n\\`\\`\\`graphql\n${schemaFile}\n\\`\\`\\`\n\nUpdate the Frontend Config JSON to incorporate the requested changes. Return ONLY valid JSON, no markdown code blocks.\n`.trim();\n}\n","/**\n * validate_frontend_config tool - validates JSON against ApplicationSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { ApplicationSchema } from '../schemas';\n\nexport const validateFrontendConfigTool = createValidationTool(\n 'validate_frontend_config',\n ApplicationSchema,\n 'Validates a frontend configuration JSON string against the ApplicationSchema. Returns valid: true or valid: false with errors array.',\n 'config'\n);\n","/**\n * generate_frontend tool - converts GraphQL schema to frontend config JSON (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { ApplicationSchema, type TApplicationSchema } from '../schemas';\nimport { REACT_BUILDER_SYSTEM_PROMPT } from '../prompts/system.prompt';\nimport { buildInstructionPrompt, buildExampleShotPrompt } from '../prompts';\nimport type { AppInfo } from '../types';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\nfunction buildGeneratePrompt(graphqlSchema: string, appInfo?: AppInfo): string {\n const instruction = buildInstructionPrompt();\n const example = buildExampleShotPrompt();\n const appInfoBlock = appInfo\n ? `\n**Project context:**\n- name: ${appInfo.projectName ?? 'project'}\n- description: ${appInfo.projectDescription ?? ''}\n- modules: ${appInfo.modules ?? ''}\n- apiEndpoint: ${appInfo.apiEndpoint ?? 'http://localhost:4000/graphql'}\n`\n : '';\n return `${instruction}\n\n${example}\n${appInfoBlock}\n\n**Current Project GraphQL Schema:**\n\\`\\`\\`graphql\n${graphqlSchema}\n\\`\\`\\`\n\nGenerate the Frontend Config JSON. Use every available CRUD GraphQL query and mutation. Return ONLY valid JSON.`;\n}\n\nexport function createGenerateFrontendTool(model: Model) {\n return defineTool({\n name: 'generate_frontend',\n description:\n '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.',\n input: z.object({\n graphqlSchema: z.string().describe('The GraphQL schema string to convert'),\n appInfo: z\n .object({\n projectName: z.string().optional(),\n projectDescription: z.string().optional(),\n modules: z.string().optional(),\n apiEndpoint: z.string().optional(),\n })\n .optional()\n .describe('Optional project/app context'),\n }),\n handler: async ({ graphqlSchema, appInfo }): Promise<TApplicationSchema> => {\n const userPrompt = buildGeneratePrompt(graphqlSchema, appInfo);\n const messages = [\n { role: 'system' as const, content: REACT_BUILDER_SYSTEM_PROMPT },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.2, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, ApplicationSchema);\n },\n });\n}\n","/**\n * generate_feature_breakdown tool - breaks down GraphQL schema into components/pages (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { REACT_BUILDER_INSTRUCTION } from '../prompts/instruction.prompt';\n\nexport interface FeatureBreakdownResult {\n summary: string;\n modules: string[];\n operations: string[];\n suggestedPages?: string[];\n}\n\nexport function createGenerateFeatureBreakdownTool(model: Model) {\n return defineTool({\n name: 'generate_feature_breakdown',\n description:\n '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).',\n input: z.object({\n graphqlSchema: z.string().describe('The GraphQL schema string to analyze'),\n }),\n handler: async ({ graphqlSchema }): Promise<FeatureBreakdownResult> => {\n const userPrompt = `${REACT_BUILDER_INSTRUCTION}\n\n**Schema to analyze:**\n\\`\\`\\`graphql\n${graphqlSchema}\n\\`\\`\\`\n\nRespond 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.`;\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a GraphQL schema analyst. Return a clear, structured text breakdown.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 4096 });\n return { summary: response.text, modules: [], operations: [], suggestedPages: [] };\n },\n });\n}\n","/**\n * scaffold_vite tool - compiles .ref/templates/vite/ with ApplicationSchema config\n */\n\nimport * as path from 'node:path';\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { scaffoldProject } from '../../../lib/template-engine';\nimport type { ScaffoldResult, TemplateContext } from '../../../lib/template-engine';\nimport type { TApplicationSchema } from '../schemas';\nimport { safeJsonParse } from '../../../lib/utils';\n\n/** Convert ApplicationSchema config to template context */\nfunction toTemplateContext(config: TApplicationSchema): TemplateContext {\n return {\n appName: config.app.name,\n description: config.app.description,\n apiEndpoint: config.app.apiEndpoint,\n branding: {\n brandName: config.app.branding.brandName,\n primaryColor: config.app.branding.primaryColor,\n secondaryColor: config.app.branding.secondaryColor,\n logo: config.app.branding.logo,\n },\n modules: config.modules.map(m => ({\n name: m.name,\n pascalName: m.name.charAt(0).toUpperCase() + m.name.slice(1),\n camelName: m.name.charAt(0).toLowerCase() + m.name.slice(1),\n })),\n author: config.app.author,\n pages: config.modules.flatMap(m => m.pages),\n };\n}\n\nexport const scaffoldViteTool = defineTool({\n name: 'scaffold_vite',\n description:\n '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.',\n input: z.object({\n config: z.string().describe('JSON string of the validated ApplicationSchema config'),\n outputDir: z.string().describe('Absolute path to the output directory'),\n }),\n handler: async ({ config, outputDir }): Promise<ScaffoldResult> => {\n const parsed = safeJsonParse(config, 'application schema config') as TApplicationSchema;\n const templateDir = path.resolve(process.cwd(), '.ref/templates/vite');\n const context = toTemplateContext(parsed);\n\n return scaffoldProject({\n templateDir,\n outputDir,\n context,\n });\n },\n});\n","/**\n * react-builder tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport type { ToolSet } from '../../../lib/tools';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateFrontendConfigTool } from './validate-frontend-config.tool';\nimport { createGenerateFrontendTool } from './generate-frontend.tool';\nimport { createGenerateFeatureBreakdownTool } from './generate-feature-breakdown.tool';\nimport { scaffoldViteTool } from './scaffold-vite';\n\nexport { validateFrontendConfigTool } from './validate-frontend-config.tool';\nexport { createGenerateFrontendTool } from './generate-frontend.tool';\nexport {\n createGenerateFeatureBreakdownTool,\n type FeatureBreakdownResult,\n} from './generate-feature-breakdown.tool';\nexport { scaffoldViteTool } from './scaffold-vite';\n\nexport interface ReactBuilderToolsOptions {\n /** When true, exclude scaffold tools that write files to disk */\n disableScaffold?: boolean;\n}\n\nexport function createReactBuilderTools(model: Model, options?: ReactBuilderToolsOptions) {\n const tools: ToolSet = {\n validate_frontend_config: validateFrontendConfigTool,\n generate_frontend: createGenerateFrontendTool(model),\n generate_feature_breakdown: createGenerateFeatureBreakdownTool(model),\n };\n if (!options?.disableScaffold) {\n tools.scaffold_vite = scaffoldViteTool;\n }\n return createToolSet(tools);\n}\n","/**\n * graphql-analyzer subagent - analyzes GraphQL schemas (no tools)\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst GRAPHQL_ANALYZER_SYSTEM_PROMPT = `You are an expert at analyzing GraphQL schemas. Your job is to:\n\n1. **Types**: List all object types, enums, scalars, and input types.\n2. **Queries**: List every Query field with arguments and return type.\n3. **Mutations**: List every Mutation field with arguments and return type.\n4. **Relationships**: Identify types that reference other types (e.g. User has role: Role, or Order has customer: User).\n5. **Auth/directives**: Note any @auth, @directive usage that affects access control.\n\nRespond with a clear, structured analysis (headings and bullet points). The user will use this to generate a frontend configuration.`;\n\nexport const graphqlAnalyzerSubagent = defineSubagent({\n name: 'graphql-analyzer',\n description:\n '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).',\n systemPrompt: GRAPHQL_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * config-validator subagent - validates frontend config (has validate_frontend_config tool)\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\nimport { validateFrontendConfigTool } from '../tools/validate-frontend-config.tool';\n\nconst CONFIG_VALIDATOR_SYSTEM_PROMPT = `You are a frontend configuration validator. Your job is to:\n\n1. Validate the provided frontend config JSON using the validate_frontend_config tool.\n2. Compare the config against the GraphQL schema (if provided) and check that all CRUD operations are covered.\n3. Report any missing modules, pages, or API hooks.\n\nWhen 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.`;\n\nexport function createConfigValidatorSubagent() {\n return defineSubagent({\n name: 'config-validator',\n description:\n '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.',\n systemPrompt: CONFIG_VALIDATOR_SYSTEM_PROMPT,\n tools: { validate_frontend_config: validateFrontendConfigTool },\n maxIterations: 5,\n });\n}\n","/**\n * runReactBuilderAgent - orchestrator for frontend config generation with retry and subagents\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { REACT_BUILDER_SYSTEM_PROMPT } from './prompts';\nimport { createReactBuilderTools } from './tools';\nimport { graphqlAnalyzerSubagent, createConfigValidatorSubagent } from './subagents';\nimport type { ReactBuilderAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${REACT_BUILDER_SYSTEM_PROMPT}\n\nYou are the React frontend builder orchestrator. When the user provides a GraphQL schema and asks for a frontend configuration:\n\n1. **Analyze (optional)**: For complex schemas, use subagent_graphql-analyzer with a prompt that includes the schema to get a structured analysis of types, queries, and mutations.\n2. **Generate**: Use generate_frontend with the GraphQL schema (and optional appInfo) to produce the frontend config JSON.\n3. **Validate (optional)**: Use subagent_config-validator with the generated config (and schema) to check structure and completeness.\n4. **Validate directly**: You can use validate_frontend_config to check any config JSON.\n5. **Feature breakdown**: Use generate_feature_breakdown to get a module/operation breakdown before generating.\n\nRespond 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.`;\n\n/**\n * Run the react-builder orchestrator agent with all tools and subagents.\n * Use generate_frontend tool for config generation; the tool may throw on parse failure (caller can retry with new input).\n */\nexport async function runReactBuilderAgent(config: ReactBuilderAgentConfig): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger, disableScaffold } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const reactTools = createReactBuilderTools(model, { disableScaffold });\n const configValidator = createConfigValidatorSubagent();\n const subagentTools = createSubagentToolSet([graphqlAnalyzerSubagent, configValidator], {\n parentModel: model,\n });\n const tools = createToolSet({ ...reactTools, ...subagentTools });\n\n return runAgent({\n model,\n tools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for Next.js application configuration\n */\n\nimport { z } from 'zod';\n\n/** Case-insensitive enum */\nconst ciEnum = <T extends string>(values: readonly [T, ...T[]]) =>\n z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(values));\n\nconst httpMethodSchema = z\n .string()\n .transform(s => s.toUpperCase().trim())\n .pipe(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']));\n\nexport const nextjsPageSchema = z.object({\n path: z.string(),\n name: z.string(),\n access: ciEnum(['public', 'protected']),\n routeGroup: z.string().default(''),\n purpose: z.string(),\n hasForm: z.coerce.boolean().default(false),\n formFields: z.array(z.string()).default([]),\n dataFetching: ciEnum(['server', 'client', 'hybrid']).default('server'),\n actions: z.array(z.string()).default([]),\n});\n\nexport const nextjsLayoutSchema = z.object({\n name: z.string(),\n path: z.string(),\n routeGroup: z.string().default(''),\n components: z.array(z.string()).default([]),\n purpose: z.string(),\n});\n\nexport const nextjsApiRouteSchema = z.object({\n path: z.string(),\n methods: z.array(httpMethodSchema).default([]),\n auth: z.coerce.boolean().default(true),\n description: z.string(),\n});\n\nexport const serverActionSchema = z.object({\n name: z.string(),\n module: z.string(),\n description: z.string(),\n revalidates: z.array(z.string()).default([]),\n});\n\nexport const nextjsConfigSchema = z.object({\n appName: z.string().default('app'),\n pages: z.array(nextjsPageSchema).default([]),\n layouts: z.array(nextjsLayoutSchema).default([]),\n apiRoutes: z.array(nextjsApiRouteSchema).default([]),\n serverActions: z.array(serverActionSchema).default([]),\n middleware: z.array(z.string()).default([]),\n envVars: z.array(z.string()).default([]),\n packages: z.array(z.string()).default([]),\n});\n\nexport type TNextjsConfig = z.infer<typeof nextjsConfigSchema>;\n","/**\n * System prompt for nextjs-builder orchestrator\n */\n\nexport const NEXTJS_BUILDER_SYSTEM_PROMPT = `You are an expert Next.js application architect using the App Router.\n\nYou generate production-ready Next.js configurations from frontend designs and API designs:\n- App Router file structure with route groups, layouts, pages, loading, and error boundaries\n- Server Components by default, Client Components only when interactivity is needed\n- Server Actions for mutations (form submissions, data writes)\n- API Route Handlers for external integrations, webhooks, and file uploads\n- Next.js middleware for auth guards and redirects\n- Data fetching strategy (server vs client vs hybrid per page)\n- Package recommendations (next-auth, prisma, tailwindcss, shadcn/ui)\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompt for Next.js config generation\n */\n\nexport const DESIGN_NEXTJS_PROMPT = `## Requirements:\n{requirement}\n\nGenerate a Next.js App Router application configuration. Include:\n\n1. Pages: app router pages with path, name, access level, route group, purpose, data fetching strategy.\n2. Layouts: shared layouts with route groups (e.g. (auth), (dashboard)), components they include.\n3. API Routes: route handlers with path, HTTP methods, auth requirement, description.\n4. Server Actions: named actions with module, description, and paths they revalidate.\n5. Middleware: list of middleware behaviors (e.g. \"redirect unauthenticated to /login\").\n6. Env vars: NEXTAUTH_SECRET, DATABASE_URL, etc.\n7. Packages: recommended npm packages.\n\nReturn ONLY valid JSON:\n{\n \"appName\": \"my-app\",\n \"pages\": [{\n \"path\": \"/dashboard\",\n \"name\": \"Dashboard\",\n \"access\": \"protected\",\n \"routeGroup\": \"(dashboard)\",\n \"purpose\": \"Main dashboard with stats\",\n \"hasForm\": false,\n \"formFields\": [],\n \"dataFetching\": \"server\",\n \"actions\": []\n }],\n \"layouts\": [{\n \"name\": \"DashboardLayout\",\n \"path\": \"app/(dashboard)/layout.tsx\",\n \"routeGroup\": \"(dashboard)\",\n \"components\": [\"Sidebar\", \"Header\"],\n \"purpose\": \"Shared layout for authenticated pages\"\n }],\n \"apiRoutes\": [{\n \"path\": \"/api/users\",\n \"methods\": [\"GET\", \"POST\"],\n \"auth\": true,\n \"description\": \"User CRUD endpoints\"\n }],\n \"serverActions\": [{\n \"name\": \"createUser\",\n \"module\": \"users\",\n \"description\": \"Create a new user\",\n \"revalidates\": [\"/dashboard/users\"]\n }],\n \"middleware\": [\"Redirect unauthenticated users to /login\"],\n \"envVars\": [\"DATABASE_URL\", \"NEXTAUTH_SECRET\"],\n \"packages\": [\"next-auth\", \"prisma\", \"@prisma/client\", \"tailwindcss\"]\n}`;\n\nexport function buildDesignNextjsPrompt(requirement: string): string {\n return DESIGN_NEXTJS_PROMPT.replace('{requirement}', requirement);\n}\n","/**\n * validate_nextjs tool - validates JSON against nextjsConfigSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { nextjsConfigSchema } from '../schemas';\n\nexport const validateNextjsTool = createValidationTool(\n 'validate_nextjs',\n nextjsConfigSchema,\n 'Validates a Next.js config JSON string against the NextjsConfig schema. Returns valid: true or valid: false with errors.',\n 'config'\n);\n","/**\n * generate_nextjs tool - generates Next.js config from requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { nextjsConfigSchema, type TNextjsConfig } from '../schemas';\nimport { buildDesignNextjsPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the generate_nextjs tool for Next.js config generation.\n */\nexport function createGenerateNextjsTool(model: Model) {\n return defineTool({\n name: 'generate_nextjs',\n description:\n 'Generate a complete Next.js App Router configuration from frontend design and requirements. Returns pages, layouts, API routes, server actions, and middleware as JSON.',\n input: z.object({\n requirement: z.string().describe('Frontend design, API design, and project requirements'),\n }),\n handler: async ({ requirement }): Promise<TNextjsConfig> => {\n const userPrompt = buildDesignNextjsPrompt(requirement);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a Next.js architect. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, {\n temperature: 0.3,\n maxOutputTokens: 16384,\n });\n return parseModelJsonResponse(response.text, nextjsConfigSchema);\n },\n });\n}\n","/**\n * nextjs-builder tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateNextjsTool } from './validate-nextjs';\nimport { createGenerateNextjsTool } from './generate-nextjs';\n\nexport { validateNextjsTool } from './validate-nextjs';\nexport { createGenerateNextjsTool } from './generate-nextjs';\n\n/**\n * Create all nextjs-builder tools. Pass the model for AI-backed tools.\n */\nexport function createNextjsBuilderTools(model: Model) {\n return createToolSet({\n validate_nextjs: validateNextjsTool,\n generate_nextjs: createGenerateNextjsTool(model),\n });\n}\n","/**\n * route-planner subagent - plans Next.js App Router file structure\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ROUTE_PLANNER_SYSTEM_PROMPT = `You are a Next.js App Router specialist. Given page specs, you plan the file structure.\n\n## Route Groups\n- (auth) for public auth pages: login, signup, forgot-password\n- (dashboard) or (app) for protected pages\n- (marketing) for public landing pages\n\n## File Structure Per Route\n- page.tsx: the page component (Server Component by default)\n- layout.tsx: shared layout for the route group\n- loading.tsx: Suspense fallback\n- error.tsx: error boundary (must be Client Component)\n- not-found.tsx: 404 page\n\n## Data Fetching\n- Server Components: fetch data directly in the component (async function)\n- Client Components: use SWR or React Query for client-side fetching\n- Server Actions: for form submissions and mutations\n\n## Conventions\n- Use lowercase kebab-case for route segments\n- Dynamic segments: [id], [slug]\n- Catch-all: [...slug]\n- Parallel routes: @modal, @sidebar\n- Intercepting routes: (.)photo, (..)details\n\nRespond with the full file tree and route structure. Do NOT return JSON.`;\n\nexport const routePlannerSubagent = defineSubagent({\n name: 'route-planner',\n description:\n 'Plans Next.js App Router file structure with route groups, layouts, and page files. Use before generating the Next.js config.',\n systemPrompt: ROUTE_PLANNER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * api-route-generator subagent - generates Next.js API routes and server actions\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst API_ROUTE_GENERATOR_SYSTEM_PROMPT = `You are a Next.js API specialist. Given an API design, you plan route handlers and server actions.\n\n## API Route Handlers (app/api/)\nFor external integrations, webhooks, and file uploads:\n- One route.ts file per resource: app/api/[resource]/route.ts\n- Export named functions: GET, POST, PUT, DELETE\n- Use NextRequest and NextResponse\n- Add auth checks using next-auth getServerSession\n\n## Server Actions (preferred for mutations)\nFor form submissions and data writes:\n- Define in separate files: app/actions/[module].ts\n- Use 'use server' directive\n- Use revalidatePath or revalidateTag after mutations\n- Return typed results with error handling\n\n## When to Use Which\n- Server Actions: form submissions, data CRUD, anything triggered by user action\n- API Routes: webhooks from external services, file uploads, OAuth callbacks, public APIs\n\n## Auth Integration\n- API Routes: check session with getServerSession\n- Server Actions: check session at the start of each action\n- Middleware: protect route groups with matcher patterns\n\nRespond with structured analysis per module. Do NOT return JSON.`;\n\nexport const apiRouteGeneratorSubagent = defineSubagent({\n name: 'api-route-generator',\n description:\n 'Generates Next.js API route handlers and server actions from API design. Use after route planning.',\n systemPrompt: API_ROUTE_GENERATOR_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * runNextjsBuilderAgent - orchestrator for Next.js project generation\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { NEXTJS_BUILDER_SYSTEM_PROMPT } from './prompts';\nimport { createNextjsBuilderTools } from './tools';\nimport { routePlannerSubagent, apiRouteGeneratorSubagent } from './subagents';\nimport type { NextjsBuilderAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${NEXTJS_BUILDER_SYSTEM_PROMPT}\n\nYou are the Next.js builder orchestrator. When the user provides requirements:\n\n1. **Plan routes**: Use subagent_route-planner to design the App Router file structure with route groups and layouts.\n2. **Generate API routes**: Use subagent_api-route-generator to design API route handlers and server actions.\n3. **Generate config**: Use generate_nextjs to produce the complete Next.js configuration as JSON.\n4. **Validate**: Use validate_nextjs to check the config JSON before returning.\n\nRespond with the final Next.js config as JSON.`;\n\n/**\n * Run the nextjs-builder orchestrator agent.\n */\nexport async function runNextjsBuilderAgent(\n config: NextjsBuilderAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createNextjsBuilderTools(model);\n const subagentTools = createSubagentToolSet([routePlannerSubagent, apiRouteGeneratorSubagent], {\n parentModel: model,\n });\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Zod schemas for ExecutionPlan\n */\n\nimport { z } from 'zod';\n\nexport const phaseStepSchema = z.object({\n order: z.number(),\n action: z.string(),\n details: z.string(),\n});\n\nexport const implementationPhaseSchema = z.object({\n name: z.string(),\n description: z.string(),\n steps: z.array(phaseStepSchema),\n});\n\nexport const edgeCaseSchema = z.object({\n area: z.string(),\n scenario: z.string(),\n handling: z.string(),\n severity: z\n .string()\n .transform(s => s.toLowerCase().trim())\n .pipe(z.enum(['critical', 'warning', 'info'])),\n});\n\nexport const testChecklistItemSchema = z.object({\n flow: z.string(),\n item: z.string(),\n expectedResult: z.string(),\n});\n\nexport const executionPlanSchema = z.object({\n phases: z.array(implementationPhaseSchema).default([]),\n currentState: z.string().default(''),\n desiredEndState: z.string().default(''),\n edgeCases: z.array(edgeCaseSchema).default([]),\n securityNotes: z.array(z.string()).default([]),\n performanceNotes: z.array(z.string()).default([]),\n testingChecklist: z.array(testChecklistItemSchema).default([]),\n});\n\nexport type TExecutionPlan = z.infer<typeof executionPlanSchema>;\n","/**\n * System prompt for execution-planner orchestrator\n */\n\nexport const EXECUTION_PLANNER_SYSTEM_PROMPT = `You are a senior tech lead specializing in implementation strategy and project execution planning.\n\nYou create enterprise-quality execution plans with:\n- Phased implementation order with concrete, numbered steps per phase\n- Current state analysis and desired end state definition\n- Edge cases per domain area with handling strategies and severity levels\n- Security considerations (passwords, tokens, CORS, input validation)\n- Performance considerations (indexing, caching, lazy loading, N+1 prevention)\n- Manual testing checklists grouped by feature flow\n\nOutput only valid JSON unless instructed otherwise.`;\n","/**\n * Design prompts for execution-planner\n */\n\nexport const CREATE_EXECUTION_PLAN_PROMPT = `## Full Plan Context:\n{context}\n\nCreate a comprehensive execution plan. Include:\n\n1. **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\").\n2. **currentState**: What the project starts with (e.g. \"vanilla Next.js, no DB, no auth\").\n3. **desiredEndState**: What must work when done (user capabilities + technical verification).\n4. **edgeCases**: Edge cases per area with scenario, handling strategy, and severity (critical/warning/info).\n5. **securityNotes**: Security considerations (password hashing, JWT config, rate limiting, etc.).\n6. **performanceNotes**: Performance considerations (indexing, caching, lazy loading, etc.).\n7. **testingChecklist**: Manual testing items per flow with expected results.\n\nReturn ONLY valid JSON:\n{\n \"phases\": [{ \"name\": \"Phase 1: Foundation\", \"description\": \"...\", \"steps\": [{ \"order\": 1, \"action\": \"Install dependencies\", \"details\": \"npm install mongoose bcryptjs jsonwebtoken\" }] }],\n \"currentState\": \"...\",\n \"desiredEndState\": \"...\",\n \"edgeCases\": [{ \"area\": \"Authentication\", \"scenario\": \"Email already exists\", \"handling\": \"Return 400 with clear message\", \"severity\": \"critical\" }],\n \"securityNotes\": [\"...\"],\n \"performanceNotes\": [\"...\"],\n \"testingChecklist\": [{ \"flow\": \"Auth Flow\", \"item\": \"Sign up with valid credentials\", \"expectedResult\": \"Account created, redirected to dashboard\" }]\n}`;\n\nexport function buildCreateExecutionPlanPrompt(context: string): string {\n return CREATE_EXECUTION_PLAN_PROMPT.replace('{context}', context);\n}\n","/**\n * validate_execution_plan tool - validates JSON against executionPlanSchema (no AI)\n */\n\nimport { createValidationTool } from '../../../lib/tools';\nimport { executionPlanSchema } from '../schemas';\n\nexport const validateExecutionPlanTool = createValidationTool(\n 'validate_execution_plan',\n executionPlanSchema,\n 'Validates an execution plan JSON string against the ExecutionPlan schema. Returns valid: true or valid: false with errors.',\n 'plan'\n);\n","/**\n * create_execution_plan tool - generates execution plan from context (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { executionPlanSchema, type TExecutionPlan } from '../schemas';\nimport { buildCreateExecutionPlanPrompt } from '../prompts';\nimport { parseModelJsonResponse } from '../../../lib/utils';\n\n/**\n * Creates the create_execution_plan tool for generating phased plans.\n */\nexport function createExecutionPlanTool(model: Model) {\n return defineTool({\n name: 'create_execution_plan',\n description:\n 'Generate a comprehensive execution plan with phases, edge cases, and testing checklist from the full plan context.',\n input: z.object({\n context: z.string().describe('Full plan context: all sections generated so far'),\n }),\n handler: async ({ context }): Promise<TExecutionPlan> => {\n const userPrompt = buildCreateExecutionPlanPrompt(context);\n const messages = [\n {\n role: 'system' as const,\n content: 'You are a tech lead. Return only valid JSON.',\n },\n { role: 'user' as const, content: userPrompt },\n ];\n const response = await model.invoke(messages, { temperature: 0.3, maxOutputTokens: 16384 });\n return parseModelJsonResponse(response.text, executionPlanSchema);\n },\n });\n}\n","/**\n * execution-planner tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateExecutionPlanTool } from './validate-plan';\nimport { createExecutionPlanTool } from './create-plan';\n\nexport { validateExecutionPlanTool } from './validate-plan';\nexport { createExecutionPlanTool } from './create-plan';\n\n/**\n * Create all execution-planner tools. Pass the model for AI-backed tools.\n */\nexport function createExecutionPlannerTools(model: Model) {\n return createToolSet({\n validate_execution_plan: validateExecutionPlanTool,\n create_execution_plan: createExecutionPlanTool(model),\n });\n}\n","/**\n * runExecutionPlannerAgent - orchestrator for execution plan design\n */\n\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { createSubagentToolSet } from '../../lib/subagents';\nimport { EXECUTION_PLANNER_SYSTEM_PROMPT } from './prompts';\nimport { createExecutionPlannerTools } from './tools';\nimport { edgeCaseAnalyzerSubagent, testingStrategistSubagent } from './subagents';\nimport type { ExecutionPlannerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${EXECUTION_PLANNER_SYSTEM_PROMPT}\n\nYou are the execution planning orchestrator. When the user provides plan sections:\n\n1. **Analyze edge cases**: Use subagent_edge-case-analyzer to identify edge cases per domain area with handling strategies.\n2. **Design testing**: Use subagent_testing-strategist to design manual testing checklists grouped by feature flow.\n3. **Generate plan**: Use create_execution_plan to produce the complete execution plan with phases, edge cases, and testing checklist.\n4. **Validate**: Use validate_execution_plan to check the final plan JSON before returning.\n\nRespond with the final execution plan as JSON.`;\n\n/**\n * Run the execution-planner orchestrator agent with all tools and subagents.\n */\nexport async function runExecutionPlannerAgent(\n config: ExecutionPlannerAgentConfig\n): Promise<AgentResult> {\n const { input, model: modelConfig, maxIterations = 15, onStep, logger } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n const tools = createExecutionPlannerTools(model);\n const subagentTools = createSubagentToolSet(\n [edgeCaseAnalyzerSubagent, testingStrategistSubagent],\n { parentModel: model }\n );\n const allTools = createToolSet({ ...tools, ...subagentTools });\n\n return runAgent({\n model,\n tools: allTools,\n systemPrompt: ORCHESTRATOR_SYSTEM_PROMPT,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Hello World tool\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../lib/tools';\n\nexport const helloWorldTool = defineTool({\n name: 'hello_world',\n description: 'Returns a greeting message for the given name',\n input: z.object({\n name: z.string().describe('Name to greet'),\n }),\n handler: async ({ name }) => {\n return { greeting: `Hello, ${name}! Welcome to sweagent.` };\n },\n});\n","/**\n * Hello World agent - runs an agent with the hello world tool\n */\n\nimport type { AgentResult, AgentStep } from '../../lib/types/agent';\nimport type { Logger } from '../../lib/types/common';\nimport type { ModelConfig } from '../../lib/types/model';\nimport { runAgent } from '../../lib/agents';\nimport { createModel } from '../../lib/models/create-model';\nimport { createToolSet } from '../../lib/tools';\nimport { helloWorldTool } from './tool';\n\nexport interface HelloWorldAgentConfig {\n /** User input (e.g. \"Say hello to Alice\") */\n input: string;\n /** Model config; defaults to OpenAI gpt-4o-mini */\n model?: ModelConfig;\n /** System prompt override */\n systemPrompt?: string;\n /** Max iterations; default 3 */\n maxIterations?: number;\n /** Callback for each step */\n onStep?: (step: AgentStep) => void;\n /** Optional logger for execution logs */\n logger?: Logger;\n}\n\nconst DEFAULT_SYSTEM_PROMPT =\n 'You are a friendly greeter. Use the hello_world tool to greet users.';\n\nexport async function runHelloWorldAgent(config: HelloWorldAgentConfig): Promise<AgentResult> {\n const {\n input,\n model: modelConfig,\n systemPrompt = DEFAULT_SYSTEM_PROMPT,\n maxIterations = 3,\n onStep,\n logger,\n } = config;\n\n const model = createModel(modelConfig ?? { provider: 'openai', model: 'gpt-4o-mini' });\n\n return runAgent({\n model,\n tools: createToolSet({ hello_world: helloWorldTool }),\n systemPrompt,\n input,\n maxIterations,\n onStep,\n logger,\n });\n}\n","/**\n * Pipeline step definitions - each step composes its input from prior outputs\n * and calls the corresponding domain agent.\n */\n\nimport { runRequirementGathererAgent } from '../requirement-gatherer';\nimport { runDataModelerAgent } from '../data-modeler';\nimport { runApiDesignerAgent } from '../api-designer';\nimport { runAuthDesignerAgent } from '../auth-designer';\nimport { runBackendArchitectAgent } from '../backend-architect';\nimport { runFrontendArchitectAgent } from '../frontend-architect';\nimport { runExecutionPlannerAgent } from '../execution-planner';\nimport type { StepRunConfig } from './types';\n\n/** A single pipeline step with its input composition logic. */\nexport interface PipelineStep {\n /** Human-readable step name (e.g. \"Requirement Gatherer\"). */\n name: string;\n /** Key used to store the output in the accumulated results map. */\n key: string;\n /** Section heading used in the combined output document. */\n heading: string;\n /** Run the step: compose input from prior outputs and call the agent. */\n run: (outputs: Record<string, string>, cfg: StepRunConfig) => Promise<string>;\n}\n\nfunction agentCfg(input: string, cfg: StepRunConfig) {\n return {\n input,\n model: cfg.model,\n maxIterations: cfg.maxIterations,\n onStep: cfg.onStep,\n logger: cfg.logger,\n };\n}\n\n/** Ordered list of all pipeline steps. */\nexport const PIPELINE_STEPS: PipelineStep[] = [\n {\n name: 'Requirement Gatherer',\n key: 'requirements',\n heading: 'Requirements',\n run: (out, cfg) =>\n runRequirementGathererAgent(agentCfg(out.userInput ?? '', cfg)).then(r => r.output),\n },\n {\n name: 'Data Modeler',\n key: 'dataModel',\n heading: 'Data Model',\n run: (out, cfg) =>\n runDataModelerAgent(\n agentCfg(`Design a data model based on these requirements:\\n${out.requirements}`, cfg)\n ).then(r => r.output),\n },\n {\n name: 'API Designer',\n key: 'apiDesign',\n heading: 'API Design',\n run: (out, cfg) =>\n runApiDesignerAgent(\n agentCfg(\n `Design the API based on this data model and requirements:\\n` +\n `Data Model:\\n${out.dataModel}\\n\\nRequirements:\\n${out.requirements}`,\n cfg\n )\n ).then(r => r.output),\n },\n {\n name: 'Auth Designer',\n key: 'authDesign',\n heading: 'Auth Design',\n run: (out, cfg) =>\n runAuthDesignerAgent(\n agentCfg(\n `Design auth for this project:\\n` +\n `Requirements:\\n${out.requirements}\\n\\nAPI Design:\\n${out.apiDesign}`,\n cfg\n )\n ).then(r => r.output),\n },\n {\n name: 'Backend Architect',\n key: 'backendDesign',\n heading: 'Backend Architecture',\n run: (out, cfg) =>\n runBackendArchitectAgent(\n agentCfg(\n `Design backend architecture:\\n` +\n `Data Model:\\n${out.dataModel}\\n\\n` +\n `API Design:\\n${out.apiDesign}\\n\\n` +\n `Auth Design:\\n${out.authDesign}`,\n cfg\n )\n ).then(r => r.output),\n },\n {\n name: 'Frontend Architect',\n key: 'frontendDesign',\n heading: 'Frontend Architecture',\n run: (out, cfg) =>\n runFrontendArchitectAgent(\n agentCfg(\n `Design frontend architecture:\\n` +\n `API Design:\\n${out.apiDesign}\\n\\nRequirements:\\n${out.requirements}`,\n cfg\n )\n ).then(r => r.output),\n },\n {\n name: 'Execution Planner',\n key: 'executionPlan',\n heading: 'Execution Plan',\n run: (out, cfg) =>\n runExecutionPlannerAgent(\n agentCfg(\n `Create an execution plan for this project:\\n` +\n `Requirements:\\n${out.requirements}\\n\\n` +\n `Data Model:\\n${out.dataModel}\\n\\n` +\n `API Design:\\n${out.apiDesign}\\n\\n` +\n `Auth Design:\\n${out.authDesign}\\n\\n` +\n `Backend Design:\\n${out.backendDesign}\\n\\n` +\n `Frontend Design:\\n${out.frontendDesign}`,\n cfg\n )\n ).then(r => r.output),\n },\n];\n","/**\n * runFullPipelineAgent - orchestrates the full 7-agent pipeline end-to-end.\n *\n * Runs: Requirements -> Data Model -> API -> Auth -> Backend -> Frontend -> Execution Plan.\n * Each agent's output feeds as context into the next.\n */\n\nimport type { AgentResult } from '../../lib/types/agent';\nimport type { FullPipelineConfig, PipelineStepResult, StepRunConfig } from './types';\nimport { PIPELINE_STEPS } from './steps';\n\nconst log = (msg: string): void => {\n process.stderr.write(`[full-pipeline] ${msg}\\n`);\n};\n\nfunction assembleOutput(results: PipelineStepResult[]): string {\n const sections = results\n .map(r => {\n const step = PIPELINE_STEPS.find(s => s.key === r.key);\n const heading = step?.heading ?? r.name;\n return `## ${heading}\\n\\n${r.output}`;\n })\n .join('\\n\\n---\\n\\n');\n\n return `# Full Application Specification\\n\\n${sections}`;\n}\n\n/**\n * Run the full pipeline: 7 domain agents chained sequentially.\n * Returns a combined specification document.\n */\nexport async function runFullPipelineAgent(config: FullPipelineConfig): Promise<AgentResult> {\n const { input, model, maxIterations = 15, onStep, logger } = config;\n\n const stepCfg: StepRunConfig = { model, maxIterations, onStep, logger };\n const outputs: Record<string, string> = { userInput: input };\n const results: PipelineStepResult[] = [];\n const total = PIPELINE_STEPS.length;\n\n for (const [i, step] of PIPELINE_STEPS.entries()) {\n log(`[${i + 1}/${total}] ${step.name}...`);\n\n const stepOutput = await step.run(outputs, stepCfg);\n outputs[step.key] = stepOutput;\n results.push({ name: step.name, key: step.key, output: stepOutput });\n\n log(`[${i + 1}/${total}] ${step.name} — done`);\n }\n\n log('Pipeline complete');\n\n return {\n output: assembleOutput(results),\n steps: [],\n messages: [],\n };\n}\n","/**\n * MCP server tool registry - maps every sweagent module to an MCP tool entry.\n */\n\nimport type { AgentStep } from '../../types/agent';\nimport type { ModelConfig } from '../../types/model';\nimport type { AgentToolEntry } from './types';\n\nimport { runPlanningAgent } from '../../../modules/planning';\nimport { runRequirementGathererAgent } from '../../../modules/requirement-gatherer';\nimport { runDataModelerAgent } from '../../../modules/data-modeler';\nimport { runApiDesignerAgent } from '../../../modules/api-designer';\nimport { runAuthDesignerAgent } from '../../../modules/auth-designer';\nimport { runBackendArchitectAgent } from '../../../modules/backend-architect';\nimport { runFrontendArchitectAgent } from '../../../modules/frontend-architect';\nimport { runExpressBuilderAgent } from '../../../modules/express-builder';\nimport { runApolloBuilderAgent } from '../../../modules/apollo-builder';\nimport { runReactBuilderAgent } from '../../../modules/react-builder';\nimport { runNextjsBuilderAgent } from '../../../modules/nextjs-builder';\nimport { runExecutionPlannerAgent } from '../../../modules/execution-planner';\nimport { runHelloWorldAgent } from '../../../modules/hello-world';\nimport { runFullPipelineAgent } from '../../../modules/full-pipeline';\n\nfunction entry(\n name: string,\n description: string,\n runner: (cfg: {\n input: string;\n model?: ModelConfig;\n onStep?: (step: AgentStep) => void;\n }) => Promise<{ output: string }>\n): AgentToolEntry {\n return {\n name,\n description,\n handler: (input, model, onStep) =>\n runner({ input, model, onStep }) as ReturnType<AgentToolEntry['handler']>,\n };\n}\n\n/** All registered agent tools, keyed by tool name. */\nexport const TOOL_REGISTRY: AgentToolEntry[] = [\n entry(\n 'create_app',\n 'Run the full pipeline (requirements, data model, API, auth, backend, frontend, execution plan) from a single project description. Returns a combined specification document with all layers. ' +\n 'Input: A natural-language project description. Example: \"Project management SaaS with teams, Kanban boards, time tracking, and billing\". ' +\n 'No prior context needed -- this tool chains all 7 agents automatically, passing each output as context to the next.',\n runFullPipelineAgent\n ),\n entry(\n 'plan',\n 'Generate a full software plan (discovery, requirements, design, synthesis) from a project description. Returns an 11-section markdown blueprint covering tech stack, data models, API routes, auth, implementation order, edge cases, and testing. ' +\n 'Input: A natural-language project description. Example: \"E-commerce site with users, products, cart, checkout, and admin dashboard\". ' +\n 'No prior context needed -- lighter and faster than create_app when you only need a high-level plan.',\n runPlanningAgent\n ),\n entry(\n 'gather_requirements',\n 'Extract structured requirements (actors, flows, stories, modules) from a project description. Returns JSON with actors and permissions, user flows with steps, user stories with acceptance criteria, modules with CRUD operations, and database/API outlines. ' +\n 'Input: A natural-language project description. Example: \"Task manager with teams, Kanban boards, and time tracking\". ' +\n 'No prior context needed -- use this as a standalone first step before calling specialist tools.',\n runRequirementGathererAgent\n ),\n entry(\n 'design_data_model',\n 'Design a database schema (MongoDB or PostgreSQL) with entities, fields, indexes, relationships, and validation rules. ' +\n 'Input: Requirements or a project description that lists the entities and relationships to model. Best results when you include the output from gather_requirements. ' +\n 'Example input: \"Design a data model based on these requirements: {paste requirements JSON here}\".',\n runDataModelerAgent\n ),\n entry(\n 'design_api',\n 'Design REST or GraphQL API contracts with endpoints, methods, request/response schemas, and auth requirements. ' +\n 'Input: A data model and/or requirements describing the resources and operations. Best results when you include both the data model output and the requirements output. ' +\n 'Example input: \"Design the API -- Data Model: {data model JSON} -- Requirements: {requirements JSON}\".',\n runApiDesignerAgent\n ),\n entry(\n 'design_auth',\n 'Design authentication and authorization strategy including providers, roles, permissions, flows, middleware, and security policies. ' +\n 'Input: Project requirements and/or API design describing the users, roles, and protected resources. Best results when you include the requirements and API design outputs. ' +\n 'Example input: \"Design auth -- Requirements: {requirements JSON} -- API Design: {api design JSON}\".',\n runAuthDesignerAgent\n ),\n entry(\n 'architect_backend',\n 'Design backend architecture including framework selection, folder structure, services, middleware, routes, and deployment config. ' +\n 'Input: The data model, API design, and auth design for the project. Best results when you include all three. ' +\n 'Example input: \"Design backend -- Data Model: {data model JSON} -- API Design: {api JSON} -- Auth Design: {auth JSON}\".',\n runBackendArchitectAgent\n ),\n entry(\n 'architect_frontend',\n 'Design frontend architecture including pages, components, routing, state management, and styling approach. ' +\n 'Input: The API design and requirements for the project. Best results when you include both. ' +\n 'Example input: \"Design frontend -- API Design: {api JSON} -- Requirements: {requirements JSON}\".',\n runFrontendArchitectAgent\n ),\n entry(\n 'build_express',\n 'Generate Express.js REST API configuration with routers, models, middleware, and environment variables. ' +\n 'Input: The data model and API design describing the endpoints and schemas to generate. ' +\n 'Example input: \"Generate Express API config -- Data Model: {data model JSON} -- API Design: {api JSON}\".',\n cfg => runExpressBuilderAgent({ ...cfg, disableScaffold: true })\n ),\n entry(\n 'build_apollo',\n 'Generate Apollo GraphQL subgraph configuration with modules, types, resolvers, and datasources (Federation v2). ' +\n 'Input: The data model and API design (GraphQL style) describing the types and operations. ' +\n 'Example input: \"Generate Apollo subgraph config -- Data Model: {data model JSON} -- API Design: {api JSON}\".',\n cfg => runApolloBuilderAgent({ ...cfg, disableScaffold: true })\n ),\n entry(\n 'build_react',\n 'Generate React + Vite application configuration with pages, components, fields, API hooks, and branding from a GraphQL schema. ' +\n 'Input: A GraphQL schema or frontend design describing the types and operations to build UI for. ' +\n 'Example input: \"Generate React config -- Frontend Design: {frontend JSON} -- API Design: {api JSON}\".',\n cfg => runReactBuilderAgent({ ...cfg, disableScaffold: true })\n ),\n entry(\n 'build_nextjs',\n 'Generate Next.js App Router configuration with pages, layouts, API routes, server actions, and middleware. ' +\n 'Input: The frontend design and API design describing the pages and data fetching requirements. ' +\n 'Example input: \"Generate Next.js config -- Frontend Design: {frontend JSON} -- API Design: {api JSON}\".',\n runNextjsBuilderAgent\n ),\n entry(\n 'plan_execution',\n 'Create a phased execution plan with implementation order, edge-case analysis, security/performance notes, and testing strategy. ' +\n 'Input: All prior design outputs (requirements, data model, API, auth, backend, frontend). Best results when you include as much context as possible. ' +\n 'Example input: \"Create execution plan -- Requirements: {requirements} -- Data Model: {data model} -- API: {api} -- Auth: {auth} -- Backend: {backend} -- Frontend: {frontend}\".',\n runExecutionPlannerAgent\n ),\n entry(\n 'hello_world',\n 'Test agent that greets users. Use to verify the MCP server is working. ' +\n 'Input: Any greeting or test message. Example: \"Say hello\".',\n runHelloWorldAgent\n ),\n];\n\n/** Lookup a tool by name. Returns undefined if not found. */\nexport function findTool(name: string): AgentToolEntry | undefined {\n return TOOL_REGISTRY.find(t => t.name === name);\n}\n","/**\n * MCP server types - shared Zod schema for agent tool inputs.\n */\n\nimport { z } from 'zod';\n\nimport type { AgentResult, AgentStep } from '../../types/agent';\nimport type { ModelConfig } from '../../types/model';\n\n/** Raw Zod shape for McpServer.registerTool inputSchema. */\nexport const AGENT_TOOL_INPUT_SHAPE = {\n input: z.string().describe('Natural language description of what to build or design'),\n provider: z\n .enum(['openai', 'anthropic', 'google'])\n .optional()\n .describe('LLM provider (defaults to openai)'),\n model: z.string().optional().describe('Model name, e.g. gpt-4o-mini, claude-3-5-sonnet-20241022'),\n temperature: z.number().min(0).max(1).optional().describe('Sampling temperature (0-1)'),\n} as const;\n\n/** Parsed tool input type. */\nexport interface AgentToolInput {\n input: string;\n provider?: 'openai' | 'anthropic' | 'google';\n model?: string;\n temperature?: number;\n}\n\n/** Build a ModelConfig from the optional overrides in the tool input. */\nexport function buildModelConfig(input: AgentToolInput): ModelConfig | undefined {\n if (!input.provider && !input.model) return undefined;\n return {\n provider: input.provider ?? 'openai',\n model: input.model ?? 'gpt-4o-mini',\n temperature: input.temperature,\n };\n}\n\n/** A registered agent tool entry. */\nexport interface AgentToolEntry {\n name: string;\n description: string;\n handler: (\n input: string,\n model?: ModelConfig,\n onStep?: (step: AgentStep) => void\n ) => Promise<AgentResult>;\n}\n","/**\n * MCP server - exposes all sweagent agent modules as MCP tools via McpServer.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\nimport type { AgentStep } from '../../types/agent';\nimport { TOOL_REGISTRY } from './tool-registry';\nimport { AGENT_TOOL_INPUT_SHAPE, buildModelConfig } from './types';\nimport type { AgentToolInput } from './types';\n\nconst SERVER_NAME = 'sweagent';\nconst SERVER_VERSION = '0.0.3';\n\nconst log = (msg: string): void => {\n process.stderr.write(`[sweagent] ${msg}\\n`);\n};\n\nconst MAX_PREVIEW = 200;\n\nfunction createStepLogger(toolName: string): (step: AgentStep) => void {\n return (step: AgentStep) => {\n const prefix = `${toolName} — step ${step.iteration + 1}`;\n if (step.content) {\n const preview =\n step.content.length > MAX_PREVIEW ? step.content.slice(0, MAX_PREVIEW) + '…' : step.content;\n log(`${prefix}: ${preview}`);\n } else {\n const tools = step.toolCalls?.map(tc => tc.toolName).join(', ');\n log(`${prefix}${tools ? ` (tools: ${tools})` : ''}`);\n }\n };\n}\n\n/** Create and return a configured McpServer with all agent tools registered. */\nexport function createSweagentServer(): McpServer {\n const server = new McpServer(\n { name: SERVER_NAME, version: SERVER_VERSION },\n { capabilities: { tools: {} } }\n );\n\n for (const entry of TOOL_REGISTRY) {\n server.registerTool(\n entry.name,\n { description: entry.description, inputSchema: AGENT_TOOL_INPUT_SHAPE },\n async (args: AgentToolInput) => {\n log(`${entry.name} — started`);\n try {\n const modelConfig = buildModelConfig(args);\n const onStep = createStepLogger(entry.name);\n const result = await entry.handler(args.input, modelConfig, onStep);\n log(`${entry.name} — completed`);\n return { content: [{ type: 'text' as const, text: result.output }] };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n log(`${entry.name} — error: ${message}`);\n return { content: [{ type: 'text' as const, text: message }], isError: true };\n }\n }\n );\n }\n\n return server;\n}\n"]}