UNPKG

@2501-ai/cli

Version:

[![npm version](https://img.shields.io/npm/v/@2501-ai/cli.svg)](https://www.npmjs.com/package/@2501-ai/cli) [![HumanEval Score](https://img.shields.io/badge/HumanEval-96.95%25-brightgreen.svg)](https://www.2501.ai/research/full-humaneval-benchmark) [![Lic

234 lines (233 loc) 10.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 (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __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.queryCommand = void 0; const chalk_1 = __importDefault(require("chalk")); const fs_1 = __importDefault(require("fs")); const marked_1 = require("marked"); const marked_terminal_1 = require("marked-terminal"); const api_1 = require("../helpers/api"); const streams_1 = require("../helpers/streams"); const workspace_1 = require("../helpers/workspace"); const agentManager_1 = require("../managers/agentManager"); const actions_1 = require("../utils/actions"); const conf_1 = require("../utils/conf"); const credentials_1 = require("../utils/credentials"); const files_1 = require("../utils/files"); const logger_1 = __importStar(require("../utils/logger")); const loopDetection_1 = require("../utils/loopDetection"); const tree_1 = require("../utils/tree"); const init_1 = require("./init"); marked_1.marked.use((0, marked_terminal_1.markedTerminal)()); const logger = new logger_1.default(); const initializeAgentConfig = (workspace, skipWarmup) => __awaiter(void 0, void 0, void 0, function* () { let eligible = (0, conf_1.getEligibleAgent)(workspace); let force = false; if (!eligible && !skipWarmup) { yield (0, init_1.initCommand)({ workspace }); eligible = (0, conf_1.getEligibleAgent)(workspace); force = true; } if (eligible && !skipWarmup) { yield synchronizeWorkspace(eligible.id, workspace, force); } return eligible; }); const executeActions = (actions, agentManager) => __awaiter(void 0, void 0, void 0, function* () { const results = []; for (const action of actions) { logger_1.default.debug('Action:', action); const args = (0, actions_1.getFunctionArgs)(action); if (args.command) { args.command = credentials_1.credentialsService.replaceCredentialPlaceholders(args.command); } const taskTitle = args.answer || args.command || (args.url ? `Browsing: ${args.url}` : ''); logger.start(`${taskTitle} ${(0, streams_1.getActionPostfix)(action)}`); const toolOutput = yield agentManager.executeAction(action, args); logger_1.default.debug('Tool output:', toolOutput); const subActionMessage = (0, streams_1.getSubActionMessage)(taskTitle, action, toolOutput.success); toolOutput.success ? logger.stop(subActionMessage, 0) : logger.stop(`(failed) ${subActionMessage}`, 1); results.push(toolOutput); } return results; }); const synchronizeWorkspace = (agentId, workspace, force = false) => __awaiter(void 0, void 0, void 0, function* () { logger_1.default.debug('Synchronizing workspace:', workspace); const { currentState, diff: workspaceDiff } = yield (0, workspace_1.getWorkspaceState)(workspace, agentId); logger_1.default.debug('Workspace diff:', { workspaceDiff }); if (workspaceDiff.isEmpty) return false; if (workspaceDiff.hasChanges || force) { logger.start('Synchronizing workspace'); logger_1.default.debug('Agent Workspace has changes, synchronizing...'); const files = yield (0, workspace_1.generateWorkspaceZip)(workspace, { fileHashes: currentState.fileHashes, totalSize: currentState.totalSize, }); if (process.env.TFZO_NODE_ENV !== 'dev') { fs_1.default.unlinkSync(files[0].path); logger_1.default.debug('Agent : Workspace ZIP deleted:', files[0].path); } yield (0, api_1.indexFiles)(agentId, files); const newState = { state_hash: currentState.md5, file_hashes: currentState.fileHashes, path: workspace, agent_id: agentId, }; (0, workspace_1.writeWorkspaceState)(newState); yield new Promise((resolve) => setTimeout(resolve, 2000)); logger.stop('Workspace synchronized'); return true; } return false; }); const handleReasoningSteps = (streamResponse) => { streamResponse.on('data', (data) => { if (!data.toString().includes('reasoning')) { return; } try { const res = JSON.parse(data.toString()); if (res.status === 'reasoning') { let stepMessage = `Reasoning steps that will be followed:`; for (const step of res.steps.steps) { stepMessage += `\n${chalk_1.default.gray('│')} ${(0, streams_1.toItalic)(` └ ${step}`)}`; } logger.stop(stepMessage); logger.start('Processing'); } } catch (e) { } }); }; const parseAgentResponse = (agentResponse, stream) => __awaiter(void 0, void 0, void 0, function* () { let actions = []; let queryResponse = ''; if ((0, streams_1.isStreamingContext)(stream, agentResponse)) { const res = yield (0, streams_1.parseStreamedResponse)(agentResponse); if (res.actions.length) actions = res.actions; if (res.message) queryResponse = res.message; } else { if (agentResponse.actions) actions = agentResponse.actions; if (agentResponse.response) queryResponse = agentResponse.response; } return [actions, queryResponse]; }); const queryCommand = (query, options) => __awaiter(void 0, void 0, void 0, function* () { var _a, _b; logger_1.default.debug('Options:', options); try { const config = (0, conf_1.readConfig)(); const workspace = (0, workspace_1.resolveWorkspacePath)(options); logger_1.default.debug('Workspace:', workspace); const skipWarmup = !!options.skipWarmup; const stream = (_b = (_a = options.stream) !== null && _a !== void 0 ? _a : config === null || config === void 0 ? void 0 : config.stream) !== null && _b !== void 0 ? _b : false; const agentConfig = yield initializeAgentConfig(workspace, skipWarmup); if (!agentConfig) { return; } const agentManager = new agentManager_1.AgentManager({ id: agentConfig.id, name: agentConfig.name, engine: agentConfig.engine, capabilities: agentConfig.capabilities, workspace, }); let workspaceChanged = false; let taskId; if (!skipWarmup) { const [syncResult, taskResult] = yield Promise.all([ synchronizeWorkspace(agentConfig.id, workspace), (0, api_1.createTask)(agentConfig.id, query), ]); workspaceChanged = syncResult; taskId = taskResult.id; } else { const taskRecord = yield (0, api_1.createTask)(agentConfig.id, query); taskId = taskRecord.id; } const workspaceData = (0, files_1.getDirectoryMd5Hash)({ directoryPath: workspace, }); const workspaceTree = (0, tree_1.generateTree)(Array.from(workspaceData.fileHashes.keys())); logger.start('Thinking'); const agentResponse = yield (0, api_1.queryAgent)(agentManager.id, workspaceChanged, taskId, workspaceTree, stream); if (stream) { const streamResponse = agentResponse; handleReasoningSteps(streamResponse); } let [actions, queryResponse] = yield parseAgentResponse(agentResponse, stream); if (queryResponse) { logger.stop(queryResponse); } let finalResponse = ''; while (actions.length) { if ((0, loopDetection_1.isLooping)(actions)) { return logger.stop('Unfortunately, a loop has been detected. Please try again.', 1); } const toolOutputs = yield executeActions(actions, agentManager); logger.start('Reviewing the job'); const submitResponse = toolOutputs.length ? yield (0, api_1.submitToolOutputs)(agentManager.id, taskId, toolOutputs, stream) : undefined; [actions, finalResponse] = yield parseAgentResponse(submitResponse, stream); if (actions.length && finalResponse) { logger.stop(finalResponse); } } if (finalResponse) { logger.stop(chalk_1.default.italic.gray('-'.repeat((0, logger_1.getTerminalWidth)() - 10))); logger_1.default.agent(finalResponse); } if (options.callback) yield options.callback(finalResponse); } catch (error) { logger.handleError(error); } }); exports.queryCommand = queryCommand;