UNPKG

@autobe/agent

Version:

AI backend server code generator

420 lines 44.9 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.orchestrateRealizeCoder = void 0; const __typia_transform__validateReport = __importStar(require("typia/lib/internal/_validateReport.js")); const core_1 = require("@agentica/core"); const typia_1 = __importDefault(require("typia")); const assertSchemaModel_1 = require("../../context/assertSchemaModel"); const backoffRetry_1 = require("../../utils/backoffRetry"); const enforceToolCall_1 = require("../../utils/enforceToolCall"); const getTestScenarioArtifacts_1 = require("../test/compile/getTestScenarioArtifacts"); const IAutoBeRealizeFailedSymbol_1 = require("./structures/IAutoBeRealizeFailedSymbol"); const transformRealizeCoderHistories_1 = require("./transformRealizeCoderHistories"); const ProviderFileSystem_1 = require("./utils/ProviderFileSystem"); const replaceImportStatements_1 = require("./utils/replaceImportStatements"); /** * Generates a TypeScript function implementation based on the given plan. * * This function transforms the plan (function name, input/output schema, * constraints, and scenarios) into a complete TypeScript function as a string. * It is responsible only for producing the code logic, and does not handle * imports, exports, or formatting. * * Import statements are handled separately and will be injected automatically. * Any unused imports will be removed by tooling (e.g. eslint). * * Type annotations should be omitted whenever possible to favor TypeScript's * type inference, unless explicit types are critical to correctness. * * @param ctx - AutoBE execution context * @param props - Planning result describing what function to generate * @returns The generated function name and TypeScript code */ const orchestrateRealizeCoder = (ctx, operation, previousCodes, props, previous, total, diagnostics, authorization) => __awaiter(void 0, void 0, void 0, function* () { var _a; total; const artifacts = yield (0, getTestScenarioArtifacts_1.getTestScenarioArtifacts)(ctx, { endpoint: { method: operation.method, path: operation.path, }, dependencies: [], }); const pointer = { value: null, }; const controller = createApplication({ model: ctx.model, build: (props) => { pointer.value = props.output; }, }); const agent = new core_1.MicroAgentica({ controllers: [controller], model: ctx.model, vendor: ctx.vendor, config: Object.assign(Object.assign({}, ctx.config), { executor: { describe: null, } }), histories: (0, transformRealizeCoderHistories_1.transformRealizeCoderHistories)(ctx.state(), previousCodes, props, artifacts, previous, diagnostics, authorization), }); (0, enforceToolCall_1.enforceToolCall)(agent); yield (0, backoffRetry_1.randomBackoffRetry)(() => agent.conversate([ `Write complete, production-ready TypeScript code that strictly follows these rules:`, "", `1. Do **not** use the native \`Date\` type anywhere.`, `2. All date or datetime values must be written as \`string & tags.Format<'date-time'>\`.`, `3. UUIDs must be generated using \`v4()\` and typed as \`string & tags.Format<'uuid'>\`.`, `4. Do not use \`as\` for type assertions — resolve types properly.`, `5. All functions must be fully typed with clear parameter and return types.`, `6. Do not skip validations or default values where necessary.`, `7. Follow functional, immutable, and consistent code structure.`, "", `Use \`@nestia/e2e\` test structure if relevant.`, ].join("\n"))).finally(() => { const tokenUsage = agent.getTokenUsage(); ctx.usage().record(tokenUsage, ["realize"]); }); if (pointer.value === null) { return IAutoBeRealizeFailedSymbol_1.FAILED; } pointer.value.implementationCode = yield (0, replaceImportStatements_1.replaceImportStatements)(ctx)(artifacts, pointer.value.implementationCode, (_a = props.decoratorEvent) === null || _a === void 0 ? void 0 : _a.payload.name); pointer.value.implementationCode = pointer.value.implementationCode.replaceAll("typia.tags.assert", "typia.assert"); return Object.assign(Object.assign({}, pointer.value), { filename: ProviderFileSystem_1.RealizeFileSystem.providerPath(props.functionName) }); }); exports.orchestrateRealizeCoder = orchestrateRealizeCoder; function createApplication(props) { (0, assertSchemaModel_1.assertSchemaModel)(props.model); const application = collection[props.model]; return { protocol: "class", name: "Write code", application, execute: { programming: (next) => { props.build(next); }, }, }; } const claude = { model: "claude", options: { reference: true, separate: null }, functions: [ { name: "programming", parameters: { description: "Description of the current {@link IAutoBeRealizeCoderApplication.IProps} type:\n\n> Properties for the component or function that consumes the output of the\n> code generation pipeline.", type: "object", properties: { output: { description: "The detailed output of the code generation process, containing all phases\nfrom planning to final implementation of a TypeScript provider function.", $ref: "#/$defs/OmitIAutoBeRealizeCoderApplication.RealizeCoderOutputfilename" } }, required: [ "output" ], additionalProperties: false, $defs: { "OmitIAutoBeRealizeCoderApplication.RealizeCoderOutputfilename": { description: "Construct a type with the properties of T except for those in type K.", type: "object", properties: { errorAnalysis: { description: "Error Analysis Phase (Optional)\n\n\uD83D\uDD0D Analyzes TypeScript compilation errors from previous attempts.\n\nThis field should contain a detailed analysis of any TypeScript errors\nencountered, with root cause identification and resolution strategies:\n\nCommon Error Patterns to Analyze:\n\n1. **\"Property does not exist\" (TS2353)**:\n\n - Root Cause: Using fields that don't exist in Prisma schema\n - Example: Using `deleted_at` when the field doesn't exist in the model\n - Resolution: Remove the non-existent field or use hard delete instead\n2. **\"Type 'void' is not assignable\" (TS2322)**:\n\n - Root Cause: Using `typia.assertGuard` instead of `typia.assert`\n - `assertGuard` returns void, `assert` returns the validated value\n - Resolution: Change `typia.assertGuard<T>()` to `typia.assert<T>()`\n3. **\"Type 'Date' is not assignable to type 'string &\n Format<'date-time'>'\"**:\n\n - Root Cause: Assigning native Date objects to string fields\n - Resolution: Use `toISOStringSafe(dateValue)` for all date conversions\n4. **Complex Prisma Type Errors**:\n\n - Root Cause: Nested operations with incompatible types\n - Resolution: Use separate queries and application-level joins\n\nAnalysis Format:\n\n- List each error with its TypeScript error code\n- Identify the root cause (schema mismatch, wrong function usage, etc.)\n- Provide specific resolution steps\n- Note any schema limitations discovered", type: "string" }, plan: { description: "Step 1.\n\n\uD83E\uDDE0 Provider Function Implementation Plan\n\nThis field outlines the strategic plan for implementing the provider\nfunction according to the Realize Coder Agent specification. Before\nwriting the actual code, think through the logic and structure.\n\nThe plan MUST follow MANDATORY SCHEMA-FIRST APPROACH:\n\n\uD83D\uDCCB STEP 1 - PRISMA SCHEMA VERIFICATION (MOST CRITICAL):\n\n- EXAMINE the actual Prisma schema model definition\n- LIST EVERY field that exists in the model with exact types\n- EXPLICITLY NOTE fields that DO NOT exist (e.g., \"Note: deleted_at field\n DOES NOT EXIST\")\n- Common assumption errors to avoid: `deleted_at`, `created_by`,\n `updated_by`, `is_deleted`, `is_active`\n\n\uD83D\uDCCB STEP 2 - FIELD INVENTORY:\n\n- List ONLY fields confirmed to exist in schema\n- Example: \"Verified fields in user model: id (String), email (String),\n created_at (DateTime), updated_at (DateTime)\"\n- Example: \"Fields that DO NOT exist: deleted_at, is_active, created_by\"\n\n\uD83D\uDCCB STEP 3 - FIELD ACCESS STRATEGY:\n\n- Plan which verified fields will be used in select, update, create\n operations\n- For complex operations with type errors, plan to use separate queries\n instead of nested operations\n\n\uD83D\uDCCB STEP 4 - TYPE COMPATIBILITY:\n\n- Plan DateTime to ISO string conversions using toISOStringSafe()\n- Plan handling of nullable vs required fields\n\n\uD83D\uDCCB STEP 5 - IMPLEMENTATION APPROACH:\n\n- \uD83E\uDDE9 Required business entities (e.g., users, posts, logs) and their\n relationships\n- \uD83D\uDEE0 Operations needed to fulfill the business scenario (e.g., fetch,\n create, update) using ONLY verified fields\n- \uD83D\uDD04 Data dependencies between steps (e.g., use userId to fetch related\n data)\n- \u2705 Validation points (based on business rules, not field presence)\n- \uD83D\uDEA7 Error and edge cases that must be handled explicitly (e.g., missing\n records)\n- \uD83C\uDFD7 Structure: always a single `async function`, using only `parameters`\n and `body`\n\n\u26A0\uFE0F Important Constraints:\n\n- Do NOT perform input validation \u2014 assume `parameters` and `body` are\n already valid\n- Use `typia.random<T>()` with an explanatory comment if logic can't be\n implemented\n- Never use `any` or make assumptions without sufficient context\n- Use only allowed imports \u2014 DTOs and Prisma types\n- Use `MyGlobal.prisma` for DB access and respect Prisma typing rules\n\n\u26A0\uFE0F TypeScript-specific considerations:\n\n- Do **not** use native `Date` objects directly; always convert all dates\n using `toISOStringSafe()` and brand as `string &\n tags.Format<'date-time'>`. This rule applies throughout all phases.\n- Prefer `satisfies` for DTO conformance instead of unsafe `as` casts\n- Avoid weak typing such as `any`, `as any`, or `satisfies any`\n- Use branded types (e.g., `tags.Format<'uuid'>`) and literal unions where\n applicable\n\n\u2705 Example Structure:\n\n```ts\nexport async function doSomething(\n user: { id: string & tags.Format<\"uuid\">; type: string },\n parameters: IParams,\n body: IBody\n): Promise<IReturn> {\n const { id } = parameters;\n const { name } = body;\n const user = await MyGlobal.prisma.users.findFirst({ where: { id } });\n if (!user) throw new Error(\"User not found\");\n ...\n return result;\n}\n```\n\n\uD83D\uDD0D Feasibility Analysis Requirement:\n\n- Before generating any code, the agent **must analyze** whether the\n requested implementation is **feasible based on the given Prisma schema\n and DTO types**.\n- If required fields or relationships are **missing or incompatible**, the\n plan should explicitly state that the implementation is **not\n possible** with the current schema/DTO, and no code should be generated\n in later stages.\n- In such cases, only a detailed **comment in the `implementationCode`**\n should be returned explaining why the logic cannot be implemented.\n\n\uD83D\uDD25 Error Handling Plan:\n\nIf an error is expected or encountered during implementation:\n\n- Clearly document the error message(s) and TypeScript error codes.\n- Analyze the root cause (e.g., type mismatch, missing field, nullability\n issue).\n- Define concrete steps to resolve the issue, such as:\n\n - Adjusting type declarations or using Prisma-generated input types.\n - Using `?? undefined` to normalize nullable fields.\n - Applying correct relation handling (e.g., `connect` instead of direct\n foreign key assignment).\n - Ensuring all date fields use `.toISOString()` and proper branding.\n- Include fallback or workaround plans if a direct fix is complex.\n- If no error is present, simply omit this section.\n\nThis plan ensures the function will:\n\n- Respect the global architecture and coding conventions\n- Be safe, predictable, and aligned with upstream logic", type: "string" }, prisma_schemas: { description: "Step 2.\n\nThe Prisma schema string that will be used to validate the implementation\nlogic in this file.\n\nYou must **explicitly specify only the relevant models and fields** from\nyour full schema that are used in this implementation. This ensures that\nyour logic is aligned with the expected database structure without\naccidentally introducing unrelated fields or models.\n\n\u26A0\uFE0F Important: The value of this field must be a valid Prisma schema\nstring containing only the models used in this code \u2014 not the entire\nschema.\n\nThis acts as a safeguard against:\n\n- Forgetting required fields used in this implementation\n- Including fields or models that are not actually used", type: "string" }, draft_without_date_type: { description: "Step 3.\n\nDraft WITHOUT using native Date type.\n\nThis is the initial drafting phase where you outline the basic skeleton\nof the function. CRITICAL: This draft must NEVER use the native Date\ntype.\n\n- The function signature must correctly include `user`, `parameters`, and\n `body` arguments.\n- Design the main flow of business logic, such as DB fetches and early\n returns based on conditions.\n- Mark any incomplete or missing parts clearly with placeholders (e.g.,\n comments or temporary values).\n\n\u26A0\uFE0F Import rules:\n\n- Do NOT add any new import statements manually.\n- All necessary imports are provided globally or by the system\n automatically.\n- Writing import statements directly is prohibited and may cause compile\n errors. If import errors occur, check your environment configuration.\n\n\u2705 Requirements:\n\n- Avoid using the `any` type at all costs to ensure type safety.\n- NEVER declare variables with `: Date` type\n- ALWAYS use `string & tags.Format<'date-time'>` for date values\n- Use `toISOStringSafe(new Date())` for current timestamps\n- Maintain a single-function structure; avoid using classes.", type: "string" }, review: { description: "Step 4.\n\nA refined version of the draft with improved completeness.\n\n- Replace placeholder logic with real DTO-conformant operations.\n- Add error handling (`throw new Error(...)`) where necessary.\n- Begin resolving structural or type mismatches.\n\n\u2705 Requirements:\n\n- Use `satisfies` to ensure DTO conformity.\n- Avoid unsafe `as` casts unless only for branding or literal narrowing.\n- Use `toISOStringSafe()` for all date conversions (NOT `.toISOString()`).\n- Ensure all object keys strictly conform to the expected type definitions.", type: "string" }, withCompilerFeedback: { description: "\uD83D\uDEE0 Phase 4-2: With compiler feedback (optional)\n\nA correction pass that applies fixes for compile-time errors that arose\nduring the review stage (if any).\n\n\u2705 Must:\n\n- Only include this field if TypeScript errors are detected in the Review\n phase.\n- Resolve all TypeScript errors without using `as any`.\n- Provide safe brand casting only if required (e.g., `as string &\n tags.Format<'uuid'>`).\n- If no TypeScript errors exist, this field MUST contain the text: \"No\n TypeScript errors detected - skipping this phase\"", type: "string" }, implementationCode: { description: "Step 5.\n\nThe complete and fully correct TypeScript function implementation.\n\n- Passes strict type checking without errors.\n- Uses only safe branding or literal type assertions.\n- Converts all date values properly using `toISOStringSafe()`.\n- Follows DTO structures using `satisfies`.\n- Avoids any weak typing such as `any`, `as any`, or `satisfies any`.\n- Uses only allowed imports (e.g., from `../api/structures` and\n `MyGlobal.prisma`).\n- NEVER creates intermediate variables for Prisma operations.\n\n\u26A0\uFE0F Fallback Behavior:\n\n- If the `plan` phase explicitly determines that the requested logic is\n **not feasible** due to mismatches or limitations in the provided\n Prisma schema and DTO types:\n\n - The implementation must still return a syntactically valid function.\n - In such cases, return mock data using `typia.random<T>()` wrapped in the\n correct structure, along with a comment explaining the limitation.\n\n Example fallback:\n\n```ts\n // \u26A0\uFE0F Cannot implement logic due to missing relation between A and B\n export async function someFunction(...) {\n return typia.random<IReturn>(); // mocked output\n }\n```\n\n\u26A0\uFE0F Prohibited Practices:\n\n- Do NOT add or modify import statements manually. Imports are handled\n automatically by the system.\n- Do NOT use `any`, `as any`, or `satisfies any` to bypass type checking.\n- Do NOT assign native `Date` objects directly; always convert them using\n `toISOStringSafe()`.\n- Do NOT use unsafe type assertions except for safe branding or literal\n narrowing.\n- Do NOT write code outside the single async function structure (e.g., no\n classes or multiple functions).\n- Do NOT perform any input validation \u2014 assume all inputs are already\n validated.\n- Do NOT use dynamic import expressions (`import()`); all imports must be\n static.\n- Do NOT use Prisma-generated input types; always use types from\n `../api/structures`.\n- Do NOT use `Object.prototype.hasOwnProperty.call()` for field checks.\n- Do NOT escape newlines or quotes in the implementation string (e.g., no\n `\\\\n` or `\\\"`); use a properly formatted template literal with actual\n line breaks instead.", type: "string" } }, required: [ "plan", "prisma_schemas", "draft_without_date_type", "review", "withCompilerFeedback", "implementationCode" ] } } }, validate: (() => { const _io0 = input => "object" === typeof input.output && null !== input.output && _io1(input.output); const _io1 = input => (undefined === input.errorAnalysis || "string" === typeof input.errorAnalysis) && "string" === typeof input.plan && "string" === typeof input.prisma_schemas && "string" === typeof input.draft_without_date_type && "string" === typeof input.review && "string" === typeof input.withCompilerFeedback && "string" === typeof input.implementationCode; const _vo0 = (input, _path, _exceptionable = true) => [("object" === typeof input.output && null !== input.output || _report(_exceptionable, { path: _path + ".output", expected: "Omit<IAutoBeRealizeCoderApplication.RealizeCoderOutput, \"filename\">", value: input.output })) && _vo1(input.output, _path + ".output", true && _exceptionable) || _report(_exceptionable, { path: _path + ".output", expected: "Omit<IAutoBeRealizeCoderApplication.RealizeCoderOutput, \"filename\">", value: input.output })].every(flag => flag); const _vo1 = (input, _path, _exceptionable = true) => [undefined === input.errorAnalysis || "string" === typeof input.errorAnalysis || _report(_exceptionable, { path: _path + ".errorAnalysis", expected: "(string | undefined)", value: input.errorAnalysis }), "string" === typeof input.plan || _report(_exceptionable, { path: _path + ".plan", expected: "string", value: input.plan }), "string" === typeof input.prisma_schemas || _report(_exceptionable, { path: _path + ".prisma_schemas", expected: "string", value: input.prisma_schemas }), "string" === typeof input.draft_without_date_type || _report(_exceptionable, { path: _path + ".draft_without_date_type", expected: "string", value: input.draft_without_date_type }), "string" === typeof input.review || _report(_exceptionable, { path: _path + ".review", expected: "string", value: input.review }), "string" === typeof input.withCompilerFeedback || _report(_exceptionable, { path: _path + ".withCompilerFeedback", expected: "string", value: input.withCompilerFeedback }), "string" === typeof input.implementationCode || _report(_exceptionable, { path: _path + ".implementationCode", expected: "string", value: input.implementationCode })].every(flag => flag); const __is = input => "object" === typeof input && null !== input && _io0(input); let errors; let _report; return input => { if (false === __is(input)) { errors = []; _report = __typia_transform__validateReport._validateReport(errors); ((input, _path, _exceptionable = true) => ("object" === typeof input && null !== input || _report(true, { path: _path + "", expected: "IAutoBeRealizeCoderApplication.IProps", value: input })) && _vo0(input, _path + "", true) || _report(true, { path: _path + "", expected: "IAutoBeRealizeCoderApplication.IProps", value: input }))(input, "$input", true); const success = 0 === errors.length; return success ? { success, data: input } : { success, errors, data: input }; } return { success: true, data: input }; }; })() } ] }; const collection = { chatgpt: { model: "chatgpt", options: { reference: true, strict: false, separate: null }, functions: [ { name: "programming", parameters: { description: "Description of the current {@link IAutoBeRealizeCoderApplication.IProps} type:\n\n> Properties for the component or function that consumes the output of the\n> code generation pipeline.\n\n### Description of {@link output} property:\n\n> The detailed output of the code generation process, containing all phases\n> from planning to final implementation of a TypeScript provider function.", type: "object", properties: { output: { $ref: "#/$defs/OmitIAutoBeRealizeCoderApplication.RealizeCoderOutputfilename" } }, required: [ "output" ], additionalProperties: false, $defs: { "OmitIAutoBeRealizeCoderApplication.RealizeCoderOutputfilename": { description: "Construct a type with the properties of T except for those in type K.", type: "object", properties: { errorAnalysis: { description: "Error Analysis Phase (Optional)\n\n\uD83D\uDD0D Analyzes TypeScript compilation errors from previous attempts.\n\nThis field should contain a detailed analysis of any TypeScript errors\nencountered, with root cause identification and resolution strategies:\n\nCommon Error Patterns to Analyze:\n\n1. **\"Property does not exist\" (TS2353)**:\n\n - Root Cause: Using fields that don't exist in Prisma schema\n - Example: Using `deleted_at` when the field doesn't exist in the model\n - Resolution: Remove the non-existent field or use hard delete instead\n2. **\"Type 'void' is not assignable\" (TS2322)**:\n\n - Root Cause: Using `typia.assertGuard` instead of `typia.assert`\n - `assertGuard` returns void, `assert` returns the validated value\n - Resolution: Change `typia.assertGuard<T>()` to `typia.assert<T>()`\n3. **\"Type 'Date' is not assignable to type 'string &\n Format<'date-time'>'\"**:\n\n - Root Cause: Assigning native Date objects to string fields\n - Resolution: Use `toISOStringSafe(dateValue)` for all date conversions\n4. **Complex Prisma Type Errors**:\n\n - Root Cause: Nested operations with incompatible types\n - Resolution: Use separate queries and application-level joins\n\nAnalysis Format:\n\n- List each error with its TypeScript error code\n- Identify the root cause (schema mismatch, wrong function usage, etc.)\n- Provide specific resolution steps\n- Note any schema limitations discovered", type: "string" }, plan: { description: "Step 1.\n\n\uD83E\uDDE0 Provider Function Implementation Plan\n\nThis field outlines the strategic plan for implementing the provider\nfunction according to the Realize Coder Agent specification. Before\nwriting the actual code, think through the logic and structure.\n\nThe plan MUST follow MANDATORY SCHEMA-FIRST APPROACH:\n\n\uD83D\uDCCB STEP 1 - PRISMA SCHEMA VERIFICATION (MOST CRITICAL):\n\n- EXAMINE the actual Prisma schema model definition\n- LIST EVERY field that exists in the model with exact types\n- EXPLICITLY NOTE fields that DO NOT exist (e.g., \"Note: deleted_at field\n DOES NOT EXIST\")\n- Common assumption errors to avoid: `deleted_at`, `created_by`,\n `updated_by`, `is_deleted`, `is_active`\n\n\uD83D\uDCCB STEP 2 - FIELD INVENTORY:\n\n- List ONLY fields confirmed to exist in schema\n- Example: \"Verified fields in user model: id (String), email (String),\n created_at (DateTime), updated_at (DateTime)\"\n- Example: \"Fields that DO NOT exist: deleted_at, is_active, created_by\"\n\n\uD83D\uDCCB STEP 3 - FIELD ACCESS STRATEGY:\n\n- Plan which verified fields will be used in select, update, create\n operations\n- For complex operations with type errors, plan to use separate queries\n instead of nested operations\n\n\uD83D\uDCCB STEP 4 - TYPE COMPATIBILITY:\n\n- Plan DateTime to ISO string conversions using toISOStringSafe()\n- Plan handling of nullable vs required fields\n\n\uD83D\uDCCB STEP 5 - IMPLEMENTATION APPROACH:\n\n- \uD83E\uDDE9 Required business entities (e.g., users, posts, logs) and their\n relationships\n- \uD83D\uDEE0 Operations needed to fulfill the business scenario (e.g., fetch,\n create, update) using ONLY verified fields\n- \uD83D\uDD04 Data dependencies between steps (e.g., use userId to fetch related\n data)\n- \u2705 Validation points (based on business rules, not field presence)\n- \uD83D\uDEA7 Error and edge cases that must be handled explicitly (e.g., missing\n records)\n- \uD83C\uDFD7 Structure: always a single `async function`, using only `parameters`\n and `body`\n\n\u26A0\uFE0F Important Constraints:\n\n- Do NOT perform input validation \u2014 assume `parameters` and `body` are\n already valid\n- Use `typia.random<T>()` with an explanatory comment if logic can't be\n implemented\n- Never use `any` or make assumptions without sufficient context\n- Use only allowed imports \u2014 DTOs and Prisma types\n- Use `MyGlobal.prisma` for DB access and respect Prisma typing rules\n\n\u26A0\uFE0F TypeScript-specific considerations:\n\n- Do **not** use native `Date` objects directly; always convert all dates\n using `toISOStringSafe()` and brand as `string &\n tags.Format<'date-time'>`. This rule applies throughout all phases.\n- Prefer `satisfies` for DTO conformance instead of unsafe `as` casts\n- Avoid weak typing such as `any`, `as any`, or `satisfies any`\n- Use branded types (e.g., `tags.Format<'uuid'>`) and literal unions where\n applicable\n\n\u2705 Example Structure:\n\n```ts\nexport async function doSomething(\n user: { id: string & tags.Format<\"uuid\">; type: string },\n parameters: IParams,\n body: IBody\n): Promise<IReturn> {\n const { id } = parameters;\n const { name } = body;\n const user = await MyGlobal.prisma.users.findFirst({ where: { id } });\n if (!user) throw new Error(\"User not found\");\n ...\n return result;\n}\n```\n\n\uD83D\uDD0D Feasibility Analysis Requirement:\n\n- Before generating any code, the agent **must analyze** whether the\n requested implementation is **feasible based on the given Prisma schema\n and DTO types**.\n- If required fields or relationships are **missing or incompatible**, the\n plan should explicitly state that the implementation is **not\n possible** with the current schema/DTO, and no code should be generated\n in later stages.\n- In such cases, only a detailed **comment in the `implementationCode`**\n should be returned explaining why the logic cannot be implemented.\n\n\uD83D\uDD25 Error Handling Plan:\n\nIf an error is expected or encountered during implementation:\n\n- Clearly document the error message(s) and TypeScript error codes.\n- Analyze the root cause (e.g., type mismatch, missing field, nullability\n issue).\n- Define concrete steps to resolve the issue, such as:\n\n - Adjusting type declarations or using Prisma-generated input types.\n - Using `?? undefined` to normalize nullable fields.\n - Applying correct relation handling (e.g., `connect` instead of direct\n foreign key assignment).\n - Ensuring all date fields use `.toISOString()` and proper branding.\n- Include fallback or workaround plans if a direct fix is complex.\n- If no error is present, simply omit this section.\n\nThis plan ensures the function will:\n\n- Respect the global architecture and coding conventions\n- Be safe, predictable, and aligned with upstream logic", type: "string" }, prisma_schemas: { description: "Step 2.\n\nThe Prisma schema string that will be used to validate the implementation\nlogic in this file.\n\nYou must **explicitly specify only the relevant models and fields** from\nyour full schema that are used in this implementation. This ensures that\nyour logic is aligned with the expected database structure without\naccidentally introducing unrelated fields or models.\n\n\u26A0\uFE0F Important: The value of this field must be a valid Prisma schema\nstring containing only the models used in this code \u2014 not the entire\nschema.\n\nThis acts as a safeguard against:\n\n- Forgetting required fields used in this implementation\n- Including fields or models that are not actually used", type: "string" }, draft_without_date_type: { description: "Step 3.\n\nDraft WITHOUT using native Date type.\n\nThis is the initial drafting phase where you outline the basic skeleton\nof the function. CRITICAL: This draft must NEVER use the native Date\ntype.\n\n- The function signature must correctly include `user`, `parameters`, and\n `body` arguments.\n- Design the main flow of business logic, such as DB fetches and early\n returns based on conditions.\n- Mark any incomplete or missing parts clearly with placeholders (e.g.,\n comments or temporary values).\n\n\u26A0\uFE0F Import rules:\n\n- Do NOT add any new import statements manually.\n- All necessary imports are provided globally or by the system\n automatically.\n- Writing import statements directly is prohibited and may cause compile\n errors. If import errors occur, check your environment configuration.\n\n\u2705 Requirements:\n\n- Avoid using the `any` type at all costs to ensure type safety.\n- NEVER declare variables with `: Date` type\n- ALWAYS use `string & tags.Format<'date-time'>` for date values\n- Use `toISOStringSafe(new Date())` for current timestamps\n- Maintain a single-function structure; avoid using classes.", type: "string" }, review: { description: "Step 4.\n\nA refined version of the draft with improved completeness.\n\n- Replace placeholder logic with real DTO-conformant operations.\n- Add error handling (`throw new Error(...)`) where necessary.\n- Begin resolving structural or type mismatches.\n\n\u2705 Requirements:\n\n- Use `satisfies` to ensure DTO conformity.\n- Avoid unsafe `as` casts unless only for branding or literal narrowing.\n- Use `toISOStringSafe()` for all date conversions (NOT `.toISOString()`).\n- Ensure all object keys strictly conform to the expected type definitions.", type: "string" }, withCompilerFeedback: { description: "\uD83D\uDEE0 Phase 4-2: With compiler feedback (optional)\n\nA correction pass that applies fixes for compile-time errors that arose\nduring the review stage (if any).\n\n\u2705 Must:\n\n- Only include this field if TypeScript errors are detected in the Review\n phase.\n- Resolve all TypeScript errors without using `as any`.\n- Provide safe brand casting only if required (e.g., `as string &\n tags.Format<'uuid'>`).\n- If no TypeScript errors exist, this field MUST contain the text: \"No\n TypeScript errors detected - skipping this phase\"", type: "string" }, implementationCode: { description: "Step 5.\n\nThe complete and fully correct TypeScript function implementation.\n\n- Passes strict type checking without errors.\n- Uses only safe branding or literal type assertions.\n- Converts all date values properly using `toISOStringSafe()`.\n- Follows DTO structures using `satisfies`.\n- Avoids any weak typing such as `any`, `as any`, or `satisfies any`.\n- Uses only allowed imports (e.g., from `../api/structures` and\n `MyGlobal.prisma`).\n- NEVER creates intermediate variables for Prisma operations.\n\n\u26A0\uFE0F Fallback Behavior:\n\n- If the `plan` phase explicitly determines that the requested logic is\n **not feasible** due to mismatches or limitations in the provided\n Prisma schema and DTO types:\n\n - The implementation must still return a syntactically valid function.\n - In such cases, return mock data using `typia.random<T>()` wrapped in the\n correct structure, along with a comment explaining the limitation.\n\n Example fallback:\n\n```ts\n // \u26A0\uFE0F Cannot implement logic due to missing relation between A and B\n export async function someFunction(...) {\n return typia.random<IReturn>(); // mocked output\n }\n```\n\n\u26A0\uFE0F Prohibited Practices:\n\n- Do NOT add or modify import statements manually. Imports are handled\n automatically by the system.\n- Do NOT use `any`, `as any`, or `satisfies any` to bypass type checking.\n- Do NOT assign native `Date` objects directly; always convert them using\n `toISOStringSafe()`.\n- Do NOT use unsafe type assertions except for safe branding or literal\n narrowing.\n- Do NOT write code outside the single async function structure (e.g., no\n classes or multiple functions).\n- Do NOT perform any input validation \u2014 assume all inputs are already\n validated.\n- Do NOT use dynamic import expressions (`import()`); all imports must be\n static.\n- Do NOT use Prisma-generated input types; always use types from\n `../api/structures`.\n- Do NOT use `Object.prototype.hasOwnProperty.call()` for field checks.\n- Do NOT escape newlines or quotes in the implementation string (e.g., no\n `\\\\n` or `\\\"`); use a properly formatted template literal with actual\n line breaks instead.", type: "string" } }, required: [ "plan", "prisma_schemas", "draft_without_date_type", "review", "withCompilerFeedback", "implementationCode" ] } } }, validate: (() => { const _io0 = input => "object" === typeof input.output && null !== input.output && _io1(input.output); const _io1 = input => (undefined === input.errorAnalysis || "string" === typeof input.errorAnalysis) && "string" === typeof input.plan && "string" === typeof input.prisma_schemas && "string" === typeof input.draft_without_date_type && "string" === typeof input.review && "string" === typeof input.withCompilerFeedback && "string" === typeof input.implementationCode; const _vo0 = (input, _path, _exceptionable = true) => [("object" === typeof input.output && null !== input.output || _report(_exceptionable, { path: _path + ".output", expected: "Omit<IAutoBeRealizeCoderApplication.RealizeCoderOutput, \"filename\">", value: input.output })) && _vo1(input.output, _path + ".output", true && _exceptionable) || _report(_exceptionable, { path: _path + ".output", expected: "Omit<IAutoBeRealizeCoderApplication.RealizeCoderOutput, \"filename\">", value: input.output })].every(flag => flag); const _vo1 = (input, _path, _exceptionable = true) => [undefined === input.errorAnalysis || "string" === typeof input.errorAnalysis || _report(_exceptionable, { path: _path + ".errorAnalysis", expected: "(string | undefined)", value: input.errorAnalysis }), "string" === typeof input.plan || _report(_exceptionable, { path: _path + ".plan", expected: "string", value: input.plan }), "string" === typeof input.prisma_schemas || _report(_exceptionable, { path: _path + ".prisma_schemas", expected: "string", value: input.prisma_schemas }), "string" === typeof input.draft_without_date_type || _report(_exceptionable, { path: _path + ".draft_without_date_type", expected: "string", value: input.draft_without_date_type }), "string" === typeof input.review || _report(_exceptionable, { path: _path + ".review", expected: "string", value: input.review }), "string" === typeof input.withCompilerFeedback || _report(_exceptionable, { path: _path + ".withCompilerFeedback", expected: "string", value: input.withCompilerFeedback }), "string" === typeof input.implementationCode || _report(_exceptionable, { path: _path + ".implementationCode", expected: "string", value: input.implementationCode })].every(flag => flag); const __is = input => "object" === typeof input && null !== input && _io0(input); let errors; let _report; return input => { if (false === __is(input)) { errors = []; _report = __typia_transform__validateReport._validateReport(errors); ((input, _path, _exceptionable = true) => ("object" === typeof input && null !== input || _report(true, { path: _path + "", expected: "IAutoBeRealizeCoderApplication.IProps", value: input })) && _vo0(input, _path + "", true) || _report(true, { path: _path + "", expected: "IAutoBeRealizeCoderApplication.IProps", value: input }))(input, "$input", true); const success = 0 === errors.length; return success ? { success, data: input } : { success, errors, data: input }; } return { success: true, data: input }; }; })() } ] }, claude, llama: claude, deepseek: claude, "3.1": claude, }; //# sourceMappingURL=orchestrateRealizeCoder.js.map