UNPKG

@autobe/agent

Version:

AI backend server code generator

422 lines 23.3 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.orchestrateTestAuthorizeWrite = void 0; const __typia_transform__validateReport = __importStar(require("typia/lib/internal/_validateReport")); const __typia_transform__llmApplicationFinalize = __importStar(require("typia/lib/internal/_llmApplicationFinalize")); const utils_1 = require("@autobe/utils"); const tstl_1 = require("tstl"); const typia_1 = __importDefault(require("typia")); const uuid_1 = require("uuid"); const AutoBeTokenUsageComponent_1 = require("../../context/AutoBeTokenUsageComponent"); 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 transformTestAuthorizeWriteHistory_1 = require("./histories/transformTestAuthorizeWriteHistory"); const AutoBeTestAuthorizeProgrammer_1 = require("./programmers/AutoBeTestAuthorizeProgrammer"); /** * Test Authorization Write Orchestrator * * Creates authorization utility functions for test scenarios using LLM to * generate proper authentication handling code. */ const orchestrateTestAuthorizeWrite = (ctx, props) => __awaiter(void 0, void 0, void 0, function* () { const authOperations = props.document.operations.filter((op) => { var _a; return op.authorizationActor !== null && op.authorizationType !== null && op.parameters.length === 0 && op.requestBody !== null && op.responseBody !== null && utils_1.AutoBeOpenApiTypeChecker.isObject((_a = props.document.components.schemas[op.requestBody.typeName]) !== null && _a !== void 0 ? _a : {}); }); return yield (0, executeCachedBatch_1.executeCachedBatch)(ctx, authOperations.map((operation) => (promptCacheKey) => __awaiter(void 0, void 0, void 0, function* () { const artifacts = yield (0, getTestArtifacts_1.getTestArtifacts)(ctx, { endpoint: { method: operation.method, path: operation.path, }, }); const counter = new tstl_1.Singleton(() => ++props.progress.completed); let event; try { event = operation.authorizationType === "join" ? yield (0, forceRetry_1.forceRetry)(() => process(ctx, { operation, artifacts, progress: props.progress, counter, promptCacheKey, })) : yield write(ctx, { document: props.document, progress: props.progress, counter, artifacts, operation, }); } catch (error) { counter.get(); throw error; } ctx.dispatch(event); return { type: "authorize", artifacts, function: event.function, operation, }; }))); }); exports.orchestrateTestAuthorizeWrite = orchestrateTestAuthorizeWrite; function write(ctx, props) { return __awaiter(this, void 0, void 0, function* () { var _a, _b, _c, _d; const schema = props.document.components.schemas[(_b = (_a = props.operation.requestBody) === null || _a === void 0 ? void 0 : _a.typeName) !== null && _b !== void 0 ? _b : ""]; if (schema === undefined || utils_1.AutoBeOpenApiTypeChecker.isObject(schema) === false) throw new Error("Authorization operation needs object request body."); else if (props.operation.authorizationActor === null) throw new Error("Operation is not an authorization operation."); const functionName = AutoBeTestAuthorizeProgrammer_1.AutoBeTestAuthorizeProgrammer.getFunctionName(props.operation); const content = AutoBeTestAuthorizeProgrammer_1.AutoBeTestAuthorizeProgrammer.writeTemplate({ operation: props.operation, schema, }); const authorizationFunction = { type: "authorize", endpoint: { method: props.operation.method, path: props.operation.path, }, actor: props.operation.authorizationActor, authType: props.operation.authorizationType, location: `test/authorize/${functionName}.ts`, name: functionName, content: yield AutoBeTestAuthorizeProgrammer_1.AutoBeTestAuthorizeProgrammer.replaceImportStatements({ compiler: yield ctx.compiler(), artifacts: props.artifacts, content, }), }; return { type: "testWrite", id: (0, uuid_1.v7)(), created_at: new Date().toISOString(), function: authorizationFunction, metric: utils_1.AutoBeFunctionCallingMetricFactory.create(), tokenUsage: new AutoBeTokenUsageComponent_1.AutoBeTokenUsageComponent(), completed: props.counter.get(), total: props.progress.total, step: (_d = (_c = ctx.state().interface) === null || _c === void 0 ? void 0 : _c.step) !== null && _d !== void 0 ? _d : 0, }; }); } 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({ operation: props.operation, build: (next) => { pointer.value = next; }, }), enforceFunctionCall: true, promptCacheKey: props.promptCacheKey }, (yield (0, transformTestAuthorizeWriteHistory_1.transformTestAuthorizeWriteHistory)(ctx, { operation: props.operation, artifacts: props.artifacts, })))); if (pointer.value === null) { props.counter.get(); throw new Error("Failed to create authorization function."); } // Create the authorize function const functionName = AutoBeTestAuthorizeProgrammer_1.AutoBeTestAuthorizeProgrammer.getFunctionName(props.operation); const authorizationFunction = { type: "authorize", endpoint: { method: props.operation.method, path: props.operation.path, }, actor: pointer.value.actor, authType: props.operation.authorizationType, location: `test/authorize/${functionName}.ts`, name: functionName, content: yield AutoBeTestAuthorizeProgrammer_1.AutoBeTestAuthorizeProgrammer.replaceImportStatements({ compiler: yield ctx.compiler(), artifacts: props.artifacts, content: (_a = pointer.value.revise.final) !== null && _a !== void 0 ? _a : pointer.value.draft, }), }; return { type: "testWrite", id: (0, uuid_1.v7)(), created_at: new Date().toISOString(), function: authorizationFunction, 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.think && "string" === typeof input.actor && "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.actor || _report(_exceptionable, { path: _path + ".actor", expected: "string", value: input.actor }), "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: "IAutoBeTestAuthorizationWriteApplication.IReviseProps", value: input.revise })) && _vo1(input.revise, _path + ".revise", true && _exceptionable) || _report(_exceptionable, { path: _path + ".revise", expected: "IAutoBeTestAuthorizationWriteApplication.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: "IAutoBeTestAuthorizationWriteApplication.IProps", value: input })) && _vo0(input, _path + "", true) || _report(true, { path: _path + "", expected: "IAutoBeTestAuthorizationWriteApplication.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 functionName = AutoBeTestAuthorizeProgrammer_1.AutoBeTestAuthorizeProgrammer.getFunctionName(props.operation); const errors = (0, validateEmptyCode_1.validateEmptyCode)({ name: functionName, draft: result.data.draft, revise: result.data.revise, path: "$input", asynchronous: true, }); return errors.length ? { success: false, errors, data: result.data, } : result; }; const application = __typia_transform__llmApplicationFinalize._llmApplicationFinalize({ functions: [ { name: "write", parameters: { description: "Current Type: {@link IAutoBeTestAuthorizationWriteApplication.IProps}", type: "object", properties: { think: { description: "Step 1: Strategic authorization analysis.\n\nAI analyzes the operation to understand authorization requirements,\nincluding the type of authentication flow, actor permissions, and\nrequired SDK functions. This analysis forms the foundation for generating\nappropriate authorization utilities.\n\nWorkflow: Operation analysis \u2192 Authorization strategy \u2192 Implementation\nplan", type: "string" }, actor: { description: "Step 2: Actor identification.\n\nAI determines the actor (user type) for this authorization function. This\nshould be extracted from the context, such as the API path or operation\ndetails.\n\nExamples: \"user\", \"admin\", \"moderator\", \"seller\", \"customer\"", type: "string" }, draft: { description: "Step 4: Initial authorization function implementation.\n\nAI generates the authorization utility function that properly handles the\nauthentication flow. The implementation must use correct SDK functions,\nreturn required authentication data, and include comprehensive error\nhandling with fallback logic where needed.\n\nCritical: NO import statements, start directly with 'export async\nfunction'", type: "string" }, revise: { description: "Steps 5-6: Code review and final refinement process.\n\nContains the iterative improvement workflow that transforms the initial\ndraft into production-ready authorization code. The review phase\nidentifies issues to fix, followed by the final phase that produces the\npolished implementation ready for use in test scenarios.\n\nWorkflow: Draft \u2192 Review analysis \u2192 Final implementation", $ref: "#/$defs/IAutoBeTestAuthorizationWriteApplication.IReviseProps" } }, required: [ "think", "actor", "draft", "revise" ], additionalProperties: false, $defs: { "IAutoBeTestAuthorizationWriteApplication.IReviseProps": { type: "object", properties: { review: { description: "Step 5: Code review and quality assessment.\n\nAI performs a thorough review of the draft implementation, checking for:\n\n**Technical Correctness:**\n\n- Proper SDK function usage and parameter types\n- Appropriate return types and data structures\n- TypeScript compilation compatibility\n\n**Authorization Logic:**\n\n- Proper handling of authentication flows\n- Correct token/session management\n- Appropriate error handling and fallback strategies\n- Security best practices\n\n**Code Quality:**\n\n- Clear variable naming and code organization\n- Comprehensive error messages\n- Proper async/await usage\n- Type safety without any/unknown usage\n\nThe review must provide specific, actionable feedback for improvements.", type: "string" }, final: { description: "Step 6: Final production-ready authorization function.\n\nAI produces the final version incorporating all review feedback. This\nrepresents the completed authorization utility ready for use in test\nscenarios. When the draft is already perfect with no issues found during\nreview, this value can be null.\n\nAll identified issues must be resolved, and the code must meet production\nquality standards for test utilities.\n\nWorkflow: Review feedback \u2192 Apply improvements \u2192 Production-ready code\n(or null if no changes needed)", anyOf: [ { type: "null" }, { type: "string" } ] } }, required: [ "review", "final" ] } } }, description: "Main entry point for AI Function Call - generates authorization utility\nfunctions.\n\nThe AI executes this function to generate authorization functions that\nhandle authentication flows (login, join, refresh, etc.) for different\nactor types. This structured approach ensures consistent authentication\nhandling across the test suite.", validate: (() => { const _io0 = input => "string" === typeof input.think && "string" === typeof input.actor && "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.actor || _report(_exceptionable, { path: _path + ".actor", expected: "string", value: input.actor }), "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: "IAutoBeTestAuthorizationWriteApplication.IReviseProps", value: input.revise })) && _vo1(input.revise, _path + ".revise", true && _exceptionable) || _report(_exceptionable, { path: _path + ".revise", expected: "IAutoBeTestAuthorizationWriteApplication.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: "IAutoBeTestAuthorizationWriteApplication.IProps", value: input })) && _vo0(input, _path + "", true) || _report(true, { path: _path + "", expected: "IAutoBeTestAuthorizationWriteApplication.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: "TestAuthorizationWrite", application, execute: { write: (next) => { props.build(next); }, }, }; } //# sourceMappingURL=orchestrateTestAuthorizeWrite.js.map