sweagent 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +755 -0
- package/dist/index.cjs +487 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1816 -0
- package/dist/index.d.ts +1816 -0
- package/dist/index.js +487 -0
- package/dist/index.js.map +1 -0
- package/package.json +107 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/utils/errors.ts","../src/lib/utils/logger.ts","../src/lib/utils/utils.ts","../src/lib/tools/tools.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/mcp/transports.ts","../src/lib/mcp/client.ts","../src/modules/hello-world/tool.ts","../src/modules/hello-world/agent.ts","../src/modules/db-designer/schemas/field.schema.ts","../src/modules/db-designer/schemas/module.schema.ts","../src/modules/db-designer/schemas/project.schema.ts","../src/modules/db-designer/prompts/system.prompt.ts","../src/modules/db-designer/prompts/design.prompt.ts","../src/modules/db-designer/prompts/redesign.prompt.ts","../src/modules/db-designer/tools/validate-schema.tool.ts","../src/modules/db-designer/tools/design-database.tool.ts","../src/modules/db-designer/tools/design-database-pro.tool.ts","../src/modules/db-designer/tools/redesign-database.tool.ts","../src/modules/db-designer/tools/index.ts","../src/modules/db-designer/subagents/entity-analyzer.subagent.ts","../src/modules/db-designer/subagents/schema-refiner.subagent.ts","../src/modules/db-designer/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/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"],"names":["LibraryError","message","cause","ModelError","provider","ToolError","toolName","ValidationError","errors","AgentError","iteration","SubagentError","subagentName","LOG_LEVELS","createLogger","config","prefix","level","timestamps","minLevel","formatMessage","logLevel","parts","shouldLog","data","error","emptyDetails","emptyOutputDetails","sumTokenUsage","usages","inputTokens","outputTokens","totalTokens","usage","defineTool","name","description","inputSchema","handler","tool","args","parsed","e","createToolSet","tools","getTools","toolSet","getTool","executeTool","toolImpl","input","options","executeToolByName","runAgent","model","systemPrompt","maxIterations","onStep","messages","steps","response","step","s","assistantContent","tc","toolResults","toolCall","execResult","agentResult","outputVal","createAIModel","params","modelName","getModel","schemaOnlyTools","t","_execute","rest","result","generateText","toolCalls","err","prompt","images","content","img","createOpenAIModel","apiKey","baseUrl","createOpenAI","createAnthropicModel","createAnthropic","createGoogleModel","createGoogleGenerativeAI","createModel","NAME_REGEX","defineSubagent","resolveTools","definition","parentTools","base","disallowed","filtered","key","runSubagent","parentModel","createSubagentTool","z","createSubagentToolSet","definitions","out","def","getSdkRoot","entry","createRequire","path","sdkRoot","parseToolResult","first","text","createHttpTransport","url","headers","modPath","mod","pathToFileURL","requestInit","createStdioTransport","command","BaseMcpClient","info","resolveOpts","envPrefix","serverLabel","apiKeyHeader","argsEnv","a","client","Client","helloWorldTool","DEFAULT_SYSTEM_PROMPT","runHelloWorldAgent","modelConfig","fieldSchema","moduleSchema","projectSchema","DB_DESIGN_SYSTEM_PROMPT","createDbDesignPrompt","requirement","formatUserTypes","actors","actor","index","goals","g","formatUserFlows","flows","flow","actorName","formatUserStories","stories","storiesByFlow","story","flowStories","sections","preconditions","p","postconditions","dataInvolved","d","storyText","orphanStories","f","formatTechnicalRequirements","tech","lines","extractDataEntities","entities","extractRoles","buildPromptVariables","createProDbDesignPrompt","vars","createRedesignPrompt","existingSchema","userFeedback","validateSchemaTool","schema","extractJson","trimmed","codeBlock","createDesignDatabaseTool","userPrompt","raw","jsonStr","structuredInputSchema","createDesignDatabaseProTool","dbDesign","metadata","createRedesignDatabaseTool","feedback","createDbDesignerTools","ENTITY_ANALYZER_SYSTEM_PROMPT","entityAnalyzerSubagent","SCHEMA_REFINER_SYSTEM_PROMPT","createSchemaRefinerSubagent","ORCHESTRATOR_SYSTEM_PROMPT","runDbDesignerAgent","dbTools","schemaRefiner","subagentTools","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","schemaFile","validateFrontendConfigTool","buildGeneratePrompt","graphqlSchema","appInfo","instruction","example","appInfoBlock","createGenerateFrontendTool","createGenerateFeatureBreakdownTool","createReactBuilderTools","GRAPHQL_ANALYZER_SYSTEM_PROMPT","graphqlAnalyzerSubagent","CONFIG_VALIDATOR_SYSTEM_PROMPT","createConfigValidatorSubagent","runReactBuilderAgent","reactTools","configValidator"],"mappings":"oXAOO,IAAMA,CAAAA,CAAN,cAA2B,KAAM,CACtC,WAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAAe,CAC1C,KAAA,CAAMD,CA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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 * Simple logger with optional prefix and progress support\n */\n\nimport type { Logger } from '../types/common';\n\n/**\n * Log levels\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Logger configuration\n */\nexport interface LoggerConfig {\n /** Prefix for all log messages */\n prefix?: string;\n /** Minimum log level to output */\n level?: LogLevel;\n /** Whether to output timestamps */\n timestamps?: boolean;\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Create a logger with the given configuration\n */\nexport function createLogger(config: LoggerConfig = {}): Logger {\n const { prefix = '', level = 'info', timestamps = false } = config;\n const minLevel = LOG_LEVELS[level];\n\n function formatMessage(logLevel: LogLevel, message: string): string {\n const parts: string[] = [];\n if (timestamps) {\n parts.push(`[${new Date().toISOString()}]`);\n }\n parts.push(`[${logLevel.toUpperCase()}]`);\n if (prefix) {\n parts.push(`[${prefix}]`);\n }\n parts.push(message);\n return parts.join(' ');\n }\n\n function shouldLog(logLevel: LogLevel): boolean {\n return LOG_LEVELS[logLevel] >= minLevel;\n }\n\n return {\n debug(message: string, data?: Record<string, unknown>): void {\n if (shouldLog('debug')) {\n console.debug(formatMessage('debug', message), data ?? '');\n }\n },\n\n info(message: string, data?: Record<string, unknown>): void {\n if (shouldLog('info')) {\n console.info(formatMessage('info', message), data ?? '');\n }\n },\n\n warn(message: string, data?: Record<string, unknown>): void {\n if (shouldLog('warn')) {\n console.warn(formatMessage('warn', message), data ?? '');\n }\n },\n\n error(message: string, error?: Error | Record<string, unknown>): void {\n if (shouldLog('error')) {\n console.error(formatMessage('error', message), error ?? '');\n }\n },\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 { 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 async function executeTool<TInput, TOutput>(\n toolImpl: Tool<TInput, TOutput>,\n input: TInput,\n options?: { toolCallId?: string; abortSignal?: AbortSignal }\n): Promise<ToolExecutionResult<TOutput>> {\n if (!toolImpl.execute) return { success: false, error: 'Tool has no execute function' };\n try {\n const out = await toolImpl.execute(input, {\n toolCallId: options?.toolCallId ?? '',\n messages: [],\n abortSignal: options?.abortSignal,\n } as ToolExecutionOptions);\n return { success: true, output: out as TOutput };\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return { success: false, error: msg };\n }\n}\n\nexport async function executeToolByName(\n tools: ToolSet,\n name: string,\n input: unknown,\n options?: { toolCallId?: string; abortSignal?: AbortSignal }\n): Promise<ToolExecutionResult> {\n const toolImpl = tools[name];\n if (!toolImpl) throw new ToolError(`Tool not found: ${name}`);\n return executeTool(toolImpl, input, options);\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 * 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';\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 { model, tools, systemPrompt, input, maxIterations = 10, onStep } = config;\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 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 steps.push(step);\n onStep?.(step);\n return {\n output: response.text,\n steps,\n totalUsage: sumTokenUsage(steps.map(s => s.usage)),\n messages,\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 });\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\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 }\n\n throw new AgentError(\n `Agent reached maximum iterations (${maxIterations}) without completing`,\n maxIterations - 1\n );\n}\n","/**\n * Shared AI SDK adapter - pass-through to generateText (no conversions)\n */\n\nimport { generateText } from 'ai';\nimport type { LanguageModelV3 } from '@ai-sdk/provider';\nimport type {\n Model,\n ModelResponse,\n InvokeOptions,\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}\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 * 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 * 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 { 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}\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 } = 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 });\n}\n","/**\n * Field-level schema for MongoDB collection fields\n */\n\nimport { z } from 'zod';\n\nexport const fieldSchema = z.object({\n fieldName: z.string().describe('fieldName must be in camelCase'),\n fieldType: z.enum([\n 'string',\n 'number',\n 'boolean',\n 'Types.ObjectId',\n 'Date',\n 'object',\n 'email',\n 'password',\n 'enum',\n ]),\n isArray: z.boolean(),\n isRequired: z.boolean(),\n isUnique: z.boolean(),\n values: z.array(z.string()).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.enum(['one-to-one', 'many-to-one', '']).optional(),\n isPrivate: z.boolean().describe('True if password field, else false'),\n});\n\nexport type TFieldSchema = z.infer<typeof fieldSchema>;\n","/**\n * Module (collection) level schema for MongoDB\n */\n\nimport { z } from 'zod';\nimport { fieldSchema } from './field.schema';\n\nexport const moduleSchema = z.object({\n moduleName: z.string().describe('camelCase, single word, never auth/authentication'),\n isUserModule: z.boolean(),\n authMethod: z.enum(['EMAIL_AND_PASSWORD', 'PHONE_AND_OTP', '']).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.array(fieldSchema),\n});\n\nexport type TModuleSchema = z.infer<typeof moduleSchema>;\n","/**\n * Root project schema for MongoDB database design\n */\n\nimport { z } from 'zod';\nimport { moduleSchema } from './module.schema';\n\nexport const projectSchema = z.object({\n projectName: z.string().describe('projectName must be in kebab-case'),\n projectDescription: z.string(),\n modules: z.array(moduleSchema),\n author: z.string().default('sijeeshmiziha'),\n});\n\nexport type TBackendProjectSchema = z.infer<typeof projectSchema>;\n","/**\n * System prompt for database design - 5-phase analysis framework\n */\n\nexport const DB_DESIGN_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\n - Pattern: \"User Profile\" → user collection with profile fields\n - Pattern: \"Order Items\" → order collection + item collection with relationship\n - Pattern: \"Product Inventory\" → product collection with inventory fields\n\n2. **From User Types (Actors)**: Each actor type may indicate a User variant or role\n - Pattern: \"Admin\", \"Customer\", \"Vendor\" → User collection with role enum\n - Pattern: \"Guest\" → May not need persistence, or limited session data\n\n3. **From User Flow Actions**: Action verbs reveal implicit entities\n - \"creates order\" → Order collection\n - \"submits payment\" → Payment collection\n - \"uploads document\" → Document collection\n - \"sends message\" → Message collection\n\n4. **From Flow States**: Transitions reveal status enums\n - Flow: pending → approved → completed → Order.status enum\n - Flow: draft → published → archived → Content.status enum\n\n### PHASE 2: Relationship Mapping\nFor each entity pair, determine relationships based on:\n\n1. **Ownership Patterns** (from actor actions):\n - \"Customer places Order\" → Order.customer (many-to-one to User)\n - \"Admin approves Request\" → Request.approvedBy (many-to-one to User)\n - \"User creates Post\" → Post.author (many-to-one to User)\n\n2. **Cardinality from Flow Context**:\n - \"User has one profile\" → one-to-one\n - \"User places multiple orders\" → many-to-one (Order → User)\n - \"Order contains items\" → many-to-one (OrderItem → Order)\n\n3. **Shared Entities** (referenced across flows):\n - Entity referenced by multiple actors → likely needs relationships to User\n - Entity in multiple flows → likely a core/central entity\n\n4. **Bidirectional References** (for one-to-one):\n - Include reference field in BOTH collections for one-to-one relationships\n\n### PHASE 3: Permission Derivation\nMap actors to RBAC permissions:\n\n1. **Role Extraction**: Each actor type becomes a role value\n - actors: [Admin, Customer, Vendor] → role enum: ['admin', 'customer', 'vendor']\n\n2. **Permission Mining from User Stories**:\n - \"As Admin, I can delete users\" → admin: ['CREATE', 'READ', 'UPDATE', 'DELETE'] on user\n - \"As Customer, I can view my orders\" → customer: ['READ'] on order (own records)\n - \"As Vendor, I can update products\" → vendor: ['CREATE', 'READ', 'UPDATE'] on product\n\n3. **Data Visibility Rules**:\n - \"view own\" → READ permission with ownership filter\n - \"view all\" → READ permission without filter\n - \"manage\" → full CRUD permissions\n\n### PHASE 4: Query Pattern Inference\nAnalyze flows to predict database access patterns:\n\n1. **Read Patterns** (suggest indexes):\n - \"list orders by date\" → index on order.createdAt\n - \"search products by category\" → index on product.category\n - \"find user by email\" → unique index on user.email\n - \"filter by status\" → index on status field\n\n2. **Write Patterns** (affect schema design):\n - High-frequency writes → consider denormalization\n - Audit requirements → add createdBy, updatedBy fields\n\n3. **Aggregation Needs** (from reporting flows):\n - \"view sales dashboard\" → may need summary collections\n - \"generate reports\" → ensure proper indexing for date ranges\n\n### PHASE 5: Schema Construction\nSynthesize all analyses into the final schema:\n\n1. **Module Definition**:\n - One module per core entity\n - camelCase module names (never 'auth' or 'authentication')\n - Mark user modules with isUserModule: true\n\n2. **Field Completeness**:\n - All fields from dataInvolved\n - Relationship fields (Types.ObjectId with relationTo)\n - Status/lifecycle fields (enum type with values from flow states)\n - Audit fields: createdAt, updatedAt (Date, required)\n - createdBy, updatedBy when flows mention \"who did what\"\n\n3. **Validation Constraints**:\n - isRequired: true for fields mentioned in preconditions\n - isUnique: true for identifier fields (email, slug, code)\n - enum values from flow states and categorical data\n\n4. **Security Fields**:\n - password fields: fieldType: 'password', isPrivate: true\n - email fields: fieldType: 'email', isUnique: true\n\n## CORE CONSTRAINTS (MUST FOLLOW)\n\n1. **Primary Key**: _id with Types.ObjectId (auto-generated, do not include in fields)\n\n2. **Relationships**:\n - One-to-One: Reference field in BOTH collections\n - Many-to-One: Reference in the \"many\" side only\n - Many-to-Many: ONLY when necessary, use intermediate collection\n - One-to-Many: FORBIDDEN - invert to many-to-one from child\n\n3. **Data Types**:\n - NO arrays of ObjectIds for relationships\n - Timestamps: createdAt, updatedAt (Date) in EVERY collection\n - Enums: Use fieldType: 'enum' with values array\n\n4. **Security**:\n - NO separate \"Auth\" or \"Authentication\" collection\n - NO token storage in database\n - Password fields: isPrivate: true\n\n5. **Authorization (RBAC)**:\n - Define permissions per role on user modules\n - Format: {{ \"roleName\": [\"CREATE\", \"READ\", \"UPDATE\", \"DELETE\"] }}`;\n","/**\n * Design prompts - legacy and pro-level, plus structured requirement formatters\n */\n\nimport type { Actor, ExtractedFlow, ExtractedStory, StructuredRequirementsInput, TechnicalRequirements } from '../types';\nimport { DB_DESIGN_SYSTEM_PROMPT } from './system.prompt';\n\n/**\n * Legacy: build design prompt from plain requirement string\n */\nexport function createDbDesignPrompt(requirement: string): string {\n return `${DB_DESIGN_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 * Format actors/user types into prompt-friendly string\n */\nexport function formatUserTypes(actors: Actor[]): 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, index) => {\n const goals = actor.goals.filter((g) => g.trim()).join('\\n - ');\n return `### ${index + 1}. ${actor.name}\n**Description:** ${actor.description}\n**Goals:**\n - ${goals || 'No specific goals defined'}`;\n })\n .join('\\n\\n');\n}\n\n/**\n * Format user flows into prompt-friendly string\n */\nexport function formatUserFlows(flows: ExtractedFlow[], actors: Actor[]): string {\n if (!flows || flows.length === 0) {\n return 'No specific user flows defined.';\n }\n return flows\n .map((flow, index) => {\n const actor = actors.find((a) => a.id === flow.actorId);\n const actorName = actor?.name || 'User';\n return `### ${index + 1}. ${flow.name}\n**Actor:** ${actorName}\n**Description:** ${flow.description}\n**Trigger:** ${flow.trigger || 'User initiates action'}\n**Outcome:** ${flow.outcome || 'Action completed'}`;\n })\n .join('\\n\\n');\n}\n\n/**\n * Format user stories with dataInvolved into prompt-friendly string\n */\nexport function formatUserStories(stories: ExtractedStory[], flows: ExtractedFlow[]): string {\n if (!stories || stories.length === 0) {\n return 'No specific user stories defined.';\n }\n const storiesByFlow = new Map<string, ExtractedStory[]>();\n for (const story of stories) {\n const flowStories = storiesByFlow.get(story.flowId) || [];\n flowStories.push(story);\n storiesByFlow.set(story.flowId, flowStories);\n }\n const sections: string[] = [];\n for (const flow of flows) {\n const flowStories = storiesByFlow.get(flow.id) || [];\n if (flowStories.length === 0) continue;\n sections.push(`### Flow: ${flow.name}\\n`);\n for (const story of flowStories) {\n const preconditions = story.preconditions.filter((p) => p.trim());\n const postconditions = story.postconditions.filter((p) => p.trim());\n const dataInvolved = story.dataInvolved.filter((d) => d.trim());\n let storyText = `**As a** ${story.actor}, **I want to** ${story.action}, **so that** ${story.benefit}\\n`;\n if (preconditions.length > 0) {\n storyText += `\\n**Preconditions:**\\n${preconditions.map((p) => `- ${p}`).join('\\n')}\\n`;\n }\n if (postconditions.length > 0) {\n storyText += `\\n**Postconditions:**\\n${postconditions.map((p) => `- ${p}`).join('\\n')}\\n`;\n }\n if (dataInvolved.length > 0) {\n storyText += `\\n**Data Involved (IMPORTANT - these indicate entities/fields):**\\n${dataInvolved.map((d) => `- ${d}`).join('\\n')}\\n`;\n }\n sections.push(storyText);\n }\n }\n const orphanStories = stories.filter((s) => !flows.some((f) => f.id === s.flowId));\n if (orphanStories.length > 0) {\n sections.push(`### Other Stories\\n`);\n for (const story of orphanStories) {\n const dataInvolved = story.dataInvolved.filter((d) => d.trim());\n let storyText = `**As a** ${story.actor}, **I want to** ${story.action}, **so that** ${story.benefit}\\n`;\n if (dataInvolved.length > 0) {\n storyText += `\\n**Data Involved:** ${dataInvolved.join(', ')}\\n`;\n }\n sections.push(storyText);\n }\n }\n return sections.join('\\n');\n}\n\n/**\n * Format technical requirements into prompt-friendly string\n */\nexport function formatTechnicalRequirements(tech?: TechnicalRequirements): string {\n if (!tech) {\n return 'No specific technical requirements. Use defaults.';\n }\n const lines: string[] = [];\n lines.push(`**Authentication:** ${tech.authentication || 'none'}`);\n if (tech.authorization) {\n lines.push(`**Authorization (RBAC):** Enabled`);\n if (tech.roles && tech.roles.length > 0) {\n lines.push(`**Defined Roles:** ${tech.roles.join(', ')}`);\n }\n } else {\n lines.push(`**Authorization:** Disabled`);\n }\n if (tech.realtime) {\n lines.push(`**Realtime Features:** Required (consider subscription patterns)`);\n }\n if (tech.fileUpload) {\n lines.push(`**File Upload:** Required (consider file/document collection)`);\n }\n if (tech.search) {\n lines.push(`**Search Functionality:** Required (consider text indexes)`);\n }\n if (tech.integrations && tech.integrations.length > 0) {\n lines.push(`**Integrations:** ${tech.integrations.join(', ')}`);\n }\n return lines.join('\\n');\n}\n\n/**\n * Extract all unique dataInvolved items from stories for entity hints\n */\nexport function extractDataEntities(stories: ExtractedStory[]): string[] {\n const entities = new Set<string>();\n for (const story of stories) {\n for (const data of story.dataInvolved) {\n if (data.trim()) entities.add(data.trim());\n }\n }\n return Array.from(entities);\n}\n\n/**\n * Extract roles from actors for RBAC configuration\n */\nexport function extractRoles(actors: Actor[]): string[] {\n return actors.map((a) => a.name.toLowerCase().replaceAll(/\\s+/g, '_'));\n}\n\n/**\n * Build complete prompt variables from structured requirements\n */\nexport function buildPromptVariables(input: StructuredRequirementsInput): 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/**\n * Pro-level DB design prompt from structured requirements\n */\nexport function createProDbDesignPrompt(input: StructuredRequirementsInput): string {\n const vars = buildPromptVariables(input);\n return `${DB_DESIGN_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\nThese are the different types of users who will interact with the system. Each actor represents a potential role in your RBAC system.\n\n${vars.userTypes}\n\n---\n\n## USER FLOWS\n\nThese represent the key journeys users take through the system. Analyze these for:\n- Entity creation/modification patterns\n- State transitions (status enums)\n- Relationship ownership\n\n${vars.userFlows}\n\n---\n\n## USER STORIES WITH DATA REQUIREMENTS\n\nEach story includes dataInvolved - these are CRITICAL signals for your entity and field design.\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- Identify bidirectional relationships\n\n### Step 3: Permission Derivation\n- Map each actor to a role\n- Extract CRUD permissions from user story actions\n- Define the permissions object for user modules\n\n### Step 4: Query Pattern Inference\n- Identify likely query patterns from flows\n- Note which fields need indexing (for your reference)\n\n### Step 5: Schema Construction\nGenerate the final schema with:\n- Complete module definitions\n- All fields with proper types\n- Relationships with relationTo and relationType\n- Status enums from flow states\n- RBAC permissions on user modules\n- Timestamps on every module\n\nReturn ONLY valid JSON matching the schema specified. No markdown code blocks, no explanations.`;\n}\n","/**\n * Redesign prompt - update existing schema based on user feedback\n */\n\nimport { DB_DESIGN_SYSTEM_PROMPT } from './system.prompt';\n\nexport function createRedesignPrompt(existingSchema: string, userFeedback: string): string {\n return `${DB_DESIGN_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${userFeedback}\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 projectSchema (no AI)\n */\n\nimport { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { projectSchema } from '../schemas';\n\nexport const validateSchemaTool = defineTool({\n name: 'validate_schema',\n description:\n 'Validates a MongoDB project schema JSON string against the expected schema. Returns valid: true or valid: false with errors array.',\n input: z.object({\n schema: z.string().describe('JSON string of the database project schema to validate'),\n }),\n handler: async ({ schema }): Promise<{ valid: boolean; errors?: string[] }> => {\n try {\n const parsed = JSON.parse(schema) as unknown;\n projectSchema.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 * design_database tool - generates MongoDB schema from plain text requirement (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { projectSchema, type TBackendProjectSchema } from '../schemas';\nimport { createDbDesignPrompt } from '../prompts';\n\nfunction 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 * Creates the design_database tool. Requires a model to invoke for 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. Use for ad-hoc or legacy 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<TBackendProjectSchema> => {\n const userPrompt = createDbDesignPrompt(requirement);\n const messages = [\n { role: 'system' as const, content: 'You are a MongoDB schema expert. 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 const raw = response.text;\n const jsonStr = extractJson(raw);\n const parsed = JSON.parse(jsonStr) as unknown;\n return projectSchema.parse(parsed);\n },\n });\n}\n","/**\n * design_database_pro tool - generates MongoDB schema from structured requirements (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { projectSchema, type TBackendProjectSchema } from '../schemas';\nimport { createProDbDesignPrompt, extractDataEntities, extractRoles } from '../prompts';\n\nfunction 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\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.enum(['none', 'email', 'oauth', 'phone', 'email_and_phone']),\n authorization: z.boolean(),\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. Requires a model for schema generation.\n */\nexport function createDesignDatabaseProTool(model: Model) {\n return defineTool({\n name: 'design_database_pro',\n description:\n 'Generate a MongoDB schema from structured requirements (project name, goal, actors, flows, user stories with dataInvolved, technical requirements). Use for pro-level 5-phase analysis. Returns dbDesign and metadata (entitiesDetected, rolesExtracted).',\n input: structuredInputSchema,\n handler: async (input): Promise<{ dbDesign: TBackendProjectSchema; metadata: { entitiesDetected: string[]; rolesExtracted: string[] } }> => {\n const userPrompt = createProDbDesignPrompt(input);\n const messages = [\n { role: 'system' as const, content: 'You are a MongoDB schema expert. 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 const jsonStr = extractJson(response.text);\n const parsed = JSON.parse(jsonStr) as unknown;\n const dbDesign = projectSchema.parse(parsed);\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 schema based on user feedback (uses AI)\n */\n\nimport { z } from 'zod';\nimport type { Model } from '../../../lib/types/model';\nimport { defineTool } from '../../../lib/tools';\nimport { projectSchema, type TBackendProjectSchema } from '../schemas';\nimport { createRedesignPrompt } from '../prompts';\n\nfunction 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 * Creates the redesign_database tool. Requires a model for schema update.\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. Returns the updated schema as JSON.',\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<TBackendProjectSchema> => {\n const userPrompt = createRedesignPrompt(existingSchema, feedback);\n const messages = [\n { role: 'system' as const, content: 'You are a MongoDB schema expert. 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 const jsonStr = extractJson(response.text);\n const parsed = JSON.parse(jsonStr) as unknown;\n return projectSchema.parse(parsed);\n },\n });\n}\n","/**\n * db-designer tools\n */\n\nimport type { Model } from '../../../lib/types/model';\nimport { createToolSet } from '../../../lib/tools';\nimport { validateSchemaTool } from './validate-schema.tool';\nimport { createDesignDatabaseTool } from './design-database.tool';\nimport { createDesignDatabaseProTool } from './design-database-pro.tool';\nimport { createRedesignDatabaseTool } from './redesign-database.tool';\n\nexport { validateSchemaTool } from './validate-schema.tool';\nexport { createDesignDatabaseTool } from './design-database.tool';\nexport { createDesignDatabaseProTool } from './design-database-pro.tool';\nexport { createRedesignDatabaseTool } from './redesign-database.tool';\n\n/**\n * Create all db-designer tools for the agent. Pass the model for AI-backed tools.\n */\nexport function createDbDesignerTools(model: Model) {\n return createToolSet({\n validate_schema: validateSchemaTool,\n design_database: createDesignDatabaseTool(model),\n design_database_pro: createDesignDatabaseProTool(model),\n redesign_database: createRedesignDatabaseTool(model),\n });\n}\n","/**\n * entity-analyzer subagent - extracts entities, relationships, and roles from requirements (no tools)\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\n\nconst ENTITY_ANALYZER_SYSTEM_PROMPT = `You are an expert at analyzing software requirements to extract database design signals.\n\nFocus on PHASES 1-3 of the analysis framework:\n\n## PHASE 1: Entity Discovery\n- List every entity implied by the requirements (from dataInvolved, user types, flow actions, flow states).\n- Identify user/actor types that become roles.\n- Extract status enums from flow transitions.\n\n## PHASE 2: Relationship Mapping\n- For each entity pair, determine ownership (which actor creates/owns it).\n- Determine cardinality (one-to-one, many-to-one).\n- Note bidirectional relationships.\n\n## PHASE 3: Permission Derivation\n- Map each actor type to a role name.\n- From user story actions, infer CRUD permissions per role per entity.\n\nRespond with a clear, structured analysis (you can use headings and bullet points). The user will use this to generate or refine a MongoDB schema.`;\n\nexport const entityAnalyzerSubagent = defineSubagent({\n name: 'entity-analyzer',\n description:\n 'Analyzes raw requirements text to extract entities, relationships, and roles. Use when you need to understand what data and actors the system has before designing the schema. Returns structured analysis (no JSON).',\n systemPrompt: ENTITY_ANALYZER_SYSTEM_PROMPT,\n tools: {},\n maxIterations: 2,\n});\n","/**\n * schema-refiner subagent - validates schema and suggests refinements (has validate_schema tool)\n */\n\nimport { defineSubagent } from '../../../lib/subagents';\nimport { validateSchemaTool } from '../tools/validate-schema.tool';\n\nconst SCHEMA_REFINER_SYSTEM_PROMPT = `You are an expert MongoDB schema reviewer. Your job is to:\n\n1. Validate the provided schema using the validate_schema tool.\n2. Compare the schema against the original requirements and identify gaps (missing fields, wrong relationships, missing permissions).\n3. Suggest concrete improvements or return a corrected schema description.\n\nWhen the user gives you a schema (as JSON string) and optionally the original requirements, first call validate_schema to check structure. Then analyze completeness and correctness. Respond with either refinement suggestions or a summary of issues.`;\n\nexport function createSchemaRefinerSubagent() {\n return defineSubagent({\n name: 'schema-refiner',\n description:\n 'Validates a MongoDB project schema and suggests refinements based on requirements. Use when you have a draft schema and want to check it or improve it. Has access to validate_schema tool.',\n systemPrompt: SCHEMA_REFINER_SYSTEM_PROMPT,\n tools: { validate_schema: validateSchemaTool },\n maxIterations: 5,\n });\n}\n","/**\n * runDbDesignerAgent - orchestrator for the full DB design workflow\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 { DB_DESIGN_SYSTEM_PROMPT } from './prompts';\nimport { createDbDesignerTools } from './tools';\nimport { entityAnalyzerSubagent, createSchemaRefinerSubagent } from './subagents';\nimport type { DbDesignerAgentConfig } from './types';\nimport type { AgentResult } from '../../lib/types/agent';\n\nconst ORCHESTRATOR_SYSTEM_PROMPT = `${DB_DESIGN_SYSTEM_PROMPT}\n\nYou are the database design orchestrator. When the user asks for a database design:\n\n1. **Analyze first**: For complex or vague requirements, use subagent_entity-analyzer with a prompt that includes the user's requirements to get a structured analysis of entities, relationships, and roles.\n2. **Generate schema**: Use design_database (for plain text requirements) or design_database_pro (when the user provides structured requirements: project name, goal, actors, flows, user stories with dataInvolved, technical requirements) to produce the MongoDB schema.\n3. **Refine (optional)**: If the user wants validation or refinements, use subagent_schema-refiner with the current schema and requirements.\n4. **Validate**: You can use validate_schema to check any schema JSON before returning.\n5. **Redesign**: If the user asks for changes to an existing schema, use redesign_database with the existing schema string and their feedback.\n\nRespond with the final schema (as JSON) or a clear summary and the schema.`;\n\n/**\n * Run the db-designer orchestrator agent with all tools and subagents.\n */\nexport async function runDbDesignerAgent(config: DbDesignerAgentConfig): Promise<AgentResult> {\n const {\n input,\n model: modelConfig,\n maxIterations = 15,\n onStep,\n } = 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 });\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.string().describe('Author or owner of the application').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('Additional dynamic or static options for this field'),\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(\n 'Name of the GraphQL hook (e.g. useGetAllUserQuery, useCreateUserMutation)'\n ),\n queryString: z.string().describe('Actual GraphQL query string'),\n responseType: ApiResponseTypeSchema.describe('Optional schema describing shape of the API response'),\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('Optional schema describing shape of the API response'),\n});\n\nexport const DrawerSchema = z.object({\n title: z.string().describe('Title displayed on the drawer'),\n graphqlHook: z\n .string()\n .describe(\n 'Name of the GraphQL hook (e.g. useCreateUserMutation, useDeleteOneUserMutation)'\n ),\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.array(FormFieldSchema).optional().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', [\n AuthPageSchema,\n ListingPageSchema,\n]);\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.array(z.string()).optional().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.number().optional().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.array(z.string()).min(1).optional().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 rapid app development.\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.\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 { z } from 'zod';\nimport { defineTool } from '../../../lib/tools';\nimport { ApplicationSchema } from '../schemas';\n\nexport const validateFrontendConfigTool = defineTool({\n name: 'validate_frontend_config',\n description:\n 'Validates a frontend configuration JSON string against the ApplicationSchema. Returns valid: true or valid: false with errors array.',\n input: z.object({\n config: z.string().describe('JSON string of the frontend application config to validate'),\n }),\n handler: async ({ config }): Promise<{ valid: boolean; errors?: string[] }> => {\n try {\n const parsed = JSON.parse(config) as unknown;\n ApplicationSchema.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 * 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';\n\nfunction 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\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 const jsonStr = extractJson(response.text);\n const parsed = JSON.parse(jsonStr) as unknown;\n return ApplicationSchema.parse(parsed);\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 { role: 'system' as const, content: 'You are a GraphQL schema analyst. Return a clear, structured text breakdown.' },\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 * 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';\n\nexport { validateFrontendConfigTool } from './validate-frontend-config.tool';\nexport { createGenerateFrontendTool } from './generate-frontend.tool';\nexport { createGenerateFeatureBreakdownTool, type FeatureBreakdownResult } from './generate-feature-breakdown.tool';\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 });\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 {\n input,\n model: modelConfig,\n maxIterations = 15,\n onStep,\n } = 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 });\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "sweagent",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Multi-provider AI software engineering agent framework with tool calling support",
|
|
5
|
+
"author": {
|
|
6
|
+
"name": "sijeeshmiziha",
|
|
7
|
+
"email": "sijeeshmonbalan@gmail.com",
|
|
8
|
+
"url": "https://github.com/sijeeshmiziha"
|
|
9
|
+
},
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "https://github.com/sijeeshmiziha/sweagent.git"
|
|
13
|
+
},
|
|
14
|
+
"homepage": "https://github.com/sijeeshmiziha/sweagent",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/sijeeshmiziha/sweagent/issues"
|
|
17
|
+
},
|
|
18
|
+
"type": "module",
|
|
19
|
+
"main": "./dist/index.cjs",
|
|
20
|
+
"module": "./dist/index.js",
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"scripts": {
|
|
23
|
+
"build": "npm run typecheck && npm run lint && tsup",
|
|
24
|
+
"dev": "tsup --watch",
|
|
25
|
+
"test": "vitest run tests/unit tests/tools tests/core",
|
|
26
|
+
"test:unit": "vitest run tests/unit tests/tools tests/core",
|
|
27
|
+
"test:integration": "vitest run tests/integration",
|
|
28
|
+
"test:all": "vitest run",
|
|
29
|
+
"test:watch": "vitest",
|
|
30
|
+
"test:coverage": "vitest run --coverage",
|
|
31
|
+
"lint": "eslint src/",
|
|
32
|
+
"lint:fix": "eslint src/ --fix",
|
|
33
|
+
"format": "prettier --write .",
|
|
34
|
+
"format:check": "prettier --check .",
|
|
35
|
+
"typecheck": "tsc --noEmit",
|
|
36
|
+
"example": "tsx --env-file=.env",
|
|
37
|
+
"example:interactive": "tsx --env-file=.env examples/run.ts",
|
|
38
|
+
"tokens": "tsx .scripts/token-calculator.ts",
|
|
39
|
+
"tokens:verbose": "tsx .scripts/token-calculator.ts --verbose",
|
|
40
|
+
"tokens:json": "tsx .scripts/token-calculator.ts --json",
|
|
41
|
+
"ci": "npm run typecheck && npm run lint && npm run test:unit && npm run build",
|
|
42
|
+
"prepublishOnly": "npm run ci",
|
|
43
|
+
"prepare": "husky"
|
|
44
|
+
},
|
|
45
|
+
"exports": {
|
|
46
|
+
".": {
|
|
47
|
+
"import": {
|
|
48
|
+
"types": "./dist/index.d.ts",
|
|
49
|
+
"default": "./dist/index.js"
|
|
50
|
+
},
|
|
51
|
+
"require": {
|
|
52
|
+
"types": "./dist/index.d.cts",
|
|
53
|
+
"default": "./dist/index.cjs"
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
"files": [
|
|
58
|
+
"dist"
|
|
59
|
+
],
|
|
60
|
+
"keywords": [
|
|
61
|
+
"ai",
|
|
62
|
+
"swe",
|
|
63
|
+
"software-engineering",
|
|
64
|
+
"agents",
|
|
65
|
+
"tools",
|
|
66
|
+
"ai-sdk",
|
|
67
|
+
"openai",
|
|
68
|
+
"anthropic",
|
|
69
|
+
"google"
|
|
70
|
+
],
|
|
71
|
+
"license": "MIT",
|
|
72
|
+
"dependencies": {
|
|
73
|
+
"@ai-sdk/anthropic": "^3.0.0",
|
|
74
|
+
"@ai-sdk/google": "^3.0.0",
|
|
75
|
+
"@ai-sdk/openai": "^3.0.0",
|
|
76
|
+
"@modelcontextprotocol/sdk": "^1.26.0",
|
|
77
|
+
"ai": "^6.0.0",
|
|
78
|
+
"zod": "^4.1.8"
|
|
79
|
+
},
|
|
80
|
+
"devDependencies": {
|
|
81
|
+
"@eslint/js": "^9.39.2",
|
|
82
|
+
"@inquirer/prompts": "^7.2.0",
|
|
83
|
+
"@types/node": "^25.2.0",
|
|
84
|
+
"eslint": "^9.16.0",
|
|
85
|
+
"eslint-config-prettier": "^10.1.8",
|
|
86
|
+
"eslint-plugin-prettier": "^5.5.5",
|
|
87
|
+
"husky": "^9.1.7",
|
|
88
|
+
"lint-staged": "^16.2.7",
|
|
89
|
+
"prettier": "^3.8.1",
|
|
90
|
+
"tsup": "^8.3.5",
|
|
91
|
+
"typescript": "^5.7.2",
|
|
92
|
+
"typescript-eslint": "^8.18.0",
|
|
93
|
+
"vitest": "^4.0.18"
|
|
94
|
+
},
|
|
95
|
+
"optionalDependencies": {
|
|
96
|
+
"@rollup/rollup-linux-x64-gnu": "^4.40.0"
|
|
97
|
+
},
|
|
98
|
+
"lint-staged": {
|
|
99
|
+
"*.ts": [
|
|
100
|
+
"eslint --fix",
|
|
101
|
+
"prettier --write"
|
|
102
|
+
],
|
|
103
|
+
"*.{json,md,yml,yaml}": [
|
|
104
|
+
"prettier --write"
|
|
105
|
+
]
|
|
106
|
+
}
|
|
107
|
+
}
|