@autobe/agent
Version:
AI backend server code generator
374 lines • 22.1 kB
JavaScript
;
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.orchestrateTestOperationWrite = orchestrateTestOperationWrite;
const __typia_transform__validateReport = __importStar(require("typia/lib/internal/_validateReport"));
const __typia_transform__llmApplicationFinalize = __importStar(require("typia/lib/internal/_llmApplicationFinalize"));
const utils_1 = require("@typia/utils");
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 validateEmptyCode_1 = require("../../utils/validateEmptyCode");
const getTestArtifacts_1 = require("./compile/getTestArtifacts");
const transformTestOperationWriteHistory_1 = require("./histories/transformTestOperationWriteHistory");
const AutoBeTestOperationProgrammer_1 = require("./programmers/AutoBeTestOperationProgrammer");
function orchestrateTestOperationWrite(ctx, props) {
return __awaiter(this, void 0, void 0, function* () {
const result = yield (0, executeCachedBatch_1.executeCachedBatch)(ctx,
/**
* Generate test code for each scenario. Maps through plans array to
* create individual test code implementations. Each scenario is processed
* to generate corresponding test code and progress events.
*/
props.scenarios.map((scenario) => (promptCacheKey) => __awaiter(this, void 0, void 0, function* () {
const artifacts = yield (0, getTestArtifacts_1.getTestScenarioArtifacts)(ctx, scenario);
const usedActors = new Set(artifacts.document.operations
.map((o) => o.authorizationActor)
.filter((a) => a !== null));
const authorizationFunctions = props.authorizes.filter((f) => usedActors.has(f.actor));
const generationFunctions = props.generates.filter((f) => artifacts.document.operations.some((o) => o.method === f.endpoint.method && o.path === f.endpoint.path));
const prepareFunctions = props.prepares.filter((f) => Object.keys(artifacts.document.components.schemas).includes(f.typeName));
const counter = new tstl_1.Singleton(() => ++props.progress.completed);
try {
return yield (0, forceRetry_1.forceRetry)(() => __awaiter(this, void 0, void 0, function* () {
const event = yield process(ctx, {
document: props.document,
scenario,
authorizes: authorizationFunctions,
generates: generationFunctions,
prepares: prepareFunctions,
artifacts,
progress: props.progress,
counter,
promptCacheKey,
instruction: props.instruction,
});
ctx.dispatch(event);
if (event.function.type !== "operation")
throw new Error(`Unexpected testOperationWrite function kind: ${event.function.type}`);
return {
type: "operation",
artifacts,
function: event.function,
authorizes: authorizationFunctions,
generates: generationFunctions,
prepares: prepareFunctions,
};
}));
}
catch (_a) {
counter.get();
return null;
}
})));
return result.filter((r) => r !== null);
});
}
function process(ctx, props) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c;
const pointer = {
value: null,
};
const { metric, tokenUsage } = yield ctx.conversate(Object.assign({ source: "testWrite", controller: createController({
functionName: props.scenario.functionName,
build: (next) => {
next.domain = utils_1.NamingConvention.snake(next.domain);
pointer.value = next;
},
}), enforceFunctionCall: true, promptCacheKey: props.promptCacheKey }, (yield (0, transformTestOperationWriteHistory_1.transformTestOperationWriteHistory)(ctx, {
authorizationFunctions: props.authorizes,
generationFunctions: props.generates,
scenario: props.scenario,
artifacts: props.artifacts,
instruction: props.instruction,
}))));
if (pointer.value === null) {
props.counter.get();
throw new Error("Failed to create test code.");
}
const location = `test/features/api/${pointer.value.domain}/${props.scenario.functionName}.ts`;
return {
type: "testWrite",
id: (0, uuid_1.v7)(),
created_at: new Date().toISOString(),
function: {
type: "operation",
domain: pointer.value.domain,
scenario: props.scenario,
name: props.scenario.functionName,
location,
content: yield AutoBeTestOperationProgrammer_1.AutoBeTestOperationProgrammer.replaceImportStatements({
compiler: yield ctx.compiler(),
artifacts: props.artifacts,
authorizes: props.authorizes,
prepares: props.prepares,
generates: props.generates,
location,
content: (_a = pointer.value.revise.final) !== null && _a !== void 0 ? _a : pointer.value.draft,
}),
},
metric,
tokenUsage,
completed: props.counter.get(),
total: props.progress.total,
step: (_c = (_b = ctx.state().interface) === null || _b === void 0 ? void 0 : _b.step) !== null && _c !== void 0 ? _c : 0,
};
});
}
function createController(props) {
const validate = (input) => {
const result = (() => { const _io0 = input => "string" === typeof input.scenario && "string" === typeof input.domain && "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.scenario || _report(_exceptionable, {
path: _path + ".scenario",
expected: "string",
value: input.scenario
}), "string" === typeof input.domain || _report(_exceptionable, {
path: _path + ".domain",
expected: "string",
value: input.domain
}), "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: "IAutoBeTestOperationWriteApplication.IReviseProps",
value: input.revise
})) && _vo1(input.revise, _path + ".revise", true && _exceptionable) || _report(_exceptionable, {
path: _path + ".revise",
expected: "IAutoBeTestOperationWriteApplication.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: "IAutoBeTestOperationWriteApplication.IProps",
value: input
})) && _vo0(input, _path + "", true) || _report(true, {
path: _path + "",
expected: "IAutoBeTestOperationWriteApplication.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;
const errors = (0, validateEmptyCode_1.validateEmptyCode)({
name: props.functionName,
draft: result.data.draft,
revise: result.data.revise,
asynchronous: true,
path: "$input",
});
return errors.length
? {
success: false,
errors,
data: result.data,
}
: result;
};
const application = __typia_transform__llmApplicationFinalize._llmApplicationFinalize({
functions: [
{
name: "write",
parameters: {
description: "Current Type: {@link IAutoBeTestOperationWriteApplication.IProps}",
type: "object",
properties: {
scenario: {
description: "Step 1: Strategic test planning and scenario analysis.\n\nAI analyzes the given test scenario and creates a comprehensive\nimplementation strategy. This planning phase is crucial for generating\nwell-structured, maintainable test code. The AI must define test\nmethodology, data preparation, execution flow, and validation logic\nbefore proceeding to code implementation.\n\nWorkflow: Input scenario \u2192 Strategic analysis \u2192 Detailed test plan",
type: "string"
},
domain: {
description: "Step 2: Functional domain classification for test organization.\n\nAI determines the appropriate domain category based on the scenario\nanalysis. This classification drives file structure, test categorization,\nand logical grouping. The domain must be a single, lowercase word in\nsnake_case format that represents the primary API resource.\n\nWorkflow: Scenario analysis \u2192 Domain identification \u2192 Test organization\nstructure",
type: "string"
},
draft: {
description: "Step 3: Initial TypeScript E2E test code implementation.\n\nAI generates the first working version of the test code based on the\nstrategic plan. This draft must be compilation-error-free and follow",
type: "string"
},
revise: {
description: "Steps 4-5: Code review and final refinement process.\n\nContains the iterative improvement workflow that transforms the initial\ndraft into production-ready test code. The review phase identifies issues\nto fix or code to delete, followed by the final phase that produces the\npolished, production-ready test implementation.\n\nWorkflow: Draft \u2192 Review analysis \u2192 Final implementation",
$ref: "#/$defs/IAutoBeTestOperationWriteApplication.IReviseProps"
}
},
required: [
"scenario",
"domain",
"draft",
"revise"
],
additionalProperties: false,
$defs: {
"IAutoBeTestOperationWriteApplication.IReviseProps": {
type: "object",
properties: {
review: {
description: "Step 4: Code review and quality assessment.\n\n**\uD83D\uDEA8 TWO TYPES OF REVISIONS: FIX AND DELETE \uD83D\uDEA8**\n\nAI performs a thorough review of the draft implementation for:\n\n**1. FIX - Improve existing code:**\n\n**Compilation & Syntax:**\n\n- TypeScript compilation errors and type mismatches\n- Syntax errors and missing semicolons/brackets\n- Correct function signatures and parameter types\n\n**Framework Compliance:**\n\n-",
type: "string"
},
final: {
description: "Step 5: Final production-ready test code.\n\nAI produces the final, polished version of the test code incorporating\nall review feedback. This code represents the completed test\nimplementation, ready for production deployment. When the draft code is\nalready perfect with no issues found during review, this value can be\nnull, indicating no revisions were necessary.\n\n**\uD83D\uDEA8 CRITICAL: APPLY ALL FIXES AND DELETIONS FROM REVIEW \uD83D\uDEA8**\n\n- FIX all correctable issues identified in review\n- DELETE all prohibited code identified in review\n- If review found type error tests, they MUST be deleted in final\n- If review found code to DELETE, final MUST be different from draft\n- If review finds NO issues requiring changes, set to null\n\nAll identified issues must be resolved, and the code must meet the\nhighest quality standards. A null value indicates the draft code already\nmeets all requirements without modification.\n\nWorkflow: Review feedback \u2192 Apply FIXES \u2192 Apply DELETIONS \u2192\nProduction-ready implementation (or null if no changes needed)\n\nThis is the ultimate deliverable that will be used in the actual test\nsuite when provided, otherwise the draft is used as-is.",
anyOf: [
{
type: "null"
},
{
type: "string"
}
]
}
},
required: [
"review",
"final"
]
}
}
},
description: "Main entry point for AI Function Call - generates complete E2E test code.\n\nThe AI executes this function to perform the entire test generation\nworkflow: scenario analysis \u2192 draft implementation \u2192 code review \u2192 final\ncode production. This structured approach ensures high-quality,\ncompilation-error-free test code.",
validate: (() => { const _io0 = input => "string" === typeof input.scenario && "string" === typeof input.domain && "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.scenario || _report(_exceptionable, {
path: _path + ".scenario",
expected: "string",
value: input.scenario
}), "string" === typeof input.domain || _report(_exceptionable, {
path: _path + ".domain",
expected: "string",
value: input.domain
}), "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: "IAutoBeTestOperationWriteApplication.IReviseProps",
value: input.revise
})) && _vo1(input.revise, _path + ".revise", true && _exceptionable) || _report(_exceptionable, {
path: _path + ".revise",
expected: "IAutoBeTestOperationWriteApplication.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: "IAutoBeTestOperationWriteApplication.IProps",
value: input
})) && _vo0(input, _path + "", true) || _report(true, {
path: _path + "",
expected: "IAutoBeTestOperationWriteApplication.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
};
}; })()
}
]
}, {
validate: {
write: validate,
},
});
return {
protocol: "class",
name: "Create Test Code",
application,
execute: {
write: (next) => {
props.build(next);
},
},
};
}
//# sourceMappingURL=orchestrateTestOperationWrite.js.map