UNPKG

@autobe/agent

Version:

AI backend server code generator

510 lines 23.5 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.orchestrateRealizeCorrectCasting = void 0; const __typia_transform__validateReport = __importStar(require("typia/lib/internal/_validateReport")); const __typia_transform__llmApplicationFinalize = __importStar(require("typia/lib/internal/_llmApplicationFinalize")); const tstl_1 = require("tstl"); const typia_1 = __importDefault(require("typia")); const uuid_1 = require("uuid"); const executeCachedBatch_1 = require("../../../utils/executeCachedBatch"); const forceRetry_1 = require("../../../utils/forceRetry"); const transformRealizeCorrectCastingHistory_1 = require("../histories/transformRealizeCorrectCastingHistory"); const compileRealizeFiles_1 = require("../programmers/compileRealizeFiles"); const orchestrateRealizeCorrectCasting = (ctx_1, props_1, ...args_1) => __awaiter(void 0, [ctx_1, props_1, ...args_1], void 0, function* (ctx, props, life = 4 /* AutoBeConfigConstant.COMPILER_RETRY */) { const validateEvent = yield compileWithFiltering(ctx, { functions: props.functions, programmer: props.programmer, progress: props.progress, }); return predicate(ctx, { programmer: props.programmer, functions: props.functions, previousFailures: [], progress: props.progress, event: validateEvent, }, life); }); exports.orchestrateRealizeCorrectCasting = orchestrateRealizeCorrectCasting; const predicate = (ctx, props, life) => __awaiter(void 0, void 0, void 0, function* () { if (props.event.result.type === "failure") { ctx.dispatch(props.event); return yield correct(ctx, props, life); } return props.functions; }); const correct = (ctx, props, life) => __awaiter(void 0, void 0, void 0, function* () { // Early returns for non-correctable cases if (props.event.result.type !== "failure" || life < 0) { return props.functions; } const failure = props.event.result; const errorLocations = getErrorFiles({ location: props.programmer.location, failure, }).filter((l) => props.functions.map((f) => f.location).includes(l)); // If no locations to correct, return original functions if (errorLocations.length === 0) { return props.functions; } props.progress.total += errorLocations.length; const converted = yield (0, executeCachedBatch_1.executeCachedBatch)(ctx, errorLocations.map((location) => () => __awaiter(void 0, void 0, void 0, function* () { const counter = new tstl_1.Singleton(() => ++props.progress.completed); const localFunction = props.functions.find((f) => f.location === location); const localPreviousFailures = props.previousFailures .map((pf) => { var _a; return (_a = pf.find((f) => f.function.location === localFunction.location)) !== null && _a !== void 0 ? _a : null; }) .filter((x) => x !== null); const localDiagnostics = failure.diagnostics.filter((d) => d.file === localFunction.location); try { return yield (0, forceRetry_1.forceRetry)(() => process(ctx, { programmer: props.programmer, function: localFunction, previousFailures: localPreviousFailures, diagnostic: localDiagnostics, progress: props.progress, })); } catch (error) { console.log("realizeCorrectCasting", localFunction.location, error); counter.get(); return { type: "exception", function: localFunction, }; } }))); // Get functions that were not modified (not in locations array) const unchangedFunctions = props.functions.filter((f) => !errorLocations.includes(f.location)); // Merge converted functions with unchanged functions for validation const allFunctionsForValidation = [ ...converted.map((c) => c.function), ...unchangedFunctions, ]; const newValidate = yield compileWithFiltering(ctx, { functions: allFunctionsForValidation, programmer: props.programmer, progress: props.progress, }); const newResult = newValidate.result; if (newResult.type === "success") { return allFunctionsForValidation; } else if (newResult.type === "exception") { // Compilation exception, return current functions. because retrying won't help. return props.functions; } const newLocations = newValidate.result.type === "failure" ? getErrorFiles({ failure: newValidate.result, location: props.programmer.location, }) : []; // Separate successful, failed, and ignored corrections const { success, failed, ignored } = separateCorrectionResults(converted, newLocations); // If no failures to retry, return all functions if (failed.length === 0) { return [...success, ...ignored, ...unchangedFunctions]; } // Recursively retry failed functions const retriedFunctions = yield predicate(ctx, { programmer: props.programmer, functions: failed, previousFailures: [ ...props.previousFailures, failed.map((f) => ({ function: f, diagnostics: newValidate.result.type === "failure" ? newValidate.result.diagnostics.filter((d) => d.file === f.location) : [], })), ], progress: props.progress, event: newValidate, }, life - 1); return [...success, ...ignored, ...retriedFunctions, ...unchangedFunctions]; }); const process = (ctx, props) => __awaiter(void 0, void 0, void 0, function* () { var _a, _b, _c; const template = props.programmer.template(props.function); const pointer = { value: null, }; const { metric, tokenUsage } = yield ctx.conversate(Object.assign({ source: "realizeCorrect", controller: createController({ then: (next) => { pointer.value = next; }, reject: () => { pointer.value = false; }, }), enforceFunctionCall: true }, (0, transformRealizeCorrectCastingHistory_1.transformRealizeCorrectCastingHistory)({ template, function: props.function, failures: [ ...props.previousFailures, { function: props.function, diagnostics: props.diagnostic, }, ], }))); if (pointer.value === null) return { type: "exception", function: props.function, }; else if (pointer.value === false) return { type: "ignore", function: props.function, }; const content = yield props.programmer.replaceImportStatements({ function: props.function, code: (_a = pointer.value.revise.final) !== null && _a !== void 0 ? _a : pointer.value.draft, }); const corrected = Object.assign(Object.assign({}, props.function), { content, template }); ctx.dispatch({ id: (0, uuid_1.v7)(), type: "realizeCorrect", kind: "casting", function: corrected, created_at: new Date().toISOString(), step: (_c = (_b = ctx.state().analyze) === null || _b === void 0 ? void 0 : _b.step) !== null && _c !== void 0 ? _c : 0, metric, tokenUsage, }); return { type: "success", function: corrected, }; }); const createController = (props) => { const validate = (input) => { const result = (() => { const _io0 = input => "string" === typeof input.think && "string" === typeof input.draft && ("object" === typeof input.revise && null !== input.revise && _io1(input.revise)); const _io1 = input => "string" === typeof input.review && (null === input.final || "string" === typeof input.final); const _vo0 = (input, _path, _exceptionable = true) => ["string" === typeof input.think || _report(_exceptionable, { path: _path + ".think", expected: "string", value: input.think }), "string" === typeof input.draft || _report(_exceptionable, { path: _path + ".draft", expected: "string", value: input.draft }), ("object" === typeof input.revise && null !== input.revise || _report(_exceptionable, { path: _path + ".revise", expected: "IAutoBeCommonCorrectCastingApplication.IReviseProps", value: input.revise })) && _vo1(input.revise, _path + ".revise", true && _exceptionable) || _report(_exceptionable, { path: _path + ".revise", expected: "IAutoBeCommonCorrectCastingApplication.IReviseProps", value: input.revise })].every(flag => flag); const _vo1 = (input, _path, _exceptionable = true) => ["string" === typeof input.review || _report(_exceptionable, { path: _path + ".review", expected: "string", value: input.review }), null === input.final || "string" === typeof input.final || _report(_exceptionable, { path: _path + ".final", expected: "(null | string)", value: input.final })].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: "IAutoBeCommonCorrectCastingApplication.IProps", value: input })) && _vo0(input, _path + "", true) || _report(true, { path: _path + "", expected: "IAutoBeCommonCorrectCastingApplication.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 }; }; })()(input); if (result.success === false) return result; // @todo: validate empty code? return result; }; const application = __typia_transform__llmApplicationFinalize._llmApplicationFinalize({ functions: [ { name: "rewrite", parameters: { description: "Current Type: {@link IAutoBeCommonCorrectCastingApplication.IProps}", type: "object", properties: { think: { description: "Analysis of the error pattern and chosen fix strategy.", type: "string" }, draft: { description: "Draft code with initial syntax/type fixes applied.", type: "string" }, revise: { description: "Self-review pass that checks corrections and produces final code.", $ref: "#/$defs/IAutoBeCommonCorrectCastingApplication.IReviseProps" } }, required: [ "think", "draft", "revise" ], additionalProperties: false, $defs: { "IAutoBeCommonCorrectCastingApplication.IReviseProps": { type: "object", properties: { review: { description: "Review of correction patterns applied and confirmation all errors\nresolved.", type: "string" }, final: { description: "Final corrected code, or `null` when draft already resolves all issues.", anyOf: [ { type: "null" }, { type: "string" } ] } }, required: [ "review", "final" ] } } }, description: "Rewrite code to fix severe syntax structure or type system errors.", validate: (() => { const _io0 = input => "string" === typeof input.think && "string" === typeof input.draft && ("object" === typeof input.revise && null !== input.revise && _io1(input.revise)); const _io1 = input => "string" === typeof input.review && (null === input.final || "string" === typeof input.final); const _vo0 = (input, _path, _exceptionable = true) => ["string" === typeof input.think || _report(_exceptionable, { path: _path + ".think", expected: "string", value: input.think }), "string" === typeof input.draft || _report(_exceptionable, { path: _path + ".draft", expected: "string", value: input.draft }), ("object" === typeof input.revise && null !== input.revise || _report(_exceptionable, { path: _path + ".revise", expected: "IAutoBeCommonCorrectCastingApplication.IReviseProps", value: input.revise })) && _vo1(input.revise, _path + ".revise", true && _exceptionable) || _report(_exceptionable, { path: _path + ".revise", expected: "IAutoBeCommonCorrectCastingApplication.IReviseProps", value: input.revise })].every(flag => flag); const _vo1 = (input, _path, _exceptionable = true) => ["string" === typeof input.review || _report(_exceptionable, { path: _path + ".review", expected: "string", value: input.review }), null === input.final || "string" === typeof input.final || _report(_exceptionable, { path: _path + ".final", expected: "(null | string)", value: input.final })].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: "IAutoBeCommonCorrectCastingApplication.IProps", value: input })) && _vo0(input, _path + "", true) || _report(true, { path: _path + "", expected: "IAutoBeCommonCorrectCastingApplication.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 }; }; })() }, { name: "reject", parameters: { type: "object", properties: {}, additionalProperties: false, required: [], $defs: {} }, description: "Reject when error is outside scope (handled by subsequent agents).", validate: (() => { const __is = input => true; let errors; let _report; return input => { if (false === __is(input)) { errors = []; _report = __typia_transform__validateReport._validateReport(errors); ((input, _path, _exceptionable = true) => true)(input, "$input", true); const success = 0 === errors.length; return success ? { success, data: input } : { success, errors, data: input }; } return { success: true, data: input }; }; })() } ] }, { validate: { rewrite: validate, reject: () => ({ success: true, data: undefined, }), }, }); return { protocol: "class", name: "correctInvalidRequest", application, execute: { rewrite: (next) => { props.then(next); }, reject: () => { props.reject(); }, }, }; }; /** * Extract unique file locations from validation event diagnostics * * @param event - Validation event containing compilation results * @returns Array of unique file paths that have errors */ const getErrorFiles = (props) => { const diagnostics = props.failure.diagnostics; const locations = diagnostics .map((d) => d.file) .filter((f) => f !== null) .filter((f) => f.startsWith(props.location)); return Array.from(new Set(locations)); }; const compileWithFiltering = (ctx, props) => __awaiter(void 0, void 0, void 0, function* () { const compiled = yield (0, compileRealizeFiles_1.compileRealizeFiles)(ctx, { functions: props.functions, additional: props.programmer.additional(props.functions), progress: (result) => { if (result.type === "success") props.progress.completed = props.functions.length; else if (result.type === "failure") props.progress.completed = props.progress.total - new Set(result.diagnostics .map((d) => d.file) .filter((f) => f !== null) .filter((x) => !!props.functions.find((y) => y.location === x))).size; return props.progress; }, }); if (compiled.result.type !== "failure") { return compiled; } const functionLocations = props.functions.map((f) => f.location); compiled.result.diagnostics = compiled.result.diagnostics.filter((d) => d.file !== null && functionLocations.includes(d.file)); if (compiled.result.diagnostics.length === 0) { compiled.result = { type: "success" }; } return compiled; }); /** * Separate correction results into successful, failed, and ignored functions * * @param corrections - Array of correction results * @param errorLocations - File paths that still have errors * @returns Object with success, failed, and ignored function arrays */ const separateCorrectionResults = (corrections, errorLocations) => { const success = corrections .filter((c) => c.type === "success" && !errorLocations.includes(c.function.location)) .map((c) => c.function); const failed = corrections .filter((c) => c.type === "success" && errorLocations.includes(c.function.location)) .map((c) => c.function); const ignored = corrections .filter((c) => c.type === "ignore" || c.type === "exception") .map((c) => c.function); return { success, failed, ignored }; }; //# sourceMappingURL=orchestrateRealizeCorrectCasting.js.map