@xagent/x-cli 1.2.12 → 1.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import OpenAI from 'openai';
3
- import * as fs7 from 'fs';
4
- import fs7__default, { existsSync, promises } from 'fs';
3
+ import * as fs10 from 'fs';
4
+ import fs10__default, { existsSync, promises } from 'fs';
5
5
  import * as path8 from 'path';
6
6
  import path8__default from 'path';
7
7
  import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
@@ -13,7 +13,8 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
13
13
  import { exec, execSync, spawn } from 'child_process';
14
14
  import { promisify } from 'util';
15
15
  import { createTwoFilesPatch } from 'diff';
16
- import fs3, { writeFile } from 'fs/promises';
16
+ import * as fs7 from 'fs/promises';
17
+ import fs7__default, { writeFile } from 'fs/promises';
17
18
  import * as ops6 from 'fs-extra';
18
19
  import { parse } from '@typescript-eslint/typescript-estree';
19
20
  import Fuse from 'fuse.js';
@@ -169,11 +170,11 @@ var init_client = __esm({
169
170
  };
170
171
  const logPath = process.env.XCLI_TOKEN_LOG || `${process.env.HOME}/.grok/token-usage.jsonl`;
171
172
  const dir = path8__default.dirname(logPath);
172
- if (!fs7__default.existsSync(dir)) {
173
- fs7__default.mkdirSync(dir, { recursive: true });
173
+ if (!fs10__default.existsSync(dir)) {
174
+ fs10__default.mkdirSync(dir, { recursive: true });
174
175
  }
175
176
  const logLine = JSON.stringify(tokenData) + "\n";
176
- fs7__default.appendFileSync(logPath, logLine);
177
+ fs10__default.appendFileSync(logPath, logLine);
177
178
  } catch (error) {
178
179
  console.warn("Failed to log token usage:", error);
179
180
  }
@@ -434,8 +435,8 @@ var init_settings_manager = __esm({
434
435
  */
435
436
  ensureDirectoryExists(filePath) {
436
437
  const dir = path8.dirname(filePath);
437
- if (!fs7.existsSync(dir)) {
438
- fs7.mkdirSync(dir, { recursive: true, mode: 448 });
438
+ if (!fs10.existsSync(dir)) {
439
+ fs10.mkdirSync(dir, { recursive: true, mode: 448 });
439
440
  }
440
441
  }
441
442
  /**
@@ -443,11 +444,11 @@ var init_settings_manager = __esm({
443
444
  */
444
445
  loadUserSettings() {
445
446
  try {
446
- if (!fs7.existsSync(this.userSettingsPath)) {
447
+ if (!fs10.existsSync(this.userSettingsPath)) {
447
448
  this.saveUserSettings(DEFAULT_USER_SETTINGS);
448
449
  return { ...DEFAULT_USER_SETTINGS };
449
450
  }
450
- const content = fs7.readFileSync(this.userSettingsPath, "utf-8");
451
+ const content = fs10.readFileSync(this.userSettingsPath, "utf-8");
451
452
  const settings = JSON.parse(content);
452
453
  return { ...DEFAULT_USER_SETTINGS, ...settings };
453
454
  } catch (error) {
@@ -465,9 +466,9 @@ var init_settings_manager = __esm({
465
466
  try {
466
467
  this.ensureDirectoryExists(this.userSettingsPath);
467
468
  let existingSettings = { ...DEFAULT_USER_SETTINGS };
468
- if (fs7.existsSync(this.userSettingsPath)) {
469
+ if (fs10.existsSync(this.userSettingsPath)) {
469
470
  try {
470
- const content = fs7.readFileSync(this.userSettingsPath, "utf-8");
471
+ const content = fs10.readFileSync(this.userSettingsPath, "utf-8");
471
472
  const parsed = JSON.parse(content);
472
473
  existingSettings = { ...DEFAULT_USER_SETTINGS, ...parsed };
473
474
  } catch (_error) {
@@ -475,7 +476,7 @@ var init_settings_manager = __esm({
475
476
  }
476
477
  }
477
478
  const mergedSettings = { ...existingSettings, ...settings };
478
- fs7.writeFileSync(
479
+ fs10.writeFileSync(
479
480
  this.userSettingsPath,
480
481
  JSON.stringify(mergedSettings, null, 2),
481
482
  { mode: 384 }
@@ -508,11 +509,11 @@ var init_settings_manager = __esm({
508
509
  */
509
510
  loadProjectSettings() {
510
511
  try {
511
- if (!fs7.existsSync(this.projectSettingsPath)) {
512
+ if (!fs10.existsSync(this.projectSettingsPath)) {
512
513
  this.saveProjectSettings(DEFAULT_PROJECT_SETTINGS);
513
514
  return { ...DEFAULT_PROJECT_SETTINGS };
514
515
  }
515
- const content = fs7.readFileSync(this.projectSettingsPath, "utf-8");
516
+ const content = fs10.readFileSync(this.projectSettingsPath, "utf-8");
516
517
  const settings = JSON.parse(content);
517
518
  return { ...DEFAULT_PROJECT_SETTINGS, ...settings };
518
519
  } catch (error) {
@@ -530,9 +531,9 @@ var init_settings_manager = __esm({
530
531
  try {
531
532
  this.ensureDirectoryExists(this.projectSettingsPath);
532
533
  let existingSettings = { ...DEFAULT_PROJECT_SETTINGS };
533
- if (fs7.existsSync(this.projectSettingsPath)) {
534
+ if (fs10.existsSync(this.projectSettingsPath)) {
534
535
  try {
535
- const content = fs7.readFileSync(this.projectSettingsPath, "utf-8");
536
+ const content = fs10.readFileSync(this.projectSettingsPath, "utf-8");
536
537
  const parsed = JSON.parse(content);
537
538
  existingSettings = { ...DEFAULT_PROJECT_SETTINGS, ...parsed };
538
539
  } catch (_error) {
@@ -540,7 +541,7 @@ var init_settings_manager = __esm({
540
541
  }
541
542
  }
542
543
  const mergedSettings = { ...existingSettings, ...settings };
543
- fs7.writeFileSync(
544
+ fs10.writeFileSync(
544
545
  this.projectSettingsPath,
545
546
  JSON.stringify(mergedSettings, null, 2)
546
547
  );
@@ -1925,12 +1926,12 @@ ${data ? JSON.stringify(data, null, 2) : "No additional data"}
1925
1926
  `;
1926
1927
  const workingDir = process.cwd();
1927
1928
  const logsDir = path8.join(workingDir, "logs");
1928
- const fs19 = fs7;
1929
- if (fs19.existsSync(logsDir)) {
1930
- const sessionFiles = fs19.readdirSync(logsDir).filter((f) => f.startsWith("session-") && f.endsWith(".log"));
1929
+ const fs22 = fs10;
1930
+ if (fs22.existsSync(logsDir)) {
1931
+ const sessionFiles = fs22.readdirSync(logsDir).filter((f) => f.startsWith("session-") && f.endsWith(".log"));
1931
1932
  if (sessionFiles.length > 0) {
1932
1933
  const sessionFile = path8.join(logsDir, sessionFiles[sessionFiles.length - 1]);
1933
- fs19.appendFileSync(sessionFile, logEntry);
1934
+ fs22.appendFileSync(sessionFile, logEntry);
1934
1935
  }
1935
1936
  }
1936
1937
  } catch (error) {
@@ -1943,7 +1944,7 @@ var init_text_editor = __esm({
1943
1944
  init_confirmation_service();
1944
1945
  pathExists = async (filePath) => {
1945
1946
  try {
1946
- await fs7.promises.access(filePath, fs7.constants.F_OK);
1947
+ await fs10.promises.access(filePath, fs10.constants.F_OK);
1947
1948
  return true;
1948
1949
  } catch {
1949
1950
  return false;
@@ -1958,16 +1959,16 @@ var init_text_editor = __esm({
1958
1959
  try {
1959
1960
  const resolvedPath = path8.resolve(filePath);
1960
1961
  if (await pathExists(resolvedPath)) {
1961
- const stats = await fs7.promises.stat(resolvedPath);
1962
+ const stats = await fs10.promises.stat(resolvedPath);
1962
1963
  if (stats.isDirectory()) {
1963
- const files = await fs7.promises.readdir(resolvedPath);
1964
+ const files = await fs10.promises.readdir(resolvedPath);
1964
1965
  return {
1965
1966
  success: true,
1966
1967
  output: `Directory contents of ${filePath}:
1967
1968
  ${files.join("\n")}`
1968
1969
  };
1969
1970
  }
1970
- const content = await fs7.promises.readFile(resolvedPath, "utf-8");
1971
+ const content = await fs10.promises.readFile(resolvedPath, "utf-8");
1971
1972
  const lines = content.split("\n");
1972
1973
  if (viewRange) {
1973
1974
  const [start, end] = viewRange;
@@ -2017,7 +2018,7 @@ ${numberedLines}${additionalLinesMessage}`
2017
2018
  error: `File not found: ${filePath}`
2018
2019
  };
2019
2020
  }
2020
- const content = await fs7.promises.readFile(resolvedPath, "utf-8");
2021
+ const content = await fs10.promises.readFile(resolvedPath, "utf-8");
2021
2022
  if (!content.includes(oldStr)) {
2022
2023
  if (oldStr.includes("\n")) {
2023
2024
  const fuzzyResult = this.findFuzzyMatch(content, oldStr);
@@ -2117,7 +2118,7 @@ ${numberedLines}${additionalLinesMessage}`
2117
2118
  }
2118
2119
  }
2119
2120
  const dir = path8.dirname(resolvedPath);
2120
- await fs7.promises.mkdir(dir, { recursive: true });
2121
+ await fs10.promises.mkdir(dir, { recursive: true });
2121
2122
  await writeFile(resolvedPath, content, "utf-8");
2122
2123
  this.editHistory.push({
2123
2124
  command: "create",
@@ -2147,7 +2148,7 @@ ${numberedLines}${additionalLinesMessage}`
2147
2148
  error: `File not found: ${filePath}`
2148
2149
  };
2149
2150
  }
2150
- const fileContent = await fs7.promises.readFile(resolvedPath, "utf-8");
2151
+ const fileContent = await fs10.promises.readFile(resolvedPath, "utf-8");
2151
2152
  const lines = fileContent.split("\n");
2152
2153
  if (startLine < 1 || startLine > lines.length) {
2153
2154
  return {
@@ -2215,7 +2216,7 @@ ${numberedLines}${additionalLinesMessage}`
2215
2216
  error: `File not found: ${filePath}`
2216
2217
  };
2217
2218
  }
2218
- const fileContent = await fs7.promises.readFile(resolvedPath, "utf-8");
2219
+ const fileContent = await fs10.promises.readFile(resolvedPath, "utf-8");
2219
2220
  const lines = fileContent.split("\n");
2220
2221
  lines.splice(insertLine - 1, 0, content);
2221
2222
  const newContent = lines.join("\n");
@@ -2249,7 +2250,7 @@ ${numberedLines}${additionalLinesMessage}`
2249
2250
  switch (lastEdit.command) {
2250
2251
  case "str_replace":
2251
2252
  if (lastEdit.path && lastEdit.old_str && lastEdit.new_str) {
2252
- const content = await fs7.promises.readFile(lastEdit.path, "utf-8");
2253
+ const content = await fs10.promises.readFile(lastEdit.path, "utf-8");
2253
2254
  const revertedContent = content.replace(
2254
2255
  lastEdit.new_str,
2255
2256
  lastEdit.old_str
@@ -2259,12 +2260,12 @@ ${numberedLines}${additionalLinesMessage}`
2259
2260
  break;
2260
2261
  case "create":
2261
2262
  if (lastEdit.path) {
2262
- await fs7.promises.rm(lastEdit.path);
2263
+ await fs10.promises.rm(lastEdit.path);
2263
2264
  }
2264
2265
  break;
2265
2266
  case "insert":
2266
2267
  if (lastEdit.path && lastEdit.insert_line) {
2267
- const content = await fs7.promises.readFile(lastEdit.path, "utf-8");
2268
+ const content = await fs10.promises.readFile(lastEdit.path, "utf-8");
2268
2269
  const lines = content.split("\n");
2269
2270
  lines.splice(lastEdit.insert_line - 1, 1);
2270
2271
  await writeFile(lastEdit.path, lines.join("\n"), "utf-8");
@@ -2592,13 +2593,17 @@ ${numberedLines}${additionalLinesMessage}`
2592
2593
  };
2593
2594
  }
2594
2595
  });
2596
+ var init_smart_edit = __esm({
2597
+ "src/tools/smart-edit.ts"() {
2598
+ }
2599
+ });
2595
2600
  var pathExists2, MorphEditorTool;
2596
2601
  var init_morph_editor = __esm({
2597
2602
  "src/tools/morph-editor.ts"() {
2598
2603
  init_confirmation_service();
2599
2604
  pathExists2 = async (filePath) => {
2600
2605
  try {
2601
- await fs7.promises.access(filePath, fs7.constants.F_OK);
2606
+ await fs10.promises.access(filePath, fs10.constants.F_OK);
2602
2607
  return true;
2603
2608
  } catch {
2604
2609
  return false;
@@ -2651,7 +2656,7 @@ var init_morph_editor = __esm({
2651
2656
  error: "MORPH_API_KEY not configured. Please set your Morph API key."
2652
2657
  };
2653
2658
  }
2654
- const initialCode = await fs7.promises.readFile(resolvedPath, "utf-8");
2659
+ const initialCode = await fs10.promises.readFile(resolvedPath, "utf-8");
2655
2660
  const sessionFlags = this.confirmationService.getSessionFlags();
2656
2661
  if (!sessionFlags.fileOperations && !sessionFlags.allOperations) {
2657
2662
  const confirmationResult = await this.confirmationService.requestConfirmation(
@@ -2674,7 +2679,7 @@ ${codeEdit}`
2674
2679
  }
2675
2680
  }
2676
2681
  const mergedCode = await this.callMorphApply(instructions, initialCode, codeEdit);
2677
- await fs7.promises.writeFile(resolvedPath, mergedCode, "utf-8");
2682
+ await fs10.promises.writeFile(resolvedPath, mergedCode, "utf-8");
2678
2683
  const oldLines = initialCode.split("\n");
2679
2684
  const newLines = mergedCode.split("\n");
2680
2685
  const diff = this.generateDiff(oldLines, newLines, targetFile);
@@ -2848,16 +2853,16 @@ ${codeEdit}`
2848
2853
  try {
2849
2854
  const resolvedPath = path8.resolve(filePath);
2850
2855
  if (await pathExists2(resolvedPath)) {
2851
- const stats = await fs7.promises.stat(resolvedPath);
2856
+ const stats = await fs10.promises.stat(resolvedPath);
2852
2857
  if (stats.isDirectory()) {
2853
- const files = await fs7.promises.readdir(resolvedPath);
2858
+ const files = await fs10.promises.readdir(resolvedPath);
2854
2859
  return {
2855
2860
  success: true,
2856
2861
  output: `Directory contents of ${filePath}:
2857
2862
  ${files.join("\n")}`
2858
2863
  };
2859
2864
  }
2860
- const content = await fs7.promises.readFile(resolvedPath, "utf-8");
2865
+ const content = await fs10.promises.readFile(resolvedPath, "utf-8");
2861
2866
  const lines = content.split("\n");
2862
2867
  if (viewRange) {
2863
2868
  const [start, end] = viewRange;
@@ -3285,7 +3290,7 @@ var init_search = __esm({
3285
3290
  const walkDir = async (dir, depth = 0) => {
3286
3291
  if (depth > 10 || files.length >= maxResults) return;
3287
3292
  try {
3288
- const entries = await fs7.promises.readdir(dir, { withFileTypes: true });
3293
+ const entries = await fs10.promises.readdir(dir, { withFileTypes: true });
3289
3294
  for (const entry of entries) {
3290
3295
  if (files.length >= maxResults) break;
3291
3296
  const fullPath = path8.join(dir, entry.name);
@@ -3925,7 +3930,7 @@ var init_advanced_search = __esm({
3925
3930
  init_confirmation_service();
3926
3931
  pathExists4 = async (filePath) => {
3927
3932
  try {
3928
- await fs7.promises.access(filePath, fs7.constants.F_OK);
3933
+ await fs10.promises.access(filePath, fs10.constants.F_OK);
3929
3934
  return true;
3930
3935
  } catch {
3931
3936
  return false;
@@ -3947,7 +3952,7 @@ var init_advanced_search = __esm({
3947
3952
  error: `Path not found: ${searchPath}`
3948
3953
  };
3949
3954
  }
3950
- const stats = await fs7.promises.stat(resolvedPath);
3955
+ const stats = await fs10.promises.stat(resolvedPath);
3951
3956
  const filesToSearch = [];
3952
3957
  if (stats.isFile()) {
3953
3958
  filesToSearch.push(resolvedPath);
@@ -3990,7 +3995,7 @@ var init_advanced_search = __esm({
3990
3995
  error: `Path not found: ${searchPath}`
3991
3996
  };
3992
3997
  }
3993
- const stats = await fs7.promises.stat(resolvedPath);
3998
+ const stats = await fs10.promises.stat(resolvedPath);
3994
3999
  const filesToProcess = [];
3995
4000
  if (stats.isFile()) {
3996
4001
  filesToProcess.push(resolvedPath);
@@ -4035,7 +4040,7 @@ var init_advanced_search = __esm({
4035
4040
  }
4036
4041
  for (const result of results) {
4037
4042
  if (result.success && result.preview) {
4038
- await fs7.promises.writeFile(result.filePath, result.preview, "utf-8");
4043
+ await fs10.promises.writeFile(result.filePath, result.preview, "utf-8");
4039
4044
  }
4040
4045
  }
4041
4046
  }
@@ -4097,7 +4102,7 @@ ${matchingFiles.join("\n")}` : "No matching files found"
4097
4102
  * Search in a single file
4098
4103
  */
4099
4104
  async searchInFile(filePath, options) {
4100
- const content = await fs7.promises.readFile(filePath, "utf-8");
4105
+ const content = await fs10.promises.readFile(filePath, "utf-8");
4101
4106
  const lines = content.split("\n");
4102
4107
  const matches = [];
4103
4108
  let pattern;
@@ -4148,7 +4153,7 @@ ${matchingFiles.join("\n")}` : "No matching files found"
4148
4153
  */
4149
4154
  async replaceInFile(filePath, options) {
4150
4155
  try {
4151
- const content = await fs7.promises.readFile(filePath, "utf-8");
4156
+ const content = await fs10.promises.readFile(filePath, "utf-8");
4152
4157
  let pattern;
4153
4158
  try {
4154
4159
  if (options.isRegex) {
@@ -4199,7 +4204,7 @@ ${matchingFiles.join("\n")}` : "No matching files found"
4199
4204
  async getFilesRecursively(dirPath, options) {
4200
4205
  const files = [];
4201
4206
  const walk = async (currentPath) => {
4202
- const entries = await fs7.promises.readdir(currentPath, { withFileTypes: true });
4207
+ const entries = await fs10.promises.readdir(currentPath, { withFileTypes: true });
4203
4208
  for (const entry of entries) {
4204
4209
  const fullPath = path8.join(currentPath, entry.name);
4205
4210
  if (entry.isDirectory()) {
@@ -4957,7 +4962,7 @@ var init_code_aware_editor = __esm({
4957
4962
  init_confirmation_service();
4958
4963
  pathExists6 = async (filePath) => {
4959
4964
  try {
4960
- await fs7.promises.access(filePath, fs7.constants.F_OK);
4965
+ await fs10.promises.access(filePath, fs10.constants.F_OK);
4961
4966
  return true;
4962
4967
  } catch {
4963
4968
  return false;
@@ -4979,7 +4984,7 @@ var init_code_aware_editor = __esm({
4979
4984
  error: `File not found: ${filePath}`
4980
4985
  };
4981
4986
  }
4982
- const content = await fs7.promises.readFile(resolvedPath, "utf-8");
4987
+ const content = await fs10.promises.readFile(resolvedPath, "utf-8");
4983
4988
  const language = this.detectLanguage(filePath);
4984
4989
  const context = await this.parseCodeContext(content, language);
4985
4990
  const output = this.formatCodeAnalysis(context, filePath);
@@ -5006,7 +5011,7 @@ var init_code_aware_editor = __esm({
5006
5011
  error: `File not found: ${filePath}`
5007
5012
  };
5008
5013
  }
5009
- const content = await fs7.promises.readFile(resolvedPath, "utf-8");
5014
+ const content = await fs10.promises.readFile(resolvedPath, "utf-8");
5010
5015
  const language = this.detectLanguage(filePath);
5011
5016
  const context = await this.parseCodeContext(content, language);
5012
5017
  const result = await this.performRefactoring(content, context, operation, language);
@@ -5032,7 +5037,7 @@ var init_code_aware_editor = __esm({
5032
5037
  };
5033
5038
  }
5034
5039
  }
5035
- await fs7.promises.writeFile(resolvedPath, result.newContent, "utf-8");
5040
+ await fs10.promises.writeFile(resolvedPath, result.newContent, "utf-8");
5036
5041
  return {
5037
5042
  success: true,
5038
5043
  output: result.output
@@ -5056,7 +5061,7 @@ var init_code_aware_editor = __esm({
5056
5061
  error: `File not found: ${filePath}`
5057
5062
  };
5058
5063
  }
5059
- const content = await fs7.promises.readFile(resolvedPath, "utf-8");
5064
+ const content = await fs10.promises.readFile(resolvedPath, "utf-8");
5060
5065
  const language = this.detectLanguage(filePath);
5061
5066
  const context = await this.parseCodeContext(content, language);
5062
5067
  const insertionPoint = this.findInsertionPoint(content, context, location, target);
@@ -5086,7 +5091,7 @@ var init_code_aware_editor = __esm({
5086
5091
  };
5087
5092
  }
5088
5093
  }
5089
- await fs7.promises.writeFile(resolvedPath, newContent, "utf-8");
5094
+ await fs10.promises.writeFile(resolvedPath, newContent, "utf-8");
5090
5095
  return {
5091
5096
  success: true,
5092
5097
  output: `Code inserted at line ${insertionPoint.line + 1} in ${filePath}`
@@ -5110,7 +5115,7 @@ var init_code_aware_editor = __esm({
5110
5115
  error: `File not found: ${filePath}`
5111
5116
  };
5112
5117
  }
5113
- const content = await fs7.promises.readFile(resolvedPath, "utf-8");
5118
+ const content = await fs10.promises.readFile(resolvedPath, "utf-8");
5114
5119
  const language = this.detectLanguage(filePath);
5115
5120
  const formattedContent = await this.formatCodeContent(content, language, options);
5116
5121
  if (formattedContent === content) {
@@ -5138,7 +5143,7 @@ var init_code_aware_editor = __esm({
5138
5143
  };
5139
5144
  }
5140
5145
  }
5141
- await fs7.promises.writeFile(resolvedPath, formattedContent, "utf-8");
5146
+ await fs10.promises.writeFile(resolvedPath, formattedContent, "utf-8");
5142
5147
  return {
5143
5148
  success: true,
5144
5149
  output: `Code formatted in ${filePath}`
@@ -5162,7 +5167,7 @@ var init_code_aware_editor = __esm({
5162
5167
  error: `File not found: ${filePath}`
5163
5168
  };
5164
5169
  }
5165
- const content = await fs7.promises.readFile(resolvedPath, "utf-8");
5170
+ const content = await fs10.promises.readFile(resolvedPath, "utf-8");
5166
5171
  const language = this.detectLanguage(filePath);
5167
5172
  const context = await this.parseCodeContext(content, language);
5168
5173
  const missingImports = symbols.filter(
@@ -5203,7 +5208,7 @@ ${importsToAdd.join("\n")}`;
5203
5208
  };
5204
5209
  }
5205
5210
  }
5206
- await fs7.promises.writeFile(resolvedPath, newContent, "utf-8");
5211
+ await fs10.promises.writeFile(resolvedPath, newContent, "utf-8");
5207
5212
  return {
5208
5213
  success: true,
5209
5214
  output: `Added ${missingImports.length} missing imports to ${filePath}`
@@ -6562,7 +6567,7 @@ var init_ast_parser = __esm({
6562
6567
  }
6563
6568
  pathExists8 = async (filePath) => {
6564
6569
  try {
6565
- await fs7.promises.access(filePath, fs7.constants.F_OK);
6570
+ await fs10.promises.access(filePath, fs10.constants.F_OK);
6566
6571
  return true;
6567
6572
  } catch {
6568
6573
  return false;
@@ -6638,7 +6643,7 @@ var init_ast_parser = __esm({
6638
6643
  if (!await pathExists8(filePath)) {
6639
6644
  throw new Error(`File not found: ${filePath}`);
6640
6645
  }
6641
- const content = await fs7.promises.readFile(filePath, "utf-8");
6646
+ const content = await fs10.promises.readFile(filePath, "utf-8");
6642
6647
  const language = this.detectLanguage(filePath);
6643
6648
  let result;
6644
6649
  if (language === "typescript" || language === "tsx") {
@@ -7332,7 +7337,7 @@ var init_symbol_search = __esm({
7332
7337
  async findSymbolUsages(symbolRef) {
7333
7338
  const usages = [];
7334
7339
  try {
7335
- const content = await fs7.promises.readFile(symbolRef.filePath, "utf-8");
7340
+ const content = await fs10.promises.readFile(symbolRef.filePath, "utf-8");
7336
7341
  const lines = content.split("\n");
7337
7342
  for (let i = 0; i < lines.length; i++) {
7338
7343
  const line = lines[i];
@@ -7512,7 +7517,7 @@ var init_dependency_analyzer = __esm({
7512
7517
  init_ast_parser();
7513
7518
  pathExists9 = async (filePath) => {
7514
7519
  try {
7515
- await fs7.promises.access(filePath, fs7.constants.F_OK);
7520
+ await fs10.promises.access(filePath, fs10.constants.F_OK);
7516
7521
  return true;
7517
7522
  } catch {
7518
7523
  return false;
@@ -7714,10 +7719,10 @@ var init_dependency_analyzer = __esm({
7714
7719
  const circularDeps = [];
7715
7720
  const visited = /* @__PURE__ */ new Set();
7716
7721
  const visiting = /* @__PURE__ */ new Set();
7717
- const dfs = (filePath, path41) => {
7722
+ const dfs = (filePath, path43) => {
7718
7723
  if (visiting.has(filePath)) {
7719
- const cycleStart = path41.indexOf(filePath);
7720
- const cycle = path41.slice(cycleStart).concat([filePath]);
7724
+ const cycleStart = path43.indexOf(filePath);
7725
+ const cycle = path43.slice(cycleStart).concat([filePath]);
7721
7726
  circularDeps.push({
7722
7727
  cycle: cycle.map((fp) => graph.nodes.get(fp)?.filePath || fp),
7723
7728
  severity: cycle.length <= 2 ? "error" : "warning",
@@ -7733,7 +7738,7 @@ var init_dependency_analyzer = __esm({
7733
7738
  if (node) {
7734
7739
  for (const dependency of node.dependencies) {
7735
7740
  if (graph.nodes.has(dependency)) {
7736
- dfs(dependency, [...path41, filePath]);
7741
+ dfs(dependency, [...path43, filePath]);
7737
7742
  }
7738
7743
  }
7739
7744
  }
@@ -7990,7 +7995,7 @@ var init_code_context = __esm({
7990
7995
  init_dependency_analyzer();
7991
7996
  pathExists10 = async (filePath) => {
7992
7997
  try {
7993
- await fs7.promises.access(filePath, fs7.constants.F_OK);
7998
+ await fs10.promises.access(filePath, fs10.constants.F_OK);
7994
7999
  return true;
7995
8000
  } catch {
7996
8001
  return false;
@@ -8135,7 +8140,7 @@ var init_code_context = __esm({
8135
8140
  async analyzeUsagePatterns(symbol, filePath) {
8136
8141
  const patterns = [];
8137
8142
  try {
8138
- const content = await fs7.promises.readFile(filePath, "utf-8");
8143
+ const content = await fs10.promises.readFile(filePath, "utf-8");
8139
8144
  const lines = content.split("\n");
8140
8145
  let callCount = 0;
8141
8146
  let assignmentCount = 0;
@@ -8288,7 +8293,7 @@ var init_code_context = __esm({
8288
8293
  }
8289
8294
  async analyzeSemanticContext(filePath, symbols, dependencies) {
8290
8295
  const fileName = path8__default.basename(filePath);
8291
- const content = await fs7.promises.readFile(filePath, "utf-8");
8296
+ const content = await fs10.promises.readFile(filePath, "utf-8");
8292
8297
  const purpose = this.inferPurpose(fileName, symbols, content);
8293
8298
  const domain = this.extractDomain(filePath, symbols, dependencies);
8294
8299
  const patterns = this.detectDesignPatterns(content, symbols);
@@ -8417,7 +8422,7 @@ var init_code_context = __esm({
8417
8422
  };
8418
8423
  }
8419
8424
  async calculateCodeMetrics(filePath, symbols) {
8420
- const content = await fs7.promises.readFile(filePath, "utf-8");
8425
+ const content = await fs10.promises.readFile(filePath, "utf-8");
8421
8426
  const lines = content.split("\n");
8422
8427
  const codeLines = lines.filter((line) => line.trim().length > 0 && !line.trim().startsWith("//"));
8423
8428
  const linesOfCode = codeLines.length;
@@ -8526,7 +8531,7 @@ var init_refactoring_assistant = __esm({
8526
8531
  init_operation_history();
8527
8532
  pathExists11 = async (filePath) => {
8528
8533
  try {
8529
- await fs7.promises.access(filePath, fs7.constants.F_OK);
8534
+ await fs10.promises.access(filePath, fs10.constants.F_OK);
8530
8535
  return true;
8531
8536
  } catch {
8532
8537
  return false;
@@ -8646,7 +8651,7 @@ var init_refactoring_assistant = __esm({
8646
8651
  if (!await pathExists11(filePath)) {
8647
8652
  throw new Error(`File not found: ${filePath}`);
8648
8653
  }
8649
- const content = await fs7.promises.readFile(filePath, "utf-8");
8654
+ const content = await fs10.promises.readFile(filePath, "utf-8");
8650
8655
  const lines = content.split("\n");
8651
8656
  if (startLine < 0 || endLine >= lines.length || startLine > endLine) {
8652
8657
  throw new Error("Invalid line range");
@@ -8721,7 +8726,7 @@ var init_refactoring_assistant = __esm({
8721
8726
  if (!filePath || !variableName) {
8722
8727
  throw new Error("File path and variable name are required");
8723
8728
  }
8724
- const content = await fs7.promises.readFile(filePath, "utf-8");
8729
+ const content = await fs10.promises.readFile(filePath, "utf-8");
8725
8730
  const lines = content.split("\n");
8726
8731
  const startLineContent = lines[startLine];
8727
8732
  const endLineContent = lines[endLine];
@@ -8796,7 +8801,7 @@ var init_refactoring_assistant = __esm({
8796
8801
  if (!functionSymbol) {
8797
8802
  throw new Error(`Function '${symbolName}' not found`);
8798
8803
  }
8799
- const content = await fs7.promises.readFile(filePath, "utf-8");
8804
+ const content = await fs10.promises.readFile(filePath, "utf-8");
8800
8805
  const lines = content.split("\n");
8801
8806
  const functionLines = lines.slice(functionSymbol.startPosition.row, functionSymbol.endPosition.row + 1);
8802
8807
  const functionBody = this.extractFunctionBody(functionLines.join("\n"));
@@ -8906,7 +8911,7 @@ var init_refactoring_assistant = __esm({
8906
8911
  }
8907
8912
  async generateRenameChanges(ref, oldName, newName, includeComments, includeStrings) {
8908
8913
  const changes = [];
8909
- const content = await fs7.promises.readFile(ref.filePath, "utf-8");
8914
+ const content = await fs10.promises.readFile(ref.filePath, "utf-8");
8910
8915
  const lines = content.split("\n");
8911
8916
  for (let i = 0; i < lines.length; i++) {
8912
8917
  const line = lines[i];
@@ -9281,7 +9286,7 @@ var init_codebase_explorer = __esm({
9281
9286
  return files;
9282
9287
  }
9283
9288
  try {
9284
- const entries = await fs3.readdir(dirPath, { withFileTypes: true });
9289
+ const entries = await fs7__default.readdir(dirPath, { withFileTypes: true });
9285
9290
  for (const entry of entries) {
9286
9291
  const fullPath = path8__default.join(dirPath, entry.name);
9287
9292
  const relativePath = path8__default.relative(options.rootPath, fullPath);
@@ -9304,7 +9309,7 @@ var init_codebase_explorer = __esm({
9304
9309
  files.push(...subFiles);
9305
9310
  } else {
9306
9311
  try {
9307
- const stats = await fs3.stat(fullPath);
9312
+ const stats = await fs7__default.stat(fullPath);
9308
9313
  fileInfo.size = stats.size;
9309
9314
  fileInfo.lastModified = stats.mtimeMs;
9310
9315
  if (fileInfo.size > this.settings.maxFileSize) {
@@ -9577,7 +9582,7 @@ var init_codebase_explorer = __esm({
9577
9582
  async detectProjectType(rootPath, files) {
9578
9583
  const packageJsonPath = path8__default.join(rootPath, "package.json");
9579
9584
  try {
9580
- const packageJson = await fs3.readFile(packageJsonPath, "utf-8");
9585
+ const packageJson = await fs7__default.readFile(packageJsonPath, "utf-8");
9581
9586
  const pkg = JSON.parse(packageJson);
9582
9587
  if (pkg.dependencies?.react || pkg.devDependencies?.react) return "react";
9583
9588
  if (pkg.dependencies?.vue || pkg.devDependencies?.vue) return "vue";
@@ -9773,7 +9778,7 @@ var init_codebase_explorer = __esm({
9773
9778
  */
9774
9779
  async calculateFileChecksum(filePath) {
9775
9780
  try {
9776
- const content = await fs3.readFile(filePath);
9781
+ const content = await fs7__default.readFile(filePath);
9777
9782
  return crypto2.createHash("sha256").update(content).digest("hex");
9778
9783
  } catch {
9779
9784
  return "";
@@ -9957,7 +9962,7 @@ var init_incremental_indexer = __esm({
9957
9962
  async scanDirectory(dirPath, options, files, depth = 0) {
9958
9963
  if (depth > 10) return;
9959
9964
  try {
9960
- const entries = await fs3.readdir(dirPath, { withFileTypes: true });
9965
+ const entries = await fs7__default.readdir(dirPath, { withFileTypes: true });
9961
9966
  for (const entry of entries) {
9962
9967
  const fullPath = path8__default.join(dirPath, entry.name);
9963
9968
  if (!this.shouldTrackFile(fullPath, options)) {
@@ -9967,7 +9972,7 @@ var init_incremental_indexer = __esm({
9967
9972
  await this.scanDirectory(fullPath, options, files, depth + 1);
9968
9973
  } else {
9969
9974
  try {
9970
- const stats = await fs3.stat(fullPath);
9975
+ const stats = await fs7__default.stat(fullPath);
9971
9976
  if (options.maxFileSize && stats.size > options.maxFileSize) {
9972
9977
  continue;
9973
9978
  }
@@ -10007,7 +10012,7 @@ var init_incremental_indexer = __esm({
10007
10012
  }
10008
10013
  async calculateChecksum(filePath) {
10009
10014
  try {
10010
- const content = await fs3.readFile(filePath);
10015
+ const content = await fs7__default.readFile(filePath);
10011
10016
  return crypto2.createHash("sha256").update(content).digest("hex");
10012
10017
  } catch {
10013
10018
  return "";
@@ -10694,8 +10699,936 @@ Use \`--action=incremental\` for faster subsequent updates.`
10694
10699
  }
10695
10700
  });
10696
10701
 
10697
- // src/services/autonomous-executor.ts
10698
- var AutonomousExecutor;
10702
+ // src/services/semantic-planner.ts
10703
+ var SemanticPlanner;
10704
+ var init_semantic_planner = __esm({
10705
+ "src/services/semantic-planner.ts"() {
10706
+ SemanticPlanner = class {
10707
+ constructor(vectorSearch) {
10708
+ this.intentPatterns = /* @__PURE__ */ new Map();
10709
+ this.operationMappings = /* @__PURE__ */ new Map();
10710
+ this.contextHistory = [];
10711
+ this.vectorSearch = vectorSearch;
10712
+ this.initializeIntentPatterns();
10713
+ this.initializeOperationMappings();
10714
+ }
10715
+ /**
10716
+ * Parse natural language intent and create executable operations
10717
+ */
10718
+ async parseIntent(goal, description = "", context) {
10719
+ console.log(`\u{1F9E0} Analyzing intent: ${goal}`);
10720
+ const searchResults = await this.vectorSearch.semanticSearch(goal, 5);
10721
+ const analysis = await this.analyzeGoalIntent(goal, description, searchResults);
10722
+ analysis.decompositionNeeded = this.shouldDecompose(analysis, context);
10723
+ analysis.suggestedTools = this.suggestTools(analysis);
10724
+ if (context) {
10725
+ this.contextHistory.push(context);
10726
+ this.learnFromContext(context, analysis);
10727
+ }
10728
+ return analysis;
10729
+ }
10730
+ /**
10731
+ * Map declarative intent to executable tool sequences
10732
+ */
10733
+ async mapToOperations(analysis, context) {
10734
+ const operations = [];
10735
+ if (analysis.decompositionNeeded) {
10736
+ const decomposed = await this.decomposeIntent(analysis, context);
10737
+ operations.push(...decomposed);
10738
+ } else {
10739
+ const operation = this.mapSimpleIntent(analysis);
10740
+ if (operation) {
10741
+ operations.push(operation);
10742
+ }
10743
+ }
10744
+ return this.optimizeOperationSequence(operations, context);
10745
+ }
10746
+ /**
10747
+ * Convert operations to executable task steps
10748
+ */
10749
+ async operationsToSteps(operations, context) {
10750
+ const steps = [];
10751
+ for (const operation of operations) {
10752
+ const step = await this.operationToStep(operation, context);
10753
+ steps.push(step);
10754
+ }
10755
+ return steps;
10756
+ }
10757
+ /**
10758
+ * Initialize intent pattern recognition
10759
+ */
10760
+ initializeIntentPatterns() {
10761
+ this.intentPatterns.set("refactor", /refactor|redesign|restructure|reorganize/i);
10762
+ this.intentPatterns.set("implement", /implement|add|create|build|develop|feature/i);
10763
+ this.intentPatterns.set("fix", /fix|bug|issue|error|problem|resolve/i);
10764
+ this.intentPatterns.set("test", /test|validate|verify|check/i);
10765
+ this.intentPatterns.set("optimize", /optimize|improve|performance|efficiency/i);
10766
+ this.intentPatterns.set("document", /document|docs|readme|comment/i);
10767
+ this.intentPatterns.set("configure", /config|setup|initialize|install/i);
10768
+ }
10769
+ /**
10770
+ * Initialize operation mappings
10771
+ */
10772
+ initializeOperationMappings() {
10773
+ this.operationMappings.set("refactor_component", {
10774
+ operation: "refactor_component",
10775
+ tools: ["autonomous_task", "multi_file_editor", "ast_parser"],
10776
+ parameters: /* @__PURE__ */ new Map([["component", "target"], ["approach", "strategy"]]),
10777
+ dependencies: [],
10778
+ estimatedEffort: 5
10779
+ });
10780
+ this.operationMappings.set("implement_feature", {
10781
+ operation: "implement_feature",
10782
+ tools: ["autonomous_task", "search", "code_context"],
10783
+ parameters: /* @__PURE__ */ new Map([["feature", "description"], ["location", "path"]]),
10784
+ dependencies: ["analysis"],
10785
+ estimatedEffort: 4
10786
+ });
10787
+ this.operationMappings.set("fix_bug", {
10788
+ operation: "fix_bug",
10789
+ tools: ["search", "symbol_search", "autonomous_task"],
10790
+ parameters: /* @__PURE__ */ new Map([["bug", "description"], ["location", "file"]]),
10791
+ dependencies: ["locate"],
10792
+ estimatedEffort: 3
10793
+ });
10794
+ }
10795
+ /**
10796
+ * Analyze goal intent using NLP patterns
10797
+ */
10798
+ async analyzeGoalIntent(goal, description, searchResults) {
10799
+ const fullText = `${goal} ${description}`.toLowerCase();
10800
+ let bestIntent = "general";
10801
+ let highestConfidence = 0;
10802
+ for (const [intent, pattern] of this.intentPatterns) {
10803
+ const matches = fullText.match(pattern);
10804
+ if (matches) {
10805
+ const confidence = this.calculateConfidence(fullText, pattern);
10806
+ if (confidence > highestConfidence) {
10807
+ highestConfidence = confidence;
10808
+ bestIntent = intent;
10809
+ }
10810
+ }
10811
+ }
10812
+ const entities = this.extractEntities(fullText, searchResults);
10813
+ const complexity = this.determineComplexity(fullText, entities);
10814
+ return {
10815
+ intent: bestIntent,
10816
+ confidence: highestConfidence,
10817
+ entities,
10818
+ complexity,
10819
+ suggestedTools: [],
10820
+ decompositionNeeded: false
10821
+ };
10822
+ }
10823
+ /**
10824
+ * Calculate confidence score for intent matching
10825
+ */
10826
+ calculateConfidence(text, pattern) {
10827
+ const matches = text.match(pattern);
10828
+ if (!matches) return 0;
10829
+ const matchLength = matches[0].length;
10830
+ const textLength = text.length;
10831
+ const positionBonus = matches.index === 0 ? 0.2 : 0;
10832
+ return Math.min(1, matchLength / textLength + positionBonus);
10833
+ }
10834
+ /**
10835
+ * Extract entities from goal text
10836
+ */
10837
+ extractEntities(text, searchResults) {
10838
+ const entities = /* @__PURE__ */ new Map();
10839
+ const filePatterns = [
10840
+ /\b(?:\.\/|\.\.\/)?(?:src|lib|app|components?)\/[^\s]+\.[jt]sx?\b/g,
10841
+ /\b[a-zA-Z0-9_\-\/]+\.[jt]sx?\b/g
10842
+ ];
10843
+ for (const pattern of filePatterns) {
10844
+ const matches = text.match(pattern);
10845
+ if (matches) {
10846
+ entities.set("files", matches);
10847
+ break;
10848
+ }
10849
+ }
10850
+ const namePatterns = [
10851
+ /\b[A-Z][a-zA-Z0-9]*\b/g,
10852
+ // PascalCase
10853
+ /\b[a-z][a-zA-Z0-9]*\b/g
10854
+ // camelCase
10855
+ ];
10856
+ for (const pattern of namePatterns) {
10857
+ const matches = text.match(pattern);
10858
+ if (matches && matches.length > 0) {
10859
+ entities.set("names", matches.slice(0, 5));
10860
+ break;
10861
+ }
10862
+ }
10863
+ if (searchResults.length > 0) {
10864
+ entities.set("related_symbols", searchResults.map((r) => r.symbol?.name).filter(Boolean));
10865
+ entities.set("affected_files", searchResults.map((r) => r.filePath));
10866
+ }
10867
+ return entities;
10868
+ }
10869
+ /**
10870
+ * Determine complexity of the goal
10871
+ */
10872
+ determineComplexity(text, entities) {
10873
+ let complexityScore = 0;
10874
+ if (text.length > 200) complexityScore += 2;
10875
+ else if (text.length > 100) complexityScore += 1;
10876
+ const fileCount = entities.get("files")?.length || 0;
10877
+ const nameCount = entities.get("names")?.length || 0;
10878
+ complexityScore += Math.min(2, fileCount);
10879
+ complexityScore += Math.min(2, nameCount / 2);
10880
+ const complexKeywords = ["system", "architecture", "framework", "multiple", "all", "entire"];
10881
+ for (const keyword of complexKeywords) {
10882
+ if (text.includes(keyword)) complexityScore += 1;
10883
+ }
10884
+ if (complexityScore >= 4) return "high";
10885
+ if (complexityScore >= 2) return "medium";
10886
+ return "low";
10887
+ }
10888
+ /**
10889
+ * Determine if intent should be decomposed
10890
+ */
10891
+ shouldDecompose(analysis, context) {
10892
+ if (analysis.complexity === "high") return true;
10893
+ if (analysis.entities.get("files")?.length > 3) return true;
10894
+ if (context?.previousOperations && context.previousOperations.length > 5) return true;
10895
+ return false;
10896
+ }
10897
+ /**
10898
+ * Suggest appropriate tools for the intent
10899
+ */
10900
+ suggestTools(analysis) {
10901
+ const toolSuggestions = {
10902
+ refactor: ["autonomous_task", "multi_file_editor", "ast_parser", "dependency_analyzer"],
10903
+ implement: ["autonomous_task", "search", "code_context", "symbol_search"],
10904
+ fix: ["search", "symbol_search", "autonomous_task", "run_terminal_cmd"],
10905
+ test: ["run_terminal_cmd", "autonomous_task", "search"],
10906
+ optimize: ["code_context", "autonomous_task", "performance_analyzer"],
10907
+ document: ["autonomous_task", "search", "read_file"],
10908
+ configure: ["run_terminal_cmd", "autonomous_task", "search"]
10909
+ };
10910
+ return toolSuggestions[analysis.intent] || ["autonomous_task", "search"];
10911
+ }
10912
+ /**
10913
+ * Decompose complex intent into multiple operations
10914
+ */
10915
+ async decomposeIntent(analysis, context) {
10916
+ const operations = [];
10917
+ operations.push({
10918
+ operation: "analyze_context",
10919
+ tools: ["search", "code_context"],
10920
+ parameters: /* @__PURE__ */ new Map([["query", analysis.entities.get("files")?.[0] || ""]]),
10921
+ dependencies: [],
10922
+ estimatedEffort: 1
10923
+ });
10924
+ const mainOperation = this.operationMappings.get(`${analysis.intent}_${analysis.intent === "implement" ? "feature" : analysis.intent === "fix" ? "bug" : "component"}`);
10925
+ if (mainOperation) {
10926
+ operations.push({
10927
+ ...mainOperation,
10928
+ parameters: new Map([...mainOperation.parameters, ...analysis.entities])
10929
+ });
10930
+ }
10931
+ operations.push({
10932
+ operation: "validate_changes",
10933
+ tools: ["run_terminal_cmd", "autonomous_task"],
10934
+ parameters: /* @__PURE__ */ new Map([["type", "syntax_check"]]),
10935
+ dependencies: ["main_operation"],
10936
+ estimatedEffort: 1
10937
+ });
10938
+ return operations;
10939
+ }
10940
+ /**
10941
+ * Map simple intent to single operation
10942
+ */
10943
+ mapSimpleIntent(analysis) {
10944
+ const mappingKey = `${analysis.intent}_${analysis.intent === "implement" ? "feature" : analysis.intent === "fix" ? "bug" : "component"}`;
10945
+ return this.operationMappings.get(mappingKey) || null;
10946
+ }
10947
+ /**
10948
+ * Optimize operation sequence for efficiency
10949
+ */
10950
+ optimizeOperationSequence(operations, context) {
10951
+ const sorted = this.topologicalSort(operations);
10952
+ const merged = this.mergeSimilarOperations(sorted);
10953
+ if (context?.learnedPatterns) {
10954
+ return this.applyLearnedOptimizations(merged, context);
10955
+ }
10956
+ return merged;
10957
+ }
10958
+ /**
10959
+ * Convert operation to executable task step
10960
+ */
10961
+ async operationToStep(operation, context) {
10962
+ return {
10963
+ id: `step_${operation.operation}_${Date.now()}`,
10964
+ type: this.inferStepType(operation),
10965
+ description: `Execute ${operation.operation}`,
10966
+ inputs: Object.fromEntries(operation.parameters),
10967
+ status: "pending"
10968
+ };
10969
+ }
10970
+ /**
10971
+ * Infer step type from operation
10972
+ */
10973
+ inferStepType(operation) {
10974
+ if (operation.tools.includes("search")) return "search";
10975
+ if (operation.tools.includes("multi_file_editor")) return "edit";
10976
+ if (operation.tools.includes("run_terminal_cmd")) return "test";
10977
+ return "analyze";
10978
+ }
10979
+ /**
10980
+ * Topological sort operations by dependencies
10981
+ */
10982
+ topologicalSort(operations) {
10983
+ const sorted = [];
10984
+ const visited = /* @__PURE__ */ new Set();
10985
+ const visit = (op) => {
10986
+ if (visited.has(op.operation)) return;
10987
+ visited.add(op.operation);
10988
+ for (const dep of op.dependencies) {
10989
+ const depOp = operations.find((o) => o.operation === dep);
10990
+ if (depOp) visit(depOp);
10991
+ }
10992
+ sorted.push(op);
10993
+ };
10994
+ for (const op of operations) {
10995
+ visit(op);
10996
+ }
10997
+ return sorted;
10998
+ }
10999
+ /**
11000
+ * Merge similar operations to reduce redundancy
11001
+ */
11002
+ mergeSimilarOperations(operations) {
11003
+ const operationMap = /* @__PURE__ */ new Map();
11004
+ for (const op of operations) {
11005
+ const key = `${op.operation}_${Array.from(op.parameters.keys()).sort().join("_")}`;
11006
+ if (operationMap.has(key)) {
11007
+ const existing = operationMap.get(key);
11008
+ existing.tools = [.../* @__PURE__ */ new Set([...existing.tools, ...op.tools])];
11009
+ existing.estimatedEffort = Math.max(existing.estimatedEffort, op.estimatedEffort);
11010
+ } else {
11011
+ operationMap.set(key, { ...op });
11012
+ }
11013
+ }
11014
+ return Array.from(operationMap.values());
11015
+ }
11016
+ /**
11017
+ * Apply learned optimizations from context
11018
+ */
11019
+ applyLearnedOptimizations(operations, context) {
11020
+ const optimizations = context.learnedPatterns.get("operation_optimizations") || [];
11021
+ for (const optimization of optimizations) {
11022
+ if (optimization.type === "merge_operations") {
11023
+ const searchOps = operations.filter((op) => op.tools.includes("search"));
11024
+ const analyzeOps = operations.filter((op) => op.tools.includes("code_context"));
11025
+ if (searchOps.length > 0 && analyzeOps.length > 0) {
11026
+ const mergedOp = {
11027
+ ...searchOps[0],
11028
+ tools: [.../* @__PURE__ */ new Set([...searchOps[0].tools, ...analyzeOps[0].tools])],
11029
+ operation: "search_and_analyze",
11030
+ estimatedEffort: searchOps[0].estimatedEffort + analyzeOps[0].estimatedEffort - 1
11031
+ };
11032
+ const searchIndex = operations.indexOf(searchOps[0]);
11033
+ const analyzeIndex = operations.indexOf(analyzeOps[0]);
11034
+ operations.splice(Math.max(searchIndex, analyzeIndex), 1);
11035
+ operations.splice(Math.min(searchIndex, analyzeIndex), 1, mergedOp);
11036
+ }
11037
+ }
11038
+ }
11039
+ return operations;
11040
+ }
11041
+ /**
11042
+ * Learn patterns from successful operations
11043
+ */
11044
+ learnFromContext(context, analysis) {
11045
+ if (!context.learnedPatterns.has("intent_patterns")) {
11046
+ context.learnedPatterns.set("intent_patterns", /* @__PURE__ */ new Map());
11047
+ }
11048
+ const patterns = context.learnedPatterns.get("intent_patterns");
11049
+ patterns.set(analysis.intent, (patterns.get(analysis.intent) || 0) + 1);
11050
+ if (context.previousOperations.length > 1) {
11051
+ const sequence = context.previousOperations.map((op) => op.operation);
11052
+ context.learnedPatterns.set("successful_sequences", sequence);
11053
+ }
11054
+ }
11055
+ };
11056
+ }
11057
+ });
11058
+
11059
+ // src/services/enhanced-error-handler.ts
11060
+ var EnhancedErrorHandler;
11061
+ var init_enhanced_error_handler = __esm({
11062
+ "src/services/enhanced-error-handler.ts"() {
11063
+ EnhancedErrorHandler = class {
11064
+ constructor() {
11065
+ this.errorPatterns = /* @__PURE__ */ new Map();
11066
+ this.recoveryStrategies = /* @__PURE__ */ new Map();
11067
+ this.errorHistory = /* @__PURE__ */ new Map();
11068
+ this.retryConfigs = /* @__PURE__ */ new Map();
11069
+ this.initializeErrorPatterns();
11070
+ this.initializeRecoveryStrategies();
11071
+ this.initializeRetryConfigurations();
11072
+ }
11073
+ /**
11074
+ * Analyze an error and provide comprehensive handling information
11075
+ */
11076
+ async analyzeError(error, context = {}) {
11077
+ console.log(`\u{1F50D} Analyzing error: ${error.message}`);
11078
+ const classification = this.classifyError(error, context);
11079
+ const rootCause = await this.identifyRootCause(error, classification, context);
11080
+ const recoveryStrategies = this.generateRecoveryStrategies(classification, context);
11081
+ const userExplanation = this.generateUserExplanation(error, classification, rootCause);
11082
+ const suggestedActions = this.generateSuggestedActions(classification, recoveryStrategies);
11083
+ const preventionTips = this.generatePreventionTips(classification);
11084
+ const analysis = {
11085
+ originalError: error,
11086
+ classification,
11087
+ rootCause,
11088
+ context,
11089
+ recoveryStrategies,
11090
+ userExplanation,
11091
+ suggestedActions,
11092
+ preventionTips
11093
+ };
11094
+ this.storeErrorAnalysis(analysis);
11095
+ return analysis;
11096
+ }
11097
+ /**
11098
+ * Attempt automatic error recovery
11099
+ */
11100
+ async attemptRecovery(errorAnalysis, context = {}) {
11101
+ const automaticStrategies = errorAnalysis.recoveryStrategies.filter((strategy) => strategy.type === "automatic").sort((a, b) => b.successRate - a.successRate);
11102
+ for (const strategy of automaticStrategies) {
11103
+ try {
11104
+ console.log(`\u{1F527} Attempting recovery strategy: ${strategy.name}`);
11105
+ const result = await this.executeRecoveryStrategy(strategy, errorAnalysis, context);
11106
+ if (result.success) {
11107
+ return {
11108
+ success: true,
11109
+ strategy,
11110
+ result: result.output,
11111
+ explanation: `Successfully recovered using: ${strategy.name}`
11112
+ };
11113
+ }
11114
+ } catch (recoveryError) {
11115
+ console.warn(`Recovery strategy ${strategy.name} failed:`, recoveryError);
11116
+ }
11117
+ }
11118
+ return {
11119
+ success: false,
11120
+ explanation: "No automatic recovery strategy succeeded. Manual intervention required."
11121
+ };
11122
+ }
11123
+ /**
11124
+ * Execute retry with intelligent backoff
11125
+ */
11126
+ async executeWithRetry(operation, operationName, customConfig) {
11127
+ const config2 = { ...this.retryConfigs.get("default"), ...customConfig };
11128
+ let lastError = null;
11129
+ let attempt = 0;
11130
+ while (attempt < config2.maxAttempts) {
11131
+ attempt++;
11132
+ try {
11133
+ console.log(`\u{1F504} Attempt ${attempt}/${config2.maxAttempts} for ${operationName}`);
11134
+ const result = await operation();
11135
+ return { success: true, result, attempts: attempt };
11136
+ } catch (error) {
11137
+ lastError = error;
11138
+ console.warn(`Attempt ${attempt} failed:`, error);
11139
+ if (!this.isRetryableError(lastError, config2.retryableErrors)) {
11140
+ break;
11141
+ }
11142
+ if (attempt < config2.maxAttempts) {
11143
+ const delay = this.calculateBackoffDelay(config2, attempt);
11144
+ console.log(`\u23F3 Waiting ${delay}ms before retry...`);
11145
+ await this.delay(delay);
11146
+ }
11147
+ }
11148
+ }
11149
+ return { success: false, error: lastError, attempts: attempt };
11150
+ }
11151
+ /**
11152
+ * Classify error based on patterns and context
11153
+ */
11154
+ classifyError(error, context) {
11155
+ const errorMessage = error.message.toLowerCase();
11156
+ const errorStack = error.stack?.toLowerCase() || "";
11157
+ for (const [pattern, classification] of this.errorPatterns) {
11158
+ if (pattern.test(errorMessage) || pattern.test(errorStack)) {
11159
+ return {
11160
+ ...classification,
11161
+ confidence: this.calculatePatternConfidence(pattern, errorMessage)
11162
+ };
11163
+ }
11164
+ }
11165
+ return this.fallbackClassification(error, context);
11166
+ }
11167
+ /**
11168
+ * Identify the root cause of an error
11169
+ */
11170
+ async identifyRootCause(error, classification, context) {
11171
+ const message = error.message.toLowerCase();
11172
+ switch (classification.type) {
11173
+ case "syntax":
11174
+ if (message.includes("unexpected token") || message.includes("syntax error")) {
11175
+ return "Invalid syntax in code file";
11176
+ }
11177
+ if (message.includes("cannot find module") || message.includes("module not found")) {
11178
+ return "Missing or incorrect module import";
11179
+ }
11180
+ break;
11181
+ case "dependency":
11182
+ if (message.includes("cannot resolve dependency")) {
11183
+ return "Unresolved package dependency";
11184
+ }
11185
+ if (message.includes("version conflict") || message.includes("incompatible")) {
11186
+ return "Package version incompatibility";
11187
+ }
11188
+ break;
11189
+ case "permission":
11190
+ if (message.includes("permission denied") || message.includes("access denied")) {
11191
+ return "Insufficient file system permissions";
11192
+ }
11193
+ break;
11194
+ case "network":
11195
+ if (message.includes("timeout") || message.includes("connection refused")) {
11196
+ return "Network connectivity issue";
11197
+ }
11198
+ break;
11199
+ }
11200
+ return `Unspecified ${classification.type} error`;
11201
+ }
11202
+ /**
11203
+ * Generate recovery strategies for an error
11204
+ */
11205
+ generateRecoveryStrategies(classification, context) {
11206
+ const strategies = this.recoveryStrategies.get(classification.category) || [];
11207
+ return strategies.filter((strategy) => {
11208
+ return strategy.prerequisites.every((prereq) => {
11209
+ switch (prereq) {
11210
+ case "git_available":
11211
+ return context.hasGit !== false;
11212
+ case "package_manager_available":
11213
+ return context.hasPackageManager !== false;
11214
+ case "write_permissions":
11215
+ return context.hasWritePermissions !== false;
11216
+ default:
11217
+ return true;
11218
+ }
11219
+ });
11220
+ });
11221
+ }
11222
+ /**
11223
+ * Generate user-friendly explanation
11224
+ */
11225
+ generateUserExplanation(error, classification, rootCause) {
11226
+ let explanation = `**${classification.severity.toUpperCase()} ${classification.type.toUpperCase()} ERROR**
11227
+
11228
+ `;
11229
+ explanation += `**What happened:** ${error.message}
11230
+
11231
+ `;
11232
+ explanation += `**Root cause:** ${rootCause}
11233
+
11234
+ `;
11235
+ switch (classification.type) {
11236
+ case "syntax":
11237
+ explanation += `**What to check:**
11238
+ `;
11239
+ explanation += `- Verify code syntax and formatting
11240
+ `;
11241
+ explanation += `- Check for missing semicolons, brackets, or quotes
11242
+ `;
11243
+ explanation += `- Ensure all imports are correct
11244
+ `;
11245
+ break;
11246
+ case "dependency":
11247
+ explanation += `**What to check:**
11248
+ `;
11249
+ explanation += `- Verify package.json dependencies
11250
+ `;
11251
+ explanation += `- Check if packages are installed: \`npm install\` or \`yarn install\`
11252
+ `;
11253
+ explanation += `- Update packages if needed: \`npm update\`
11254
+ `;
11255
+ break;
11256
+ case "permission":
11257
+ explanation += `**What to check:**
11258
+ `;
11259
+ explanation += `- Verify file permissions
11260
+ `;
11261
+ explanation += `- Check if files are read-only
11262
+ `;
11263
+ explanation += `- Ensure write access to target directory
11264
+ `;
11265
+ break;
11266
+ }
11267
+ return explanation;
11268
+ }
11269
+ /**
11270
+ * Generate suggested immediate actions
11271
+ */
11272
+ generateSuggestedActions(classification, recoveryStrategies) {
11273
+ const actions = [];
11274
+ const autoStrategies = recoveryStrategies.filter((s) => s.type === "automatic");
11275
+ if (autoStrategies.length > 0) {
11276
+ actions.push(`\u{1F527} Try automatic recovery: ${autoStrategies[0].name}`);
11277
+ }
11278
+ const manualStrategies = recoveryStrategies.filter((s) => s.type === "manual");
11279
+ if (manualStrategies.length > 0) {
11280
+ actions.push(`\u{1F4CB} Manual recovery options available (${manualStrategies.length})`);
11281
+ }
11282
+ switch (classification.type) {
11283
+ case "syntax":
11284
+ actions.push("\u{1F50D} Check recent code changes for syntax errors");
11285
+ actions.push("\u{1F9EA} Run linter: `npm run lint` or similar");
11286
+ break;
11287
+ case "dependency":
11288
+ actions.push("\u{1F4E6} Check package versions: `npm ls`");
11289
+ actions.push("\u{1F504} Clear cache and reinstall: `rm -rf node_modules && npm install`");
11290
+ break;
11291
+ case "runtime":
11292
+ actions.push("\u{1F41B} Add debugging logs to identify issue location");
11293
+ actions.push("\u{1F9EA} Write unit test to reproduce the error");
11294
+ break;
11295
+ }
11296
+ return actions;
11297
+ }
11298
+ /**
11299
+ * Generate prevention tips
11300
+ */
11301
+ generatePreventionTips(classification) {
11302
+ const tips = [];
11303
+ switch (classification.type) {
11304
+ case "syntax":
11305
+ tips.push("Use a linter (ESLint, Prettier) to catch syntax errors early");
11306
+ tips.push("Enable syntax checking in your IDE");
11307
+ tips.push("Write tests to validate code changes");
11308
+ break;
11309
+ case "dependency":
11310
+ tips.push("Keep dependencies updated regularly");
11311
+ tips.push("Use exact versions in package.json to avoid conflicts");
11312
+ tips.push("Test dependency updates in isolation");
11313
+ break;
11314
+ case "runtime":
11315
+ tips.push("Add comprehensive error handling");
11316
+ tips.push("Write unit and integration tests");
11317
+ tips.push("Use type checking (TypeScript) to catch errors early");
11318
+ break;
11319
+ case "permission":
11320
+ tips.push("Avoid running as root unless necessary");
11321
+ tips.push("Check file permissions before operations");
11322
+ tips.push("Use proper user accounts for different services");
11323
+ break;
11324
+ }
11325
+ return tips;
11326
+ }
11327
+ /**
11328
+ * Initialize error classification patterns
11329
+ */
11330
+ initializeErrorPatterns() {
11331
+ this.errorPatterns.set(/syntax error|unexpected token|parsing error/i, {
11332
+ type: "syntax",
11333
+ severity: "high",
11334
+ category: "code_quality",
11335
+ confidence: 0.9,
11336
+ recoverable: true
11337
+ });
11338
+ this.errorPatterns.set(/cannot find module|module not found|cannot resolve/i, {
11339
+ type: "dependency",
11340
+ severity: "medium",
11341
+ category: "dependencies",
11342
+ confidence: 0.95,
11343
+ recoverable: true
11344
+ });
11345
+ this.errorPatterns.set(/permission denied|access denied|eacces/i, {
11346
+ type: "permission",
11347
+ severity: "high",
11348
+ category: "filesystem",
11349
+ confidence: 0.9,
11350
+ recoverable: false
11351
+ });
11352
+ this.errorPatterns.set(/timeout|connection refused|network error/i, {
11353
+ type: "network",
11354
+ severity: "medium",
11355
+ category: "connectivity",
11356
+ confidence: 0.8,
11357
+ recoverable: true
11358
+ });
11359
+ this.errorPatterns.set(/type error|reference error|null pointer|undefined/i, {
11360
+ type: "runtime",
11361
+ severity: "high",
11362
+ category: "logic",
11363
+ confidence: 0.7,
11364
+ recoverable: true
11365
+ });
11366
+ }
11367
+ /**
11368
+ * Initialize recovery strategies
11369
+ */
11370
+ initializeRecoveryStrategies() {
11371
+ this.recoveryStrategies.set("code_quality", [
11372
+ {
11373
+ id: "syntax_check",
11374
+ name: "Run Syntax Validation",
11375
+ description: "Automatically check and fix common syntax issues",
11376
+ type: "automatic",
11377
+ estimatedEffort: 1,
11378
+ successRate: 0.7,
11379
+ prerequisites: ["package_manager_available"],
11380
+ steps: [
11381
+ {
11382
+ id: "run_linter",
11383
+ description: "Execute code linter to identify issues",
11384
+ action: "run_terminal_cmd",
11385
+ parameters: { command: "npm run lint" },
11386
+ timeout: 3e4,
11387
+ rollbackOnFailure: false
11388
+ }
11389
+ ]
11390
+ },
11391
+ {
11392
+ id: "format_code",
11393
+ name: "Auto-format Code",
11394
+ description: "Automatically format code to fix indentation and spacing issues",
11395
+ type: "automatic",
11396
+ estimatedEffort: 1,
11397
+ successRate: 0.8,
11398
+ prerequisites: ["package_manager_available"],
11399
+ steps: [
11400
+ {
11401
+ id: "run_formatter",
11402
+ description: "Execute code formatter",
11403
+ action: "run_terminal_cmd",
11404
+ parameters: { command: "npm run format" },
11405
+ timeout: 3e4,
11406
+ rollbackOnFailure: false
11407
+ }
11408
+ ]
11409
+ }
11410
+ ]);
11411
+ this.recoveryStrategies.set("dependencies", [
11412
+ {
11413
+ id: "install_deps",
11414
+ name: "Install Missing Dependencies",
11415
+ description: "Automatically install missing packages",
11416
+ type: "automatic",
11417
+ estimatedEffort: 2,
11418
+ successRate: 0.9,
11419
+ prerequisites: ["package_manager_available"],
11420
+ steps: [
11421
+ {
11422
+ id: "npm_install",
11423
+ description: "Install npm dependencies",
11424
+ action: "run_terminal_cmd",
11425
+ parameters: { command: "npm install" },
11426
+ timeout: 12e4,
11427
+ rollbackOnFailure: false
11428
+ }
11429
+ ]
11430
+ },
11431
+ {
11432
+ id: "clear_cache",
11433
+ name: "Clear Package Cache",
11434
+ description: "Clear package manager cache and reinstall",
11435
+ type: "semi-automatic",
11436
+ estimatedEffort: 3,
11437
+ successRate: 0.75,
11438
+ prerequisites: ["package_manager_available"],
11439
+ steps: [
11440
+ {
11441
+ id: "clear_npm_cache",
11442
+ description: "Clear npm cache",
11443
+ action: "run_terminal_cmd",
11444
+ parameters: { command: "npm cache clean --force" },
11445
+ timeout: 3e4,
11446
+ rollbackOnFailure: false
11447
+ },
11448
+ {
11449
+ id: "reinstall_deps",
11450
+ description: "Reinstall all dependencies",
11451
+ action: "run_terminal_cmd",
11452
+ parameters: { command: "rm -rf node_modules package-lock.json && npm install" },
11453
+ timeout: 18e4,
11454
+ rollbackOnFailure: false
11455
+ }
11456
+ ]
11457
+ }
11458
+ ]);
11459
+ this.recoveryStrategies.set("filesystem", [
11460
+ {
11461
+ id: "fix_permissions",
11462
+ name: "Fix File Permissions",
11463
+ description: "Automatically fix common file permission issues",
11464
+ type: "automatic",
11465
+ estimatedEffort: 1,
11466
+ successRate: 0.6,
11467
+ prerequisites: ["write_permissions"],
11468
+ steps: [
11469
+ {
11470
+ id: "chmod_files",
11471
+ description: "Set proper permissions on files",
11472
+ action: "run_terminal_cmd",
11473
+ parameters: { command: "chmod -R u+w ." },
11474
+ timeout: 3e4,
11475
+ rollbackOnFailure: false
11476
+ }
11477
+ ]
11478
+ }
11479
+ ]);
11480
+ }
11481
+ /**
11482
+ * Initialize retry configurations
11483
+ */
11484
+ initializeRetryConfigurations() {
11485
+ this.retryConfigs.set("default", {
11486
+ maxAttempts: 3,
11487
+ backoffStrategy: "exponential",
11488
+ baseDelay: 1e3,
11489
+ maxDelay: 3e4,
11490
+ jitter: true,
11491
+ retryableErrors: ["timeout", "network", "temporary"]
11492
+ });
11493
+ this.retryConfigs.set("aggressive", {
11494
+ maxAttempts: 5,
11495
+ backoffStrategy: "linear",
11496
+ baseDelay: 500,
11497
+ maxDelay: 1e4,
11498
+ jitter: false,
11499
+ retryableErrors: ["timeout", "network"]
11500
+ });
11501
+ this.retryConfigs.set("conservative", {
11502
+ maxAttempts: 2,
11503
+ backoffStrategy: "fixed",
11504
+ baseDelay: 5e3,
11505
+ maxDelay: 5e3,
11506
+ jitter: false,
11507
+ retryableErrors: ["network"]
11508
+ });
11509
+ }
11510
+ /**
11511
+ * Execute a recovery strategy
11512
+ */
11513
+ async executeRecoveryStrategy(strategy, errorAnalysis, context) {
11514
+ console.log(`Executing recovery strategy: ${strategy.name}`);
11515
+ for (const step of strategy.steps) {
11516
+ try {
11517
+ console.log(`Step: ${step.description}`);
11518
+ switch (step.action) {
11519
+ case "run_terminal_cmd":
11520
+ const command = step.parameters.command;
11521
+ if (command.includes("npm install")) {
11522
+ await this.delay(2e3);
11523
+ return { success: true, output: "Dependencies installed successfully" };
11524
+ }
11525
+ if (command.includes("lint") || command.includes("format")) {
11526
+ await this.delay(1e3);
11527
+ return { success: true, output: "Code validated/formatted successfully" };
11528
+ }
11529
+ break;
11530
+ default:
11531
+ console.warn(`Unknown recovery action: ${step.action}`);
11532
+ }
11533
+ } catch (stepError) {
11534
+ console.error(`Recovery step failed: ${step.description}`, stepError);
11535
+ if (step.rollbackOnFailure) ;
11536
+ return { success: false };
11537
+ }
11538
+ }
11539
+ return { success: true };
11540
+ }
11541
+ /**
11542
+ * Calculate pattern confidence score
11543
+ */
11544
+ calculatePatternConfidence(pattern, text) {
11545
+ const matches = text.match(pattern);
11546
+ if (!matches) return 0;
11547
+ const matchLength = matches[0].length;
11548
+ const textLength = text.length;
11549
+ const exactMatch = matches[0].toLowerCase() === text.toLowerCase();
11550
+ let confidence = matchLength / textLength;
11551
+ if (exactMatch) confidence += 0.3;
11552
+ return Math.min(1, confidence);
11553
+ }
11554
+ /**
11555
+ * Fallback error classification
11556
+ */
11557
+ fallbackClassification(error, context) {
11558
+ const message = error.message.toLowerCase();
11559
+ if (message.includes("cannot") || message.includes("failed") || message.includes("error")) {
11560
+ return {
11561
+ type: "runtime",
11562
+ severity: "medium",
11563
+ category: "execution",
11564
+ confidence: 0.5,
11565
+ recoverable: true
11566
+ };
11567
+ }
11568
+ return {
11569
+ type: "unknown",
11570
+ severity: "medium",
11571
+ category: "general",
11572
+ confidence: 0.1,
11573
+ recoverable: false
11574
+ };
11575
+ }
11576
+ /**
11577
+ * Calculate backoff delay for retries
11578
+ */
11579
+ calculateBackoffDelay(config2, attempt) {
11580
+ let delay;
11581
+ switch (config2.backoffStrategy) {
11582
+ case "linear":
11583
+ delay = config2.baseDelay * attempt;
11584
+ break;
11585
+ case "exponential":
11586
+ delay = config2.baseDelay * Math.pow(2, attempt - 1);
11587
+ break;
11588
+ case "fixed":
11589
+ default:
11590
+ delay = config2.baseDelay;
11591
+ break;
11592
+ }
11593
+ delay = Math.min(delay, config2.maxDelay);
11594
+ if (config2.jitter) {
11595
+ delay = delay * (0.5 + Math.random() * 0.5);
11596
+ }
11597
+ return Math.floor(delay);
11598
+ }
11599
+ /**
11600
+ * Check if an error is retryable
11601
+ */
11602
+ isRetryableError(error, retryablePatterns) {
11603
+ const message = error.message.toLowerCase();
11604
+ return retryablePatterns.some(
11605
+ (pattern) => message.includes(pattern.toLowerCase())
11606
+ );
11607
+ }
11608
+ /**
11609
+ * Store error analysis for learning
11610
+ */
11611
+ storeErrorAnalysis(analysis) {
11612
+ const key = `${analysis.classification.type}_${analysis.classification.category}`;
11613
+ if (!this.errorHistory.has(key)) {
11614
+ this.errorHistory.set(key, []);
11615
+ }
11616
+ const history = this.errorHistory.get(key);
11617
+ history.push(analysis);
11618
+ if (history.length > 100) {
11619
+ history.shift();
11620
+ }
11621
+ }
11622
+ /**
11623
+ * Utility delay function
11624
+ */
11625
+ delay(ms) {
11626
+ return new Promise((resolve8) => setTimeout(resolve8, ms));
11627
+ }
11628
+ };
11629
+ }
11630
+ });
11631
+ var TransactionManager, AutonomousExecutor;
10699
11632
  var init_autonomous_executor = __esm({
10700
11633
  "src/services/autonomous-executor.ts"() {
10701
11634
  init_vector_search_engine();
@@ -10704,6 +11637,123 @@ var init_autonomous_executor = __esm({
10704
11637
  init_ast_parser();
10705
11638
  init_symbol_search();
10706
11639
  init_dependency_analyzer();
11640
+ init_semantic_planner();
11641
+ init_enhanced_error_handler();
11642
+ TransactionManager = class {
11643
+ constructor(backupDir = "/tmp/autonomous-backups") {
11644
+ this.transactions = /* @__PURE__ */ new Map();
11645
+ this.backupDir = backupDir;
11646
+ }
11647
+ /**
11648
+ * Start a new transaction
11649
+ */
11650
+ async beginTransaction(transactionId) {
11651
+ const transaction = {
11652
+ id: transactionId,
11653
+ steps: [],
11654
+ status: "active",
11655
+ createdAt: Date.now()
11656
+ };
11657
+ this.transactions.set(transactionId, transaction);
11658
+ }
11659
+ /**
11660
+ * Add a file operation to the transaction
11661
+ */
11662
+ async addFileOperation(transactionId, filePath, newContent, operation = "update") {
11663
+ const transaction = this.transactions.get(transactionId);
11664
+ if (!transaction || transaction.status !== "active") {
11665
+ throw new Error(`Transaction ${transactionId} not found or not active`);
11666
+ }
11667
+ let originalContent = "";
11668
+ try {
11669
+ if (operation !== "create") {
11670
+ originalContent = await fs7.readFile(filePath, "utf-8");
11671
+ }
11672
+ } catch (error) {
11673
+ if (operation === "update") {
11674
+ throw new Error(`Failed to read original content of ${filePath}: ${error}`);
11675
+ }
11676
+ }
11677
+ const fileTransaction = {
11678
+ filePath,
11679
+ originalContent,
11680
+ newContent,
11681
+ operation,
11682
+ timestamp: Date.now()
11683
+ };
11684
+ transaction.steps.push(fileTransaction);
11685
+ }
11686
+ /**
11687
+ * Commit the transaction (apply all changes)
11688
+ */
11689
+ async commitTransaction(transactionId) {
11690
+ const transaction = this.transactions.get(transactionId);
11691
+ if (!transaction || transaction.status !== "active") {
11692
+ throw new Error(`Transaction ${transactionId} not found or not active`);
11693
+ }
11694
+ try {
11695
+ for (const step of transaction.steps) {
11696
+ await this.applyFileTransaction(step);
11697
+ }
11698
+ transaction.status = "committed";
11699
+ transaction.committedAt = Date.now();
11700
+ } catch (error) {
11701
+ await this.rollbackTransaction(transactionId);
11702
+ throw error;
11703
+ }
11704
+ }
11705
+ /**
11706
+ * Rollback the transaction (restore original state)
11707
+ */
11708
+ async rollbackTransaction(transactionId) {
11709
+ const transaction = this.transactions.get(transactionId);
11710
+ if (!transaction) {
11711
+ throw new Error(`Transaction ${transactionId} not found`);
11712
+ }
11713
+ if (transaction.status === "committed") {
11714
+ for (const step of transaction.steps.reverse()) {
11715
+ await this.rollbackFileTransaction(step);
11716
+ }
11717
+ }
11718
+ transaction.status = "rolled_back";
11719
+ transaction.rolledBackAt = Date.now();
11720
+ }
11721
+ /**
11722
+ * Apply a single file transaction
11723
+ */
11724
+ async applyFileTransaction(step) {
11725
+ const dir = path8.dirname(step.filePath);
11726
+ await fs7.mkdir(dir, { recursive: true });
11727
+ if (step.operation === "delete") {
11728
+ await fs7.unlink(step.filePath);
11729
+ } else {
11730
+ await fs7.writeFile(step.filePath, step.newContent, "utf-8");
11731
+ }
11732
+ }
11733
+ /**
11734
+ * Rollback a single file transaction
11735
+ */
11736
+ async rollbackFileTransaction(step) {
11737
+ if (step.operation === "create") {
11738
+ try {
11739
+ await fs7.unlink(step.filePath);
11740
+ } catch {
11741
+ }
11742
+ } else if (step.operation === "update") {
11743
+ await fs7.writeFile(step.filePath, step.originalContent, "utf-8");
11744
+ } else if (step.operation === "delete") {
11745
+ const dir = path8.dirname(step.filePath);
11746
+ await fs7.mkdir(dir, { recursive: true });
11747
+ await fs7.writeFile(step.filePath, step.originalContent, "utf-8");
11748
+ }
11749
+ }
11750
+ /**
11751
+ * Get transaction status
11752
+ */
11753
+ getTransaction(transactionId) {
11754
+ return this.transactions.get(transactionId);
11755
+ }
11756
+ };
10707
11757
  AutonomousExecutor = class {
10708
11758
  constructor(config2 = {}) {
10709
11759
  this.activeTasks = /* @__PURE__ */ new Map();
@@ -10735,6 +11785,9 @@ var init_autonomous_executor = __esm({
10735
11785
  this.astParser = new ASTParserTool();
10736
11786
  this.symbolSearch = new SymbolSearchTool();
10737
11787
  this.dependencyAnalyzer = new DependencyAnalyzerTool();
11788
+ this.transactionManager = new TransactionManager();
11789
+ this.semanticPlanner = new SemanticPlanner(this.vectorSearch);
11790
+ this.errorHandler = new EnhancedErrorHandler();
10738
11791
  }
10739
11792
  /**
10740
11793
  * Plan and execute a complex task autonomously
@@ -10754,16 +11807,17 @@ var init_autonomous_executor = __esm({
10754
11807
  console.log(`\u2699\uFE0F Step ${i + 1}/${plan.steps.length}: ${step.description}`);
10755
11808
  step.status = "running";
10756
11809
  plan.status = "executing";
10757
- plan.progress = Math.round(i / plan.steps.length * 100);
10758
11810
  const stepResult = await this.executeStep(step, context);
10759
11811
  step.outputs = stepResult;
10760
11812
  step.status = "completed";
10761
11813
  step.duration = Date.now() - startTime;
10762
- console.log(`\u2705 Step ${i + 1} completed`);
11814
+ console.log(`\u2705 Step ${i + 1} completed (${plan.progress}% complete)`);
10763
11815
  } catch (error) {
10764
11816
  step.status = "failed";
10765
- step.error = error instanceof Error ? error.message : String(error);
11817
+ const stepError = error instanceof Error ? error : new Error(String(error));
11818
+ step.error = stepError.message;
10766
11819
  console.error(`\u274C Step ${i + 1} failed:`, step.error);
11820
+ await this.updateTaskProgress(plan, context);
10767
11821
  const recovered = await this.attemptRecovery(step, context);
10768
11822
  if (!recovered) {
10769
11823
  plan.status = "failed";
@@ -10807,15 +11861,32 @@ var init_autonomous_executor = __esm({
10807
11861
  }
10808
11862
  }
10809
11863
  /**
10810
- * Create an execution plan by analyzing the goal
11864
+ * Create an execution plan using semantic planning
10811
11865
  */
10812
11866
  async createExecutionPlan(taskId, goal, description) {
10813
- const searchResults = await this.vectorSearch.semanticSearch(goal, 10);
11867
+ console.log(`\u{1F4CB} Creating execution plan for: ${goal}`);
11868
+ const semanticContext = {
11869
+ userGoal: goal,
11870
+ projectContext: /* @__PURE__ */ new Map([
11871
+ ["rootPath", this.config.rootPath],
11872
+ ["description", description]
11873
+ ]),
11874
+ previousOperations: [],
11875
+ learnedPatterns: /* @__PURE__ */ new Map()
11876
+ };
11877
+ const intentAnalysis = await this.semanticPlanner.parseIntent(goal, description, semanticContext);
11878
+ console.log(`\u{1F3AF} Detected intent: ${intentAnalysis.intent} (confidence: ${(intentAnalysis.confidence * 100).toFixed(1)}%)`);
11879
+ console.log(`\u{1F527} Suggested tools: ${intentAnalysis.suggestedTools.join(", ")}`);
11880
+ const operations = await this.semanticPlanner.mapToOperations(intentAnalysis, semanticContext);
11881
+ const steps = await this.semanticPlanner.operationsToSteps(operations, semanticContext);
10814
11882
  const context = {
10815
11883
  rootPath: this.config.rootPath,
10816
- affectedFiles: searchResults.map((r) => r.filePath),
10817
- relatedSymbols: searchResults.map((r) => r.symbol.name),
10818
- dependencies: []
11884
+ affectedFiles: intentAnalysis.entities.get("affected_files") || [],
11885
+ relatedSymbols: intentAnalysis.entities.get("related_symbols") || [],
11886
+ dependencies: [],
11887
+ intent: intentAnalysis.intent,
11888
+ confidence: intentAnalysis.confidence,
11889
+ suggestedTools: intentAnalysis.suggestedTools
10819
11890
  };
10820
11891
  if (context.affectedFiles.length > 0) {
10821
11892
  const depResult = await this.dependencyAnalyzer.execute({
@@ -10828,7 +11899,6 @@ var init_autonomous_executor = __esm({
10828
11899
  context.dependencies = parsed.result?.dependencies?.map((d) => d.name) || [];
10829
11900
  }
10830
11901
  }
10831
- const steps = await this.generateExecutionSteps(goal, description, context);
10832
11902
  return {
10833
11903
  id: taskId,
10834
11904
  goal,
@@ -10841,144 +11911,247 @@ var init_autonomous_executor = __esm({
10841
11911
  };
10842
11912
  }
10843
11913
  /**
10844
- * Generate execution steps based on goal analysis
11914
+ * Generate execution steps based on advanced goal analysis and task decomposition
10845
11915
  */
10846
11916
  async generateExecutionSteps(goal, description, context) {
10847
11917
  const steps = [];
10848
- if (goal.toLowerCase().includes("refactor")) {
10849
- steps.push(
10850
- {
10851
- id: "analyze_code",
10852
- type: "analyze",
10853
- description: "Analyze current code structure and dependencies",
10854
- inputs: { files: context.affectedFiles },
10855
- status: "pending"
10856
- },
10857
- {
10858
- id: "plan_refactoring",
10859
- type: "analyze",
10860
- description: "Plan refactoring approach and identify changes",
10861
- inputs: { symbols: context.relatedSymbols },
10862
- status: "pending"
10863
- },
10864
- {
10865
- id: "apply_changes",
10866
- type: "edit",
10867
- description: "Apply refactoring changes to codebase",
10868
- inputs: { files: context.affectedFiles },
10869
- status: "pending"
10870
- },
10871
- {
10872
- id: "validate_changes",
10873
- type: "validate",
10874
- description: "Validate refactoring maintains functionality",
10875
- inputs: {},
10876
- status: "pending"
10877
- }
10878
- );
10879
- } else if (goal.toLowerCase().includes("add") || goal.toLowerCase().includes("implement")) {
10880
- steps.push(
10881
- {
10882
- id: "research_context",
10883
- type: "search",
10884
- description: "Research existing patterns and implementations",
10885
- inputs: { query: goal },
10886
- status: "pending"
10887
- },
10888
- {
10889
- id: "identify_location",
10890
- type: "analyze",
10891
- description: "Identify optimal location for new implementation",
10892
- inputs: { files: context.affectedFiles },
10893
- status: "pending"
10894
- },
10895
- {
10896
- id: "implement_feature",
10897
- type: "edit",
10898
- description: "Implement the new feature or functionality",
10899
- inputs: {},
10900
- status: "pending"
10901
- },
10902
- {
10903
- id: "update_dependencies",
10904
- type: "edit",
10905
- description: "Update imports, exports, and dependencies",
10906
- inputs: { dependencies: context.dependencies },
10907
- status: "pending"
10908
- },
10909
- {
10910
- id: "validate_implementation",
10911
- type: "validate",
10912
- description: "Validate implementation works correctly",
10913
- inputs: {},
10914
- status: "pending"
10915
- }
10916
- );
10917
- } else if (goal.toLowerCase().includes("fix") || goal.toLowerCase().includes("bug")) {
10918
- steps.push(
10919
- {
10920
- id: "locate_issue",
10921
- type: "search",
10922
- description: "Locate the source of the issue",
10923
- inputs: { query: description },
10924
- status: "pending"
10925
- },
10926
- {
10927
- id: "analyze_impact",
10928
- type: "analyze",
10929
- description: "Analyze impact and related components",
10930
- inputs: { files: context.affectedFiles },
10931
- status: "pending"
10932
- },
10933
- {
10934
- id: "apply_fix",
10935
- type: "edit",
10936
- description: "Apply fix to resolve the issue",
10937
- inputs: {},
10938
- status: "pending"
10939
- },
10940
- {
10941
- id: "test_fix",
10942
- type: "validate",
10943
- description: "Test that fix resolves issue without side effects",
10944
- inputs: {},
10945
- status: "pending"
11918
+ const decomposedTasks = await this.decomposeGoal(goal, description, context);
11919
+ for (const subTask of decomposedTasks) {
11920
+ const taskSteps = await this.generateStepsForSubTask(subTask, context);
11921
+ steps.push(...taskSteps);
11922
+ }
11923
+ if (steps.length > 0) {
11924
+ steps.push({
11925
+ id: "final_validation",
11926
+ type: "validate",
11927
+ description: "Perform comprehensive validation of all changes",
11928
+ inputs: { allSteps: steps.map((s) => s.id) },
11929
+ status: "pending"
11930
+ });
11931
+ steps.push({
11932
+ id: "run_tests",
11933
+ type: "test",
11934
+ description: "Execute relevant tests to ensure functionality",
11935
+ inputs: { affectedFiles: context.affectedFiles },
11936
+ status: "pending"
11937
+ });
11938
+ }
11939
+ return steps;
11940
+ }
11941
+ /**
11942
+ * Decompose complex goals into manageable subtasks using AI planning
11943
+ */
11944
+ async decomposeGoal(goal, description, context) {
11945
+ const subTasks = [];
11946
+ const goalAnalysis = await this.analyzeGoalComplexity(goal, description);
11947
+ if (goalAnalysis.complexity === "high") {
11948
+ const initialSubTasks = this.generateInitialSubTasks(goal, description, context);
11949
+ subTasks.push(...initialSubTasks);
11950
+ for (const subTask of subTasks) {
11951
+ const refinedSubTasks = await this.refineSubTask(subTask, context);
11952
+ if (refinedSubTasks.length > 1) {
11953
+ const index = subTasks.indexOf(subTask);
11954
+ subTasks.splice(index, 1, ...refinedSubTasks);
10946
11955
  }
10947
- );
11956
+ }
10948
11957
  } else {
10949
- steps.push(
10950
- {
10951
- id: "understand_task",
10952
- type: "search",
10953
- description: "Understand task requirements and context",
10954
- inputs: { query: goal },
10955
- status: "pending"
10956
- },
10957
- {
10958
- id: "analyze_codebase",
10959
- type: "analyze",
10960
- description: "Analyze relevant codebase components",
10961
- inputs: { files: context.affectedFiles },
10962
- status: "pending"
10963
- },
10964
- {
10965
- id: "execute_changes",
10966
- type: "edit",
10967
- description: "Execute required changes",
10968
- inputs: {},
10969
- status: "pending"
10970
- },
10971
- {
10972
- id: "validate_result",
10973
- type: "validate",
10974
- description: "Validate execution results",
10975
- inputs: {},
10976
- status: "pending"
11958
+ subTasks.push({
11959
+ id: "main_task",
11960
+ description: goal,
11961
+ type: this.inferTaskType(goal),
11962
+ complexity: goalAnalysis.complexity,
11963
+ dependencies: [],
11964
+ estimatedEffort: goalAnalysis.estimatedSteps
11965
+ });
11966
+ }
11967
+ return subTasks;
11968
+ }
11969
+ /**
11970
+ * Analyze goal complexity to determine planning approach
11971
+ */
11972
+ async analyzeGoalComplexity(goal, description) {
11973
+ const keywords = {
11974
+ high: ["refactor", "migrate", "redesign", "architect", "system", "framework"],
11975
+ low: ["fix", "update", "change", "modify", "improve", "optimize"]
11976
+ };
11977
+ const goal_lower = goal.toLowerCase();
11978
+ let complexity = "medium";
11979
+ let estimatedSteps = 3;
11980
+ if (keywords.high.some((k) => goal_lower.includes(k))) {
11981
+ complexity = "high";
11982
+ estimatedSteps = 8;
11983
+ } else if (keywords.low.some((k) => goal_lower.includes(k))) {
11984
+ complexity = "low";
11985
+ estimatedSteps = 2;
11986
+ }
11987
+ if (description.length < 50) {
11988
+ complexity = "low";
11989
+ estimatedSteps = Math.max(1, estimatedSteps - 1);
11990
+ } else if (description.length > 200) {
11991
+ complexity = "high";
11992
+ estimatedSteps = Math.min(15, estimatedSteps + 3);
11993
+ }
11994
+ return { complexity, estimatedSteps };
11995
+ }
11996
+ /**
11997
+ * Generate initial subtasks for complex goals
11998
+ */
11999
+ generateInitialSubTasks(goal, description, context) {
12000
+ const subTasks = [];
12001
+ subTasks.push({
12002
+ id: "analysis",
12003
+ description: "Analyze current codebase and requirements",
12004
+ type: "analysis",
12005
+ complexity: "low",
12006
+ dependencies: [],
12007
+ estimatedEffort: 2
12008
+ });
12009
+ subTasks.push({
12010
+ id: "planning",
12011
+ description: "Create detailed implementation plan",
12012
+ type: "planning",
12013
+ complexity: "medium",
12014
+ dependencies: ["analysis"],
12015
+ estimatedEffort: 3
12016
+ });
12017
+ subTasks.push({
12018
+ id: "implementation",
12019
+ description: "Execute the planned changes",
12020
+ type: "implementation",
12021
+ complexity: "high",
12022
+ dependencies: ["planning"],
12023
+ estimatedEffort: 5
12024
+ });
12025
+ subTasks.push({
12026
+ id: "validation",
12027
+ description: "Validate implementation and test results",
12028
+ type: "validation",
12029
+ complexity: "medium",
12030
+ dependencies: ["implementation"],
12031
+ estimatedEffort: 2
12032
+ });
12033
+ return subTasks;
12034
+ }
12035
+ /**
12036
+ * Refine subtasks based on codebase context
12037
+ */
12038
+ async refineSubTask(subTask, context) {
12039
+ if (subTask.type === "implementation") {
12040
+ const fileTasks = [];
12041
+ for (const file of context.affectedFiles.slice(0, 5)) {
12042
+ fileTasks.push({
12043
+ id: `implement_${file.replace(/[^a-zA-Z0-9]/g, "_")}`,
12044
+ description: `Implement changes in ${file}`,
12045
+ type: "implementation",
12046
+ complexity: "medium",
12047
+ dependencies: [subTask.id],
12048
+ estimatedEffort: 2,
12049
+ targetFile: file
12050
+ });
12051
+ }
12052
+ return fileTasks.length > 0 ? fileTasks : [subTask];
12053
+ }
12054
+ return [subTask];
12055
+ }
12056
+ /**
12057
+ * Generate execution steps for a specific subtask
12058
+ */
12059
+ async generateStepsForSubTask(subTask, context) {
12060
+ const steps = [];
12061
+ switch (subTask.type) {
12062
+ case "analysis":
12063
+ steps.push(
12064
+ {
12065
+ id: `${subTask.id}_search`,
12066
+ type: "search",
12067
+ description: "Search for relevant code patterns and examples",
12068
+ inputs: { query: subTask.description },
12069
+ status: "pending"
12070
+ },
12071
+ {
12072
+ id: `${subTask.id}_analyze`,
12073
+ type: "analyze",
12074
+ description: "Analyze code structure and dependencies",
12075
+ inputs: { files: context.affectedFiles },
12076
+ status: "pending"
12077
+ }
12078
+ );
12079
+ break;
12080
+ case "planning":
12081
+ steps.push(
12082
+ {
12083
+ id: `${subTask.id}_design`,
12084
+ type: "analyze",
12085
+ description: "Design the implementation approach",
12086
+ inputs: { symbols: context.relatedSymbols },
12087
+ status: "pending"
12088
+ },
12089
+ {
12090
+ id: `${subTask.id}_dependencies`,
12091
+ type: "analyze",
12092
+ description: "Identify and plan dependency updates",
12093
+ inputs: { dependencies: context.dependencies },
12094
+ status: "pending"
12095
+ }
12096
+ );
12097
+ break;
12098
+ case "implementation":
12099
+ if (subTask.targetFile) {
12100
+ steps.push({
12101
+ id: `${subTask.id}_edit`,
12102
+ type: "edit",
12103
+ description: `Apply changes to ${subTask.targetFile}`,
12104
+ inputs: { file: subTask.targetFile, goal: subTask.description },
12105
+ status: "pending"
12106
+ });
12107
+ } else {
12108
+ steps.push({
12109
+ id: `${subTask.id}_edit`,
12110
+ type: "edit",
12111
+ description: "Apply implementation changes",
12112
+ inputs: { files: context.affectedFiles, goal: subTask.description },
12113
+ status: "pending"
12114
+ });
10977
12115
  }
10978
- );
12116
+ break;
12117
+ case "validation":
12118
+ steps.push(
12119
+ {
12120
+ id: `${subTask.id}_syntax`,
12121
+ type: "validate",
12122
+ description: "Check syntax and compilation",
12123
+ inputs: { files: context.affectedFiles },
12124
+ status: "pending"
12125
+ },
12126
+ {
12127
+ id: `${subTask.id}_logic`,
12128
+ type: "validate",
12129
+ description: "Validate logic and functionality",
12130
+ inputs: {},
12131
+ status: "pending"
12132
+ }
12133
+ );
12134
+ break;
10979
12135
  }
10980
12136
  return steps;
10981
12137
  }
12138
+ /**
12139
+ * Infer task type from goal description
12140
+ */
12141
+ inferTaskType(goal) {
12142
+ const goal_lower = goal.toLowerCase();
12143
+ if (goal_lower.includes("refactor") || goal_lower.includes("redesign")) {
12144
+ return "refactoring";
12145
+ } else if (goal_lower.includes("add") || goal_lower.includes("implement") || goal_lower.includes("create")) {
12146
+ return "implementation";
12147
+ } else if (goal_lower.includes("fix") || goal_lower.includes("bug") || goal_lower.includes("issue")) {
12148
+ return "bug_fix";
12149
+ } else if (goal_lower.includes("test") || goal_lower.includes("validate")) {
12150
+ return "testing";
12151
+ } else {
12152
+ return "general";
12153
+ }
12154
+ }
10982
12155
  /**
10983
12156
  * Initialize execution context with tools and state
10984
12157
  */
@@ -10992,7 +12165,11 @@ var init_autonomous_executor = __esm({
10992
12165
  codebaseExplorer: this.codebaseExplorer,
10993
12166
  currentFiles: /* @__PURE__ */ new Set(),
10994
12167
  symbolCache: /* @__PURE__ */ new Map(),
10995
- validationResults: /* @__PURE__ */ new Map()
12168
+ validationResults: /* @__PURE__ */ new Map(),
12169
+ stepMemory: /* @__PURE__ */ new Map(),
12170
+ fileSnapshots: /* @__PURE__ */ new Map(),
12171
+ dependencyGraph: /* @__PURE__ */ new Map(),
12172
+ learnedPatterns: /* @__PURE__ */ new Map()
10996
12173
  };
10997
12174
  }
10998
12175
  /**
@@ -11048,11 +12225,52 @@ var init_autonomous_executor = __esm({
11048
12225
  return { analyses: analysisResults, fileCount: files.length };
11049
12226
  }
11050
12227
  async executeEditStep(step, context) {
11051
- console.log(`\u{1F4DD} Edit step: ${step.description}`);
11052
- return {
11053
- message: "Edit step executed (placeholder)",
11054
- filesModified: Array.from(context.currentFiles).slice(0, 3)
11055
- };
12228
+ const transactionId = `txn_${step.id}_${Date.now()}`;
12229
+ try {
12230
+ await this.transactionManager.beginTransaction(transactionId);
12231
+ console.log(`\u{1F4DD} Edit step: ${step.description}`);
12232
+ let filesModified = [];
12233
+ if (step.inputs.file) {
12234
+ const filePath = step.inputs.file;
12235
+ const goal = step.inputs.goal || step.description;
12236
+ const newContent = await this.generateFileChanges(filePath, goal, context);
12237
+ await this.transactionManager.addFileOperation(transactionId, filePath, newContent, "update");
12238
+ filesModified.push(filePath);
12239
+ } else if (step.inputs.files) {
12240
+ const files = step.inputs.files;
12241
+ const goal = step.inputs.goal || step.description;
12242
+ for (const filePath of files) {
12243
+ try {
12244
+ const newContent = await this.generateFileChanges(filePath, goal, context);
12245
+ await this.transactionManager.addFileOperation(transactionId, filePath, newContent, "update");
12246
+ filesModified.push(filePath);
12247
+ } catch (error) {
12248
+ console.warn(`Failed to process ${filePath}:`, error);
12249
+ }
12250
+ }
12251
+ }
12252
+ context.stepMemory.set(step.id, { transactionId, filesModified });
12253
+ await this.transactionManager.commitTransaction(transactionId);
12254
+ for (const file of filesModified) {
12255
+ try {
12256
+ const content = await fs7.readFile(file, "utf-8");
12257
+ context.fileSnapshots.set(file, content);
12258
+ } catch {
12259
+ }
12260
+ }
12261
+ return {
12262
+ message: "Edit step executed successfully",
12263
+ filesModified,
12264
+ transactionId
12265
+ };
12266
+ } catch (error) {
12267
+ try {
12268
+ await this.transactionManager.rollbackTransaction(transactionId);
12269
+ } catch (rollbackError) {
12270
+ console.error("Failed to rollback transaction:", rollbackError);
12271
+ }
12272
+ throw new Error(`Edit step failed: ${error instanceof Error ? error.message : String(error)}`);
12273
+ }
11056
12274
  }
11057
12275
  async executeValidateStep(step, context) {
11058
12276
  console.log(`\u2705 Validation step: ${step.description}`);
@@ -11073,12 +12291,28 @@ var init_autonomous_executor = __esm({
11073
12291
  async attemptRecovery(step, context) {
11074
12292
  console.log(`\u{1F504} Attempting recovery for failed step: ${step.description}`);
11075
12293
  try {
12294
+ const stepMemory = context.stepMemory.get(step.id);
12295
+ if (stepMemory?.transactionId) {
12296
+ console.log(`\u{1F519} Rolling back transaction ${stepMemory.transactionId}`);
12297
+ await this.transactionManager.rollbackTransaction(stepMemory.transactionId);
12298
+ if (stepMemory.filesModified) {
12299
+ for (const file of stepMemory.filesModified) {
12300
+ context.fileSnapshots.delete(file);
12301
+ }
12302
+ }
12303
+ }
11076
12304
  step.status = "running";
12305
+ step.inputs.retryAttempt = (step.inputs.retryAttempt || 0) + 1;
12306
+ step.inputs.previousError = step.error;
12307
+ step.inputs.recoveryAttempt = true;
11077
12308
  await this.executeStep(step, context);
11078
12309
  step.status = "completed";
12310
+ console.log(`\u2705 Recovery successful for step: ${step.description}`);
11079
12311
  return true;
11080
- } catch (error) {
12312
+ } catch (retryError) {
12313
+ console.log(`\u274C Recovery failed for step: ${step.description}`);
11081
12314
  step.status = "failed";
12315
+ step.error = `Recovery failed: ${retryError instanceof Error ? retryError.message : String(retryError)}`;
11082
12316
  return false;
11083
12317
  }
11084
12318
  }
@@ -11113,32 +12347,673 @@ var init_autonomous_executor = __esm({
11113
12347
  if (task) {
11114
12348
  task.status = "failed";
11115
12349
  task.endTime = Date.now();
12350
+ for (const step of task.steps) {
12351
+ if (step.status === "running" || step.status === "completed") ;
12352
+ }
11116
12353
  this.executionHistory.push(task);
11117
12354
  this.activeTasks.delete(taskId);
11118
12355
  return true;
11119
12356
  }
11120
12357
  return false;
11121
12358
  }
12359
+ /**
12360
+ * Save task state for persistence and recovery
12361
+ */
12362
+ async saveTaskState(task) {
12363
+ try {
12364
+ const stateFile = path8.join(this.config.rootPath, ".autonomous", `task_${task.id}.json`);
12365
+ await fs7.mkdir(path8.dirname(stateFile), { recursive: true });
12366
+ const state = {
12367
+ task,
12368
+ timestamp: Date.now(),
12369
+ version: "1.0"
12370
+ };
12371
+ await fs7.writeFile(stateFile, JSON.stringify(state, null, 2), "utf-8");
12372
+ } catch (error) {
12373
+ console.warn("Failed to save task state:", error);
12374
+ }
12375
+ }
12376
+ /**
12377
+ * Load task state for recovery
12378
+ */
12379
+ async loadTaskState(taskId) {
12380
+ try {
12381
+ const stateFile = path8.join(this.config.rootPath, ".autonomous", `task_${taskId}.json`);
12382
+ const content = await fs7.readFile(stateFile, "utf-8");
12383
+ const state = JSON.parse(content);
12384
+ return state.task;
12385
+ } catch {
12386
+ return null;
12387
+ }
12388
+ }
12389
+ /**
12390
+ * Update task progress with persistence
12391
+ */
12392
+ async updateTaskProgress(task, context) {
12393
+ const totalSteps = task.steps.length;
12394
+ const completedSteps = task.steps.filter((s) => s.status === "completed").length;
12395
+ const runningSteps = task.steps.filter((s) => s.status === "running").length;
12396
+ task.progress = Math.round((completedSteps + runningSteps * 0.5) / totalSteps * 100);
12397
+ if (task.progress % 10 === 0 || task.status !== "executing") {
12398
+ await this.saveTaskState(task);
12399
+ }
12400
+ context.stepMemory.set("task_progress", {
12401
+ taskId: task.id,
12402
+ progress: task.progress,
12403
+ completedSteps,
12404
+ totalSteps,
12405
+ status: task.status,
12406
+ timestamp: Date.now()
12407
+ });
12408
+ }
12409
+ /**
12410
+ * Generate file changes based on goal and context using AI-powered analysis
12411
+ */
12412
+ async generateFileChanges(filePath, goal, context) {
12413
+ console.log(`\u{1F916} Generating changes for: "${goal}" in ${filePath}`);
12414
+ let currentContent = "";
12415
+ try {
12416
+ currentContent = await fs7.readFile(filePath, "utf-8");
12417
+ } catch {
12418
+ currentContent = "";
12419
+ }
12420
+ const goalAnalysis = await this.analyzeGoalForChanges(goal, context);
12421
+ const fileStructure = await this.analyzeFileStructure(filePath, currentContent);
12422
+ const similarPatterns = await this.findSimilarPatterns(goal, context);
12423
+ const modifiedContent = await this.applyCodeTransformations(
12424
+ currentContent,
12425
+ fileStructure,
12426
+ goalAnalysis,
12427
+ similarPatterns
12428
+ );
12429
+ const validation = await this.validateCodeChanges(filePath, modifiedContent);
12430
+ if (!validation.isValid) {
12431
+ console.warn(`\u26A0\uFE0F Generated changes may have issues: ${validation.errors.join(", ")}`);
12432
+ }
12433
+ return modifiedContent;
12434
+ }
12435
+ /**
12436
+ * Analyze the goal to understand what type of changes are needed
12437
+ */
12438
+ async analyzeGoalForChanges(goal, context) {
12439
+ const goal_lower = goal.toLowerCase();
12440
+ let action = "general";
12441
+ if (goal_lower.includes("add") && goal_lower.includes("function")) {
12442
+ action = "add_function";
12443
+ } else if (goal_lower.includes("modify") || goal_lower.includes("update") || goal_lower.includes("change")) {
12444
+ action = "modify_function";
12445
+ } else if (goal_lower.includes("add") && (goal_lower.includes("variable") || goal_lower.includes("const") || goal_lower.includes("let"))) {
12446
+ action = "add_variable";
12447
+ } else if (goal_lower.includes("import")) {
12448
+ action = "add_import";
12449
+ }
12450
+ const target = this.extractTargetFromGoal(goal);
12451
+ const complexity = goal_lower.includes("complex") || goal_lower.includes("system") ? "complex" : goal_lower.includes("simple") || goal.length < 50 ? "simple" : "medium";
12452
+ return {
12453
+ action,
12454
+ target,
12455
+ description: goal,
12456
+ complexity
12457
+ };
12458
+ }
12459
+ /**
12460
+ * Analyze the structure of the current file
12461
+ */
12462
+ async analyzeFileStructure(filePath, content) {
12463
+ const isTypeScript = filePath.endsWith(".ts") || filePath.endsWith(".tsx");
12464
+ const language = isTypeScript ? "typescript" : "javascript";
12465
+ try {
12466
+ const parseResult = await this.astParser.execute({
12467
+ filePath,
12468
+ includeSymbols: true,
12469
+ includeImports: true
12470
+ });
12471
+ if (parseResult.success && parseResult.output) {
12472
+ const parsed = JSON.parse(parseResult.output);
12473
+ const symbols = parsed.result?.symbols || [];
12474
+ const functions = symbols.filter((s) => s.type === "function").map((s) => s.name);
12475
+ const variables = symbols.filter((s) => ["variable", "const", "let", "var"].includes(s.type)).map((s) => s.name);
12476
+ const classes = symbols.filter((s) => s.type === "class").map((s) => s.name);
12477
+ return {
12478
+ hasExports: content.includes("export"),
12479
+ hasImports: content.includes("import") || content.includes("require"),
12480
+ functions,
12481
+ variables,
12482
+ classes,
12483
+ language,
12484
+ structure: "module"
12485
+ };
12486
+ }
12487
+ } catch (error) {
12488
+ console.warn("AST parsing failed, using fallback analysis:", error);
12489
+ }
12490
+ return {
12491
+ hasExports: content.includes("export"),
12492
+ hasImports: content.includes("import") || content.includes("require"),
12493
+ functions: this.extractFunctionsFromContent(content),
12494
+ variables: this.extractVariablesFromContent(content),
12495
+ classes: [],
12496
+ language,
12497
+ structure: content.includes("import") || content.includes("export") ? "module" : "script"
12498
+ };
12499
+ }
12500
+ /**
12501
+ * Find similar code patterns using vector search
12502
+ */
12503
+ async findSimilarPatterns(goal, context) {
12504
+ try {
12505
+ const searchResults = await context.searchEngine.semanticSearch(goal, 5);
12506
+ return searchResults;
12507
+ } catch (error) {
12508
+ console.warn("Vector search failed:", error);
12509
+ return [];
12510
+ }
12511
+ }
12512
+ /**
12513
+ * Apply the actual code transformations
12514
+ */
12515
+ async applyCodeTransformations(content, fileStructure, goalAnalysis, similarPatterns) {
12516
+ console.log(`\u{1F527} Applying ${goalAnalysis.action} transformation: ${goalAnalysis.target}`);
12517
+ switch (goalAnalysis.action) {
12518
+ case "add_function":
12519
+ return this.addFunctionToFile(content, fileStructure, goalAnalysis);
12520
+ case "add_variable":
12521
+ return this.addVariableToFile(content, fileStructure, goalAnalysis);
12522
+ case "modify_function":
12523
+ return this.modifyFunctionInFile(content, fileStructure, goalAnalysis);
12524
+ default:
12525
+ return this.applyPatternBasedChanges(content, fileStructure, goalAnalysis, similarPatterns);
12526
+ }
12527
+ }
12528
+ /**
12529
+ * Add a function to the file
12530
+ */
12531
+ addFunctionToFile(content, fileStructure, goalAnalysis) {
12532
+ const lines = content.split("\n");
12533
+ let insertIndex = lines.length;
12534
+ for (let i = 0; i < lines.length; i++) {
12535
+ const line = lines[i].trim();
12536
+ if (line.startsWith("console.log(") || line.startsWith("export") || line === "main();" || line === "}") {
12537
+ insertIndex = i;
12538
+ break;
12539
+ }
12540
+ }
12541
+ const functionCode = this.generateFunctionCode(goalAnalysis.target, goalAnalysis.description);
12542
+ lines.splice(insertIndex, 0, "", functionCode, "");
12543
+ return lines.join("\n");
12544
+ }
12545
+ /**
12546
+ * Generate function code based on the target description
12547
+ */
12548
+ generateFunctionCode(target, description) {
12549
+ const desc_lower = description.toLowerCase();
12550
+ if (desc_lower.includes("timestamp") || desc_lower.includes("time") || desc_lower.includes("current time")) {
12551
+ return `function logCurrentTime(): void {
12552
+ const now = new Date();
12553
+ console.log(\`Current time: \${now.toLocaleString()}\`);
12554
+ }`;
12555
+ }
12556
+ if (desc_lower.includes("random") || desc_lower.includes("number")) {
12557
+ return `function generateRandomNumber(): number {
12558
+ return Math.floor(Math.random() * 100);
12559
+ }`;
12560
+ }
12561
+ const functionName = target.replace(/[^a-zA-Z0-9]/g, "").toLowerCase() || "newFunction";
12562
+ return `function ${functionName}(): void {
12563
+ // TODO: Implement ${description}
12564
+ console.log('${functionName} called');
12565
+ }`;
12566
+ }
12567
+ /**
12568
+ * Add a variable to the file
12569
+ */
12570
+ addVariableToFile(content, fileStructure, goalAnalysis) {
12571
+ const lines = content.split("\n");
12572
+ let insertIndex = 0;
12573
+ for (let i = 0; i < lines.length; i++) {
12574
+ const line = lines[i].trim();
12575
+ if (line.startsWith("function") || line.startsWith("const") || line.startsWith("let") || line.startsWith("var")) {
12576
+ insertIndex = i;
12577
+ break;
12578
+ }
12579
+ }
12580
+ const variableCode = this.generateVariableCode(goalAnalysis.target, goalAnalysis.description);
12581
+ lines.splice(insertIndex, 0, variableCode, "");
12582
+ return lines.join("\n");
12583
+ }
12584
+ /**
12585
+ * Generate variable code
12586
+ */
12587
+ generateVariableCode(target, description) {
12588
+ const desc_lower = description.toLowerCase();
12589
+ if (desc_lower.includes("timestamp") || desc_lower.includes("time")) {
12590
+ return "const currentTimestamp: number = Date.now();";
12591
+ }
12592
+ if (desc_lower.includes("version") || desc_lower.includes("v1")) {
12593
+ return 'const version: string = "1.0.0";';
12594
+ }
12595
+ const varName = target.replace(/[^a-zA-Z0-9]/g, "").toLowerCase() || "newVariable";
12596
+ return `const ${varName}: string = "TODO: Initialize ${description}";`;
12597
+ }
12598
+ /**
12599
+ * Modify existing function in the file
12600
+ */
12601
+ modifyFunctionInFile(content, fileStructure, goalAnalysis) {
12602
+ const modificationComment = `// MODIFIED: ${goalAnalysis.description}
12603
+ `;
12604
+ return modificationComment + content;
12605
+ }
12606
+ /**
12607
+ * Apply pattern-based changes using similar code patterns
12608
+ */
12609
+ applyPatternBasedChanges(content, fileStructure, goalAnalysis, similarPatterns) {
12610
+ if (similarPatterns.length > 0) {
12611
+ const bestPattern = similarPatterns[0];
12612
+ console.log(`\u{1F4CB} Using pattern from ${bestPattern.filePath} as reference`);
12613
+ }
12614
+ const changeComment = `// AUTONOMOUS CHANGE: ${goalAnalysis.description}
12615
+ // Applied at ${(/* @__PURE__ */ new Date()).toISOString()}
12616
+
12617
+ `;
12618
+ return changeComment + content;
12619
+ }
12620
+ /**
12621
+ * Validate the generated code changes
12622
+ */
12623
+ async validateCodeChanges(filePath, content) {
12624
+ const errors = [];
12625
+ try {
12626
+ const parseResult = await this.astParser.execute({
12627
+ filePath,
12628
+ includeSymbols: false
12629
+ });
12630
+ if (!parseResult.success) {
12631
+ errors.push("Generated code has syntax errors");
12632
+ }
12633
+ } catch (error) {
12634
+ errors.push(`Validation failed: ${error}`);
12635
+ }
12636
+ return {
12637
+ isValid: errors.length === 0,
12638
+ errors
12639
+ };
12640
+ }
12641
+ /**
12642
+ * Extract target from goal description
12643
+ */
12644
+ extractTargetFromGoal(goal) {
12645
+ const words = goal.toLowerCase().split(" ");
12646
+ const targetKeywords = ["function", "variable", "class", "method"];
12647
+ for (let i = 0; i < words.length; i++) {
12648
+ if (targetKeywords.includes(words[i])) {
12649
+ const targetWords = [];
12650
+ for (let j = i + 1; j < words.length && j < i + 4; j++) {
12651
+ if (!["to", "that", "with", "for", "in"].includes(words[j])) {
12652
+ targetWords.push(words[j]);
12653
+ } else {
12654
+ break;
12655
+ }
12656
+ }
12657
+ return targetWords.join(" ");
12658
+ }
12659
+ }
12660
+ return goal.split(" ").slice(-3).join(" ");
12661
+ }
12662
+ /**
12663
+ * Extract function names from content (fallback when AST fails)
12664
+ */
12665
+ extractFunctionsFromContent(content) {
12666
+ const functionRegex = /function\s+(\w+)/g;
12667
+ const matches = [];
12668
+ let match;
12669
+ while ((match = functionRegex.exec(content)) !== null) {
12670
+ matches.push(match[1]);
12671
+ }
12672
+ return matches;
12673
+ }
12674
+ /**
12675
+ * Extract variable names from content (fallback when AST fails)
12676
+ */
12677
+ extractVariablesFromContent(content) {
12678
+ const varRegex = /(?:const|let|var)\s+(\w+)/g;
12679
+ const matches = [];
12680
+ let match;
12681
+ while ((match = varRegex.exec(content)) !== null) {
12682
+ matches.push(match[1]);
12683
+ }
12684
+ return matches;
12685
+ }
11122
12686
  generateTaskId() {
11123
12687
  return `task_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
11124
12688
  }
11125
12689
  };
11126
12690
  }
11127
12691
  });
12692
+ var AgentFramework;
12693
+ var init_agent_framework = __esm({
12694
+ "src/services/agent-framework.ts"() {
12695
+ AgentFramework = class {
12696
+ constructor(autonomousExecutor, memoryPath = "/tmp/agent-memory", pluginPath = "/tmp/agent-plugins") {
12697
+ this.sessions = /* @__PURE__ */ new Map();
12698
+ this.plugins = /* @__PURE__ */ new Map();
12699
+ this.autonomousExecutor = autonomousExecutor;
12700
+ this.memoryPath = memoryPath;
12701
+ this.pluginPath = pluginPath;
12702
+ }
12703
+ /**
12704
+ * Initialize the agent framework
12705
+ */
12706
+ async initialize() {
12707
+ await this.loadPersistedMemory();
12708
+ await this.loadPlugins();
12709
+ console.log(`\u{1F916} Agent Framework initialized with ${this.plugins.size} plugins`);
12710
+ }
12711
+ /**
12712
+ * Create or resume an agent session
12713
+ */
12714
+ async createSession(userId, sessionId) {
12715
+ const id = sessionId || `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
12716
+ let session = this.sessions.get(id);
12717
+ if (!session) {
12718
+ session = {
12719
+ id,
12720
+ userId,
12721
+ startTime: Date.now(),
12722
+ lastActivity: Date.now(),
12723
+ context: /* @__PURE__ */ new Map(),
12724
+ memory: {
12725
+ shortTerm: [],
12726
+ longTerm: /* @__PURE__ */ new Map(),
12727
+ episodic: [],
12728
+ semantic: /* @__PURE__ */ new Map()
12729
+ },
12730
+ activeTasks: [],
12731
+ learnedPatterns: /* @__PURE__ */ new Map()
12732
+ };
12733
+ this.sessions.set(id, session);
12734
+ await this.loadSessionMemory(session);
12735
+ }
12736
+ session.lastActivity = Date.now();
12737
+ return session;
12738
+ }
12739
+ /**
12740
+ * Execute an action within an agent session
12741
+ */
12742
+ async executeInSession(sessionId, action, parameters = {}) {
12743
+ const session = this.sessions.get(sessionId);
12744
+ if (!session) {
12745
+ throw new Error(`Session ${sessionId} not found`);
12746
+ }
12747
+ session.lastActivity = Date.now();
12748
+ try {
12749
+ const pluginResult = await this.tryExecuteWithPlugin(session, action, parameters);
12750
+ if (pluginResult) {
12751
+ await this.recordExperience(session, action, parameters, pluginResult, pluginResult.success ? 1 : -1);
12752
+ return pluginResult;
12753
+ }
12754
+ const result = await this.autonomousExecutor.executeTask(action, JSON.stringify(parameters));
12755
+ await this.recordExperience(session, action, parameters, result, result.status === "completed" ? 1 : -0.5);
12756
+ return result;
12757
+ } catch (error) {
12758
+ await this.recordExperience(session, action, parameters, error, -1);
12759
+ throw error;
12760
+ }
12761
+ }
12762
+ /**
12763
+ * Learn from interactions and improve performance
12764
+ */
12765
+ async learnFromInteraction(sessionId, interaction) {
12766
+ const session = this.sessions.get(sessionId);
12767
+ if (!session) return;
12768
+ if (interaction.outcome === "success") {
12769
+ await this.extractPatterns(session, interaction);
12770
+ }
12771
+ await this.consolidateMemory(session);
12772
+ await this.persistSessionMemory(session);
12773
+ }
12774
+ /**
12775
+ * Register a plugin
12776
+ */
12777
+ async registerPlugin(plugin) {
12778
+ this.plugins.set(plugin.name, plugin);
12779
+ await plugin.initialize(this);
12780
+ console.log(`\u{1F50C} Plugin registered: ${plugin.name} v${plugin.version}`);
12781
+ }
12782
+ /**
12783
+ * Get session memory and context
12784
+ */
12785
+ getSessionContext(sessionId) {
12786
+ return this.sessions.get(sessionId) || null;
12787
+ }
12788
+ /**
12789
+ * Clean up inactive sessions
12790
+ */
12791
+ async cleanupInactiveSessions(maxAge = 24 * 60 * 60 * 1e3) {
12792
+ const now = Date.now();
12793
+ const toRemove = [];
12794
+ for (const [id, session] of this.sessions) {
12795
+ if (now - session.lastActivity > maxAge) {
12796
+ await this.persistSessionMemory(session);
12797
+ toRemove.push(id);
12798
+ }
12799
+ }
12800
+ for (const id of toRemove) {
12801
+ this.sessions.delete(id);
12802
+ }
12803
+ console.log(`\u{1F9F9} Cleaned up ${toRemove.length} inactive sessions`);
12804
+ }
12805
+ /**
12806
+ * Try to execute action with registered plugins
12807
+ */
12808
+ async tryExecuteWithPlugin(session, action, parameters) {
12809
+ for (const plugin of this.plugins.values()) {
12810
+ if (plugin.capabilities.includes(action) || plugin.capabilities.includes("general")) {
12811
+ try {
12812
+ const context = {
12813
+ session,
12814
+ input: { action, parameters },
12815
+ previousResults: this.getRecentResults(session)
12816
+ };
12817
+ const result = await plugin.execute(context);
12818
+ if (result.success) {
12819
+ return result;
12820
+ }
12821
+ } catch (error) {
12822
+ console.warn(`Plugin ${plugin.name} failed:`, error);
12823
+ }
12824
+ }
12825
+ }
12826
+ return null;
12827
+ }
12828
+ /**
12829
+ * Record experience for learning
12830
+ */
12831
+ async recordExperience(session, action, parameters, result, reward) {
12832
+ const experience = {
12833
+ context: session.context.get("current_context") || "general",
12834
+ action,
12835
+ outcome: result,
12836
+ reward,
12837
+ timestamp: Date.now()
12838
+ };
12839
+ const episodicMemory = {
12840
+ id: `epi_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
12841
+ timestamp: experience.timestamp,
12842
+ context: experience.context,
12843
+ action: experience.action,
12844
+ outcome: reward > 0 ? "success" : reward === 0 ? "partial" : "failure",
12845
+ lesson: this.extractLesson(experience),
12846
+ confidence: Math.abs(reward)
12847
+ };
12848
+ session.memory.episodic.push(episodicMemory);
12849
+ const memoryItem = {
12850
+ id: `mem_${Date.now()}`,
12851
+ type: "interaction",
12852
+ content: experience,
12853
+ timestamp: Date.now(),
12854
+ importance: Math.abs(reward),
12855
+ accessCount: 1,
12856
+ lastAccessed: Date.now()
12857
+ };
12858
+ session.memory.shortTerm.push(memoryItem);
12859
+ for (const plugin of this.plugins.values()) {
12860
+ if (plugin.learn) {
12861
+ try {
12862
+ await plugin.learn(experience);
12863
+ } catch (error) {
12864
+ console.warn(`Plugin ${plugin.name} learning failed:`, error);
12865
+ }
12866
+ }
12867
+ }
12868
+ }
12869
+ /**
12870
+ * Extract patterns from successful interactions
12871
+ */
12872
+ async extractPatterns(session, interaction) {
12873
+ const patterns = session.learnedPatterns;
12874
+ if (interaction.action && interaction.parameters) {
12875
+ const actionKey = interaction.action.toLowerCase();
12876
+ const paramKeys = Object.keys(interaction.parameters);
12877
+ if (!patterns.has(actionKey)) {
12878
+ patterns.set(actionKey, /* @__PURE__ */ new Map());
12879
+ }
12880
+ const actionPatterns = patterns.get(actionKey);
12881
+ const paramHash = paramKeys.sort().join(",");
12882
+ actionPatterns.set(paramHash, (actionPatterns.get(paramHash) || 0) + 1);
12883
+ }
12884
+ }
12885
+ /**
12886
+ * Consolidate memory from short-term to long-term
12887
+ */
12888
+ async consolidateMemory(session) {
12889
+ const now = Date.now();
12890
+ const consolidationThreshold = 5;
12891
+ const ageThreshold = 60 * 60 * 1e3;
12892
+ const toMove = [];
12893
+ for (const item of session.memory.shortTerm) {
12894
+ if (item.accessCount >= consolidationThreshold || now - item.timestamp > ageThreshold) {
12895
+ toMove.push(item);
12896
+ }
12897
+ }
12898
+ for (const item of toMove) {
12899
+ session.memory.longTerm.set(item.id, item);
12900
+ session.memory.shortTerm = session.memory.shortTerm.filter((i) => i.id !== item.id);
12901
+ }
12902
+ if (session.memory.shortTerm.length > 50) {
12903
+ session.memory.shortTerm = session.memory.shortTerm.slice(-50);
12904
+ }
12905
+ if (session.memory.episodic.length > 100) {
12906
+ session.memory.episodic = session.memory.episodic.slice(-100);
12907
+ }
12908
+ }
12909
+ /**
12910
+ * Load persisted memory
12911
+ */
12912
+ async loadPersistedMemory() {
12913
+ try {
12914
+ await fs7.mkdir(this.memoryPath, { recursive: true });
12915
+ const files = await fs7.readdir(this.memoryPath);
12916
+ for (const file of files) {
12917
+ if (file.endsWith(".json")) {
12918
+ try {
12919
+ const content = await fs7.readFile(path8.join(this.memoryPath, file), "utf-8");
12920
+ const sessionData = JSON.parse(content);
12921
+ const session = {
12922
+ ...sessionData,
12923
+ context: new Map(sessionData.context),
12924
+ memory: {
12925
+ shortTerm: sessionData.memory.shortTerm || [],
12926
+ longTerm: new Map(sessionData.memory.longTerm || []),
12927
+ episodic: sessionData.memory.episodic || [],
12928
+ semantic: new Map(sessionData.memory.semantic || [])
12929
+ },
12930
+ learnedPatterns: new Map(sessionData.learnedPatterns || [])
12931
+ };
12932
+ this.sessions.set(session.id, session);
12933
+ } catch (error) {
12934
+ console.warn(`Failed to load session ${file}:`, error);
12935
+ }
12936
+ }
12937
+ }
12938
+ console.log(`\u{1F4BE} Loaded ${this.sessions.size} persisted sessions`);
12939
+ } catch (error) {
12940
+ console.warn("Failed to load persisted memory:", error);
12941
+ }
12942
+ }
12943
+ /**
12944
+ * Persist session memory
12945
+ */
12946
+ async persistSessionMemory(session) {
12947
+ try {
12948
+ const fileName = `session_${session.id}.json`;
12949
+ const filePath = path8.join(this.memoryPath, fileName);
12950
+ const serializable = {
12951
+ ...session,
12952
+ context: Array.from(session.context.entries()),
12953
+ memory: {
12954
+ ...session.memory,
12955
+ longTerm: Array.from(session.memory.longTerm.entries()),
12956
+ semantic: Array.from(session.memory.semantic.entries())
12957
+ },
12958
+ learnedPatterns: Array.from(session.learnedPatterns.entries())
12959
+ };
12960
+ await fs7.writeFile(filePath, JSON.stringify(serializable, null, 2), "utf-8");
12961
+ } catch (error) {
12962
+ console.warn(`Failed to persist session ${session.id}:`, error);
12963
+ }
12964
+ }
12965
+ /**
12966
+ * Load session memory from disk
12967
+ */
12968
+ async loadSessionMemory(session) {
12969
+ }
12970
+ /**
12971
+ * Load plugins from plugin directory
12972
+ */
12973
+ async loadPlugins() {
12974
+ try {
12975
+ await fs7.mkdir(this.pluginPath, { recursive: true });
12976
+ } catch (error) {
12977
+ console.warn("Failed to load plugins:", error);
12978
+ }
12979
+ }
12980
+ /**
12981
+ * Extract lesson from experience
12982
+ */
12983
+ extractLesson(experience) {
12984
+ if (experience.reward > 0) {
12985
+ return `Successful: ${experience.action} with parameters ${JSON.stringify(experience.parameters || {})}`;
12986
+ } else {
12987
+ return `Failed: ${experience.action} - avoid similar approaches`;
12988
+ }
12989
+ }
12990
+ /**
12991
+ * Get recent results from session memory
12992
+ */
12993
+ getRecentResults(session) {
12994
+ return session.memory.shortTerm.filter((item) => item.type === "interaction").slice(-5).map((item) => item.content.outcome);
12995
+ }
12996
+ };
12997
+ }
12998
+ });
11128
12999
 
11129
13000
  // src/tools/intelligence/autonomous-task-tool.ts
11130
13001
  var AutonomousTaskTool;
11131
13002
  var init_autonomous_task_tool = __esm({
11132
13003
  "src/tools/intelligence/autonomous-task-tool.ts"() {
11133
13004
  init_autonomous_executor();
13005
+ init_agent_framework();
11134
13006
  AutonomousTaskTool = class {
11135
13007
  constructor() {
11136
13008
  this.name = "autonomous_task";
11137
13009
  this.description = "Execute complex multi-step coding tasks autonomously using AI-powered planning and execution. Handles refactoring, feature implementation, bug fixes, and more.";
11138
13010
  this.executor = null;
13011
+ this.agentFramework = null;
11139
13012
  this.isExecuting = false;
13013
+ this.currentSession = null;
11140
13014
  }
11141
13015
  async execute(args) {
13016
+ console.log(`\u{1F527} AutonomousTaskTool.execute called with args:`, JSON.stringify(args, null, 2));
11142
13017
  try {
11143
13018
  const {
11144
13019
  goal,
@@ -11149,6 +13024,7 @@ var init_autonomous_task_tool = __esm({
11149
13024
  maxSteps = 50,
11150
13025
  timeoutMs = 5 * 60 * 1e3
11151
13026
  } = args;
13027
+ console.log(`\u{1F4CB} Parsed args - goal: "${goal}", action: "${action}", rootPath: "${rootPath}"`);
11152
13028
  if (!this.executor) {
11153
13029
  this.executor = new AutonomousExecutor({
11154
13030
  rootPath,
@@ -11157,6 +13033,14 @@ var init_autonomous_task_tool = __esm({
11157
13033
  validationEnabled: true,
11158
13034
  backupEnabled: true
11159
13035
  });
13036
+ this.agentFramework = new AgentFramework(this.executor);
13037
+ await this.agentFramework.initialize();
13038
+ }
13039
+ if (!this.currentSession) {
13040
+ const session = await this.agentFramework.createSession("default_user");
13041
+ if (session) {
13042
+ this.currentSession = session.id;
13043
+ }
11160
13044
  }
11161
13045
  switch (action) {
11162
13046
  case "execute":
@@ -11166,7 +13050,7 @@ var init_autonomous_task_tool = __esm({
11166
13050
  error: 'Goal is required for task execution. Example: "refactor the authentication system to use JWT tokens"'
11167
13051
  };
11168
13052
  }
11169
- return await this.handleExecute(goal, description);
13053
+ return await this.handleExecute(goal, description, maxSteps, timeoutMs);
11170
13054
  case "status":
11171
13055
  if (!taskId) {
11172
13056
  return {
@@ -11198,7 +13082,7 @@ var init_autonomous_task_tool = __esm({
11198
13082
  };
11199
13083
  }
11200
13084
  }
11201
- async handleExecute(goal, description) {
13085
+ async handleExecute(goal, description, maxSteps = 50, timeoutMs = 5 * 60 * 1e3) {
11202
13086
  if (this.isExecuting) {
11203
13087
  return {
11204
13088
  success: false,
@@ -11207,11 +13091,21 @@ var init_autonomous_task_tool = __esm({
11207
13091
  }
11208
13092
  try {
11209
13093
  this.isExecuting = true;
11210
- console.log(`\u{1F916} Starting autonomous task execution...`);
11211
- const taskPlan = await this.executor.executeTask(goal, description);
11212
- const output = this.formatTaskResult(taskPlan);
13094
+ console.log(`\u{1F916} Starting autonomous task execution in agent session...`);
13095
+ const result = await this.agentFramework.executeInSession(
13096
+ this.currentSession,
13097
+ goal,
13098
+ { description, maxSteps, timeoutMs }
13099
+ );
13100
+ await this.agentFramework.learnFromInteraction(this.currentSession, {
13101
+ goal,
13102
+ description,
13103
+ outcome: result.status === "completed" ? "success" : "failure",
13104
+ result
13105
+ });
13106
+ const output = this.formatTaskResult(result);
11213
13107
  return {
11214
- success: taskPlan.status === "completed",
13108
+ success: result.status === "completed",
11215
13109
  output
11216
13110
  };
11217
13111
  } catch (error) {
@@ -11281,6 +13175,7 @@ var init_autonomous_task_tool = __esm({
11281
13175
  };
11282
13176
  }
11283
13177
  async handleCancel(taskId) {
13178
+ if (this.agentFramework && this.currentSession) ;
11284
13179
  const cancelled = this.executor.cancelTask(taskId);
11285
13180
  if (cancelled) {
11286
13181
  this.isExecuting = false;
@@ -11297,6 +13192,14 @@ All partial changes have been preserved.`
11297
13192
  error: `Task ${taskId} not found or already completed`
11298
13193
  };
11299
13194
  }
13195
+ /**
13196
+ * Clean up agent sessions and memory
13197
+ */
13198
+ async cleanup() {
13199
+ if (this.agentFramework) {
13200
+ await this.agentFramework.cleanupInactiveSessions();
13201
+ }
13202
+ }
11300
13203
  formatTaskResult(task) {
11301
13204
  const duration = task.endTime && task.startTime ? task.endTime - task.startTime : 0;
11302
13205
  const statusIcon = task.status === "completed" ? "\u2705" : "\u274C";
@@ -11494,6 +13397,7 @@ var init_tools2 = __esm({
11494
13397
  "src/tools/index.ts"() {
11495
13398
  init_bash();
11496
13399
  init_text_editor();
13400
+ init_smart_edit();
11497
13401
  init_morph_editor();
11498
13402
  init_todo_tool();
11499
13403
  init_confirmation_tool();
@@ -11573,10 +13477,10 @@ var init_token_counter = __esm({
11573
13477
  function loadCustomInstructions(workingDirectory = process.cwd()) {
11574
13478
  try {
11575
13479
  const instructionsPath = path8.join(workingDirectory, ".grok", "GROK.md");
11576
- if (!fs7.existsSync(instructionsPath)) {
13480
+ if (!fs10.existsSync(instructionsPath)) {
11577
13481
  return null;
11578
13482
  }
11579
- const customInstructions = fs7.readFileSync(instructionsPath, "utf-8");
13483
+ const customInstructions = fs10.readFileSync(instructionsPath, "utf-8");
11580
13484
  return customInstructions.trim();
11581
13485
  } catch (error) {
11582
13486
  console.warn("Failed to load custom instructions:", error);
@@ -11692,10 +13596,10 @@ var init_execution_orchestrator = __esm({
11692
13596
  const state = /* @__PURE__ */ new Map();
11693
13597
  try {
11694
13598
  const walkDir = (dir) => {
11695
- const files = fs7.readdirSync(dir);
13599
+ const files = fs10.readdirSync(dir);
11696
13600
  for (const file of files) {
11697
13601
  const filePath = path8.join(dir, file);
11698
- const stat = fs7.statSync(filePath);
13602
+ const stat = fs10.statSync(filePath);
11699
13603
  if (stat.isDirectory() && !file.startsWith(".") && file !== "node_modules") {
11700
13604
  walkDir(filePath);
11701
13605
  } else if (stat.isFile()) {
@@ -11743,7 +13647,7 @@ var init_execution_orchestrator = __esm({
11743
13647
  console.log(`[grok-one-shot] #${step.id} Changes detected:`);
11744
13648
  for (const change of step.changes) {
11745
13649
  console.log(` ${change.changeType.toUpperCase()}: ${change.filePath}`);
11746
- if (change.changeType === "modified" && fs7.existsSync(change.filePath)) {
13650
+ if (change.changeType === "modified" && fs10.existsSync(change.filePath)) {
11747
13651
  try {
11748
13652
  if (this.isGitRepository()) {
11749
13653
  const diff = execSync(`git diff --no-index /dev/null ${change.filePath} 2>/dev/null || git diff ${change.filePath}`, {
@@ -11769,8 +13673,8 @@ var init_execution_orchestrator = __esm({
11769
13673
  }
11770
13674
  try {
11771
13675
  const patchesDir = path8.join(__require("os").homedir(), ".grok", "patches");
11772
- if (!fs7.existsSync(patchesDir)) {
11773
- fs7.mkdirSync(patchesDir, { recursive: true });
13676
+ if (!fs10.existsSync(patchesDir)) {
13677
+ fs10.mkdirSync(patchesDir, { recursive: true });
11774
13678
  }
11775
13679
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
11776
13680
  const patchFile = path8.join(patchesDir, `step-${step.id}-${timestamp}.patch`);
@@ -11780,7 +13684,7 @@ var init_execution_orchestrator = __esm({
11780
13684
 
11781
13685
  `;
11782
13686
  for (const change of step.changes) {
11783
- if (change.changeType === "modified" && fs7.existsSync(change.filePath)) {
13687
+ if (change.changeType === "modified" && fs10.existsSync(change.filePath)) {
11784
13688
  try {
11785
13689
  const diff = execSync(`git diff ${change.filePath}`, {
11786
13690
  encoding: "utf-8",
@@ -11794,7 +13698,7 @@ ${diff}
11794
13698
  }
11795
13699
  }
11796
13700
  }
11797
- fs7.writeFileSync(patchFile, patchContent);
13701
+ fs10.writeFileSync(patchFile, patchContent);
11798
13702
  console.log(`[grok-one-shot] #${step.id} Patch saved: ${patchFile}`);
11799
13703
  return patchFile;
11800
13704
  } catch (error) {
@@ -11810,10 +13714,10 @@ ${diff}
11810
13714
  return;
11811
13715
  }
11812
13716
  for (const change of step.changes) {
11813
- if ((change.changeType === "modified" || change.changeType === "created") && fs7.existsSync(change.filePath)) {
13717
+ if ((change.changeType === "modified" || change.changeType === "created") && fs10.existsSync(change.filePath)) {
11814
13718
  try {
11815
13719
  const backupPath = `${change.filePath}.bak`;
11816
- fs7.copyFileSync(change.filePath, backupPath);
13720
+ fs10.copyFileSync(change.filePath, backupPath);
11817
13721
  change.backupPath = backupPath;
11818
13722
  console.log(`[grok-one-shot] #${step.id} Backup created: ${backupPath}`);
11819
13723
  } catch (_error) {
@@ -11905,10 +13809,10 @@ Auto-generated by grok-one-shot execution orchestrator`;
11905
13809
  try {
11906
13810
  const testFiles = [];
11907
13811
  const walkDir = (dir) => {
11908
- const files = fs7.readdirSync(dir);
13812
+ const files = fs10.readdirSync(dir);
11909
13813
  for (const file of files) {
11910
13814
  const filePath = path8.join(dir, file);
11911
- const stat = fs7.statSync(filePath);
13815
+ const stat = fs10.statSync(filePath);
11912
13816
  if (stat.isDirectory() && !file.startsWith(".") && file !== "node_modules") {
11913
13817
  walkDir(filePath);
11914
13818
  } else if (stat.isFile() && (file.includes("test") || file.includes("spec"))) {
@@ -11927,7 +13831,7 @@ Auto-generated by grok-one-shot execution orchestrator`;
11927
13831
  */
11928
13832
  findBuildFiles() {
11929
13833
  const buildFiles = ["package.json", "tsconfig.json", "webpack.config.js", "babel.config.js"];
11930
- return buildFiles.filter((file) => fs7.existsSync(file));
13834
+ return buildFiles.filter((file) => fs10.existsSync(file));
11931
13835
  }
11932
13836
  /**
11933
13837
  * Find source files
@@ -11936,10 +13840,10 @@ Auto-generated by grok-one-shot execution orchestrator`;
11936
13840
  try {
11937
13841
  const sourceFiles = [];
11938
13842
  const walkDir = (dir) => {
11939
- const files = fs7.readdirSync(dir);
13843
+ const files = fs10.readdirSync(dir);
11940
13844
  for (const file of files) {
11941
13845
  const filePath = path8.join(dir, file);
11942
- const stat = fs7.statSync(filePath);
13846
+ const stat = fs10.statSync(filePath);
11943
13847
  if (stat.isDirectory() && !file.startsWith(".") && file !== "node_modules") {
11944
13848
  walkDir(filePath);
11945
13849
  } else if (stat.isFile() && (file.endsWith(".ts") || file.endsWith(".js") || file.endsWith(".tsx") || file.endsWith(".jsx"))) {
@@ -13070,8 +14974,8 @@ var init_parseUtil = __esm({
13070
14974
  init_errors();
13071
14975
  init_en();
13072
14976
  makeIssue = (params) => {
13073
- const { data, path: path41, errorMaps, issueData } = params;
13074
- const fullPath = [...path41, ...issueData.path || []];
14977
+ const { data, path: path43, errorMaps, issueData } = params;
14978
+ const fullPath = [...path43, ...issueData.path || []];
13075
14979
  const fullIssue = {
13076
14980
  ...issueData,
13077
14981
  path: fullPath
@@ -13379,11 +15283,11 @@ var init_types = __esm({
13379
15283
  init_parseUtil();
13380
15284
  init_util();
13381
15285
  ParseInputLazyPath = class {
13382
- constructor(parent, value, path41, key) {
15286
+ constructor(parent, value, path43, key) {
13383
15287
  this._cachedPath = [];
13384
15288
  this.parent = parent;
13385
15289
  this.data = value;
13386
- this._path = path41;
15290
+ this._path = path43;
13387
15291
  this._key = key;
13388
15292
  }
13389
15293
  get path() {
@@ -16964,8 +18868,8 @@ var init_codebase_indexer = __esm({
16964
18868
  };
16965
18869
  }
16966
18870
  async indexFile(filePath) {
16967
- const stats = await fs7__default.promises.stat(filePath);
16968
- const content = await fs7__default.promises.readFile(filePath, "utf8");
18871
+ const stats = await fs10__default.promises.stat(filePath);
18872
+ const content = await fs10__default.promises.readFile(filePath, "utf8");
16969
18873
  const extension = path8__default.extname(filePath);
16970
18874
  const language = this.detectLanguage(extension);
16971
18875
  return {
@@ -16980,7 +18884,7 @@ var init_codebase_indexer = __esm({
16980
18884
  };
16981
18885
  }
16982
18886
  async extractSymbols(filePath) {
16983
- const content = await fs7__default.promises.readFile(filePath, "utf8");
18887
+ const content = await fs10__default.promises.readFile(filePath, "utf8");
16984
18888
  const extension = path8__default.extname(filePath);
16985
18889
  const symbols = [];
16986
18890
  if (extension === ".ts" || extension === ".js" || extension === ".tsx" || extension === ".jsx") {
@@ -17130,7 +19034,7 @@ var init_codebase_indexer = __esm({
17130
19034
  const dirInfo = dirMap.get(dir);
17131
19035
  dirInfo.fileCount++;
17132
19036
  try {
17133
- const stats = await fs7__default.promises.stat(file);
19037
+ const stats = await fs10__default.promises.stat(file);
17134
19038
  dirInfo.totalSize += stats.size;
17135
19039
  } catch (error) {
17136
19040
  }
@@ -17157,7 +19061,7 @@ var init_codebase_indexer = __esm({
17157
19061
  const packageJson = configFiles.find((f) => path8__default.basename(f) === "package.json");
17158
19062
  if (packageJson) {
17159
19063
  try {
17160
- const pkg = JSON.parse(fs7__default.readFileSync(packageJson, "utf8"));
19064
+ const pkg = JSON.parse(fs10__default.readFileSync(packageJson, "utf8"));
17161
19065
  if (pkg.main) entryPoints.push(path8__default.resolve(path8__default.dirname(packageJson), pkg.main));
17162
19066
  if (pkg.types) entryPoints.push(path8__default.resolve(path8__default.dirname(packageJson), pkg.types));
17163
19067
  } catch (error) {
@@ -17939,7 +19843,7 @@ var init_semantic_code_search = __esm({
17939
19843
  }
17940
19844
  async extractContext(symbol) {
17941
19845
  try {
17942
- const content = await fs3.readFile(symbol.filePath, "utf8");
19846
+ const content = await fs7__default.readFile(symbol.filePath, "utf8");
17943
19847
  const lines = content.split("\n");
17944
19848
  const startLine = Math.max(0, symbol.line - 3);
17945
19849
  const endLine = Math.min(lines.length, symbol.line + 3);
@@ -17980,7 +19884,7 @@ var init_semantic_code_search = __esm({
17980
19884
  for (const [filePath, fileInfo] of index.files) {
17981
19885
  if (fileInfo.language === "unknown" || fileInfo.size > 1e5) continue;
17982
19886
  try {
17983
- const content = await fs3.readFile(filePath, "utf8");
19887
+ const content = await fs7__default.readFile(filePath, "utf8");
17984
19888
  const lines = content.split("\n");
17985
19889
  for (let i = 0; i < lines.length; i++) {
17986
19890
  const line = lines[i].toLowerCase();
@@ -19435,10 +21339,10 @@ Current working directory: ${process.cwd()}`
19435
21339
  return await this.textEditor.view(args.path, range);
19436
21340
  } catch (error) {
19437
21341
  console.warn(`view_file tool failed, falling back to bash: ${error.message}`);
19438
- const path41 = args.path;
19439
- let command = `cat "${path41}"`;
21342
+ const path43 = args.path;
21343
+ let command = `cat "${path43}"`;
19440
21344
  if (args.start_line && args.end_line) {
19441
- command = `sed -n '${args.start_line},${args.end_line}p' "${path41}"`;
21345
+ command = `sed -n '${args.start_line},${args.end_line}p' "${path43}"`;
19442
21346
  }
19443
21347
  return await this.bash.execute(command);
19444
21348
  }
@@ -19723,12 +21627,12 @@ EOF`;
19723
21627
  saveSessionLog() {
19724
21628
  try {
19725
21629
  const sessionDir = path8__default.join(__require("os").homedir(), ".grok");
19726
- if (!fs7__default.existsSync(sessionDir)) {
19727
- fs7__default.mkdirSync(sessionDir, { recursive: true });
21630
+ if (!fs10__default.existsSync(sessionDir)) {
21631
+ fs10__default.mkdirSync(sessionDir, { recursive: true });
19728
21632
  }
19729
21633
  const sessionFile = path8__default.join(sessionDir, "session.log");
19730
21634
  const logLines = this.chatHistory.map((entry) => JSON.stringify(entry)).join("\n") + "\n";
19731
- fs7__default.writeFileSync(sessionFile, logLines);
21635
+ fs10__default.writeFileSync(sessionFile, logLines);
19732
21636
  } catch (error) {
19733
21637
  console.warn("Failed to save session log:", error);
19734
21638
  }
@@ -19769,17 +21673,6 @@ EOF`;
19769
21673
  timestamp: Date.now()
19770
21674
  });
19771
21675
  }
19772
- if (!result.success) {
19773
- console.warn(`[GrokAgent] Tool chain validation failed at ${toolCall.function.name}:`, {
19774
- operationId: this.toolChainContext.operationId,
19775
- chainLength: this.toolChainContext.chainedOperations.length,
19776
- previousOperations: this.toolChainContext.chainedOperations.slice(-3).map((op) => ({
19777
- tool: op.toolName,
19778
- success: op.success,
19779
- ago: Date.now() - op.timestamp
19780
- }))
19781
- });
19782
- }
19783
21676
  if (this.toolChainContext.chainedOperations.length > 50) {
19784
21677
  this.toolChainContext.chainedOperations = this.toolChainContext.chainedOperations.slice(-25);
19785
21678
  this.toolChainContext.rollbackPoints = this.toolChainContext.rollbackPoints.slice(-10);
@@ -19988,8 +21881,8 @@ EOF`;
19988
21881
  logEntry(entry) {
19989
21882
  try {
19990
21883
  const dir = path8__default.dirname(this.sessionLogPath);
19991
- if (!fs7__default.existsSync(dir)) {
19992
- fs7__default.mkdirSync(dir, { recursive: true });
21884
+ if (!fs10__default.existsSync(dir)) {
21885
+ fs10__default.mkdirSync(dir, { recursive: true });
19993
21886
  }
19994
21887
  const logLine = JSON.stringify({
19995
21888
  type: entry.type,
@@ -19998,7 +21891,7 @@ EOF`;
19998
21891
  toolCallId: entry.toolCall?.id,
19999
21892
  toolCallsCount: entry.toolCalls?.length
20000
21893
  }) + "\n";
20001
- fs7__default.appendFileSync(this.sessionLogPath, logLine);
21894
+ fs10__default.appendFileSync(this.sessionLogPath, logLine);
20002
21895
  } catch (error) {
20003
21896
  console.warn("Failed to log session entry:", error);
20004
21897
  }
@@ -22188,7 +24081,7 @@ var init_readonly_filesystem_overlay = __esm({
22188
24081
  };
22189
24082
  }
22190
24083
  try {
22191
- const actualContent = await fs7__default.promises.readFile(resolvedPath, "utf-8");
24084
+ const actualContent = await fs10__default.promises.readFile(resolvedPath, "utf-8");
22192
24085
  return {
22193
24086
  success: true,
22194
24087
  output: this.formatFileContent(actualContent, args),
@@ -22245,7 +24138,7 @@ var init_readonly_filesystem_overlay = __esm({
22245
24138
  const filePath = args.path || args.file_path || args.filename;
22246
24139
  const content = args.content || "";
22247
24140
  const resolvedPath = path8__default.resolve(this.config.baseDirectory, filePath);
22248
- const fileExists = fs7__default.existsSync(resolvedPath);
24141
+ const fileExists = fs10__default.existsSync(resolvedPath);
22249
24142
  const sizeImpact = content.length;
22250
24143
  return {
22251
24144
  type: "file_creation",
@@ -22274,7 +24167,7 @@ var init_readonly_filesystem_overlay = __esm({
22274
24167
  const filePath = args.path || args.file_path || args.filename;
22275
24168
  const resolvedPath = path8__default.resolve(this.config.baseDirectory, filePath);
22276
24169
  try {
22277
- const originalContent = fs7__default.existsSync(resolvedPath) ? await fs7__default.promises.readFile(resolvedPath, "utf-8") : "";
24170
+ const originalContent = fs10__default.existsSync(resolvedPath) ? await fs10__default.promises.readFile(resolvedPath, "utf-8") : "";
22278
24171
  let newContent = originalContent;
22279
24172
  if (args.old_string && args.new_string !== void 0) {
22280
24173
  newContent = args.replace_all ? originalContent.split(args.old_string).join(args.new_string) : originalContent.replace(args.old_string, args.new_string);
@@ -22317,11 +24210,11 @@ var init_readonly_filesystem_overlay = __esm({
22317
24210
  async simulateFileDeletion(args) {
22318
24211
  const filePath = args.path || args.file_path || args.filename;
22319
24212
  const resolvedPath = path8__default.resolve(this.config.baseDirectory, filePath);
22320
- const fileExists = fs7__default.existsSync(resolvedPath);
24213
+ const fileExists = fs10__default.existsSync(resolvedPath);
22321
24214
  let originalSize = 0;
22322
24215
  if (fileExists) {
22323
24216
  try {
22324
- const stats = await fs7__default.promises.stat(resolvedPath);
24217
+ const stats = await fs10__default.promises.stat(resolvedPath);
22325
24218
  originalSize = stats.size;
22326
24219
  } catch {
22327
24220
  }
@@ -27387,7 +29280,7 @@ var init_package = __esm({
27387
29280
  package_default = {
27388
29281
  type: "module",
27389
29282
  name: "@xagent/one-shot",
27390
- version: "1.2.12",
29283
+ version: "1.2.14",
27391
29284
  description: "An open-source AI agent that brings advanced AI capabilities directly into your terminal with automatic documentation updates.",
27392
29285
  main: "dist/index.js",
27393
29286
  module: "dist/index.js",
@@ -29963,14 +31856,14 @@ function useContextInfo(agent) {
29963
31856
  async function getWorkspaceFileCount() {
29964
31857
  try {
29965
31858
  const cwd = process.cwd();
29966
- const entries = await fs7__default.promises.readdir(cwd, { withFileTypes: true });
31859
+ const entries = await fs10__default.promises.readdir(cwd, { withFileTypes: true });
29967
31860
  let count = 0;
29968
31861
  for (const entry of entries) {
29969
31862
  if (entry.isFile() && !shouldIgnoreFile(entry.name)) {
29970
31863
  count++;
29971
31864
  } else if (entry.isDirectory() && !shouldIgnoreDirectory(entry.name)) {
29972
31865
  try {
29973
- const subEntries = await fs7__default.promises.readdir(path8__default.join(cwd, entry.name), { withFileTypes: true });
31866
+ const subEntries = await fs10__default.promises.readdir(path8__default.join(cwd, entry.name), { withFileTypes: true });
29974
31867
  count += subEntries.filter((sub) => sub.isFile() && !shouldIgnoreFile(sub.name)).length;
29975
31868
  } catch {
29976
31869
  }
@@ -29984,15 +31877,15 @@ async function getWorkspaceFileCount() {
29984
31877
  function shouldIgnoreFile(filename) {
29985
31878
  return filename.startsWith(".") || filename.endsWith(".log") || filename.includes(".tmp");
29986
31879
  }
29987
- function shouldIgnoreDirectory(dirname5) {
31880
+ function shouldIgnoreDirectory(dirname6) {
29988
31881
  const ignoreDirs = ["node_modules", ".git", "dist", "build", ".next", "coverage"];
29989
- return ignoreDirs.includes(dirname5) || dirname5.startsWith(".");
31882
+ return ignoreDirs.includes(dirname6) || dirname6.startsWith(".");
29990
31883
  }
29991
31884
  async function getIndexSize() {
29992
31885
  try {
29993
31886
  const indexPath = path8__default.join(process.cwd(), ".grok", "index.json");
29994
- if (fs7__default.existsSync(indexPath)) {
29995
- const stats = await fs7__default.promises.stat(indexPath);
31887
+ if (fs10__default.existsSync(indexPath)) {
31888
+ const stats = await fs10__default.promises.stat(indexPath);
29996
31889
  const mb = stats.size / (1024 * 1024);
29997
31890
  return mb > 1 ? `${mb.toFixed(1)} MB` : `${(stats.size / 1024).toFixed(1)} KB`;
29998
31891
  }
@@ -30003,8 +31896,8 @@ async function getIndexSize() {
30003
31896
  async function getSessionFileCount() {
30004
31897
  try {
30005
31898
  const sessionPath = path8__default.join(os__default.homedir(), ".grok", "session.log");
30006
- if (fs7__default.existsSync(sessionPath)) {
30007
- const content = await fs7__default.promises.readFile(sessionPath, "utf8");
31899
+ if (fs10__default.existsSync(sessionPath)) {
31900
+ const content = await fs10__default.promises.readFile(sessionPath, "utf8");
30008
31901
  return content.split("\n").filter((line) => line.trim()).length;
30009
31902
  }
30010
31903
  } catch {
@@ -30014,8 +31907,8 @@ async function getSessionFileCount() {
30014
31907
  async function getGitBranch() {
30015
31908
  try {
30016
31909
  const gitPath = path8__default.join(process.cwd(), ".git", "HEAD");
30017
- if (fs7__default.existsSync(gitPath)) {
30018
- const content = await fs7__default.promises.readFile(gitPath, "utf8");
31910
+ if (fs10__default.existsSync(gitPath)) {
31911
+ const content = await fs10__default.promises.readFile(gitPath, "utf8");
30019
31912
  const match = content.match(/ref: refs\/heads\/(.+)/);
30020
31913
  return match ? match[1].trim() : "detached";
30021
31914
  }
@@ -30026,8 +31919,8 @@ async function getGitBranch() {
30026
31919
  async function getProjectName() {
30027
31920
  try {
30028
31921
  const packagePath = path8__default.join(process.cwd(), "package.json");
30029
- if (fs7__default.existsSync(packagePath)) {
30030
- const content = await fs7__default.promises.readFile(packagePath, "utf8");
31922
+ if (fs10__default.existsSync(packagePath)) {
31923
+ const content = await fs10__default.promises.readFile(packagePath, "utf8");
30031
31924
  const pkg = JSON.parse(content);
30032
31925
  return pkg.name;
30033
31926
  }
@@ -30070,20 +31963,20 @@ function useCLAUDEmd(setChatHistory) {
30070
31963
  useEffect(() => {
30071
31964
  const filesToLoad = [
30072
31965
  { path: "GROK.md", label: "GROK.md", fallback: "CLAUDE.md" },
30073
- { path: "docs-index.md", label: "Documentation Index" }
31966
+ { path: ".agent/docs-summary.md", label: "Compressed Documentation Summary" }
30074
31967
  ];
30075
31968
  const loadedDocs = [];
30076
31969
  let totalChars = 0;
30077
31970
  for (const file of filesToLoad) {
30078
31971
  let filePath = file.path;
30079
- let exists = fs7__default.existsSync(filePath);
31972
+ let exists = fs10__default.existsSync(filePath);
30080
31973
  if (!exists && file.fallback) {
30081
31974
  filePath = file.fallback;
30082
- exists = fs7__default.existsSync(filePath);
31975
+ exists = fs10__default.existsSync(filePath);
30083
31976
  }
30084
31977
  if (exists) {
30085
31978
  try {
30086
- const content = fs7__default.readFileSync(filePath, "utf8");
31979
+ const content = fs10__default.readFileSync(filePath, "utf8");
30087
31980
  const charCount = content.length;
30088
31981
  totalChars += charCount;
30089
31982
  loadedDocs.push(file.label);
@@ -30457,11 +32350,11 @@ function useSessionLogging(chatHistory) {
30457
32350
  const sessionFile = path8__default.join(os__default.homedir(), ".grok", "session.log");
30458
32351
  try {
30459
32352
  const dir = path8__default.dirname(sessionFile);
30460
- if (!fs7__default.existsSync(dir)) {
30461
- fs7__default.mkdirSync(dir, { recursive: true });
32353
+ if (!fs10__default.existsSync(dir)) {
32354
+ fs10__default.mkdirSync(dir, { recursive: true });
30462
32355
  }
30463
32356
  const lines = newEntries.map((entry) => JSON.stringify(entry)).join("\n") + "\n";
30464
- fs7__default.appendFileSync(sessionFile, lines);
32357
+ fs10__default.appendFileSync(sessionFile, lines);
30465
32358
  } catch {
30466
32359
  }
30467
32360
  }
@@ -30862,10 +32755,10 @@ ${data ? JSON.stringify(data, null, 2) : "No additional data"}
30862
32755
  `;
30863
32756
  const workingDir = process.cwd();
30864
32757
  const logsDir = path8__default.join(workingDir, "logs");
30865
- const sessionFiles = fs7__default.readdirSync(logsDir).filter((f) => f.startsWith("session-") && f.endsWith(".log"));
32758
+ const sessionFiles = fs10__default.readdirSync(logsDir).filter((f) => f.startsWith("session-") && f.endsWith(".log"));
30866
32759
  if (sessionFiles.length > 0) {
30867
32760
  const sessionFile = path8__default.join(logsDir, sessionFiles[sessionFiles.length - 1]);
30868
- fs7__default.appendFileSync(sessionFile, logEntry);
32761
+ fs10__default.appendFileSync(sessionFile, logEntry);
30869
32762
  } else {
30870
32763
  console.log(`[ColoredDiffRenderer] ${message}`, data);
30871
32764
  }
@@ -30939,10 +32832,10 @@ ${data ? JSON.stringify(data, null, 2) : "No additional data"}
30939
32832
  `;
30940
32833
  const workingDir = process.cwd();
30941
32834
  const logsDir = path8__default.join(workingDir, "logs");
30942
- const sessionFiles = fs7__default.readdirSync(logsDir).filter((f) => f.startsWith("session-") && f.endsWith(".log"));
32835
+ const sessionFiles = fs10__default.readdirSync(logsDir).filter((f) => f.startsWith("session-") && f.endsWith(".log"));
30943
32836
  if (sessionFiles.length > 0) {
30944
32837
  const sessionFile = path8__default.join(logsDir, sessionFiles[sessionFiles.length - 1]);
30945
- fs7__default.appendFileSync(sessionFile, logEntry);
32838
+ fs10__default.appendFileSync(sessionFile, logEntry);
30946
32839
  } else {
30947
32840
  console.log(`[MarkdownRenderer] ${message}`, data);
30948
32841
  }
@@ -32891,7 +34784,7 @@ var init_session_logger = __esm({
32891
34784
  this.init();
32892
34785
  }
32893
34786
  init() {
32894
- fs7__default.mkdirSync(path8__default.dirname(this.logPath), { recursive: true });
34787
+ fs10__default.mkdirSync(path8__default.dirname(this.logPath), { recursive: true });
32895
34788
  const header = `
32896
34789
  =================================================================
32897
34790
  \u{1F9EA} GROK ONE-SHOT TESTING SESSION
@@ -32900,7 +34793,7 @@ Started: ${(/* @__PURE__ */ new Date()).toISOString()}
32900
34793
  =================================================================
32901
34794
 
32902
34795
  `;
32903
- fs7__default.writeFileSync(this.logPath, header);
34796
+ fs10__default.writeFileSync(this.logPath, header);
32904
34797
  }
32905
34798
  logTerminalState(state) {
32906
34799
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
@@ -32916,7 +34809,7 @@ LAST ENTRY: ${state.chatHistory.length > 0 ? JSON.stringify(state.chatHistory[st
32916
34809
  =====================================
32917
34810
 
32918
34811
  `;
32919
- fs7__default.appendFileSync(this.logPath, entry);
34812
+ fs10__default.appendFileSync(this.logPath, entry);
32920
34813
  }
32921
34814
  logUserAction(action, details = {}) {
32922
34815
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
@@ -32924,7 +34817,7 @@ LAST ENTRY: ${state.chatHistory.length > 0 ? JSON.stringify(state.chatHistory[st
32924
34817
  Details: ${JSON.stringify(details, null, 2)}
32925
34818
 
32926
34819
  `;
32927
- fs7__default.appendFileSync(this.logPath, entry);
34820
+ fs10__default.appendFileSync(this.logPath, entry);
32928
34821
  }
32929
34822
  logPasteEvent(event) {
32930
34823
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
@@ -32932,7 +34825,7 @@ Details: ${JSON.stringify(details, null, 2)}
32932
34825
  Data: ${JSON.stringify(event.data, null, 2)}
32933
34826
 
32934
34827
  `;
32935
- fs7__default.appendFileSync(this.logPath, entry);
34828
+ fs10__default.appendFileSync(this.logPath, entry);
32936
34829
  }
32937
34830
  logTestResult(testName, result, details) {
32938
34831
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
@@ -32943,7 +34836,7 @@ Details: ${details}
32943
34836
  =================================================================
32944
34837
 
32945
34838
  `;
32946
- fs7__default.appendFileSync(this.logPath, entry);
34839
+ fs10__default.appendFileSync(this.logPath, entry);
32947
34840
  }
32948
34841
  getLogPath() {
32949
34842
  return this.logPath;
@@ -33400,7 +35293,7 @@ var require_package = __commonJS({
33400
35293
  module.exports = {
33401
35294
  type: "module",
33402
35295
  name: "@xagent/one-shot",
33403
- version: "1.2.12",
35296
+ version: "1.2.14",
33404
35297
  description: "An open-source AI agent that brings advanced AI capabilities directly into your terminal with automatic documentation updates.",
33405
35298
  main: "dist/index.js",
33406
35299
  module: "dist/index.js",
@@ -33554,7 +35447,7 @@ var require_package = __commonJS({
33554
35447
  }
33555
35448
  });
33556
35449
  dotenv.config();
33557
- var logStream = fs7__default.createWriteStream(path8__default.join(process.cwd(), "xcli-startup.log"), { flags: "a" });
35450
+ var logStream = fs10__default.createWriteStream(path8__default.join(process.cwd(), "xcli-startup.log"), { flags: "a" });
33558
35451
  var isQuietCommand = process.argv.includes("--version") || process.argv.includes("-V") || process.argv.includes("--help") || process.argv.includes("-h");
33559
35452
  if (isQuietCommand) {
33560
35453
  process.env.GROK_QUIET_MODE = "true";