@bonginkan/maria 2.0.5 → 2.0.7

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
@@ -7,11 +7,12 @@ var generativeAi = require('@google/generative-ai');
7
7
  var fetch3 = require('node-fetch');
8
8
  var chalk13 = require('chalk');
9
9
  var fs7 = require('fs');
10
- var path5 = require('path');
10
+ var path10 = require('path');
11
11
  var toml = require('toml');
12
- var os2 = require('os');
13
- var fs6 = require('fs/promises');
12
+ var os3 = require('os');
14
13
  var events = require('events');
14
+ var fs11 = require('fs/promises');
15
+ var gpt3Encoder = require('gpt-3-encoder');
15
16
  var uuid = require('uuid');
16
17
  var commander = require('commander');
17
18
  var Groq = require('groq-sdk');
@@ -20,7 +21,7 @@ var crypto = require('crypto');
20
21
  var child_process = require('child_process');
21
22
  var util = require('util');
22
23
  var dotenv = require('dotenv');
23
- var gpt3Encoder = require('gpt-3-encoder');
24
+ var glob = require('glob');
24
25
 
25
26
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
26
27
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -48,9 +49,9 @@ var Anthropic__default = /*#__PURE__*/_interopDefault(Anthropic);
48
49
  var fetch3__default = /*#__PURE__*/_interopDefault(fetch3);
49
50
  var chalk13__default = /*#__PURE__*/_interopDefault(chalk13);
50
51
  var fs7__namespace = /*#__PURE__*/_interopNamespace(fs7);
51
- var path5__namespace = /*#__PURE__*/_interopNamespace(path5);
52
- var os2__default = /*#__PURE__*/_interopDefault(os2);
53
- var fs6__namespace = /*#__PURE__*/_interopNamespace(fs6);
52
+ var path10__namespace = /*#__PURE__*/_interopNamespace(path10);
53
+ var os3__default = /*#__PURE__*/_interopDefault(os3);
54
+ var fs11__namespace = /*#__PURE__*/_interopNamespace(fs11);
54
55
  var Groq__default = /*#__PURE__*/_interopDefault(Groq);
55
56
  var readline__namespace = /*#__PURE__*/_interopNamespace(readline);
56
57
  var crypto__default = /*#__PURE__*/_interopDefault(crypto);
@@ -152,8 +153,8 @@ var init_openai_provider = __esm({
152
153
  }
153
154
  name = "OpenAI";
154
155
  models = [
155
- "gpt-5-2025-08-07",
156
- "gpt-5-mini-2025-08-07",
156
+ "gpt-5",
157
+ "gpt-5-mini",
157
158
  "gpt-4o",
158
159
  "gpt-4o-mini",
159
160
  "gpt-4-turbo",
@@ -281,7 +282,7 @@ var init_anthropic_provider = __esm({
281
282
  }
282
283
  name = "Anthropic";
283
284
  models = [
284
- "claude-opus-4.1",
285
+ "claude-4.1",
285
286
  "claude-3-5-sonnet-20241022",
286
287
  "claude-3-5-haiku-20241022",
287
288
  "claude-3-opus-20240229",
@@ -1231,7 +1232,7 @@ var init_logger = __esm({
1231
1232
  function loadConfig() {
1232
1233
  let currentDir = process.cwd();
1233
1234
  while (currentDir !== "/") {
1234
- const configPath = path5.join(currentDir, CONFIG_FILE);
1235
+ const configPath = path10.join(currentDir, CONFIG_FILE);
1235
1236
  if (fs7.existsSync(configPath)) {
1236
1237
  try {
1237
1238
  const content = fs7.readFileSync(configPath, "utf-8");
@@ -1239,7 +1240,7 @@ function loadConfig() {
1239
1240
  } catch {
1240
1241
  }
1241
1242
  }
1242
- const parentDir = path5.join(currentDir, "..");
1243
+ const parentDir = path10.join(currentDir, "..");
1243
1244
  if (parentDir === currentDir) break;
1244
1245
  currentDir = parentDir;
1245
1246
  }
@@ -1274,18 +1275,18 @@ async function readConfig() {
1274
1275
  }
1275
1276
  return config2;
1276
1277
  }
1277
- async function writeConfig(config2, path9) {
1278
+ async function writeConfig(config2, path11) {
1278
1279
  return new Promise((resolve, reject) => {
1279
1280
  try {
1280
- saveConfig(config2, path9);
1281
+ saveConfig(config2, path11);
1281
1282
  resolve();
1282
1283
  } catch (error) {
1283
1284
  reject(error);
1284
1285
  }
1285
1286
  });
1286
1287
  }
1287
- function saveConfig(config2, path9) {
1288
- const configPath = path9 || path5.join(process.cwd(), CONFIG_FILE);
1288
+ function saveConfig(config2, path11) {
1289
+ const configPath = path11 || path10.join(process.cwd(), CONFIG_FILE);
1289
1290
  const lines = [];
1290
1291
  if (config2.user) {
1291
1292
  lines.push("[user]");
@@ -1504,13 +1505,242 @@ var init_config = __esm({
1504
1505
  "src/utils/config.ts"() {
1505
1506
  init_cjs_shims();
1506
1507
  CONFIG_FILE = ".maria-code.toml";
1507
- GLOBAL_CONFIG_PATH = path5.join(os2.homedir(), ".maria-code", "config.toml");
1508
+ GLOBAL_CONFIG_PATH = path10.join(os3.homedir(), ".maria-code", "config.toml");
1508
1509
  __name(loadConfig, "loadConfig");
1509
1510
  __name(readConfig, "readConfig");
1510
1511
  __name(writeConfig, "writeConfig");
1511
1512
  __name(saveConfig, "saveConfig");
1512
1513
  }
1513
1514
  });
1515
+ var ChatContextService;
1516
+ var init_chat_context_service = __esm({
1517
+ "src/services/chat-context.service.ts"() {
1518
+ init_cjs_shims();
1519
+ ChatContextService = class _ChatContextService extends events.EventEmitter {
1520
+ static {
1521
+ __name(this, "ChatContextService");
1522
+ }
1523
+ static instance;
1524
+ contextWindow = [];
1525
+ fullHistory = [];
1526
+ config;
1527
+ currentTokens = 0;
1528
+ compressionCount = 0;
1529
+ sessionId;
1530
+ constructor(config2) {
1531
+ super();
1532
+ this.config = {
1533
+ maxTokens: config2?.maxTokens || 128e3,
1534
+ compressionThreshold: config2?.compressionThreshold || 0.8,
1535
+ summaryTokenLimit: config2?.summaryTokenLimit || 2e3,
1536
+ persistPath: config2?.persistPath || path10__namespace.join(process.env["HOME"] || "", ".maria", "context")
1537
+ };
1538
+ this.sessionId = this.generateSessionId();
1539
+ }
1540
+ static getInstance(config2) {
1541
+ if (!_ChatContextService.instance) {
1542
+ _ChatContextService.instance = new _ChatContextService(config2);
1543
+ }
1544
+ return _ChatContextService.instance;
1545
+ }
1546
+ generateSessionId() {
1547
+ return `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
1548
+ }
1549
+ countTokens(text) {
1550
+ try {
1551
+ return gpt3Encoder.encode(text).length;
1552
+ } catch {
1553
+ return Math.ceil(text.length / 4);
1554
+ }
1555
+ }
1556
+ async addMessage(message) {
1557
+ const tokens = this.countTokens(message.content);
1558
+ const fullMessage = {
1559
+ ...message,
1560
+ timestamp: /* @__PURE__ */ new Date(),
1561
+ tokens
1562
+ };
1563
+ this.fullHistory.push(fullMessage);
1564
+ this.contextWindow.push(fullMessage);
1565
+ this.currentTokens += tokens;
1566
+ await this.optimizeMemory();
1567
+ this.emit("message-added", fullMessage);
1568
+ this.emit("context-updated", this.getStats());
1569
+ }
1570
+ async optimizeMemory() {
1571
+ const usageRatio = this.currentTokens / this.config.maxTokens;
1572
+ if (usageRatio >= this.config.compressionThreshold) {
1573
+ await this.compressContext();
1574
+ }
1575
+ while (this.currentTokens > this.config.maxTokens && this.contextWindow.length > 1) {
1576
+ const removed = this.contextWindow.shift();
1577
+ if (removed?.tokens) {
1578
+ this.currentTokens -= removed.tokens;
1579
+ }
1580
+ }
1581
+ }
1582
+ async compressContext() {
1583
+ if (this.contextWindow.length <= 2) return;
1584
+ const middleMessages = this.contextWindow.slice(1, -1);
1585
+ const summary = await this.generateSummary(middleMessages);
1586
+ if (summary) {
1587
+ const summaryMessage = {
1588
+ role: "system",
1589
+ content: `[Compressed context summary]: ${summary}`,
1590
+ timestamp: /* @__PURE__ */ new Date(),
1591
+ tokens: this.countTokens(summary),
1592
+ metadata: { compressed: true, originalCount: middleMessages.length }
1593
+ };
1594
+ const firstMessage = this.contextWindow[0];
1595
+ const lastMessage = this.contextWindow[this.contextWindow.length - 1];
1596
+ if (!firstMessage || !lastMessage) return;
1597
+ this.contextWindow = [firstMessage, summaryMessage, lastMessage];
1598
+ this.recalculateTokens();
1599
+ this.compressionCount++;
1600
+ this.emit("context-compressed", {
1601
+ originalCount: middleMessages.length,
1602
+ summaryTokens: summaryMessage.tokens
1603
+ });
1604
+ }
1605
+ }
1606
+ async generateSummary(messages) {
1607
+ const keyPoints = messages.filter((m) => m.role === "user").map((m) => m.content.substring(0, 100)).join("; ");
1608
+ return `Previous discussion covered: ${keyPoints}`;
1609
+ }
1610
+ recalculateTokens() {
1611
+ this.currentTokens = this.contextWindow.reduce((sum, msg) => sum + (msg.tokens || 0), 0);
1612
+ }
1613
+ clearContext(options) {
1614
+ if (options?.soft) {
1615
+ this.emit("display-cleared");
1616
+ return;
1617
+ }
1618
+ if (options?.summary && this.contextWindow.length > 0) {
1619
+ this.generateSummary(this.contextWindow).then((summary) => {
1620
+ this.emit("summary-generated", summary);
1621
+ });
1622
+ }
1623
+ const previousStats = this.getStats();
1624
+ this.contextWindow = [];
1625
+ this.currentTokens = 0;
1626
+ this.compressionCount = 0;
1627
+ if (!options?.soft) {
1628
+ this.fullHistory = [];
1629
+ this.sessionId = this.generateSessionId();
1630
+ }
1631
+ this.emit("context-cleared", previousStats);
1632
+ }
1633
+ getContext() {
1634
+ return [...this.contextWindow];
1635
+ }
1636
+ getFullHistory() {
1637
+ return [...this.fullHistory];
1638
+ }
1639
+ getStats() {
1640
+ return {
1641
+ totalMessages: this.fullHistory.length,
1642
+ totalTokens: this.currentTokens,
1643
+ maxTokens: this.config.maxTokens,
1644
+ usagePercentage: this.currentTokens / this.config.maxTokens * 100,
1645
+ messagesInWindow: this.contextWindow.length,
1646
+ compressedCount: this.compressionCount
1647
+ };
1648
+ }
1649
+ async persistSession() {
1650
+ if (!this.config.persistPath) return;
1651
+ try {
1652
+ await fs11__namespace.mkdir(this.config.persistPath, { recursive: true });
1653
+ const sessionFile = path10__namespace.join(this.config.persistPath, `${this.sessionId}.json`);
1654
+ const sessionData = {
1655
+ sessionId: this.sessionId,
1656
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1657
+ stats: this.getStats(),
1658
+ contextWindow: this.contextWindow,
1659
+ fullHistory: this.fullHistory,
1660
+ compressionCount: this.compressionCount
1661
+ };
1662
+ await fs11__namespace.writeFile(sessionFile, JSON.stringify(sessionData, null, 2));
1663
+ this.emit("session-persisted", sessionFile);
1664
+ } catch (error) {
1665
+ this.emit("persist-error", error instanceof Error ? error : new Error(String(error)));
1666
+ }
1667
+ }
1668
+ async loadSession(sessionId) {
1669
+ if (!this.config.persistPath) return false;
1670
+ try {
1671
+ const sessionFile = path10__namespace.join(this.config.persistPath, `${sessionId}.json`);
1672
+ const data = await fs11__namespace.readFile(sessionFile, "utf-8");
1673
+ const sessionData = JSON.parse(data);
1674
+ this.sessionId = sessionData.sessionId;
1675
+ this.contextWindow = sessionData.contextWindow;
1676
+ this.fullHistory = sessionData.fullHistory;
1677
+ this.compressionCount = sessionData.compressionCount;
1678
+ this.recalculateTokens();
1679
+ this.emit("session-loaded", sessionId);
1680
+ return true;
1681
+ } catch (error) {
1682
+ this.emit("load-error", error instanceof Error ? error : new Error(String(error)));
1683
+ return false;
1684
+ }
1685
+ }
1686
+ async exportContext(format = "json") {
1687
+ if (format === "markdown") {
1688
+ return this.contextWindow.map(
1689
+ (msg) => `### ${msg.role.toUpperCase()} (${msg.timestamp.toISOString()})
1690
+ ${msg.content}
1691
+ `
1692
+ ).join("\n---\n\n");
1693
+ }
1694
+ return JSON.stringify(
1695
+ {
1696
+ sessionId: this.sessionId,
1697
+ exportDate: (/* @__PURE__ */ new Date()).toISOString(),
1698
+ stats: this.getStats(),
1699
+ context: this.contextWindow,
1700
+ fullHistory: this.fullHistory
1701
+ },
1702
+ null,
1703
+ 2
1704
+ );
1705
+ }
1706
+ async importContext(data) {
1707
+ try {
1708
+ const imported = JSON.parse(data);
1709
+ if (imported.context && Array.isArray(imported.context)) {
1710
+ this.contextWindow = imported.context;
1711
+ this.fullHistory = imported.fullHistory || imported.context;
1712
+ this.recalculateTokens();
1713
+ this.sessionId = imported.sessionId || this.generateSessionId();
1714
+ this.emit("context-imported", this.getStats());
1715
+ }
1716
+ } catch (error) {
1717
+ this.emit("import-error", error instanceof Error ? error : new Error(String(error)));
1718
+ throw error;
1719
+ }
1720
+ }
1721
+ getTokenUsageIndicator() {
1722
+ const stats = this.getStats();
1723
+ const percentage = Math.round(stats.usagePercentage);
1724
+ const blocks = Math.round(percentage / 10);
1725
+ const filled = "\u2588".repeat(blocks);
1726
+ const empty = "\u2591".repeat(10 - blocks);
1727
+ let color = "\x1B[32m";
1728
+ if (percentage > 80)
1729
+ color = "\x1B[31m";
1730
+ else if (percentage > 60) color = "\x1B[33m";
1731
+ return `${color}[${filled}${empty}] ${percentage}% (${stats.totalTokens}/${stats.maxTokens} tokens)\x1B[0m`;
1732
+ }
1733
+ reset() {
1734
+ this.contextWindow = [];
1735
+ this.fullHistory = [];
1736
+ this.currentTokens = 0;
1737
+ this.compressionCount = 0;
1738
+ this.sessionId = this.generateSessionId();
1739
+ _ChatContextService.instance = null;
1740
+ }
1741
+ };
1742
+ }
1743
+ });
1514
1744
 
1515
1745
  // src/services/code-generation.service.ts
1516
1746
  var code_generation_service_exports = {};
@@ -1875,7 +2105,7 @@ Include: function descriptions, parameter explanations, return values, usage exa
1875
2105
  // Helper methods
1876
2106
  async detectFramework() {
1877
2107
  try {
1878
- const packageJson = await fs6__namespace.readFile("package.json", "utf-8");
2108
+ const packageJson = await fs11__namespace.readFile("package.json", "utf-8");
1879
2109
  const pkg = JSON.parse(packageJson);
1880
2110
  if (pkg.dependencies?.react || pkg.devDependencies?.react) return "React";
1881
2111
  if (pkg.dependencies?.vue || pkg.devDependencies?.vue) return "Vue";
@@ -1889,7 +2119,7 @@ Include: function descriptions, parameter explanations, return values, usage exa
1889
2119
  }
1890
2120
  async detectProjectType() {
1891
2121
  try {
1892
- const files = await fs6__namespace.readdir(process.cwd());
2122
+ const files = await fs11__namespace.readdir(process.cwd());
1893
2123
  if (files.includes("package.json")) return "Node.js";
1894
2124
  if (files.includes("requirements.txt") || files.includes("setup.py")) return "Python";
1895
2125
  if (files.includes("go.mod")) return "Go";
@@ -1902,7 +2132,7 @@ Include: function descriptions, parameter explanations, return values, usage exa
1902
2132
  async detectTestFramework(context) {
1903
2133
  if (context.language === "javascript" || context.language === "typescript") {
1904
2134
  try {
1905
- const packageJson = await fs6__namespace.readFile("package.json", "utf-8");
2135
+ const packageJson = await fs11__namespace.readFile("package.json", "utf-8");
1906
2136
  const pkg = JSON.parse(packageJson);
1907
2137
  if (pkg.devDependencies?.jest) return "Jest";
1908
2138
  if (pkg.devDependencies?.mocha) return "Mocha";
@@ -1936,7 +2166,7 @@ Include: function descriptions, parameter explanations, return values, usage exa
1936
2166
  __name(this, "LanguageDetector");
1937
2167
  }
1938
2168
  async detectFromFile(filePath) {
1939
- const ext = path5__namespace.extname(filePath).toLowerCase();
2169
+ const ext = path10__namespace.extname(filePath).toLowerCase();
1940
2170
  const languageMap = {
1941
2171
  ".js": "javascript",
1942
2172
  ".jsx": "javascript",
@@ -5470,10 +5700,10 @@ var init_multi_agent_system = __esm({
5470
5700
  /**
5471
5701
  * Index current codebase for CodeRAG
5472
5702
  */
5473
- async indexCurrentCodebase(path9 = ".", options = {}) {
5703
+ async indexCurrentCodebase(path11 = ".", options = {}) {
5474
5704
  try {
5475
- logger.info(`Indexing codebase for CodeRAG: ${path9}`);
5476
- const result = await codeRAGService.indexCodebase(path9, {
5705
+ logger.info(`Indexing codebase for CodeRAG: ${path11}`);
5706
+ const result = await codeRAGService.indexCodebase(path11, {
5477
5707
  fileTypes: options.fileTypes || [".ts", ".tsx", ".js", ".jsx"],
5478
5708
  excludePaths: options.excludePaths || ["node_modules", "dist", ".git"],
5479
5709
  chunkSize: 500,
@@ -5995,119 +6225,1420 @@ var init_llm_startup_manager = __esm({
5995
6225
  console.log("\n\u{1F389} Ready! Using cloud providers");
5996
6226
  }
5997
6227
  }
5998
- async checkService(service) {
5999
- service.status = "checking";
6000
- service.progress = 0;
6228
+ async checkService(service) {
6229
+ service.status = "checking";
6230
+ service.progress = 0;
6231
+ try {
6232
+ const { LLMHealthChecker: LLMHealthChecker2 } = await Promise.resolve().then(() => (init_llm_health_checker(), llm_health_checker_exports));
6233
+ const healthChecker = new LLMHealthChecker2();
6234
+ const healthStatus = await healthChecker.checkService(service.name);
6235
+ for (let progress = 0; progress <= 100; progress += 25) {
6236
+ service.progress = progress;
6237
+ await new Promise((resolve) => setTimeout(resolve, 50));
6238
+ }
6239
+ if (healthStatus.isRunning) {
6240
+ service.status = "running";
6241
+ service.progress = 100;
6242
+ if (healthStatus.models && healthStatus.models.length > 0) {
6243
+ service.message = `${healthStatus.models.length} models available`;
6244
+ } else {
6245
+ service.message = "Running";
6246
+ }
6247
+ } else {
6248
+ service.status = "not-installed";
6249
+ service.message = "Not running";
6250
+ service.progress = 0;
6251
+ }
6252
+ } catch {
6253
+ service.status = "not-installed";
6254
+ service.message = "Skipping...";
6255
+ service.progress = 0;
6256
+ }
6257
+ }
6258
+ displayWelcome() {
6259
+ const frameWidth = 86;
6260
+ const horizontalLine = "\u2550".repeat(frameWidth - 2);
6261
+ const emptyLine = "\u2551" + " ".repeat(frameWidth - 2) + "\u2551";
6262
+ const centerText = /* @__PURE__ */ __name((text) => {
6263
+ const plainText = text.replace(/\u001B\[[0-9;]*m/g, "");
6264
+ const padding = Math.max(0, frameWidth - 2 - plainText.length);
6265
+ const leftPad = Math.floor(padding / 2);
6266
+ const rightPad = padding - leftPad;
6267
+ return "\u2551" + " ".repeat(leftPad) + text + " ".repeat(rightPad) + "\u2551";
6268
+ }, "centerText");
6269
+ console.log("\n");
6270
+ console.log(chalk13__default.default.magentaBright("\u2554" + horizontalLine + "\u2557"));
6271
+ console.log(chalk13__default.default.magentaBright(emptyLine));
6272
+ console.log(
6273
+ chalk13__default.default.magentaBright(
6274
+ centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 "))
6275
+ )
6276
+ );
6277
+ console.log(
6278
+ chalk13__default.default.magentaBright(
6279
+ centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557"))
6280
+ )
6281
+ );
6282
+ console.log(
6283
+ chalk13__default.default.magentaBright(
6284
+ centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551"))
6285
+ )
6286
+ );
6287
+ console.log(
6288
+ chalk13__default.default.magentaBright(
6289
+ centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551"))
6290
+ )
6291
+ );
6292
+ console.log(
6293
+ chalk13__default.default.magentaBright(
6294
+ centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551"))
6295
+ )
6296
+ );
6297
+ console.log(
6298
+ chalk13__default.default.magentaBright(
6299
+ centerText(chalk13__default.default.bold.magentaBright("\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D"))
6300
+ )
6301
+ );
6302
+ console.log(chalk13__default.default.magentaBright(emptyLine));
6303
+ console.log(
6304
+ chalk13__default.default.magentaBright(centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")))
6305
+ );
6306
+ console.log(
6307
+ chalk13__default.default.magentaBright(
6308
+ centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"))
6309
+ )
6310
+ );
6311
+ console.log(
6312
+ chalk13__default.default.magentaBright(
6313
+ centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 "))
6314
+ )
6315
+ );
6316
+ console.log(
6317
+ chalk13__default.default.magentaBright(
6318
+ centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D "))
6319
+ )
6320
+ );
6321
+ console.log(
6322
+ chalk13__default.default.magentaBright(
6323
+ centerText(chalk13__default.default.bold.magentaBright("\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"))
6324
+ )
6325
+ );
6326
+ console.log(
6327
+ chalk13__default.default.magentaBright(
6328
+ centerText(chalk13__default.default.bold.magentaBright(" \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"))
6329
+ )
6330
+ );
6331
+ console.log(chalk13__default.default.magentaBright(emptyLine));
6332
+ console.log(
6333
+ chalk13__default.default.magentaBright(centerText(chalk13__default.default.whiteBright("AI-Powered Development Platform")))
6334
+ );
6335
+ console.log(chalk13__default.default.magentaBright(centerText(chalk13__default.default.gray("(c) 2025 Bonginkan Inc."))));
6336
+ console.log(chalk13__default.default.magentaBright(emptyLine));
6337
+ console.log(chalk13__default.default.magentaBright("\u255A" + horizontalLine + "\u255D"));
6338
+ console.log("");
6339
+ }
6340
+ };
6341
+ }
6342
+ });
6343
+
6344
+ // src/slash-commands/base-command.ts
6345
+ exports.BaseCommand = void 0;
6346
+ var init_base_command = __esm({
6347
+ "src/slash-commands/base-command.ts"() {
6348
+ init_cjs_shims();
6349
+ init_logger();
6350
+ exports.BaseCommand = class {
6351
+ static {
6352
+ __name(this, "BaseCommand");
6353
+ }
6354
+ // Optional properties with defaults
6355
+ aliases = [];
6356
+ usage = "";
6357
+ examples = [];
6358
+ permissions;
6359
+ middleware = [];
6360
+ rateLimit;
6361
+ // Metadata with defaults
6362
+ metadata = {
6363
+ version: "1.0.0",
6364
+ author: "MARIA Team",
6365
+ since: "1.8.6",
6366
+ deprecated: false,
6367
+ experimental: false
6368
+ };
6369
+ // Cache for frequently used data
6370
+ cache = /* @__PURE__ */ new Map();
6371
+ /**
6372
+ * Initialize the command (called once when registered)
6373
+ */
6374
+ async initialize() {
6375
+ logger.debug(`Initializing command: ${this.name}`);
6376
+ }
6377
+ /**
6378
+ * Validate command arguments
6379
+ */
6380
+ async validate(args) {
6381
+ const errors = [];
6382
+ const maliciousPatterns = [
6383
+ /[;&|`$(){}]/,
6384
+ // Shell injection patterns
6385
+ /<script/i,
6386
+ // XSS patterns
6387
+ /\.\.\/\.\.\//
6388
+ // Path traversal
6389
+ ];
6390
+ for (const arg of args.raw) {
6391
+ for (const pattern of maliciousPatterns) {
6392
+ if (pattern.test(arg)) {
6393
+ errors.push(`Potentially unsafe input detected: ${arg.slice(0, 50)}`);
6394
+ break;
6395
+ }
6396
+ }
6397
+ }
6398
+ if (errors.length > 0) {
6399
+ return {
6400
+ success: false,
6401
+ error: errors.join("; "),
6402
+ suggestions: ["Please use safe input patterns", "Contact support if you need help"]
6403
+ };
6404
+ }
6405
+ return { success: true };
6406
+ }
6407
+ /**
6408
+ * Cleanup resources (called when command is unregistered)
6409
+ */
6410
+ async cleanup() {
6411
+ this.cache.clear();
6412
+ logger.debug(`Cleanup command: ${this.name}`);
6413
+ }
6414
+ /**
6415
+ * Rollback on error - override for custom rollback logic
6416
+ */
6417
+ async rollback(_context, error) {
6418
+ logger.error(`Rollback for ${this.name}:`, error);
6419
+ }
6420
+ // Helper methods for subclasses
6421
+ /**
6422
+ * Parse command arguments into structured format
6423
+ */
6424
+ parseArgs(raw) {
6425
+ const args = {
6426
+ raw,
6427
+ parsed: {},
6428
+ flags: {},
6429
+ options: {}
6430
+ };
6431
+ for (let i = 0; i < raw.length; i++) {
6432
+ const arg = raw[i];
6433
+ if (!arg) continue;
6434
+ if (arg.startsWith("--")) {
6435
+ const key = arg.slice(2);
6436
+ const nextArg = raw[i + 1];
6437
+ if (nextArg && !nextArg.startsWith("-")) {
6438
+ args.options[key] = nextArg;
6439
+ i++;
6440
+ } else {
6441
+ args.flags[key] = true;
6442
+ }
6443
+ } else if (arg && arg.startsWith("-") && arg.length === 2) {
6444
+ args.flags[arg.slice(1)] = true;
6445
+ } else {
6446
+ if (!args.parsed["positional"]) {
6447
+ args.parsed["positional"] = [];
6448
+ }
6449
+ args.parsed["positional"].push(arg);
6450
+ }
6451
+ }
6452
+ return args;
6453
+ }
6454
+ /**
6455
+ * Create a success response
6456
+ */
6457
+ success(message, data, metadata) {
6458
+ return {
6459
+ success: true,
6460
+ message,
6461
+ data,
6462
+ metadata: {
6463
+ executionTime: Date.now(),
6464
+ commandVersion: this.metadata.version,
6465
+ ...metadata
6466
+ }
6467
+ };
6468
+ }
6469
+ /**
6470
+ * Create an error response
6471
+ */
6472
+ error(message, code, details) {
6473
+ return {
6474
+ success: false,
6475
+ message,
6476
+ data: { code, details },
6477
+ metadata: {
6478
+ executionTime: Date.now(),
6479
+ commandVersion: this.metadata.version
6480
+ }
6481
+ };
6482
+ }
6483
+ /**
6484
+ * Cache data with TTL
6485
+ */
6486
+ setCache(key, data, ttlSeconds = 60) {
6487
+ this.cache.set(key, {
6488
+ data,
6489
+ expires: Date.now() + ttlSeconds * 1e3
6490
+ });
6491
+ }
6492
+ /**
6493
+ * Get cached data
6494
+ */
6495
+ getCache(key) {
6496
+ const cached = this.cache.get(key);
6497
+ if (!cached) {
6498
+ return null;
6499
+ }
6500
+ if (cached.expires < Date.now()) {
6501
+ this.cache.delete(key);
6502
+ return null;
6503
+ }
6504
+ return cached.data;
6505
+ }
6506
+ /**
6507
+ * Check if user has required permissions
6508
+ */
6509
+ async checkPermissions(context) {
6510
+ if (!this.permissions) {
6511
+ return { success: true };
6512
+ }
6513
+ const { requiresAuth, requiresPremium, role } = this.permissions;
6514
+ if (requiresAuth && !context.user) {
6515
+ return {
6516
+ success: false,
6517
+ error: "Authentication required",
6518
+ suggestions: ["Run /login to authenticate"]
6519
+ };
6520
+ }
6521
+ if (role && context.user?.role !== role) {
6522
+ return {
6523
+ success: false,
6524
+ error: `Required role: ${role}`,
6525
+ suggestions: [`Contact admin for ${role} access`]
6526
+ };
6527
+ }
6528
+ if (requiresPremium) {
6529
+ logger.warn("Premium check not implemented");
6530
+ }
6531
+ return { success: true };
6532
+ }
6533
+ /**
6534
+ * Format help text for this command
6535
+ */
6536
+ formatHelp() {
6537
+ const lines = [];
6538
+ lines.push(`\u{1F4D8} ${this.name.toUpperCase()}`);
6539
+ lines.push("\u2500".repeat(40));
6540
+ lines.push(`
6541
+ ${this.description}
6542
+ `);
6543
+ if (this.usage) {
6544
+ lines.push("**Usage:**");
6545
+ lines.push(` /${this.name} ${this.usage}
6546
+ `);
6547
+ }
6548
+ if (this.aliases && this.aliases.length > 0) {
6549
+ lines.push("**Aliases:**");
6550
+ lines.push(` ${this.aliases.map((a) => `/${a}`).join(", ")}
6551
+ `);
6552
+ }
6553
+ if (this.examples.length > 0) {
6554
+ lines.push("**Examples:**");
6555
+ this.examples.forEach((ex) => {
6556
+ lines.push(` ${ex.input}`);
6557
+ lines.push(` ${ex.description}`);
6558
+ if (ex.output) {
6559
+ lines.push(` \u2192 ${ex.output}`);
6560
+ }
6561
+ });
6562
+ lines.push("");
6563
+ }
6564
+ if (this.permissions) {
6565
+ lines.push("**Requirements:**");
6566
+ if (this.permissions.requiresAuth) {
6567
+ lines.push(" \u2022 Authentication required");
6568
+ }
6569
+ if (this.permissions.role) {
6570
+ lines.push(` \u2022 Role: ${this.permissions.role}`);
6571
+ }
6572
+ if (this.permissions.requiresPremium) {
6573
+ lines.push(" \u2022 Premium subscription");
6574
+ }
6575
+ lines.push("");
6576
+ }
6577
+ if (this.metadata.experimental) {
6578
+ lines.push("\u26A0\uFE0F **Experimental Feature**");
6579
+ }
6580
+ if (this.metadata.deprecated) {
6581
+ lines.push(`\u26A0\uFE0F **Deprecated** - Use ${this.metadata.replacedBy || "alternative"} instead`);
6582
+ }
6583
+ return lines.join("\n");
6584
+ }
6585
+ /**
6586
+ * Log command execution
6587
+ */
6588
+ logExecution(args, context, result) {
6589
+ const logData = {
6590
+ command: this.name,
6591
+ args: args.raw,
6592
+ user: context.user?.id,
6593
+ success: result.success,
6594
+ executionTime: result.metadata?.executionTime
6595
+ };
6596
+ if (result.success) {
6597
+ logger.info("Command executed", logData);
6598
+ } else {
6599
+ logger.error("Command failed", { ...logData, error: result.message });
6600
+ }
6601
+ }
6602
+ };
6603
+ }
6604
+ });
6605
+
6606
+ // src/slash-commands/middleware/auth.ts
6607
+ var auth_exports = {};
6608
+ __export(auth_exports, {
6609
+ AuthMiddleware: () => AuthMiddleware,
6610
+ authMiddleware: () => authMiddleware
6611
+ });
6612
+ var AuthMiddleware, authMiddleware;
6613
+ var init_auth = __esm({
6614
+ "src/slash-commands/middleware/auth.ts"() {
6615
+ init_cjs_shims();
6616
+ init_logger();
6617
+ AuthMiddleware = class {
6618
+ static {
6619
+ __name(this, "AuthMiddleware");
6620
+ }
6621
+ name = "auth";
6622
+ priority = 10;
6623
+ // Run early in the chain
6624
+ async execute(command, _args, context, next) {
6625
+ const cmd = command;
6626
+ if (!cmd.permissions?.requiresAuth) {
6627
+ return next();
6628
+ }
6629
+ if (!context.user) {
6630
+ logger.warn(
6631
+ `Unauthenticated access attempt for command: ${command.name}`
6632
+ );
6633
+ return {
6634
+ success: false,
6635
+ message: "\u{1F512} Authentication required",
6636
+ data: {
6637
+ suggestions: ["Run /login to authenticate", "Or use /help login for more information"]
6638
+ },
6639
+ component: "auth-flow"
6640
+ };
6641
+ }
6642
+ logger.debug(`Authenticated user ${context.user.id} executing command`);
6643
+ return next();
6644
+ }
6645
+ };
6646
+ authMiddleware = new AuthMiddleware();
6647
+ }
6648
+ });
6649
+
6650
+ // src/slash-commands/middleware/validation.ts
6651
+ var validation_exports = {};
6652
+ __export(validation_exports, {
6653
+ ValidationMiddleware: () => ValidationMiddleware,
6654
+ validationMiddleware: () => validationMiddleware
6655
+ });
6656
+ var ValidationMiddleware, validationMiddleware;
6657
+ var init_validation = __esm({
6658
+ "src/slash-commands/middleware/validation.ts"() {
6659
+ init_cjs_shims();
6660
+ init_logger();
6661
+ ValidationMiddleware = class {
6662
+ static {
6663
+ __name(this, "ValidationMiddleware");
6664
+ }
6665
+ name = "validation";
6666
+ priority = 20;
6667
+ // Run after auth
6668
+ async execute(command, args, _context, next) {
6669
+ const validationResult = await this.validateArgs(command, args);
6670
+ if (!validationResult.success) {
6671
+ return validationResult;
6672
+ }
6673
+ return next();
6674
+ }
6675
+ async validateArgs(command, args) {
6676
+ if (args.flags["help"] || args.flags["h"]) {
6677
+ return {
6678
+ success: true,
6679
+ message: this.formatHelp(command),
6680
+ component: "help-dialog"
6681
+ };
6682
+ }
6683
+ if (command.usage) {
6684
+ const requiredArgs = this.parseRequiredArgs(command.usage);
6685
+ const positional = args.parsed["positional"] || [];
6686
+ if (requiredArgs.length > positional.length) {
6687
+ return {
6688
+ success: false,
6689
+ message: `Missing required arguments
6690
+
6691
+ Usage: /${command.name} ${command.usage}`,
6692
+ data: {
6693
+ missing: requiredArgs.slice(positional.length),
6694
+ examples: command.examples
6695
+ }
6696
+ };
6697
+ }
6698
+ }
6699
+ const validationErrors = [];
6700
+ const knownFlags = this.extractKnownFlags(command.usage);
6701
+ for (const flag of Object.keys(args.flags)) {
6702
+ if (!knownFlags.includes(flag) && flag !== "help" && flag !== "h") {
6703
+ validationErrors.push(`Unknown flag: --${flag}`);
6704
+ }
6705
+ }
6706
+ if (validationErrors.length > 0) {
6707
+ logger.warn(`Validation errors for command ${command.name}:`, validationErrors);
6708
+ return {
6709
+ success: false,
6710
+ message: validationErrors.join("\n"),
6711
+ data: {
6712
+ suggestions: [`Run /${command.name} --help for usage information`]
6713
+ }
6714
+ };
6715
+ }
6716
+ return { success: true, message: "" };
6717
+ }
6718
+ parseRequiredArgs(usage) {
6719
+ const required = [];
6720
+ const regex = /<([^>]+)>/g;
6721
+ let match;
6722
+ while ((match = regex.exec(usage)) !== null) {
6723
+ if (match[1]) {
6724
+ required.push(match[1]);
6725
+ }
6726
+ }
6727
+ return required;
6728
+ }
6729
+ extractKnownFlags(usage) {
6730
+ const flags = [];
6731
+ const regex = /--([a-z-]+)/g;
6732
+ let match;
6733
+ while ((match = regex.exec(usage)) !== null) {
6734
+ if (match[1]) {
6735
+ flags.push(match[1]);
6736
+ }
6737
+ }
6738
+ return flags;
6739
+ }
6740
+ formatHelp(command) {
6741
+ const lines = [];
6742
+ lines.push(`\u{1F4D8} **${command.name.toUpperCase()}**`);
6743
+ lines.push("\u2500".repeat(40));
6744
+ lines.push("");
6745
+ lines.push(command.description);
6746
+ lines.push("");
6747
+ if (command.usage) {
6748
+ lines.push("**Usage:**");
6749
+ lines.push(` /${command.name} ${command.usage}`);
6750
+ lines.push("");
6751
+ }
6752
+ if (command.aliases && command.aliases.length > 0) {
6753
+ lines.push("**Aliases:**");
6754
+ lines.push(` ${command.aliases.map((a) => `/${a}`).join(", ")}`);
6755
+ lines.push("");
6756
+ }
6757
+ if (command.examples && command.examples.length > 0) {
6758
+ lines.push("**Examples:**");
6759
+ command.examples.forEach((ex) => {
6760
+ lines.push(` ${ex.input}`);
6761
+ lines.push(` ${ex.description}`);
6762
+ if (ex.output) {
6763
+ lines.push(` \u2192 ${ex.output}`);
6764
+ }
6765
+ });
6766
+ lines.push("");
6767
+ }
6768
+ if (command.metadata.experimental) {
6769
+ lines.push("\u26A0\uFE0F **Experimental Feature**");
6770
+ }
6771
+ if (command.metadata.deprecated) {
6772
+ lines.push(
6773
+ `\u26A0\uFE0F **Deprecated** - Use ${command.metadata.replacedBy || "alternative"} instead`
6774
+ );
6775
+ }
6776
+ return lines.join("\n");
6777
+ }
6778
+ };
6779
+ validationMiddleware = new ValidationMiddleware();
6780
+ }
6781
+ });
6782
+
6783
+ // src/slash-commands/middleware/rate-limit.ts
6784
+ var rate_limit_exports = {};
6785
+ __export(rate_limit_exports, {
6786
+ RateLimitMiddleware: () => RateLimitMiddleware,
6787
+ rateLimitMiddleware: () => rateLimitMiddleware
6788
+ });
6789
+ var RateLimitMiddleware, rateLimitMiddleware;
6790
+ var init_rate_limit = __esm({
6791
+ "src/slash-commands/middleware/rate-limit.ts"() {
6792
+ init_cjs_shims();
6793
+ init_logger();
6794
+ RateLimitMiddleware = class {
6795
+ static {
6796
+ __name(this, "RateLimitMiddleware");
6797
+ }
6798
+ name = "rate-limit";
6799
+ priority = 15;
6800
+ // Run after auth, before validation
6801
+ limits = /* @__PURE__ */ new Map();
6802
+ async execute(command, _args, context, next) {
6803
+ if (!command.rateLimit) {
6804
+ return next();
6805
+ }
6806
+ const userId = context.user?.id || context.session.id;
6807
+ const limitKey = `${command.name}:${userId}`;
6808
+ const commandLimits = this.limits.get(command.name) || /* @__PURE__ */ new Map();
6809
+ const userLimit = commandLimits.get(userId);
6810
+ const now = Date.now();
6811
+ const windowMs = this.parseWindow(command.rateLimit.window);
6812
+ if (!userLimit || userLimit.resetAt < now) {
6813
+ commandLimits.set(userId, {
6814
+ count: 1,
6815
+ resetAt: now + windowMs
6816
+ });
6817
+ this.limits.set(command.name, commandLimits);
6818
+ return next();
6819
+ }
6820
+ if (userLimit.count >= command.rateLimit.requests) {
6821
+ const retryAfter = Math.ceil((userLimit.resetAt - now) / 1e3);
6822
+ logger.warn(`Rate limit exceeded for ${limitKey}`, {
6823
+ count: userLimit.count,
6824
+ limit: command.rateLimit.requests,
6825
+ retryAfter
6826
+ });
6827
+ return {
6828
+ success: false,
6829
+ message: `\u23F1\uFE0F Rate limit exceeded`,
6830
+ data: {
6831
+ error: `Too many requests. Please wait ${retryAfter} seconds before trying again.`,
6832
+ retryAfter,
6833
+ limit: command.rateLimit.requests,
6834
+ window: command.rateLimit.window
6835
+ }
6836
+ };
6837
+ }
6838
+ userLimit.count++;
6839
+ return next();
6840
+ }
6841
+ parseWindow(window) {
6842
+ const units = {
6843
+ s: 1e3,
6844
+ m: 60 * 1e3,
6845
+ h: 60 * 60 * 1e3,
6846
+ d: 24 * 60 * 60 * 1e3
6847
+ };
6848
+ const match = window.match(/^(\d+)([smhd])$/);
6849
+ if (!match) {
6850
+ logger.warn(`Invalid rate limit window: ${window}, defaulting to 1 minute`);
6851
+ return 6e4;
6852
+ }
6853
+ const [, num, unit] = match;
6854
+ const value = parseInt(num || "60", 10);
6855
+ const multiplier = unit ? units[unit] || 6e4 : 6e4;
6856
+ return value * multiplier;
6857
+ }
6858
+ /**
6859
+ * Clear rate limits for a specific user or command
6860
+ */
6861
+ clearLimits(command, userId) {
6862
+ if (command && userId) {
6863
+ const commandLimits = this.limits.get(command);
6864
+ if (commandLimits) {
6865
+ commandLimits.delete(userId);
6866
+ }
6867
+ } else if (command) {
6868
+ this.limits.delete(command);
6869
+ } else {
6870
+ this.limits.clear();
6871
+ }
6872
+ }
6873
+ /**
6874
+ * Get current limit status for a user
6875
+ */
6876
+ getStatus(command, userId) {
6877
+ const commandLimits = this.limits.get(command);
6878
+ if (!commandLimits) {
6879
+ return null;
6880
+ }
6881
+ const userLimit = commandLimits.get(userId);
6882
+ if (!userLimit) {
6883
+ return null;
6884
+ }
6885
+ const cmd = { rateLimit: { requests: 10 } };
6886
+ return {
6887
+ remaining: Math.max(0, (cmd.rateLimit?.requests) - userLimit.count),
6888
+ resetAt: userLimit.resetAt,
6889
+ limit: cmd.rateLimit?.requests || 10
6890
+ };
6891
+ }
6892
+ };
6893
+ rateLimitMiddleware = new RateLimitMiddleware();
6894
+ }
6895
+ });
6896
+
6897
+ // src/slash-commands/middleware/logging.ts
6898
+ var logging_exports = {};
6899
+ __export(logging_exports, {
6900
+ LoggingMiddleware: () => LoggingMiddleware,
6901
+ loggingMiddleware: () => loggingMiddleware
6902
+ });
6903
+ var LoggingMiddleware, loggingMiddleware;
6904
+ var init_logging = __esm({
6905
+ "src/slash-commands/middleware/logging.ts"() {
6906
+ init_cjs_shims();
6907
+ init_logger();
6908
+ LoggingMiddleware = class {
6909
+ static {
6910
+ __name(this, "LoggingMiddleware");
6911
+ }
6912
+ name = "logging";
6913
+ priority = 0;
6914
+ // Run first
6915
+ async execute(command, args, context, next) {
6916
+ const startTime = Date.now();
6917
+ const requestId = this.generateRequestId();
6918
+ logger.info("Command execution started", {
6919
+ requestId,
6920
+ command: command.name,
6921
+ args: args.raw,
6922
+ user: context.user?.id || "anonymous",
6923
+ session: context.session.id
6924
+ });
6925
+ try {
6926
+ const result = await next();
6927
+ const duration = Date.now() - startTime;
6928
+ logger.info("Command execution completed", {
6929
+ requestId,
6930
+ command: command.name,
6931
+ success: result.success,
6932
+ duration,
6933
+ user: context.user?.id || "anonymous"
6934
+ });
6935
+ if (!result.metadata) {
6936
+ result.metadata = {
6937
+ executionTime: duration
6938
+ };
6939
+ }
6940
+ result.metadata["requestId"] = requestId;
6941
+ result.metadata["duration"] = duration;
6942
+ return result;
6943
+ } catch (error) {
6944
+ const duration = Date.now() - startTime;
6945
+ logger.error("Command execution failed", {
6946
+ requestId,
6947
+ command: command.name,
6948
+ error: error instanceof Error ? error.message : "Unknown error",
6949
+ stack: error instanceof Error ? error.stack : void 0,
6950
+ duration,
6951
+ user: context.user?.id || "anonymous"
6952
+ });
6953
+ throw error;
6954
+ }
6955
+ }
6956
+ generateRequestId() {
6957
+ return `cmd_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
6958
+ }
6959
+ };
6960
+ loggingMiddleware = new LoggingMiddleware();
6961
+ }
6962
+ });
6963
+
6964
+ // src/slash-commands/categories/conversation/clear.command.ts
6965
+ var clear_command_exports = {};
6966
+ __export(clear_command_exports, {
6967
+ ClearCommand: () => ClearCommand
6968
+ });
6969
+ var ClearCommand;
6970
+ var init_clear_command = __esm({
6971
+ "src/slash-commands/categories/conversation/clear.command.ts"() {
6972
+ init_cjs_shims();
6973
+ init_base_command();
6974
+ init_chat_context_service();
6975
+ init_logger();
6976
+ ClearCommand = class extends exports.BaseCommand {
6977
+ static {
6978
+ __name(this, "ClearCommand");
6979
+ }
6980
+ name = "clear";
6981
+ aliases = ["cls", "c", "reset"];
6982
+ category = "conversation";
6983
+ description = "Clear the conversation context and start fresh";
6984
+ usage = "[--all] [--keep-settings]";
6985
+ examples = [
6986
+ {
6987
+ input: "/clear",
6988
+ description: "Clear current conversation",
6989
+ output: "\u2728 Conversation cleared. Ready for a fresh start!"
6990
+ },
6991
+ {
6992
+ input: "/cls",
6993
+ description: "Clear using alias",
6994
+ output: "\u2728 Conversation cleared. Ready for a fresh start!"
6995
+ },
6996
+ {
6997
+ input: "/clear --all",
6998
+ description: "Clear all conversations and history",
6999
+ output: "\u{1F9F9} All conversation history and data cleared. Starting fresh!"
7000
+ },
7001
+ {
7002
+ input: "/clear --keep-settings",
7003
+ description: "Clear conversation but keep user settings",
7004
+ output: "\u2705 Cleared: conversation"
7005
+ }
7006
+ ];
7007
+ chatContext;
7008
+ constructor() {
7009
+ super();
7010
+ this.chatContext = ChatContextService.getInstance();
7011
+ }
7012
+ async execute(args, context) {
7013
+ try {
7014
+ const clearAll = args.flags["all"] || false;
7015
+ const keepSettings = args.flags["keep-settings"] || false;
7016
+ const clearOptions = {
7017
+ conversation: true,
7018
+ history: clearAll,
7019
+ settings: !keepSettings,
7020
+ cache: clearAll
7021
+ };
7022
+ logger.info("Clearing conversation context", {
7023
+ options: clearOptions,
7024
+ user: context.user?.id,
7025
+ session: context.session.id
7026
+ });
7027
+ if (clearOptions.conversation) {
7028
+ await this.clearConversation(context);
7029
+ }
7030
+ if (clearOptions.history) {
7031
+ await this.clearAllHistory(context);
7032
+ }
7033
+ if (clearOptions.settings && !keepSettings) {
7034
+ await this.clearSettings(context);
7035
+ }
7036
+ if (clearOptions.cache) {
7037
+ await this.clearCache();
7038
+ }
7039
+ const clearedItems = [];
7040
+ if (clearOptions.conversation) clearedItems.push("conversation");
7041
+ if (clearOptions.history) clearedItems.push("all history");
7042
+ if (clearOptions.settings && !keepSettings) clearedItems.push("settings");
7043
+ if (clearOptions.cache) clearedItems.push("cache");
7044
+ const message = this.buildSuccessMessage(clearedItems);
7045
+ return this.success(message, {
7046
+ cleared: clearedItems,
7047
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
7048
+ });
7049
+ } catch (error) {
7050
+ logger.error("Failed to clear conversation", error);
7051
+ return this.error(
7052
+ "Failed to clear conversation context",
7053
+ "CLEAR_ERROR",
7054
+ error instanceof Error ? error.message : "Unknown error"
7055
+ );
7056
+ }
7057
+ }
7058
+ async clearConversation(context) {
7059
+ if (context.conversation) {
7060
+ context.conversation.history = [];
7061
+ }
7062
+ await this.chatContext.clearContext();
7063
+ logger.debug("Cleared current conversation");
7064
+ }
7065
+ async clearAllHistory(context) {
7066
+ if (context.session) {
7067
+ context.session.commandHistory = [];
7068
+ }
7069
+ logger.debug("Cleared all conversation history");
7070
+ }
7071
+ async clearSettings(_context) {
7072
+ logger.debug("Cleared user settings");
7073
+ }
7074
+ async clearCache() {
7075
+ this.cleanup();
7076
+ logger.debug("Cleared all caches");
7077
+ }
7078
+ buildSuccessMessage(clearedItems) {
7079
+ if (clearedItems.length === 0) {
7080
+ return "\u2705 Nothing to clear";
7081
+ }
7082
+ if (clearedItems.includes("all history")) {
7083
+ return "\u{1F9F9} All conversation history and data cleared. Starting fresh!";
7084
+ }
7085
+ if (clearedItems.length === 1 && clearedItems[0] === "conversation") {
7086
+ return "\u2728 Conversation cleared. Ready for a fresh start!";
7087
+ }
7088
+ return `\u2705 Cleared: ${clearedItems.join(", ")}`;
7089
+ }
7090
+ async validate(args) {
7091
+ if (args.flags["all"] && args.flags["keep-settings"]) {
7092
+ return {
7093
+ success: false,
7094
+ error: "Cannot use --all and --keep-settings together"
7095
+ };
7096
+ }
7097
+ const positional = args.parsed["positional"] || [];
7098
+ if (positional.length > 0) {
7099
+ return {
7100
+ success: false,
7101
+ error: `Unexpected arguments: ${positional.join(", ")}`
7102
+ };
7103
+ }
7104
+ return { success: true };
7105
+ }
7106
+ };
7107
+ }
7108
+ });
7109
+
7110
+ // src/slash-commands/categories/config/setup.command.ts
7111
+ var setup_command_exports = {};
7112
+ __export(setup_command_exports, {
7113
+ SetupCommand: () => SetupCommand,
7114
+ default: () => setup_command_default
7115
+ });
7116
+ var SetupCommand, setup_command_default;
7117
+ var init_setup_command = __esm({
7118
+ "src/slash-commands/categories/config/setup.command.ts"() {
7119
+ init_cjs_shims();
7120
+ init_base_command();
7121
+ init_logger();
7122
+ SetupCommand = class extends exports.BaseCommand {
7123
+ static {
7124
+ __name(this, "SetupCommand");
7125
+ }
7126
+ name = "setup";
7127
+ aliases = ["config", "init", "configure"];
7128
+ category = "config";
7129
+ description = "\u{1F680} First-time environment setup wizard";
7130
+ usage = "[--quick] [--advanced] [--config <file>] [--silent] [--fix] [--rollback]";
7131
+ examples = [
7132
+ {
7133
+ input: "/setup",
7134
+ description: "Start interactive setup wizard",
7135
+ output: "Complete environment configuration wizard"
7136
+ },
7137
+ {
7138
+ input: "/setup --quick",
7139
+ description: "Quick setup with sensible defaults",
7140
+ output: "Rapid 2-minute configuration"
7141
+ },
7142
+ {
7143
+ input: "/setup --advanced",
7144
+ description: "Advanced setup with full customization",
7145
+ output: "Complete setup with all options"
7146
+ },
7147
+ {
7148
+ input: "/setup --fix",
7149
+ description: "Fix existing configuration issues",
7150
+ output: "Configuration problems resolved"
7151
+ },
7152
+ {
7153
+ input: "/setup --rollback",
7154
+ description: "Rollback previous setup changes",
7155
+ output: "Setup changes reverted"
7156
+ }
7157
+ ];
7158
+ async execute(args, context) {
7159
+ const { flags, options } = args;
7160
+ try {
7161
+ logger.info("Setup command started", { flags, options });
7162
+ if (flags["rollback"]) {
7163
+ return await this.rollbackSetup(context);
7164
+ }
7165
+ if (flags["fix"]) {
7166
+ return await this.fixConfiguration(context);
7167
+ }
7168
+ if (flags["quick"]) {
7169
+ return await this.quickSetup(context);
7170
+ }
7171
+ if (flags["advanced"]) {
7172
+ return await this.advancedSetup(context);
7173
+ }
7174
+ if (flags["silent"] && options["config"]) {
7175
+ return await this.silentSetup(context, options["config"]);
7176
+ }
7177
+ return await this.interactiveSetup(context);
7178
+ } catch (error) {
7179
+ logger.error("Setup failed:", error);
7180
+ return this.error(
7181
+ `Setup failed: ${error instanceof Error ? error.message : "Unknown error"}`,
7182
+ "SETUP_ERROR",
7183
+ error
7184
+ );
7185
+ }
7186
+ }
7187
+ async interactiveSetup(context) {
7188
+ const startTime = Date.now();
7189
+ const result = {
7190
+ success: false,
7191
+ duration: 0,
7192
+ stepsCompleted: [],
7193
+ providersConfigured: [],
7194
+ filesGenerated: [],
7195
+ errors: [],
7196
+ warnings: []
7197
+ };
7198
+ try {
7199
+ logger.info("Starting system analysis...");
7200
+ await this.analyzeSystem();
7201
+ result.stepsCompleted.push("system-analysis");
7202
+ await this.showWelcomeScreen();
7203
+ result.stepsCompleted.push("welcome");
7204
+ await this.detectExistingConfiguration(context);
7205
+ result.stepsCompleted.push("config-detection");
7206
+ logger.info("Configuring AI providers...");
7207
+ const providerResult = await this.configureProviders(context);
7208
+ if (providerResult.success) {
7209
+ result.stepsCompleted.push("provider-setup");
7210
+ result.providersConfigured = providerResult.data?.providers || [];
7211
+ result.filesGenerated.push(...providerResult.data?.files || []);
7212
+ } else {
7213
+ result.errors.push("Provider configuration failed");
7214
+ }
7215
+ logger.info("Initializing project configuration...");
7216
+ const projectResult = await this.initializeProject(context);
7217
+ if (projectResult.success) {
7218
+ result.stepsCompleted.push("project-init");
7219
+ result.filesGenerated.push(...projectResult.data?.files || []);
7220
+ } else {
7221
+ result.warnings.push("Project initialization had issues");
7222
+ }
7223
+ logger.info("Validating setup...");
7224
+ await this.validateSetup(context);
7225
+ result.stepsCompleted.push("validation");
7226
+ await this.recordSetupCompletion(context, result);
7227
+ result.stepsCompleted.push("finalization");
7228
+ await this.showSuccessMessage(result);
7229
+ result.success = true;
7230
+ result.duration = Date.now() - startTime;
7231
+ return this.success("\u{1F389} Setup completed successfully!", {
7232
+ result,
7233
+ nextSteps: [
7234
+ "Try: maria chat - Start interactive mode",
7235
+ 'Try: maria code "create a React component"',
7236
+ "Try: maria test - Generate tests",
7237
+ "Try: maria help - View all commands"
7238
+ ]
7239
+ });
7240
+ } catch (error) {
7241
+ result.success = false;
7242
+ result.duration = Date.now() - startTime;
7243
+ result.errors.push(error instanceof Error ? error.message : "Unknown error");
7244
+ logger.error("Interactive setup failed:", error);
7245
+ return this.error(
7246
+ "Setup wizard failed. Run with --fix to attempt repair.",
7247
+ "INTERACTIVE_SETUP_FAILED",
7248
+ result
7249
+ );
7250
+ }
7251
+ }
7252
+ async quickSetup(context) {
7253
+ logger.info("Starting quick setup...");
7254
+ try {
7255
+ const startTime = Date.now();
7256
+ const envResult = await this.generateQuickEnvTemplate();
7257
+ if (!envResult.success) {
7258
+ return this.error(
7259
+ "Quick setup failed during environment configuration",
7260
+ "QUICK_SETUP_FAILED",
7261
+ envResult
7262
+ );
7263
+ }
7264
+ await this.recordSetupCompletion(context, {
7265
+ success: true,
7266
+ duration: Date.now() - startTime,
7267
+ stepsCompleted: ["quick-setup", "ai-providers"],
7268
+ providersConfigured: ["openai"],
7269
+ filesGenerated: [".env.local", ".env.local.sample", ".gitignore"],
7270
+ errors: [],
7271
+ warnings: []
7272
+ });
7273
+ return this.success("\u26A1 Quick setup completed in under 2 minutes!", {
7274
+ mode: "quick",
7275
+ configured: ["OpenAI GPT-4", "Environment variables", "Git ignore"],
7276
+ nextSteps: ["Run: maria chat", 'Try: maria code "Hello World function"']
7277
+ });
7278
+ } catch (error) {
7279
+ logger.error("Quick setup failed:", error);
7280
+ return this.error(
7281
+ `Quick setup failed: ${error instanceof Error ? error.message : "Unknown error"}`,
7282
+ "QUICK_SETUP_ERROR",
7283
+ error
7284
+ );
7285
+ }
7286
+ }
7287
+ async advancedSetup(context) {
7288
+ return this.success("Advanced setup mode - Full customization available", {
7289
+ features: [
7290
+ "Multiple AI provider configuration",
7291
+ "Advanced project settings",
7292
+ "Performance optimization",
7293
+ "Custom integrations"
7294
+ ]
7295
+ });
7296
+ }
7297
+ async fixConfiguration(context) {
7298
+ logger.info("Analyzing configuration issues...");
7299
+ try {
7300
+ const issues = await this.detectConfigurationIssues(context);
7301
+ if (issues.length === 0) {
7302
+ return this.success("\u2705 No configuration issues detected", {
7303
+ status: "healthy",
7304
+ lastCheck: (/* @__PURE__ */ new Date()).toISOString()
7305
+ });
7306
+ }
7307
+ const fixes = [];
7308
+ for (const issue of issues) {
7309
+ try {
7310
+ await this.fixConfigurationIssue(issue, context);
7311
+ fixes.push({ issue: issue.description, fixed: true });
7312
+ } catch (error) {
7313
+ fixes.push({
7314
+ issue: issue.description,
7315
+ fixed: false,
7316
+ error: error instanceof Error ? error.message : "Unknown error"
7317
+ });
7318
+ }
7319
+ }
7320
+ const fixedCount = fixes.filter((f) => f.fixed).length;
7321
+ const totalIssues = fixes.length;
7322
+ return this.success(`\u{1F527} Fixed ${fixedCount}/${totalIssues} configuration issues`, {
7323
+ fixes,
7324
+ summary: {
7325
+ total: totalIssues,
7326
+ fixed: fixedCount,
7327
+ failed: totalIssues - fixedCount
7328
+ }
7329
+ });
7330
+ } catch (error) {
7331
+ logger.error("Configuration fix failed:", error);
7332
+ return this.error(
7333
+ `Configuration fix failed: ${error instanceof Error ? error.message : "Unknown error"}`,
7334
+ "CONFIG_FIX_ERROR",
7335
+ error
7336
+ );
7337
+ }
7338
+ }
7339
+ async rollbackSetup(context) {
7340
+ logger.info("Rolling back setup changes...");
7341
+ try {
7342
+ const setupRecord = await this.getSetupRecord(context);
7343
+ if (!setupRecord) {
7344
+ return this.error("No setup record found to rollback", "NO_SETUP_RECORD");
7345
+ }
7346
+ const restoredFiles = [];
7347
+ const errors = [];
7348
+ if (setupRecord.filesGenerated) {
7349
+ for (const file of setupRecord.filesGenerated) {
7350
+ try {
7351
+ const filePath = path10__namespace.default.join(context.environment.cwd, file);
7352
+ await fs11__namespace.default.unlink(filePath);
7353
+ restoredFiles.push(file);
7354
+ } catch (error) {
7355
+ errors.push(
7356
+ `Failed to remove ${file}: ${error instanceof Error ? error.message : "Unknown error"}`
7357
+ );
7358
+ }
7359
+ }
7360
+ }
7361
+ const setupRecordPath = path10__namespace.default.join(context.environment.cwd, ".maria", "setup.json");
7362
+ try {
7363
+ await fs11__namespace.default.unlink(setupRecordPath);
7364
+ } catch {
7365
+ }
7366
+ return this.success("\u21A9\uFE0F Setup changes rolled back successfully", {
7367
+ restoredFiles,
7368
+ errors,
7369
+ message: "Your environment has been restored to pre-setup state"
7370
+ });
7371
+ } catch (error) {
7372
+ logger.error("Rollback failed:", error);
7373
+ return this.error(
7374
+ `Rollback failed: ${error instanceof Error ? error.message : "Unknown error"}`,
7375
+ "ROLLBACK_ERROR",
7376
+ error
7377
+ );
7378
+ }
7379
+ }
7380
+ async silentSetup(context, configPath) {
7381
+ return this.success("Silent setup completed from configuration file", {
7382
+ configPath,
7383
+ mode: "silent"
7384
+ });
7385
+ }
7386
+ async analyzeSystem() {
7387
+ const platform = os3__default.default.platform();
7388
+ const architecture = os3__default.default.arch();
7389
+ const nodeVersion = process.version;
7390
+ let packageManager = "npm";
7391
+ try {
7392
+ await fs11__namespace.default.access("pnpm-lock.yaml");
7393
+ packageManager = "pnpm";
7394
+ } catch {
7395
+ try {
7396
+ await fs11__namespace.default.access("yarn.lock");
7397
+ packageManager = "yarn";
7398
+ } catch {
7399
+ try {
7400
+ await fs11__namespace.default.access("bun.lockb");
7401
+ packageManager = "bun";
7402
+ } catch {
7403
+ packageManager = "npm";
7404
+ }
7405
+ }
7406
+ }
7407
+ const terminalCapabilities = {
7408
+ colorSupport: !!(process.stdout.isTTY && process.env["TERM"] !== "dumb"),
7409
+ unicodeSupport: process.env["LANG"]?.includes("UTF-8") || false,
7410
+ interactiveSupport: !!process.stdin.isTTY
7411
+ };
7412
+ const networkConnectivity = true;
7413
+ const memoryAvailable = os3__default.default.totalmem() / (1024 * 1024 * 1024);
7414
+ const diskSpace = 100;
7415
+ return {
7416
+ platform,
7417
+ architecture,
7418
+ nodeVersion,
7419
+ packageManager,
7420
+ terminalCapabilities,
7421
+ networkConnectivity,
7422
+ diskSpace,
7423
+ memoryAvailable
7424
+ };
7425
+ }
7426
+ async detectExistingConfiguration(context) {
7427
+ const cwd = context.environment.cwd;
7428
+ const existingEnvFile = await this.fileExists(path10__namespace.default.join(cwd, ".env.local"));
7429
+ const existingMARIAConfig = await this.fileExists(path10__namespace.default.join(cwd, ".maria-code.toml"));
7430
+ const gitRepository = await this.fileExists(path10__namespace.default.join(cwd, ".git"));
7431
+ const configuredProviders = [];
7432
+ if (existingEnvFile) {
7433
+ const envContent = await fs11__namespace.default.readFile(path10__namespace.default.join(cwd, ".env.local"), "utf-8");
7434
+ if (envContent.includes("OPENAI_API_KEY")) configuredProviders.push("openai");
7435
+ if (envContent.includes("ANTHROPIC_API_KEY")) configuredProviders.push("anthropic");
7436
+ if (envContent.includes("GOOGLE_AI_API_KEY")) configuredProviders.push("google");
7437
+ if (envContent.includes("GROQ_API_KEY")) configuredProviders.push("groq");
7438
+ }
7439
+ return {
7440
+ existingEnvFile,
7441
+ existingMARIAConfig,
7442
+ installedCLI: true,
7443
+ // If we're running, CLI is installed
7444
+ configuredProviders,
7445
+ workingDirectory: cwd,
7446
+ gitRepository
7447
+ };
7448
+ }
7449
+ async configureProviders(context) {
7450
+ return await this.generateQuickEnvTemplate();
7451
+ }
7452
+ async initializeProject(context) {
7453
+ const mariaDir = path10__namespace.default.join(context.environment.cwd, ".maria");
7454
+ try {
7455
+ await fs11__namespace.default.mkdir(mariaDir, { recursive: true });
7456
+ const config2 = {
7457
+ project: {
7458
+ name: path10__namespace.default.basename(context.environment.cwd),
7459
+ type: "web",
7460
+ language: "typescript"
7461
+ },
7462
+ ai: {
7463
+ default_provider: "openai",
7464
+ default_model: "gpt-4"
7465
+ },
7466
+ preferences: {
7467
+ theme: "dark",
7468
+ language: "auto"
7469
+ },
7470
+ created: (/* @__PURE__ */ new Date()).toISOString()
7471
+ };
7472
+ const configPath = path10__namespace.default.join(context.environment.cwd, ".maria-code.toml");
7473
+ const tomlContent = this.generateTOMLConfig(config2);
7474
+ await fs11__namespace.default.writeFile(configPath, tomlContent, "utf-8");
7475
+ return this.success("Project initialized successfully", {
7476
+ files: [".maria-code.toml"]
7477
+ });
7478
+ } catch (error) {
7479
+ logger.error("Project initialization failed:", error);
7480
+ return this.error(
7481
+ `Project initialization failed: ${error instanceof Error ? error.message : "Unknown error"}`,
7482
+ "PROJECT_INIT_ERROR",
7483
+ error
7484
+ );
7485
+ }
7486
+ }
7487
+ async validateSetup(context) {
7488
+ const checks = [
7489
+ this.validateEnvironmentFile(context),
7490
+ this.validateConfigFile(context),
7491
+ this.validateProviderConnections(context)
7492
+ ];
7493
+ try {
7494
+ const results = await Promise.all(checks);
7495
+ return results.every((result) => result);
7496
+ } catch {
7497
+ return false;
7498
+ }
7499
+ }
7500
+ async recordSetupCompletion(context, result) {
7501
+ const mariaDir = path10__namespace.default.join(context.environment.cwd, ".maria");
7502
+ await fs11__namespace.default.mkdir(mariaDir, { recursive: true });
7503
+ const setupRecord = {
7504
+ ...result,
7505
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
7506
+ version: "1.0.0",
7507
+ environment: context.environment
7508
+ };
7509
+ const recordPath = path10__namespace.default.join(mariaDir, "setup.json");
7510
+ await fs11__namespace.default.writeFile(recordPath, JSON.stringify(setupRecord, null, 2), "utf-8");
7511
+ }
7512
+ async showWelcomeScreen() {
7513
+ logger.info(`
7514
+ \u{1F680} Welcome to MARIA CODE Setup Wizard!
7515
+
7516
+ This wizard will configure your environment in 4 simple steps:
7517
+ 1. \u{1F511} AI Provider Setup (Required)
7518
+ 2. \u{1F3D7}\uFE0F Project Configuration (Recommended)
7519
+ 3. \u{1F39B}\uFE0F Personal Preferences (Optional)
7520
+ 4. \u2705 Validation & Testing (Automatic)
7521
+
7522
+ Estimated time: 3-5 minutes
7523
+ `);
7524
+ }
7525
+ async showSuccessMessage(result) {
7526
+ logger.info(`
7527
+ \u{1F389} Setup Complete! Welcome to MARIA CODE!
7528
+
7529
+ \u2705 Environment configured
7530
+ \u2705 AI providers connected: ${result.providersConfigured.join(", ")}
7531
+ \u2705 Project initialized
7532
+ \u2705 All validation tests passed
7533
+
7534
+ \u{1F680} Ready to start! Try these commands:
7535
+ \u2022 maria chat - Start interactive mode
7536
+ \u2022 maria code "create a React component"
7537
+ \u2022 maria test - Generate tests
7538
+ \u2022 maria help - View all commands
7539
+
7540
+ Setup completed in ${Math.round(result.duration / 1e3)}s
7541
+ Happy coding! \u{1F680}
7542
+ `);
7543
+ }
7544
+ // Helper methods
7545
+ async fileExists(path11) {
7546
+ try {
7547
+ await fs11__namespace.default.access(path11);
7548
+ return true;
7549
+ } catch {
7550
+ return false;
7551
+ }
7552
+ }
7553
+ async detectConfigurationIssues(context) {
7554
+ const issues = [];
7555
+ if (!await this.fileExists(path10__namespace.default.join(context.environment.cwd, ".env.local"))) {
7556
+ issues.push({ description: "Missing .env.local file", severity: "error" });
7557
+ }
7558
+ if (!await this.fileExists(path10__namespace.default.join(context.environment.cwd, ".maria-code.toml"))) {
7559
+ issues.push({ description: "Missing .maria-code.toml file", severity: "warning" });
7560
+ }
7561
+ return issues;
7562
+ }
7563
+ async fixConfigurationIssue(issue, context) {
7564
+ if (issue.description.includes(".env.local")) {
7565
+ await this.generateQuickEnvTemplate();
7566
+ }
7567
+ }
7568
+ async getSetupRecord(context) {
6001
7569
  try {
6002
- const { LLMHealthChecker: LLMHealthChecker2 } = await Promise.resolve().then(() => (init_llm_health_checker(), llm_health_checker_exports));
6003
- const healthChecker = new LLMHealthChecker2();
6004
- const healthStatus = await healthChecker.checkService(service.name);
6005
- for (let progress = 0; progress <= 100; progress += 25) {
6006
- service.progress = progress;
6007
- await new Promise((resolve) => setTimeout(resolve, 50));
6008
- }
6009
- if (healthStatus.isRunning) {
6010
- service.status = "running";
6011
- service.progress = 100;
6012
- if (healthStatus.models && healthStatus.models.length > 0) {
6013
- service.message = `${healthStatus.models.length} models available`;
6014
- } else {
6015
- service.message = "Running";
6016
- }
6017
- } else {
6018
- service.status = "not-installed";
6019
- service.message = "Not running";
6020
- service.progress = 0;
6021
- }
7570
+ const recordPath = path10__namespace.default.join(context.environment.cwd, ".maria", "setup.json");
7571
+ const content = await fs11__namespace.default.readFile(recordPath, "utf-8");
7572
+ return JSON.parse(content);
6022
7573
  } catch {
6023
- service.status = "not-installed";
6024
- service.message = "Skipping...";
6025
- service.progress = 0;
7574
+ return null;
6026
7575
  }
6027
7576
  }
6028
- displayWelcome() {
6029
- const frameWidth = 86;
6030
- const horizontalLine = "\u2550".repeat(frameWidth - 2);
6031
- const emptyLine = "\u2551" + " ".repeat(frameWidth - 2) + "\u2551";
6032
- const centerText = /* @__PURE__ */ __name((text) => {
6033
- const plainText = text.replace(/\u001B\[[0-9;]*m/g, "");
6034
- const padding = Math.max(0, frameWidth - 2 - plainText.length);
6035
- const leftPad = Math.floor(padding / 2);
6036
- const rightPad = padding - leftPad;
6037
- return "\u2551" + " ".repeat(leftPad) + text + " ".repeat(rightPad) + "\u2551";
6038
- }, "centerText");
6039
- console.log("\n");
6040
- console.log(chalk13__default.default.magentaBright("\u2554" + horizontalLine + "\u2557"));
6041
- console.log(chalk13__default.default.magentaBright(emptyLine));
6042
- console.log(
6043
- chalk13__default.default.magentaBright(
6044
- centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 "))
6045
- )
6046
- );
6047
- console.log(
6048
- chalk13__default.default.magentaBright(
6049
- centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557"))
6050
- )
6051
- );
6052
- console.log(
6053
- chalk13__default.default.magentaBright(
6054
- centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551"))
6055
- )
6056
- );
6057
- console.log(
6058
- chalk13__default.default.magentaBright(
6059
- centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551"))
6060
- )
6061
- );
6062
- console.log(
6063
- chalk13__default.default.magentaBright(
6064
- centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551"))
6065
- )
6066
- );
6067
- console.log(
6068
- chalk13__default.default.magentaBright(
6069
- centerText(chalk13__default.default.bold.magentaBright("\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D"))
6070
- )
6071
- );
6072
- console.log(chalk13__default.default.magentaBright(emptyLine));
6073
- console.log(
6074
- chalk13__default.default.magentaBright(centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557")))
6075
- );
6076
- console.log(
6077
- chalk13__default.default.magentaBright(
6078
- centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"))
6079
- )
6080
- );
6081
- console.log(
6082
- chalk13__default.default.magentaBright(
6083
- centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 "))
6084
- )
6085
- );
6086
- console.log(
6087
- chalk13__default.default.magentaBright(
6088
- centerText(chalk13__default.default.bold.magentaBright("\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D "))
6089
- )
6090
- );
6091
- console.log(
6092
- chalk13__default.default.magentaBright(
6093
- centerText(chalk13__default.default.bold.magentaBright("\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"))
6094
- )
6095
- );
6096
- console.log(
6097
- chalk13__default.default.magentaBright(
6098
- centerText(chalk13__default.default.bold.magentaBright(" \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"))
6099
- )
6100
- );
6101
- console.log(chalk13__default.default.magentaBright(emptyLine));
6102
- console.log(
6103
- chalk13__default.default.magentaBright(centerText(chalk13__default.default.whiteBright("AI-Powered Development Platform")))
6104
- );
6105
- console.log(chalk13__default.default.magentaBright(centerText(chalk13__default.default.gray("(c) 2025 Bonginkan Inc."))));
6106
- console.log(chalk13__default.default.magentaBright(emptyLine));
6107
- console.log(chalk13__default.default.magentaBright("\u255A" + horizontalLine + "\u255D"));
6108
- console.log("");
7577
+ async validateEnvironmentFile(context) {
7578
+ return this.fileExists(path10__namespace.default.join(context.environment.cwd, ".env.local"));
7579
+ }
7580
+ async validateConfigFile(context) {
7581
+ return this.fileExists(path10__namespace.default.join(context.environment.cwd, ".maria-code.toml"));
7582
+ }
7583
+ async validateProviderConnections(context) {
7584
+ return true;
7585
+ }
7586
+ async generateQuickEnvTemplate() {
7587
+ try {
7588
+ const envContent = `# MARIA CODE Environment Configuration
7589
+ # Generated by setup wizard on ${(/* @__PURE__ */ new Date()).toISOString()}
7590
+ # Replace placeholder values with your actual credentials
7591
+
7592
+ # AI Provider API Keys
7593
+ OPENAI_API_KEY=your_openai_key_here
7594
+ ANTHROPIC_API_KEY=your_anthropic_key_here
7595
+ GOOGLE_AI_API_KEY=your_google_ai_key_here
7596
+ GROQ_API_KEY=your_groq_key_here
7597
+
7598
+ # Local AI Providers (Optional)
7599
+ LMSTUDIO_API_URL=http://localhost:1234
7600
+ OLLAMA_API_URL=http://localhost:11434
7601
+ VLLM_API_URL=http://localhost:8000
7602
+
7603
+ # Development Settings
7604
+ DEBUG=false
7605
+ LOG_LEVEL=info
7606
+ `;
7607
+ const envPath = path10__namespace.default.join(process.cwd(), ".env.local");
7608
+ await fs11__namespace.default.writeFile(envPath, envContent, "utf-8");
7609
+ return this.success("Environment template generated successfully", {
7610
+ files: [".env.local"],
7611
+ message: "Please edit .env.local and add your API keys"
7612
+ });
7613
+ } catch (error) {
7614
+ logger.error("Failed to generate environment template:", error);
7615
+ return this.error(
7616
+ `Environment template generation failed: ${error instanceof Error ? error.message : "Unknown error"}`,
7617
+ "ENV_TEMPLATE_ERROR",
7618
+ error
7619
+ );
7620
+ }
7621
+ }
7622
+ generateTOMLConfig(config2) {
7623
+ return `# MARIA CODE Configuration
7624
+ # Generated by setup wizard
7625
+
7626
+ [project]
7627
+ name = "${config2.project.name}"
7628
+ type = "web"
7629
+ language = "typescript"
7630
+
7631
+ [ai]
7632
+ default_provider = "openai"
7633
+ default_model = "gpt-4"
7634
+
7635
+ [preferences]
7636
+ theme = "dark"
7637
+ language = "auto"
7638
+ `;
6109
7639
  }
6110
7640
  };
7641
+ setup_command_default = new SetupCommand();
6111
7642
  }
6112
7643
  });
6113
7644
 
@@ -6135,7 +7666,9 @@ var GrokProvider = class extends BaseAIProvider {
6135
7666
  }
6136
7667
  name = "Grok";
6137
7668
  models = [
6138
- "grok-4-0709",
7669
+ "grok-4",
7670
+ "grok-beta",
7671
+ "grok-2",
6139
7672
  "llama-3.3-70b-versatile",
6140
7673
  "llama-3.1-70b-versatile",
6141
7674
  "llama-3.1-8b-instant",
@@ -6986,6 +8519,30 @@ var AIProviderManager = class {
6986
8519
  }
6987
8520
  }
6988
8521
  }
8522
+ const cloudProviders = ["openai", "anthropic", "google", "grok"];
8523
+ const defaultCloudModels = {
8524
+ openai: ["gpt-5", "gpt-5-mini", "gpt-4o", "gpt-4o-mini", "o1-preview", "o1-mini"],
8525
+ anthropic: ["claude-4.1", "claude-3-5-sonnet-20241022", "claude-3-5-haiku-20241022", "claude-3-opus-20240229"],
8526
+ google: ["gemini-2.5-pro", "gemini-2.5-flash", "gemini-1.5-pro", "gemini-1.5-flash"],
8527
+ grok: ["grok-4", "grok-beta", "grok-2"]
8528
+ };
8529
+ for (const providerName of cloudProviders) {
8530
+ if (!this.availableProviders.has(providerName)) {
8531
+ const models = defaultCloudModels[providerName] || [];
8532
+ const modelInfos = models.map((modelName) => ({
8533
+ id: `${providerName}-${modelName}`,
8534
+ name: modelName,
8535
+ provider: providerName,
8536
+ description: `${modelName} from ${providerName}`,
8537
+ contextLength: 8192,
8538
+ capabilities: ["text", "code", "vision"],
8539
+ available: false,
8540
+ // Mark as unavailable (need API key)
8541
+ recommendedFor: ["general"]
8542
+ }));
8543
+ allModels.push(...modelInfos);
8544
+ }
8545
+ }
6989
8546
  return allModels;
6990
8547
  }
6991
8548
  selectOptimalProvider(_taskType, priorityMode = "auto") {
@@ -7198,6 +8755,17 @@ var IntelligentRouter = class {
7198
8755
  modelId: request.model || await this.getDefaultModelForProvider(request.provider)
7199
8756
  };
7200
8757
  }
8758
+ const preferredProvider = this.config.get("preferredProvider");
8759
+ const preferredModel = this.config.get("preferredModel");
8760
+ if (preferredProvider && preferredModel) {
8761
+ const availableProviders = this.providerManager.getAvailableProviders();
8762
+ if (availableProviders.includes(preferredProvider)) {
8763
+ return {
8764
+ providerName: preferredProvider,
8765
+ modelId: preferredModel
8766
+ };
8767
+ }
8768
+ }
7201
8769
  const priorityMode = this.config.get("priority", "auto");
7202
8770
  const providerName = this.providerManager.selectOptimalProvider(taskType, priorityMode);
7203
8771
  if (!providerName) {
@@ -7230,6 +8798,10 @@ var IntelligentRouter = class {
7230
8798
  updatePriorityMode(mode) {
7231
8799
  this.config.set("priority", mode);
7232
8800
  }
8801
+ updatePreferredProvider(provider, model) {
8802
+ this.config.set("preferredProvider", provider);
8803
+ this.config.set("preferredModel", model);
8804
+ }
7233
8805
  };
7234
8806
 
7235
8807
  // src/services/health-monitor.ts
@@ -7523,10 +9095,10 @@ var HealthMonitor = class extends events.EventEmitter {
7523
9095
  */
7524
9096
  async saveHealthData() {
7525
9097
  try {
7526
- const healthDir = path5.join(os2.homedir(), ".maria", "health");
9098
+ const healthDir = path10.join(os3.homedir(), ".maria", "health");
7527
9099
  await fs7.promises.mkdir(healthDir, { recursive: true });
7528
9100
  const systemHealth = this.getSystemHealth();
7529
- const healthFile = path5.join(healthDir, "system-health.json");
9101
+ const healthFile = path10.join(healthDir, "system-health.json");
7530
9102
  await fs7.promises.writeFile(
7531
9103
  healthFile,
7532
9104
  JSON.stringify(
@@ -7547,7 +9119,7 @@ var HealthMonitor = class extends events.EventEmitter {
7547
9119
  */
7548
9120
  async loadHealthData() {
7549
9121
  try {
7550
- const healthFile = path5.join(os2.homedir(), ".maria", "health", "system-health.json");
9122
+ const healthFile = path10.join(os3.homedir(), ".maria", "health", "system-health.json");
7551
9123
  const data = await fs7.promises.readFile(healthFile, "utf8");
7552
9124
  const parsed = JSON.parse(data);
7553
9125
  return {
@@ -7634,7 +9206,9 @@ var ConfigManager = class _ConfigManager {
7634
9206
  autoStart: true,
7635
9207
  healthMonitoring: true,
7636
9208
  language: "auto",
7637
- offlineMode: false
9209
+ offlineMode: false,
9210
+ model: "gpt-5-mini",
9211
+ provider: "openai"
7638
9212
  };
7639
9213
  }
7640
9214
  mergeConfig(newConfig) {
@@ -7691,27 +9265,27 @@ var ConfigManager = class _ConfigManager {
7691
9265
  // Save configuration to file (for CLI usage)
7692
9266
  async save(configPath) {
7693
9267
  const { importNodeBuiltin: importNodeBuiltin2, safeDynamicImport: safeDynamicImport2 } = await Promise.resolve().then(() => (init_import_helper(), import_helper_exports));
7694
- const fs11 = await safeDynamicImport2("fs-extra").catch(
9268
+ const fs12 = await safeDynamicImport2("fs-extra").catch(
7695
9269
  () => importNodeBuiltin2("fs")
7696
9270
  );
7697
- const path9 = await importNodeBuiltin2("path");
7698
- const os3 = await importNodeBuiltin2("os");
7699
- const targetPath = configPath || path9.join(os3.homedir(), ".maria", "config.json");
7700
- await fs11.ensureDir(path9.dirname(targetPath));
7701
- await fs11.writeJson(targetPath, this.config, { spaces: 2 });
9271
+ const path11 = await importNodeBuiltin2("path");
9272
+ const os4 = await importNodeBuiltin2("os");
9273
+ const targetPath = configPath || path11.join(os4.homedir(), ".maria", "config.json");
9274
+ await fs12.ensureDir(path11.dirname(targetPath));
9275
+ await fs12.writeJson(targetPath, this.config, { spaces: 2 });
7702
9276
  }
7703
9277
  // Load configuration from file
7704
9278
  static async load(configPath) {
7705
9279
  const { importNodeBuiltin: importNodeBuiltin2, safeDynamicImport: safeDynamicImport2 } = await Promise.resolve().then(() => (init_import_helper(), import_helper_exports));
7706
- const fs11 = await safeDynamicImport2("fs-extra").catch(
9280
+ const fs12 = await safeDynamicImport2("fs-extra").catch(
7707
9281
  () => importNodeBuiltin2("fs")
7708
9282
  );
7709
- const path9 = await importNodeBuiltin2("path");
7710
- const os3 = await importNodeBuiltin2("os");
7711
- const targetPath = configPath || path9.join(os3.homedir(), ".maria", "config.json");
7712
- if (await fs11.pathExists(targetPath)) {
9283
+ const path11 = await importNodeBuiltin2("path");
9284
+ const os4 = await importNodeBuiltin2("os");
9285
+ const targetPath = configPath || path11.join(os4.homedir(), ".maria", "config.json");
9286
+ if (await fs12.pathExists(targetPath)) {
7713
9287
  try {
7714
- const savedConfig = await fs11.readJson(targetPath);
9288
+ const savedConfig = await fs12.readJson(targetPath);
7715
9289
  return new _ConfigManager(savedConfig);
7716
9290
  } catch (error) {
7717
9291
  console.warn("Failed to load config file, using defaults:", error);
@@ -7847,6 +9421,50 @@ Context from memory:
7847
9421
  this.config.set("priority", mode);
7848
9422
  this.router.updatePriorityMode(mode);
7849
9423
  }
9424
+ /**
9425
+ * Switch to a specific model
9426
+ */
9427
+ async switchModel(modelId) {
9428
+ try {
9429
+ const models = await this.getModels();
9430
+ const targetModel = models.find((m) => m.id === modelId || m.name === modelId);
9431
+ if (!targetModel) {
9432
+ return {
9433
+ success: false,
9434
+ message: `Model not found: ${modelId}`
9435
+ };
9436
+ }
9437
+ if (!targetModel.available) {
9438
+ return {
9439
+ success: false,
9440
+ message: `Model ${targetModel.name} is not available. Please check API keys.`
9441
+ };
9442
+ }
9443
+ this.config.set("model", targetModel.name);
9444
+ this.config.set("provider", targetModel.provider);
9445
+ this.router.updatePreferredProvider(targetModel.provider, targetModel.name);
9446
+ return {
9447
+ success: true,
9448
+ message: `Switched to ${targetModel.name} (${targetModel.provider})`
9449
+ };
9450
+ } catch (error) {
9451
+ return {
9452
+ success: false,
9453
+ message: `Failed to switch model: ${error instanceof Error ? error.message : "Unknown error"}`
9454
+ };
9455
+ }
9456
+ }
9457
+ /**
9458
+ * Get current active model
9459
+ */
9460
+ getCurrentModel() {
9461
+ const currentModel = this.config.get("model");
9462
+ const currentProvider = this.config.get("provider");
9463
+ if (currentModel && currentProvider) {
9464
+ return { name: currentModel, provider: currentProvider };
9465
+ }
9466
+ return null;
9467
+ }
7850
9468
  /**
7851
9469
  * Get current configuration
7852
9470
  */
@@ -12876,14 +14494,14 @@ var System2MemoryManager = class {
12876
14494
  return Math.min(1, weightedSum / evidence.length);
12877
14495
  }
12878
14496
  traverseDecisionTree(node, context) {
12879
- const path9 = [node];
14497
+ const path11 = [node];
12880
14498
  for (const child of node.children) {
12881
14499
  if (child.type === "condition" && this.evaluateCondition(child, context)) {
12882
- path9.push(...this.traverseDecisionTree(child, context));
14500
+ path11.push(...this.traverseDecisionTree(child, context));
12883
14501
  break;
12884
14502
  }
12885
14503
  }
12886
- return path9;
14504
+ return path11;
12887
14505
  }
12888
14506
  evaluateCondition(node, _context) {
12889
14507
  return node.confidence > 0.5;
@@ -18989,7 +20607,7 @@ var TemplateManager = class _TemplateManager {
18989
20607
  templatesDir;
18990
20608
  builtInTemplates = /* @__PURE__ */ new Map();
18991
20609
  constructor() {
18992
- this.templatesDir = path5.join(os2.homedir(), ".maria-code", "templates");
20610
+ this.templatesDir = path10.join(os3.homedir(), ".maria-code", "templates");
18993
20611
  this.ensureTemplatesDir();
18994
20612
  this.initializeBuiltInTemplates();
18995
20613
  this.loadUserTemplates();
@@ -19141,7 +20759,7 @@ var TemplateManager = class _TemplateManager {
19141
20759
  files.forEach((file) => {
19142
20760
  if (file.endsWith(".json")) {
19143
20761
  try {
19144
- const content = fs7.readFileSync(path5.join(this.templatesDir, file), "utf-8");
20762
+ const content = fs7.readFileSync(path10.join(this.templatesDir, file), "utf-8");
19145
20763
  const template = JSON.parse(content);
19146
20764
  template.createdAt = new Date(template.createdAt);
19147
20765
  template.updatedAt = new Date(template.updatedAt);
@@ -19160,7 +20778,7 @@ var TemplateManager = class _TemplateManager {
19160
20778
  */
19161
20779
  saveTemplate(template) {
19162
20780
  const filename = `${template.id}.json`;
19163
- const filepath = path5.join(this.templatesDir, filename);
20781
+ const filepath = path10.join(this.templatesDir, filename);
19164
20782
  fs7.writeFileSync(filepath, JSON.stringify(template, null, 2));
19165
20783
  }
19166
20784
  /**
@@ -19235,8 +20853,8 @@ var TemplateManager = class _TemplateManager {
19235
20853
  }
19236
20854
  this.templates.delete(id);
19237
20855
  try {
19238
- const fs11 = await import('fs');
19239
- fs11.unlinkSync(path5.join(this.templatesDir, `${id}.json`));
20856
+ const fs12 = await import('fs');
20857
+ fs12.unlinkSync(path10.join(this.templatesDir, `${id}.json`));
19240
20858
  } catch (error) {
19241
20859
  logger.error("Failed to delete template file:", error);
19242
20860
  }
@@ -19753,7 +21371,7 @@ var HotkeyManager = class _HotkeyManager {
19753
21371
  isEnabled = true;
19754
21372
  // private activeKeys: Set<string> = new Set(); // Reserved for future use
19755
21373
  constructor() {
19756
- this.configPath = path5.join(os2.homedir(), ".maria", "hotkeys.json");
21374
+ this.configPath = path10.join(os3.homedir(), ".maria", "hotkeys.json");
19757
21375
  this.loadBindings();
19758
21376
  this.initializeDefaultBindings();
19759
21377
  }
@@ -20138,7 +21756,7 @@ ${chalk13__default.default.gray("Use /hotkey to manage hotkeys")}
20138
21756
  saveBindings() {
20139
21757
  try {
20140
21758
  const config2 = this.exportConfig();
20141
- const dir = path5.join(os2.homedir(), ".maria");
21759
+ const dir = path10.join(os3.homedir(), ".maria");
20142
21760
  if (!fs7.existsSync(dir)) {
20143
21761
  fs7.mkdirSync(dir, { recursive: true });
20144
21762
  }
@@ -20155,7 +21773,7 @@ init_cjs_shims();
20155
21773
  // src/utils/env-loader.ts
20156
21774
  init_cjs_shims();
20157
21775
  function loadEnvironmentVariables() {
20158
- const localEnvPath = path5__namespace.join(process.cwd(), ".env.local");
21776
+ const localEnvPath = path10__namespace.join(process.cwd(), ".env.local");
20159
21777
  if (fs7__namespace.existsSync(localEnvPath)) {
20160
21778
  const result = dotenv__namespace.config({ path: localEnvPath });
20161
21779
  if (result.error) {
@@ -20164,14 +21782,14 @@ function loadEnvironmentVariables() {
20164
21782
  console.log("\u2705 Loaded environment from .env.local");
20165
21783
  }
20166
21784
  }
20167
- const envPath = path5__namespace.join(process.cwd(), ".env");
21785
+ const envPath = path10__namespace.join(process.cwd(), ".env");
20168
21786
  if (fs7__namespace.existsSync(envPath)) {
20169
21787
  const result = dotenv__namespace.config({ path: envPath, override: false });
20170
21788
  if (result.error) {
20171
21789
  console.warn("Error loading .env:", result.error);
20172
21790
  }
20173
21791
  }
20174
- const lmstudioEnvPath = path5__namespace.join(process.cwd(), ".env.lmstudio");
21792
+ const lmstudioEnvPath = path10__namespace.join(process.cwd(), ".env.lmstudio");
20175
21793
  if (fs7__namespace.existsSync(lmstudioEnvPath)) {
20176
21794
  const result = dotenv__namespace.config({ path: lmstudioEnvPath, override: false });
20177
21795
  if (result.error) {
@@ -20590,7 +22208,7 @@ var InteractiveModelSelector = class {
20590
22208
  }
20591
22209
  }
20592
22210
  async updateEnvironment(model) {
20593
- const envPath = path5__namespace.join(process.cwd(), ".env.local");
22211
+ const envPath = path10__namespace.join(process.cwd(), ".env.local");
20594
22212
  if (model.type === "local") {
20595
22213
  process.env["AI_PROVIDER"] = "lmstudio";
20596
22214
  process.env["LMSTUDIO_DEFAULT_MODEL"] = model.id;
@@ -20598,263 +22216,38 @@ var InteractiveModelSelector = class {
20598
22216
  } else {
20599
22217
  process.env["AI_PROVIDER"] = model.provider.toLowerCase();
20600
22218
  process.env["AI_MODEL"] = model.id;
20601
- process.env["OFFLINE_MODE"] = "false";
20602
- }
20603
- if (fs7__namespace.existsSync(envPath)) {
20604
- let content = fs7__namespace.readFileSync(envPath, "utf-8");
20605
- if (model.type === "local") {
20606
- content = content.replace(
20607
- /LMSTUDIO_DEFAULT_MODEL=.*/g,
20608
- `LMSTUDIO_DEFAULT_MODEL=${model.id}`
20609
- );
20610
- content = content.replace(/AI_PROVIDER=.*/g, "AI_PROVIDER=lmstudio");
20611
- content = content.replace(/OFFLINE_MODE=.*/g, "OFFLINE_MODE=true");
20612
- }
20613
- fs7__namespace.writeFileSync(envPath, content);
20614
- }
20615
- }
20616
- cleanup() {
20617
- if (process.stdin.isTTY) {
20618
- process.stdin.setRawMode(false);
20619
- }
20620
- process.stdin.removeAllListeners("keypress");
20621
- this.rl.close();
20622
- }
20623
- };
20624
- async function runInteractiveModelSelector() {
20625
- const selector = new InteractiveModelSelector();
20626
- await selector.initialize();
20627
- return await selector.selectModel();
20628
- }
20629
- __name(runInteractiveModelSelector, "runInteractiveModelSelector");
20630
-
20631
- // src/services/chat-context.service.ts
20632
- init_cjs_shims();
20633
- var ChatContextService = class _ChatContextService extends events.EventEmitter {
20634
- static {
20635
- __name(this, "ChatContextService");
20636
- }
20637
- static instance;
20638
- contextWindow = [];
20639
- fullHistory = [];
20640
- config;
20641
- currentTokens = 0;
20642
- compressionCount = 0;
20643
- sessionId;
20644
- constructor(config2) {
20645
- super();
20646
- this.config = {
20647
- maxTokens: config2?.maxTokens || 128e3,
20648
- compressionThreshold: config2?.compressionThreshold || 0.8,
20649
- summaryTokenLimit: config2?.summaryTokenLimit || 2e3,
20650
- persistPath: config2?.persistPath || path5__namespace.join(process.env["HOME"] || "", ".maria", "context")
20651
- };
20652
- this.sessionId = this.generateSessionId();
20653
- }
20654
- static getInstance(config2) {
20655
- if (!_ChatContextService.instance) {
20656
- _ChatContextService.instance = new _ChatContextService(config2);
20657
- }
20658
- return _ChatContextService.instance;
20659
- }
20660
- generateSessionId() {
20661
- return `session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
20662
- }
20663
- countTokens(text) {
20664
- try {
20665
- return gpt3Encoder.encode(text).length;
20666
- } catch {
20667
- return Math.ceil(text.length / 4);
20668
- }
20669
- }
20670
- async addMessage(message) {
20671
- const tokens = this.countTokens(message.content);
20672
- const fullMessage = {
20673
- ...message,
20674
- timestamp: /* @__PURE__ */ new Date(),
20675
- tokens
20676
- };
20677
- this.fullHistory.push(fullMessage);
20678
- this.contextWindow.push(fullMessage);
20679
- this.currentTokens += tokens;
20680
- await this.optimizeMemory();
20681
- this.emit("message-added", fullMessage);
20682
- this.emit("context-updated", this.getStats());
20683
- }
20684
- async optimizeMemory() {
20685
- const usageRatio = this.currentTokens / this.config.maxTokens;
20686
- if (usageRatio >= this.config.compressionThreshold) {
20687
- await this.compressContext();
20688
- }
20689
- while (this.currentTokens > this.config.maxTokens && this.contextWindow.length > 1) {
20690
- const removed = this.contextWindow.shift();
20691
- if (removed?.tokens) {
20692
- this.currentTokens -= removed.tokens;
20693
- }
20694
- }
20695
- }
20696
- async compressContext() {
20697
- if (this.contextWindow.length <= 2) return;
20698
- const middleMessages = this.contextWindow.slice(1, -1);
20699
- const summary = await this.generateSummary(middleMessages);
20700
- if (summary) {
20701
- const summaryMessage = {
20702
- role: "system",
20703
- content: `[Compressed context summary]: ${summary}`,
20704
- timestamp: /* @__PURE__ */ new Date(),
20705
- tokens: this.countTokens(summary),
20706
- metadata: { compressed: true, originalCount: middleMessages.length }
20707
- };
20708
- const firstMessage = this.contextWindow[0];
20709
- const lastMessage = this.contextWindow[this.contextWindow.length - 1];
20710
- if (!firstMessage || !lastMessage) return;
20711
- this.contextWindow = [firstMessage, summaryMessage, lastMessage];
20712
- this.recalculateTokens();
20713
- this.compressionCount++;
20714
- this.emit("context-compressed", {
20715
- originalCount: middleMessages.length,
20716
- summaryTokens: summaryMessage.tokens
20717
- });
20718
- }
20719
- }
20720
- async generateSummary(messages) {
20721
- const keyPoints = messages.filter((m) => m.role === "user").map((m) => m.content.substring(0, 100)).join("; ");
20722
- return `Previous discussion covered: ${keyPoints}`;
20723
- }
20724
- recalculateTokens() {
20725
- this.currentTokens = this.contextWindow.reduce((sum, msg) => sum + (msg.tokens || 0), 0);
20726
- }
20727
- clearContext(options) {
20728
- if (options?.soft) {
20729
- this.emit("display-cleared");
20730
- return;
20731
- }
20732
- if (options?.summary && this.contextWindow.length > 0) {
20733
- this.generateSummary(this.contextWindow).then((summary) => {
20734
- this.emit("summary-generated", summary);
20735
- });
20736
- }
20737
- const previousStats = this.getStats();
20738
- this.contextWindow = [];
20739
- this.currentTokens = 0;
20740
- this.compressionCount = 0;
20741
- if (!options?.soft) {
20742
- this.fullHistory = [];
20743
- this.sessionId = this.generateSessionId();
20744
- }
20745
- this.emit("context-cleared", previousStats);
20746
- }
20747
- getContext() {
20748
- return [...this.contextWindow];
20749
- }
20750
- getFullHistory() {
20751
- return [...this.fullHistory];
20752
- }
20753
- getStats() {
20754
- return {
20755
- totalMessages: this.fullHistory.length,
20756
- totalTokens: this.currentTokens,
20757
- maxTokens: this.config.maxTokens,
20758
- usagePercentage: this.currentTokens / this.config.maxTokens * 100,
20759
- messagesInWindow: this.contextWindow.length,
20760
- compressedCount: this.compressionCount
20761
- };
20762
- }
20763
- async persistSession() {
20764
- if (!this.config.persistPath) return;
20765
- try {
20766
- await fs6__namespace.mkdir(this.config.persistPath, { recursive: true });
20767
- const sessionFile = path5__namespace.join(this.config.persistPath, `${this.sessionId}.json`);
20768
- const sessionData = {
20769
- sessionId: this.sessionId,
20770
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
20771
- stats: this.getStats(),
20772
- contextWindow: this.contextWindow,
20773
- fullHistory: this.fullHistory,
20774
- compressionCount: this.compressionCount
20775
- };
20776
- await fs6__namespace.writeFile(sessionFile, JSON.stringify(sessionData, null, 2));
20777
- this.emit("session-persisted", sessionFile);
20778
- } catch (error) {
20779
- this.emit("persist-error", error instanceof Error ? error : new Error(String(error)));
20780
- }
20781
- }
20782
- async loadSession(sessionId) {
20783
- if (!this.config.persistPath) return false;
20784
- try {
20785
- const sessionFile = path5__namespace.join(this.config.persistPath, `${sessionId}.json`);
20786
- const data = await fs6__namespace.readFile(sessionFile, "utf-8");
20787
- const sessionData = JSON.parse(data);
20788
- this.sessionId = sessionData.sessionId;
20789
- this.contextWindow = sessionData.contextWindow;
20790
- this.fullHistory = sessionData.fullHistory;
20791
- this.compressionCount = sessionData.compressionCount;
20792
- this.recalculateTokens();
20793
- this.emit("session-loaded", sessionId);
20794
- return true;
20795
- } catch (error) {
20796
- this.emit("load-error", error instanceof Error ? error : new Error(String(error)));
20797
- return false;
20798
- }
20799
- }
20800
- async exportContext(format = "json") {
20801
- if (format === "markdown") {
20802
- return this.contextWindow.map(
20803
- (msg) => `### ${msg.role.toUpperCase()} (${msg.timestamp.toISOString()})
20804
- ${msg.content}
20805
- `
20806
- ).join("\n---\n\n");
22219
+ process.env["OFFLINE_MODE"] = "false";
20807
22220
  }
20808
- return JSON.stringify(
20809
- {
20810
- sessionId: this.sessionId,
20811
- exportDate: (/* @__PURE__ */ new Date()).toISOString(),
20812
- stats: this.getStats(),
20813
- context: this.contextWindow,
20814
- fullHistory: this.fullHistory
20815
- },
20816
- null,
20817
- 2
20818
- );
20819
- }
20820
- async importContext(data) {
20821
- try {
20822
- const imported = JSON.parse(data);
20823
- if (imported.context && Array.isArray(imported.context)) {
20824
- this.contextWindow = imported.context;
20825
- this.fullHistory = imported.fullHistory || imported.context;
20826
- this.recalculateTokens();
20827
- this.sessionId = imported.sessionId || this.generateSessionId();
20828
- this.emit("context-imported", this.getStats());
22221
+ if (fs7__namespace.existsSync(envPath)) {
22222
+ let content = fs7__namespace.readFileSync(envPath, "utf-8");
22223
+ if (model.type === "local") {
22224
+ content = content.replace(
22225
+ /LMSTUDIO_DEFAULT_MODEL=.*/g,
22226
+ `LMSTUDIO_DEFAULT_MODEL=${model.id}`
22227
+ );
22228
+ content = content.replace(/AI_PROVIDER=.*/g, "AI_PROVIDER=lmstudio");
22229
+ content = content.replace(/OFFLINE_MODE=.*/g, "OFFLINE_MODE=true");
20829
22230
  }
20830
- } catch (error) {
20831
- this.emit("import-error", error instanceof Error ? error : new Error(String(error)));
20832
- throw error;
22231
+ fs7__namespace.writeFileSync(envPath, content);
20833
22232
  }
20834
22233
  }
20835
- getTokenUsageIndicator() {
20836
- const stats = this.getStats();
20837
- const percentage = Math.round(stats.usagePercentage);
20838
- const blocks = Math.round(percentage / 10);
20839
- const filled = "\u2588".repeat(blocks);
20840
- const empty = "\u2591".repeat(10 - blocks);
20841
- let color = "\x1B[32m";
20842
- if (percentage > 80)
20843
- color = "\x1B[31m";
20844
- else if (percentage > 60) color = "\x1B[33m";
20845
- return `${color}[${filled}${empty}] ${percentage}% (${stats.totalTokens}/${stats.maxTokens} tokens)\x1B[0m`;
20846
- }
20847
- reset() {
20848
- this.contextWindow = [];
20849
- this.fullHistory = [];
20850
- this.currentTokens = 0;
20851
- this.compressionCount = 0;
20852
- this.sessionId = this.generateSessionId();
20853
- _ChatContextService.instance = null;
22234
+ cleanup() {
22235
+ if (process.stdin.isTTY) {
22236
+ process.stdin.setRawMode(false);
22237
+ }
22238
+ process.stdin.removeAllListeners("keypress");
22239
+ this.rl.close();
20854
22240
  }
20855
22241
  };
22242
+ async function runInteractiveModelSelector() {
22243
+ const selector = new InteractiveModelSelector();
22244
+ await selector.initialize();
22245
+ return await selector.selectModel();
22246
+ }
22247
+ __name(runInteractiveModelSelector, "runInteractiveModelSelector");
20856
22248
 
20857
22249
  // src/services/slash-command-handler.ts
22250
+ init_chat_context_service();
20858
22251
  init_code_generation_service();
20859
22252
 
20860
22253
  // src/services/test-generation.service.ts
@@ -20947,7 +22340,7 @@ var TestGenerationService = class _TestGenerationService {
20947
22340
  files.push(...await this.findTestableFiles("."));
20948
22341
  }
20949
22342
  } else {
20950
- const stat2 = await fs6__namespace.stat(target);
22343
+ const stat2 = await fs11__namespace.stat(target);
20951
22344
  if (stat2.isDirectory()) {
20952
22345
  files.push(...await this.findTestableFiles(target));
20953
22346
  } else if (stat2.isFile() && this.isTestableFile(target)) {
@@ -20962,9 +22355,9 @@ var TestGenerationService = class _TestGenerationService {
20962
22355
  // @ts-nocheck - Complex async type handling
20963
22356
  async findTestableFiles(dir) {
20964
22357
  const files = [];
20965
- const entries = await fs6__namespace.readdir(dir, { withFileTypes: true });
22358
+ const entries = await fs11__namespace.readdir(dir, { withFileTypes: true });
20966
22359
  for (const entry of entries) {
20967
- const fullPath = path5__namespace.join(dir, entry.name);
22360
+ const fullPath = path10__namespace.join(dir, entry.name);
20968
22361
  if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules") {
20969
22362
  files.push(...await this.findTestableFiles(fullPath));
20970
22363
  } else if (entry.isFile() && this.isTestableFile(entry.name)) {
@@ -20980,7 +22373,7 @@ var TestGenerationService = class _TestGenerationService {
20980
22373
  isTestableFile(file) {
20981
22374
  const testableExtensions = [".js", ".jsx", ".ts", ".tsx", ".py", ".go", ".rs", ".java"];
20982
22375
  const excludePatterns = [".test.", ".spec.", ".min.", "test/", "tests/", "__tests__/"];
20983
- const ext = path5__namespace.extname(file);
22376
+ const ext = path10__namespace.extname(file);
20984
22377
  const isTestable = testableExtensions.includes(ext);
20985
22378
  const isExcluded = excludePatterns.some((pattern) => file.includes(pattern));
20986
22379
  return isTestable && !isExcluded;
@@ -20994,7 +22387,7 @@ var TestGenerationService = class _TestGenerationService {
20994
22387
  const codeGenService = (await Promise.resolve().then(() => (init_code_generation_service(), code_generation_service_exports))).CodeGenerationService.getInstance();
20995
22388
  for (const file of files) {
20996
22389
  try {
20997
- const content = await fs6__namespace.readFile(file, "utf-8");
22390
+ const content = await fs11__namespace.readFile(file, "utf-8");
20998
22391
  const language = this.detectLanguage(file);
20999
22392
  const existingTest = existingTests.get(file);
21000
22393
  if (existingTest && existingTest.coverage > 80) {
@@ -21212,9 +22605,9 @@ BEGIN TEST GENERATION:
21212
22605
  async writeTestFiles(tests, ___framework) {
21213
22606
  for (const test of tests) {
21214
22607
  try {
21215
- const testDir = path5__namespace.dirname(test.testFile);
21216
- await fs6__namespace.mkdir(testDir, { recursive: true });
21217
- await fs6__namespace.writeFile(test.testFile, test.content, "utf-8");
22608
+ const testDir = path10__namespace.dirname(test.testFile);
22609
+ await fs11__namespace.mkdir(testDir, { recursive: true });
22610
+ await fs11__namespace.writeFile(test.testFile, test.content, "utf-8");
21218
22611
  logger.info(`Created test file: ${test.testFile}`);
21219
22612
  } catch (error) {
21220
22613
  logger.error(`Failed to write test file ${test.testFile}:`, error);
@@ -21345,19 +22738,19 @@ BEGIN TEST GENERATION:
21345
22738
  */
21346
22739
  // @ts-nocheck - Complex async type handling
21347
22740
  getTestFileName(file, __framework) {
21348
- const dir = path5__namespace.dirname(file);
21349
- const base = path5__namespace.basename(file, path5__namespace.extname(file));
21350
- const ext = path5__namespace.extname(file);
22741
+ const dir = path10__namespace.dirname(file);
22742
+ const base = path10__namespace.basename(file, path10__namespace.extname(file));
22743
+ const ext = path10__namespace.extname(file);
21351
22744
  if (framework === "Jest" || framework === "Vitest") {
21352
- return path5__namespace.join(dir, "__tests__", `${base}.test${ext}`);
22745
+ return path10__namespace.join(dir, "__tests__", `${base}.test${ext}`);
21353
22746
  } else if (framework === "Mocha") {
21354
- return path5__namespace.join(dir, "test", `${base}.spec${ext}`);
22747
+ return path10__namespace.join(dir, "test", `${base}.spec${ext}`);
21355
22748
  } else if (framework === "pytest") {
21356
- return path5__namespace.join(dir, `test_${base}.py`);
22749
+ return path10__namespace.join(dir, `test_${base}.py`);
21357
22750
  } else if (framework === "go test") {
21358
22751
  return file.replace(".go", "_test.go");
21359
22752
  } else {
21360
- return path5__namespace.join(dir, `${base}.test${ext}`);
22753
+ return path10__namespace.join(dir, `${base}.test${ext}`);
21361
22754
  }
21362
22755
  }
21363
22756
  /**
@@ -21365,7 +22758,7 @@ BEGIN TEST GENERATION:
21365
22758
  */
21366
22759
  // @ts-nocheck - Complex async type handling
21367
22760
  detectLanguage(file) {
21368
- const ext = path5__namespace.extname(file).toLowerCase();
22761
+ const ext = path10__namespace.extname(file).toLowerCase();
21369
22762
  const languageMap = {
21370
22763
  ".js": "javascript",
21371
22764
  ".jsx": "javascript",
@@ -21418,7 +22811,7 @@ var TestFrameworkDetector = class {
21418
22811
  }
21419
22812
  async detect() {
21420
22813
  try {
21421
- const packageJson = await fs6__namespace.readFile("package.json", "utf-8");
22814
+ const packageJson = await fs11__namespace.readFile("package.json", "utf-8");
21422
22815
  const pkg = JSON.parse(packageJson);
21423
22816
  if (pkg.devDependencies?.jest || pkg.scripts?.test?.includes("jest")) {
21424
22817
  return "Jest";
@@ -21432,12 +22825,12 @@ var TestFrameworkDetector = class {
21432
22825
  } catch {
21433
22826
  }
21434
22827
  try {
21435
- await fs6__namespace.access("pytest.ini");
22828
+ await fs11__namespace.access("pytest.ini");
21436
22829
  return "pytest";
21437
22830
  } catch {
21438
22831
  try {
21439
- await fs6__namespace.access("setup.cfg");
21440
- const content = await fs6__namespace.readFile("setup.cfg", "utf-8");
22832
+ await fs11__namespace.access("setup.cfg");
22833
+ const content = await fs11__namespace.readFile("setup.cfg", "utf-8");
21441
22834
  if (content.includes("[tool:pytest]")) {
21442
22835
  return "pytest";
21443
22836
  }
@@ -21445,12 +22838,12 @@ var TestFrameworkDetector = class {
21445
22838
  }
21446
22839
  }
21447
22840
  try {
21448
- await fs6__namespace.access("go.mod");
22841
+ await fs11__namespace.access("go.mod");
21449
22842
  return "go test";
21450
22843
  } catch {
21451
22844
  }
21452
22845
  try {
21453
- await fs6__namespace.access("Cargo.toml");
22846
+ await fs11__namespace.access("Cargo.toml");
21454
22847
  return "cargo test";
21455
22848
  } catch {
21456
22849
  }
@@ -22415,7 +23808,7 @@ Run /config to customize MARIA settings.`;
22415
23808
  async handleInit() {
22416
23809
  try {
22417
23810
  const rootPath = process.cwd();
22418
- const mariaPath = path5__namespace.join(rootPath, "MARIA.md");
23811
+ const mariaPath = path10__namespace.join(rootPath, "MARIA.md");
22419
23812
  const exists = fs7__namespace.existsSync(mariaPath);
22420
23813
  if (exists) {
22421
23814
  console.log("\u{1F4CA} Analyzing codebase for MARIA.md update...");
@@ -22573,14 +23966,14 @@ ${availableServers.map((server) => `\u2022 ${server.name}: ${server.description}
22573
23966
  }
22574
23967
  if (options.summary) {
22575
23968
  const summary = await this.chatContextService.exportContext("markdown");
22576
- const summaryPath = path5__namespace.join(
23969
+ const summaryPath = path10__namespace.join(
22577
23970
  process.env["HOME"] || "",
22578
23971
  ".maria",
22579
23972
  "summaries",
22580
23973
  `summary-${Date.now()}.md`
22581
23974
  );
22582
23975
  try {
22583
- await fs7__namespace.promises.mkdir(path5__namespace.dirname(summaryPath), { recursive: true });
23976
+ await fs7__namespace.promises.mkdir(path10__namespace.dirname(summaryPath), { recursive: true });
22584
23977
  await fs7__namespace.promises.writeFile(summaryPath, summary);
22585
23978
  this.chatContextService.clearContext({ summary: true });
22586
23979
  if (context.history) {
@@ -22680,8 +24073,8 @@ ${indicator}`,
22680
24073
  async handleResume(context) {
22681
24074
  const resumeFile = `${process.cwd()}/.maria-session.json`;
22682
24075
  try {
22683
- const fs11 = await import('fs/promises');
22684
- const resumeData = await fs11.readFile(resumeFile, "utf-8");
24076
+ const fs12 = await import('fs/promises');
24077
+ const resumeData = await fs12.readFile(resumeFile, "utf-8");
22685
24078
  const savedContext = JSON.parse(resumeData);
22686
24079
  if (!savedContext.history) {
22687
24080
  return {
@@ -22722,7 +24115,7 @@ ${indicator}`,
22722
24115
  )
22723
24116
  };
22724
24117
  }
22725
- await fs11.unlink(resumeFile);
24118
+ await fs12.unlink(resumeFile);
22726
24119
  return {
22727
24120
  success: true,
22728
24121
  message: `Conversation resumed: ${context.history.length} messages restored${context.currentTask ? ` (task: ${context.currentTask})` : ""}`,
@@ -22942,11 +24335,11 @@ ${allFeedback.slice(-3).map(
22942
24335
  severity: this.assessBugSeverity(bugType, description),
22943
24336
  reportId: `bug-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
22944
24337
  };
22945
- const fs11 = await import('fs/promises');
24338
+ const fs12 = await import('fs/promises');
22946
24339
  const reportsDir = `${process.cwd()}/.maria-reports`;
22947
24340
  try {
22948
- await fs11.mkdir(reportsDir, { recursive: true });
22949
- await fs11.writeFile(
24341
+ await fs12.mkdir(reportsDir, { recursive: true });
24342
+ await fs12.writeFile(
22950
24343
  `${reportsDir}/${bugReport.reportId}.json`,
22951
24344
  JSON.stringify(bugReport, null, 2)
22952
24345
  );
@@ -23122,10 +24515,10 @@ Vim keybindings disabled.`;
23122
24515
  }
23123
24516
  async handleVersion() {
23124
24517
  try {
23125
- const fs11 = await import('fs/promises');
23126
- const path9 = await import('path');
23127
- const packagePath = path9.resolve(process.cwd(), "package.json");
23128
- const packageData = JSON.parse(await fs11.readFile(packagePath, "utf8"));
24518
+ const fs12 = await import('fs/promises');
24519
+ const path11 = await import('path');
24520
+ const packagePath = path11.resolve(process.cwd(), "package.json");
24521
+ const packageData = JSON.parse(await fs12.readFile(packagePath, "utf8"));
23129
24522
  return {
23130
24523
  success: true,
23131
24524
  message: `MARIA CODE CLI v${packageData["version"] || "1.0.0"}
@@ -23417,8 +24810,8 @@ Try:
23417
24810
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
23418
24811
  const filename = `maria-aliases-${timestamp}.json`;
23419
24812
  try {
23420
- const fs11 = await import('fs/promises');
23421
- await fs11.writeFile(filename, exportData);
24813
+ const fs12 = await import('fs/promises');
24814
+ await fs12.writeFile(filename, exportData);
23422
24815
  return {
23423
24816
  success: true,
23424
24817
  message: `\u2705 Aliases exported to ${filename}
@@ -23441,8 +24834,8 @@ ${exportData}`
23441
24834
  };
23442
24835
  }
23443
24836
  try {
23444
- const fs11 = await import('fs/promises');
23445
- const jsonData = await fs11.readFile(filename, "utf-8");
24837
+ const fs12 = await import('fs/promises');
24838
+ const jsonData = await fs12.readFile(filename, "utf-8");
23446
24839
  return await this.aliasSystem.importAliases(jsonData);
23447
24840
  } catch (error) {
23448
24841
  return {
@@ -23651,8 +25044,8 @@ Available commands: run, save, delete, view, export, import`
23651
25044
  };
23652
25045
  }
23653
25046
  try {
23654
- const fs11 = await import('fs/promises');
23655
- const content = await fs11.readFile(filename, "utf-8");
25047
+ const fs12 = await import('fs/promises');
25048
+ const content = await fs12.readFile(filename, "utf-8");
23656
25049
  const commands2 = this.batchEngine.parseBatchString(content);
23657
25050
  const result = await this.batchEngine.executeBatch(commands2, context, {
23658
25051
  stopOnError: true
@@ -23831,8 +25224,8 @@ Batch execution ${result.success ? "completed successfully" : "completed with er
23831
25224
  const config2 = this.hotkeyManager.exportConfig();
23832
25225
  const filename = `hotkeys-${Date.now()}.json`;
23833
25226
  try {
23834
- const fs11 = await import('fs/promises');
23835
- await fs11.writeFile(filename, JSON.stringify(config2, null, 2));
25227
+ const fs12 = await import('fs/promises');
25228
+ await fs12.writeFile(filename, JSON.stringify(config2, null, 2));
23836
25229
  return {
23837
25230
  success: true,
23838
25231
  message: `\u2705 Hotkey configuration exported to ${filename}`,
@@ -23854,8 +25247,8 @@ Batch execution ${result.success ? "completed successfully" : "completed with er
23854
25247
  };
23855
25248
  }
23856
25249
  try {
23857
- const fs11 = await import('fs/promises');
23858
- const content = await fs11.readFile(filename, "utf-8");
25250
+ const fs12 = await import('fs/promises');
25251
+ const content = await fs12.readFile(filename, "utf-8");
23859
25252
  const config2 = JSON.parse(content);
23860
25253
  const result = this.hotkeyManager.importConfig(
23861
25254
  config2
@@ -23906,7 +25299,7 @@ Batch execution ${result.success ? "completed successfully" : "completed with er
23906
25299
  const shouldSave = context.history && context.history.length > 0;
23907
25300
  if (shouldSave) {
23908
25301
  try {
23909
- const fs11 = await import('fs/promises');
25302
+ const fs12 = await import('fs/promises');
23910
25303
  const sessionFile = `${process.cwd()}/.maria-session.json`;
23911
25304
  const sessionData = {
23912
25305
  sessionId: context.sessionId,
@@ -23915,7 +25308,7 @@ Batch execution ${result.success ? "completed successfully" : "completed with er
23915
25308
  metadata: context.metadata,
23916
25309
  savedAt: (/* @__PURE__ */ new Date()).toISOString()
23917
25310
  };
23918
- await fs11.writeFile(sessionFile, JSON.stringify(sessionData, null, 2));
25311
+ await fs12.writeFile(sessionFile, JSON.stringify(sessionData, null, 2));
23919
25312
  const stats = {
23920
25313
  messages: context.history?.length || 0,
23921
25314
  cost: context.metadata?.["cost"] || 0,
@@ -23946,8 +25339,8 @@ Session saved: ${stats.messages} messages, $${stats.cost.toFixed(6)}, ${Math.flo
23946
25339
  async handleMigrateInstaller() {
23947
25340
  try {
23948
25341
  const { execSync } = await import('child_process');
23949
- const fs11 = await import('fs/promises');
23950
- const path9 = await import('path');
25342
+ const fs12 = await import('fs/promises');
25343
+ const path11 = await import('path');
23951
25344
  const globalInstallCheck = {
23952
25345
  npm: false,
23953
25346
  yarn: false,
@@ -23970,11 +25363,11 @@ Session saved: ${stats.messages} messages, $${stats.cost.toFixed(6)}, ${Math.flo
23970
25363
  } catch {
23971
25364
  }
23972
25365
  const cwd = process.cwd();
23973
- const packageJsonPath = path9.join(cwd, "package.json");
25366
+ const packageJsonPath = path11.join(cwd, "package.json");
23974
25367
  let localInstall = false;
23975
25368
  let packageJson = null;
23976
25369
  try {
23977
- const packageJsonContent = await fs11.readFile(packageJsonPath, "utf-8");
25370
+ const packageJsonContent = await fs12.readFile(packageJsonPath, "utf-8");
23978
25371
  packageJson = JSON.parse(packageJsonContent);
23979
25372
  const typedPackage = packageJson;
23980
25373
  localInstall = !!(typedPackage["dependencies"]?.["@maria/code-cli"] || typedPackage["devDependencies"]?.["@maria/code-cli"]);
@@ -24232,7 +25625,7 @@ Run the steps above to complete your migration!`;
24232
25625
  devDependencies: []
24233
25626
  }
24234
25627
  };
24235
- const gitignorePath = path5__namespace.join(rootPath, ".gitignore");
25628
+ const gitignorePath = path10__namespace.join(rootPath, ".gitignore");
24236
25629
  const ignorePatterns = fs7__namespace.existsSync(gitignorePath) ? fs7__namespace.readFileSync(gitignorePath, "utf8").split("\n").filter((line) => line.trim() && !line.startsWith("#")) : ["node_modules", ".git", "dist", "build", ".env*"];
24237
25630
  await this.analyzeDirectory(rootPath, rootPath, analysis, ignorePatterns);
24238
25631
  this.inferTechStack(analysis);
@@ -24243,8 +25636,8 @@ Run the steps above to complete your migration!`;
24243
25636
  try {
24244
25637
  const items = fs7__namespace.readdirSync(currentPath);
24245
25638
  for (const item of items) {
24246
- const itemPath = path5__namespace.join(currentPath, item);
24247
- const relativePath = path5__namespace.relative(rootPath, itemPath);
25639
+ const itemPath = path10__namespace.join(currentPath, item);
25640
+ const relativePath = path10__namespace.relative(rootPath, itemPath);
24248
25641
  if (this.shouldIgnore(relativePath, ignorePatterns)) continue;
24249
25642
  const stat2 = fs7__namespace.statSync(itemPath);
24250
25643
  if (stat2.isDirectory()) {
@@ -24253,7 +25646,7 @@ Run the steps above to complete your migration!`;
24253
25646
  } else if (stat2.isFile()) {
24254
25647
  analysis.files.push(relativePath);
24255
25648
  analysis.fileCount++;
24256
- const ext = path5__namespace.extname(item).toLowerCase();
25649
+ const ext = path10__namespace.extname(item).toLowerCase();
24257
25650
  const language = this.getLanguageFromExtension(ext);
24258
25651
  if (language && !analysis.languages.includes(language)) {
24259
25652
  analysis.languages.push(language);
@@ -24325,7 +25718,7 @@ Run the steps above to complete your migration!`;
24325
25718
  analysis.techStack.push("Lerna");
24326
25719
  }
24327
25720
  try {
24328
- const packageJsonPath = path5__namespace.join(rootPath, "package.json");
25721
+ const packageJsonPath = path10__namespace.join(rootPath, "package.json");
24329
25722
  if (fs7__namespace.existsSync(packageJsonPath)) {
24330
25723
  const packageJson = JSON.parse(fs7__namespace.readFileSync(packageJsonPath, "utf8"));
24331
25724
  analysis.dependencies = {
@@ -24350,7 +25743,7 @@ Run the steps above to complete your migration!`;
24350
25743
  analysis.techStack = [...new Set(analysis.techStack)];
24351
25744
  }
24352
25745
  async createMariaMd(rootPath, analysis) {
24353
- const projectName = path5__namespace.basename(rootPath);
25746
+ const projectName = path10__namespace.basename(rootPath);
24354
25747
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
24355
25748
  return `# MARIA.md
24356
25749
 
@@ -25654,17 +27047,36 @@ async function showModels(maria) {
25654
27047
  try {
25655
27048
  const models = await maria.getModels();
25656
27049
  const available = models.filter((m) => m.available);
25657
- if (available.length === 0) {
25658
- console.log(chalk13__default.default.yellow("No models available"));
27050
+ const unavailable = models.filter((m) => !m.available);
27051
+ if (available.length === 0 && unavailable.length === 0) {
27052
+ console.log(chalk13__default.default.yellow("No models found"));
25659
27053
  return;
25660
27054
  }
25661
- for (const model of available) {
25662
- const provider = chalk13__default.default.gray(`[${model.provider}]`);
25663
- const capabilities = model.capabilities ? model.capabilities.join(", ") : "No capabilities listed";
25664
- console.log(`\u2705 ${chalk13__default.default.bold(model.name)} ${provider}`);
25665
- console.log(` ${chalk13__default.default.gray(capabilities)}`);
27055
+ if (available.length > 0) {
27056
+ console.log(chalk13__default.default.green("\u2705 Available Models:"));
27057
+ for (const model of available) {
27058
+ const provider = chalk13__default.default.gray(`[${model.provider}]`);
27059
+ const capabilities = model.capabilities ? model.capabilities.join(", ") : "No capabilities listed";
27060
+ console.log(` \u2705 ${chalk13__default.default.bold(model.name)} ${provider}`);
27061
+ console.log(` ${chalk13__default.default.gray(capabilities)}`);
27062
+ }
27063
+ console.log("");
27064
+ }
27065
+ if (unavailable.length > 0) {
27066
+ console.log(chalk13__default.default.yellow("\u26A0\uFE0F Cloud Models (Require API Keys):"));
27067
+ for (const model of unavailable) {
27068
+ const provider = chalk13__default.default.gray(`[${model.provider}]`);
27069
+ const capabilities = model.capabilities ? model.capabilities.join(", ") : "No capabilities listed";
27070
+ console.log(` \u274C ${chalk13__default.default.white(model.name)} ${provider}`);
27071
+ console.log(` ${chalk13__default.default.gray(capabilities)}`);
27072
+ }
27073
+ console.log("");
27074
+ console.log(chalk13__default.default.gray("\u{1F4A1} To use cloud models, set environment variables:"));
27075
+ console.log(chalk13__default.default.cyan(" export OPENAI_API_KEY=your_key"));
27076
+ console.log(chalk13__default.default.cyan(" export ANTHROPIC_API_KEY=your_key"));
27077
+ console.log(chalk13__default.default.cyan(" export GOOGLE_API_KEY=your_key"));
27078
+ console.log("");
25666
27079
  }
25667
- console.log("");
25668
27080
  } catch (error) {
25669
27081
  console.error(chalk13__default.default.red("\u274C Failed to get models:"), error);
25670
27082
  }
@@ -25731,32 +27143,40 @@ async function showModelSelector(maria, args) {
25731
27143
  try {
25732
27144
  const models = await maria.getModels();
25733
27145
  const available = models.filter((m) => m.available);
27146
+ const allModels = models;
25734
27147
  if (args.length > 0) {
25735
27148
  const modelName = args.join(" ");
25736
- const targetModel = available.find(
27149
+ const targetModel = allModels.find(
25737
27150
  (m) => m.name.toLowerCase().includes(modelName.toLowerCase()) || m.provider.toLowerCase().includes(modelName.toLowerCase())
25738
27151
  );
25739
27152
  if (targetModel) {
25740
- console.log(
25741
- chalk13__default.default.green(`\u2705 Target model found: ${targetModel.name} (${targetModel.provider})`)
25742
- );
25743
- console.log(chalk13__default.default.yellow("Note: Model switching will be implemented in a future version"));
25744
- console.log(
25745
- chalk13__default.default.gray("Currently, you can switch models using environment variables or CLI options")
25746
- );
27153
+ if (targetModel.available) {
27154
+ console.log(
27155
+ chalk13__default.default.green(`\u2705 Target model found: ${targetModel.name} (${targetModel.provider})`)
27156
+ );
27157
+ console.log(chalk13__default.default.yellow("Note: Model switching will be implemented in a future version"));
27158
+ console.log(
27159
+ chalk13__default.default.gray("Currently, you can switch models using environment variables or CLI options")
27160
+ );
27161
+ } else {
27162
+ console.log(
27163
+ chalk13__default.default.yellow(`\u26A0\uFE0F Target model found but unavailable: ${targetModel.name} (${targetModel.provider})`)
27164
+ );
27165
+ console.log(chalk13__default.default.gray(`This model requires API key for ${targetModel.provider}`));
27166
+ }
25747
27167
  } else {
25748
27168
  console.log(chalk13__default.default.red(`\u274C Model not found: ${modelName}`));
25749
27169
  console.log(chalk13__default.default.gray("Available models listed below:"));
25750
27170
  }
25751
27171
  return;
25752
27172
  }
25753
- await showInteractiveModelSelector(available);
27173
+ await showInteractiveModelSelector(allModels, maria);
25754
27174
  } catch (error) {
25755
27175
  console.error(chalk13__default.default.red("\u274C Failed to access model selector:"), error);
25756
27176
  }
25757
27177
  }
25758
27178
  __name(showModelSelector, "showModelSelector");
25759
- async function showInteractiveModelSelector(models) {
27179
+ async function showInteractiveModelSelector(models, maria) {
25760
27180
  if (models.length === 0) {
25761
27181
  console.log(chalk13__default.default.yellow("No models available"));
25762
27182
  return;
@@ -25770,27 +27190,43 @@ async function showInteractiveModelSelector(models) {
25770
27190
  process.stdout.write("\x1B[2J\x1B[0;0f");
25771
27191
  console.log(chalk13__default.default.blue("\u{1F916} AI Model Selector\n"));
25772
27192
  console.log(chalk13__default.default.gray("Use \u2191/\u2193 to navigate, Enter to select, Esc to cancel\n"));
27193
+ const currentModel = maria.getCurrentModel();
27194
+ if (currentModel) {
27195
+ console.log(chalk13__default.default.green(`\u{1F3AF} Current Active Model: ${currentModel.name} (${currentModel.provider})
27196
+ `));
27197
+ } else {
27198
+ console.log(chalk13__default.default.yellow(`\u{1F3AF} Current Active Model: gpt-5-mini (openai) - Default
27199
+ `));
27200
+ }
25773
27201
  console.log(chalk13__default.default.yellow("\u{1F4CB} Available AI Models:\n"));
25774
27202
  models.forEach((model, index) => {
25775
- const status = model.available ? "\u2705" : "\u26A0\uFE0F";
27203
+ const status = model.available ? "\u2705" : "\u274C";
25776
27204
  const pricing = model.pricing ? ` ($${model.pricing.input}/${model.pricing.output})` : "";
25777
27205
  const isSelected = index === selectedIndex;
27206
+ const availabilityNote = model.available ? "" : " (API key required)";
25778
27207
  if (isSelected) {
25779
27208
  console.log(
25780
- chalk13__default.default.bgBlue.white(` \u25B6 ${status} ${model.name} [${model.provider}]${pricing}`)
27209
+ chalk13__default.default.bgBlue.white(` \u25B6 ${status} ${model.name} [${model.provider}]${pricing}${availabilityNote}`)
25781
27210
  );
25782
27211
  console.log(chalk13__default.default.bgBlue.white(` ${model.description}`));
25783
27212
  if (model.capabilities && model.capabilities.length > 0) {
25784
27213
  console.log(chalk13__default.default.bgBlue.white(` Capabilities: ${model.capabilities.join(", ")}`));
25785
27214
  }
27215
+ if (!model.available) {
27216
+ console.log(chalk13__default.default.bgBlue.white(` Status: Requires ${model.provider.toUpperCase()}_API_KEY environment variable`));
27217
+ }
25786
27218
  } else {
27219
+ const nameColor = model.available ? chalk13__default.default.bold : chalk13__default.default.white;
25787
27220
  console.log(
25788
- ` ${status} ${chalk13__default.default.bold(model.name)} ${chalk13__default.default.gray(`[${model.provider}]`)}${pricing}`
27221
+ ` ${status} ${nameColor(model.name)} ${chalk13__default.default.gray(`[${model.provider}]`)}${pricing}${availabilityNote}`
25789
27222
  );
25790
27223
  console.log(` ${chalk13__default.default.gray(model.description)}`);
25791
27224
  if (model.capabilities && model.capabilities.length > 0) {
25792
27225
  console.log(` ${chalk13__default.default.cyan("Capabilities:")} ${model.capabilities.join(", ")}`);
25793
27226
  }
27227
+ if (!model.available) {
27228
+ console.log(` ${chalk13__default.default.yellow("Status:")} Requires ${model.provider.toUpperCase()}_API_KEY environment variable`);
27229
+ }
25794
27230
  }
25795
27231
  console.log("");
25796
27232
  });
@@ -25801,7 +27237,7 @@ async function showInteractiveModelSelector(models) {
25801
27237
  stdin.removeAllListeners("data");
25802
27238
  }, "cleanup");
25803
27239
  return new Promise((resolve) => {
25804
- const handleKeypress = /* @__PURE__ */ __name((chunk) => {
27240
+ const handleKeypress = /* @__PURE__ */ __name(async (chunk) => {
25805
27241
  const key = chunk.toString();
25806
27242
  switch (key) {
25807
27243
  case "\x1B[A":
@@ -25813,31 +27249,45 @@ async function showInteractiveModelSelector(models) {
25813
27249
  renderModels();
25814
27250
  break;
25815
27251
  case "\r":
25816
- isSelecting = false;
25817
27252
  cleanup();
25818
27253
  const selectedModel = models[selectedIndex];
25819
- console.log(
25820
- chalk13__default.default.green(`
25821
- \u2705 Selected: ${selectedModel.name} (${selectedModel.provider})`)
25822
- );
25823
- console.log(
25824
- chalk13__default.default.yellow("Note: Model switching will be implemented in a future version")
25825
- );
25826
- console.log(
25827
- chalk13__default.default.gray(
25828
- "Currently, you can switch models using environment variables or CLI options\n"
25829
- )
25830
- );
27254
+ if (selectedModel.available) {
27255
+ try {
27256
+ const result = await maria.switchModel(selectedModel.id);
27257
+ if (result.success) {
27258
+ console.log(chalk13__default.default.green(`
27259
+ \u2705 ${result.message}`));
27260
+ console.log(chalk13__default.default.gray("Model switch completed successfully\n"));
27261
+ } else {
27262
+ console.log(chalk13__default.default.red(`
27263
+ \u274C ${result.message}
27264
+ `));
27265
+ }
27266
+ } catch (error) {
27267
+ console.log(chalk13__default.default.red(`
27268
+ \u274C Failed to switch model: ${error}
27269
+ `));
27270
+ }
27271
+ } else {
27272
+ console.log(
27273
+ chalk13__default.default.yellow(`
27274
+ \u26A0\uFE0F Selected: ${selectedModel.name} (${selectedModel.provider})`)
27275
+ );
27276
+ console.log(
27277
+ chalk13__default.default.red(`\u274C This model is not available. Please set ${selectedModel.provider.toUpperCase()}_API_KEY environment variable.`)
27278
+ );
27279
+ console.log(chalk13__default.default.gray("Example:"));
27280
+ console.log(chalk13__default.default.cyan(` export ${selectedModel.provider.toUpperCase()}_API_KEY=your_api_key`));
27281
+ console.log("");
27282
+ }
25831
27283
  resolve();
25832
27284
  break;
25833
27285
  case "\x1B":
25834
- isSelecting = false;
25835
27286
  cleanup();
25836
27287
  console.log(chalk13__default.default.gray("\n\u{1F4CB} Model selection cancelled\n"));
25837
27288
  resolve();
25838
27289
  break;
25839
27290
  case "":
25840
- isSelecting = false;
25841
27291
  cleanup();
25842
27292
  console.log(chalk13__default.default.gray("\n\u{1F4CB} Model selection cancelled\n"));
25843
27293
  resolve();
@@ -25853,7 +27303,7 @@ async function showAvatar() {
25853
27303
  console.log(chalk13__default.default.blue("\n\u{1F3AD} MARIA Avatar Interface\n"));
25854
27304
  const avatarPath = "/Users/bongin_max/maria_code/face_only_96x96_ramp.txt";
25855
27305
  try {
25856
- const avatarData = await fs6__namespace.readFile(avatarPath, "utf-8");
27306
+ const avatarData = await fs11__namespace.readFile(avatarPath, "utf-8");
25857
27307
  const lines = avatarData.split("\n").slice(0, 30);
25858
27308
  console.log(chalk13__default.default.white("\u2550".repeat(80)));
25859
27309
  lines.forEach((line) => {
@@ -26936,13 +28386,13 @@ __name(loadConfig2, "loadConfig");
26936
28386
  async function loadEnvironmentConfig() {
26937
28387
  try {
26938
28388
  const { importNodeBuiltin: importNodeBuiltin2, safeDynamicImport: safeDynamicImport2 } = await Promise.resolve().then(() => (init_import_helper(), import_helper_exports));
26939
- const fs11 = await safeDynamicImport2("fs-extra").catch(
28389
+ const fs12 = await safeDynamicImport2("fs-extra").catch(
26940
28390
  () => importNodeBuiltin2("fs")
26941
28391
  );
26942
- const path9 = await importNodeBuiltin2("path");
26943
- const envPath = path9.join(process.cwd(), ".env.local");
26944
- if (await fs11.pathExists(envPath)) {
26945
- const envContent = await fs11.readFile(envPath, "utf-8");
28392
+ const path11 = await importNodeBuiltin2("path");
28393
+ const envPath = path11.join(process.cwd(), ".env.local");
28394
+ if (await fs12.pathExists(envPath)) {
28395
+ const envContent = await fs12.readFile(envPath, "utf-8");
26946
28396
  if (process.env["DEBUG"]) {
26947
28397
  console.log("Loading environment from:", envPath);
26948
28398
  }
@@ -27022,7 +28472,7 @@ async function checkOllamaInstalled() {
27022
28472
  __name(checkOllamaInstalled, "checkOllamaInstalled");
27023
28473
  async function installOllama() {
27024
28474
  return new Promise((resolve, reject) => {
27025
- const platform = os2__default.default.platform();
28475
+ const platform = os3__default.default.platform();
27026
28476
  if (platform === "darwin") {
27027
28477
  const brewChild = child_process.spawn("brew", ["install", "ollama"], { stdio: "inherit" });
27028
28478
  brewChild.on("close", (code) => {
@@ -27114,15 +28564,15 @@ async function downloadOllamaModel(model) {
27114
28564
  }
27115
28565
  __name(downloadOllamaModel, "downloadOllamaModel");
27116
28566
  async function setupEnvironmentVariables() {
27117
- const homeDir = os2__default.default.homedir();
28567
+ const homeDir = os3__default.default.homedir();
27118
28568
  const shell = process.env["SHELL"] || "/bin/bash";
27119
28569
  let rcFile = "";
27120
28570
  if (shell.includes("zsh")) {
27121
- rcFile = path5__namespace.default.join(homeDir, ".zshrc");
28571
+ rcFile = path10__namespace.default.join(homeDir, ".zshrc");
27122
28572
  } else if (shell.includes("bash")) {
27123
- rcFile = path5__namespace.default.join(homeDir, ".bashrc");
28573
+ rcFile = path10__namespace.default.join(homeDir, ".bashrc");
27124
28574
  } else {
27125
- rcFile = path5__namespace.default.join(homeDir, ".profile");
28575
+ rcFile = path10__namespace.default.join(homeDir, ".profile");
27126
28576
  }
27127
28577
  const envVars = `
27128
28578
  # MARIA Ollama Configuration
@@ -27181,8 +28631,8 @@ function registerSetupVllmCommand(program) {
27181
28631
  if (!options.skipPythonCheck) {
27182
28632
  await checkPythonVersion();
27183
28633
  }
27184
- const venvPath = options.venvPath.replace("~", os2__default.default.homedir());
27185
- const modelDir = options.modelDir.replace("~", os2__default.default.homedir());
28634
+ const venvPath = options.venvPath.replace("~", os3__default.default.homedir());
28635
+ const modelDir = options.modelDir.replace("~", os3__default.default.homedir());
27186
28636
  console.log(chalk13__default.default.yellow("\u{1F40D} Creating Python virtual environment..."));
27187
28637
  await createVirtualEnvironment(venvPath);
27188
28638
  console.log(chalk13__default.default.yellow("\u{1F4E6} Installing vLLM and dependencies..."));
@@ -27261,7 +28711,7 @@ async function createVirtualEnvironment(venvPath) {
27261
28711
  }
27262
28712
  __name(createVirtualEnvironment, "createVirtualEnvironment");
27263
28713
  async function installVllm(venvPath) {
27264
- const pipPath = path5__namespace.default.join(venvPath, "bin", "pip");
28714
+ const pipPath = path10__namespace.default.join(venvPath, "bin", "pip");
27265
28715
  return new Promise((resolve, reject) => {
27266
28716
  const upgradeChild = child_process.spawn(pipPath, ["install", "--upgrade", "pip"], { stdio: "inherit" });
27267
28717
  upgradeChild.on("close", (code) => {
@@ -27285,8 +28735,8 @@ async function installVllm(venvPath) {
27285
28735
  }
27286
28736
  __name(installVllm, "installVllm");
27287
28737
  async function downloadModel(venvPath, modelName, modelDir) {
27288
- const pythonPath = path5__namespace.default.join(venvPath, "bin", "python");
27289
- const modelPath = path5__namespace.default.join(modelDir, modelName.replace("/", "_"));
28738
+ const pythonPath = path10__namespace.default.join(venvPath, "bin", "python");
28739
+ const modelPath = path10__namespace.default.join(modelDir, modelName.replace("/", "_"));
27290
28740
  return new Promise((resolve, reject) => {
27291
28741
  console.log(chalk13__default.default.cyan(` Downloading ${modelName}...`));
27292
28742
  const downloadScript = `
@@ -27317,9 +28767,9 @@ except Exception as e:
27317
28767
  }
27318
28768
  __name(downloadModel, "downloadModel");
27319
28769
  async function createStartupScript(venvPath, modelDir, defaultModel) {
27320
- const scriptsDir = path5__namespace.default.join(process.cwd(), "scripts");
27321
- const scriptPath = path5__namespace.default.join(scriptsDir, "start-vllm.sh");
27322
- const modelPath = path5__namespace.default.join(modelDir, defaultModel.replace("/", "_"));
28770
+ const scriptsDir = path10__namespace.default.join(process.cwd(), "scripts");
28771
+ const scriptPath = path10__namespace.default.join(scriptsDir, "start-vllm.sh");
28772
+ const modelPath = path10__namespace.default.join(modelDir, defaultModel.replace("/", "_"));
27323
28773
  const scriptContent = `#!/bin/bash
27324
28774
 
27325
28775
  # MARIA vLLM Startup Script
@@ -27380,15 +28830,15 @@ done
27380
28830
  }
27381
28831
  __name(createStartupScript, "createStartupScript");
27382
28832
  async function setupEnvironmentVariables2() {
27383
- const homeDir = os2__default.default.homedir();
28833
+ const homeDir = os3__default.default.homedir();
27384
28834
  const shell = process.env["SHELL"] || "/bin/bash";
27385
28835
  let rcFile = "";
27386
28836
  if (shell.includes("zsh")) {
27387
- rcFile = path5__namespace.default.join(homeDir, ".zshrc");
28837
+ rcFile = path10__namespace.default.join(homeDir, ".zshrc");
27388
28838
  } else if (shell.includes("bash")) {
27389
- rcFile = path5__namespace.default.join(homeDir, ".bashrc");
28839
+ rcFile = path10__namespace.default.join(homeDir, ".bashrc");
27390
28840
  } else {
27391
- rcFile = path5__namespace.default.join(homeDir, ".profile");
28841
+ rcFile = path10__namespace.default.join(homeDir, ".profile");
27392
28842
  }
27393
28843
  const envVars = `
27394
28844
  # MARIA vLLM Configuration
@@ -27412,14 +28862,14 @@ export VLLM_DEFAULT_MODEL="DialoGPT-medium"
27412
28862
  __name(setupEnvironmentVariables2, "setupEnvironmentVariables");
27413
28863
  async function testVllmSetup(venvPath, modelDir, defaultModel) {
27414
28864
  console.log(chalk13__default.default.yellow("\u{1F9EA} Testing vLLM setup..."));
27415
- const pythonPath = path5__namespace.default.join(venvPath, "bin", "python");
28865
+ const pythonPath = path10__namespace.default.join(venvPath, "bin", "python");
27416
28866
  try {
27417
28867
  await fs7.promises.access(pythonPath);
27418
28868
  console.log(chalk13__default.default.green("\u2705 Virtual environment test passed"));
27419
28869
  } catch (error) {
27420
28870
  throw new Error("Virtual environment not found");
27421
28871
  }
27422
- const modelPath = path5__namespace.default.join(modelDir, defaultModel.replace("/", "_"));
28872
+ const modelPath = path10__namespace.default.join(modelDir, defaultModel.replace("/", "_"));
27423
28873
  try {
27424
28874
  await fs7.promises.access(modelPath);
27425
28875
  console.log(chalk13__default.default.green("\u2705 Model directory test passed"));
@@ -27460,14 +28910,14 @@ ${chalk13__default.default.cyan("Examples:")}
27460
28910
  ${chalk13__default.default.gray("$")} maria coderag similar "function calc()" # Find similar patterns
27461
28911
  `
27462
28912
  );
27463
- coderagCommand.command("index").argument("<path>", "Path to codebase directory").option("--types <types>", "File types to include (comma-separated)", ".ts,.tsx,.js,.jsx").option("--exclude <paths>", "Paths to exclude (comma-separated)", "node_modules,dist,.git").option("--chunk-size <size>", "Chunk size for indexing", "500").description("Index codebase for vector search").action(async (path9, options) => {
28913
+ coderagCommand.command("index").argument("<path>", "Path to codebase directory").option("--types <types>", "File types to include (comma-separated)", ".ts,.tsx,.js,.jsx").option("--exclude <paths>", "Paths to exclude (comma-separated)", "node_modules,dist,.git").option("--chunk-size <size>", "Chunk size for indexing", "500").description("Index codebase for vector search").action(async (path11, options) => {
27464
28914
  try {
27465
28915
  console.log(chalk13__default.default.blue("\u{1F50D} Indexing codebase for CodeRAG..."));
27466
- console.log(chalk13__default.default.gray(`Path: ${path9}`));
28916
+ console.log(chalk13__default.default.gray(`Path: ${path11}`));
27467
28917
  const fileTypes = options.types.split(",").map((t) => t.trim());
27468
28918
  const excludePaths = options.exclude.split(",").map((p) => p.trim());
27469
28919
  await codeRAGService.initialize();
27470
- const result = await codeRAGService.indexCodebase(path9, {
28920
+ const result = await codeRAGService.indexCodebase(path11, {
27471
28921
  fileTypes,
27472
28922
  excludePaths,
27473
28923
  chunkSize: parseInt(options.chunkSize, 10),
@@ -27622,8 +29072,8 @@ ${chalk13__default.default.cyan("Examples:")}
27622
29072
  if (status.indexedPaths.length > 0) {
27623
29073
  console.log();
27624
29074
  console.log(chalk13__default.default.cyan("Indexed paths:"));
27625
- status.indexedPaths.forEach((path9) => {
27626
- console.log(` \u2022 ${path9}`);
29075
+ status.indexedPaths.forEach((path11) => {
29076
+ console.log(` \u2022 ${path11}`);
27627
29077
  });
27628
29078
  }
27629
29079
  } catch (error) {
@@ -28375,7 +29825,7 @@ __name(handleApprovalShow, "handleApprovalShow");
28375
29825
 
28376
29826
  // package.json
28377
29827
  var package_default = {
28378
- version: "2.0.4"};
29828
+ version: "2.0.7"};
28379
29829
 
28380
29830
  // src/cli.ts
28381
29831
  function createCLI() {
@@ -28463,7 +29913,7 @@ __name(generateCode, "generateCode");
28463
29913
  async function processVision(imagePath, prompt, config2) {
28464
29914
  const maria = new MariaAI(config2);
28465
29915
  await maria.initialize();
28466
- const fs11 = await (async () => {
29916
+ const fs12 = await (async () => {
28467
29917
  try {
28468
29918
  return await import('fs-extra');
28469
29919
  } catch {
@@ -28473,7 +29923,7 @@ async function processVision(imagePath, prompt, config2) {
28473
29923
  })();
28474
29924
  try {
28475
29925
  console.log(chalk13__default.default.blue("\u{1F441}\uFE0F Analyzing image..."));
28476
- const imageBuffer = await fs11.readFile(imagePath);
29926
+ const imageBuffer = await fs12.readFile(imagePath);
28477
29927
  const response = await maria.vision(imageBuffer, prompt);
28478
29928
  console.log("\n" + chalk13__default.default.green(response.content));
28479
29929
  } catch (error) {
@@ -28571,7 +30021,500 @@ async function checkHealth(options) {
28571
30021
  }
28572
30022
  __name(checkHealth, "checkHealth");
28573
30023
 
30024
+ // src/slash-commands/index.ts
30025
+ init_cjs_shims();
30026
+
30027
+ // src/slash-commands/types.ts
30028
+ init_cjs_shims();
30029
+ var CommandError = class extends Error {
30030
+ constructor(message, code, statusCode = 400, details) {
30031
+ super(message);
30032
+ this.code = code;
30033
+ this.statusCode = statusCode;
30034
+ this.details = details;
30035
+ this.name = "CommandError";
30036
+ }
30037
+ static {
30038
+ __name(this, "CommandError");
30039
+ }
30040
+ };
30041
+
30042
+ // src/slash-commands/index.ts
30043
+ init_base_command();
30044
+
30045
+ // src/slash-commands/registry.ts
30046
+ init_cjs_shims();
30047
+ init_logger();
30048
+ var CommandRegistry = class {
30049
+ static {
30050
+ __name(this, "CommandRegistry");
30051
+ }
30052
+ commands = /* @__PURE__ */ new Map();
30053
+ aliases = /* @__PURE__ */ new Map();
30054
+ middlewares = /* @__PURE__ */ new Map();
30055
+ rateLimits = /* @__PURE__ */ new Map();
30056
+ _initialized = false;
30057
+ get initialized() {
30058
+ return this._initialized;
30059
+ }
30060
+ set initialized(value) {
30061
+ this._initialized = value;
30062
+ }
30063
+ constructor() {
30064
+ this.setupDefaultMiddlewares();
30065
+ }
30066
+ /**
30067
+ * Register a command
30068
+ */
30069
+ register(command) {
30070
+ if (this.commands.has(command.name)) {
30071
+ logger.warn(`Command ${command.name} already registered, overwriting`);
30072
+ }
30073
+ this.commands.set(command.name, command);
30074
+ if (command.aliases) {
30075
+ for (const alias of command.aliases) {
30076
+ if (this.aliases.has(alias)) {
30077
+ logger.warn(`Alias ${alias} already registered, overwriting`);
30078
+ }
30079
+ this.aliases.set(alias, command.name);
30080
+ }
30081
+ }
30082
+ logger.info(`Registered command: ${command.name}`);
30083
+ }
30084
+ /**
30085
+ * Unregister a command
30086
+ */
30087
+ unregister(name) {
30088
+ const command = this.commands.get(name);
30089
+ if (!command) {
30090
+ return false;
30091
+ }
30092
+ if (command.aliases) {
30093
+ for (const alias of command.aliases) {
30094
+ this.aliases.delete(alias);
30095
+ }
30096
+ }
30097
+ if (command.cleanup) {
30098
+ command.cleanup().catch((err) => logger.error(`Error cleaning up command ${name}:`, err));
30099
+ }
30100
+ this.commands.delete(name);
30101
+ return true;
30102
+ }
30103
+ /**
30104
+ * Get a command by name or alias
30105
+ */
30106
+ get(nameOrAlias) {
30107
+ const cleanName = nameOrAlias.startsWith("/") ? nameOrAlias.slice(1) : nameOrAlias;
30108
+ const command = this.commands.get(cleanName);
30109
+ if (command) {
30110
+ return command;
30111
+ }
30112
+ const actualName = this.aliases.get(cleanName);
30113
+ if (actualName) {
30114
+ return this.commands.get(actualName);
30115
+ }
30116
+ return void 0;
30117
+ }
30118
+ /**
30119
+ * Check if a command exists
30120
+ */
30121
+ has(nameOrAlias) {
30122
+ return this.get(nameOrAlias) !== void 0;
30123
+ }
30124
+ /**
30125
+ * Get all registered commands
30126
+ */
30127
+ getAll() {
30128
+ return Array.from(this.commands.values());
30129
+ }
30130
+ /**
30131
+ * Get commands by category
30132
+ */
30133
+ getByCategory(category) {
30134
+ return this.getAll().filter((cmd) => cmd.category === category);
30135
+ }
30136
+ /**
30137
+ * Execute a command
30138
+ */
30139
+ async execute(commandName, args, context) {
30140
+ const startTime = Date.now();
30141
+ try {
30142
+ const command = this.get(commandName);
30143
+ if (!command) {
30144
+ return {
30145
+ success: false,
30146
+ message: `Command not found: ${commandName}`,
30147
+ data: {
30148
+ suggestions: this.getSuggestions(commandName)
30149
+ }
30150
+ };
30151
+ }
30152
+ const parsedArgs = this.parseArguments(args);
30153
+ if (command.rateLimit) {
30154
+ const rateLimitResult = this.checkRateLimit(command, context);
30155
+ if (!rateLimitResult.success) {
30156
+ return rateLimitResult;
30157
+ }
30158
+ }
30159
+ const result = await this.runMiddlewareChain(command, parsedArgs, context, async () => {
30160
+ const permCheck = await this.checkPermissions(command, context);
30161
+ if (!permCheck.success) {
30162
+ return permCheck;
30163
+ }
30164
+ if (command.validate) {
30165
+ const validation = await command.validate(parsedArgs);
30166
+ if (!validation.success) {
30167
+ return {
30168
+ success: false,
30169
+ message: validation.error || "Validation failed",
30170
+ data: { suggestions: validation.suggestions }
30171
+ };
30172
+ }
30173
+ }
30174
+ const result2 = await command.execute(parsedArgs, context);
30175
+ result2.metadata = {
30176
+ ...result2.metadata,
30177
+ executionTime: Date.now() - startTime,
30178
+ commandVersion: command.metadata.version
30179
+ };
30180
+ return result2;
30181
+ });
30182
+ this.logExecution(command, parsedArgs, context, result);
30183
+ return result;
30184
+ } catch (error) {
30185
+ if (error instanceof CommandError) {
30186
+ return {
30187
+ success: false,
30188
+ message: error.message,
30189
+ data: {
30190
+ code: error.code,
30191
+ details: error.details
30192
+ }
30193
+ };
30194
+ }
30195
+ logger.error(`Command execution error for ${commandName}:`, error);
30196
+ return {
30197
+ success: false,
30198
+ message: error instanceof Error ? error.message : "Command execution failed",
30199
+ metadata: {
30200
+ executionTime: Date.now() - startTime
30201
+ }
30202
+ };
30203
+ }
30204
+ }
30205
+ /**
30206
+ * Auto-register commands from directory
30207
+ */
30208
+ async autoRegister(directory) {
30209
+ logger.info(`Auto-registering commands from ${directory}`);
30210
+ try {
30211
+ const pattern = path10__namespace.join(directory, "**/*.command.{ts,js}");
30212
+ const files = await glob.glob(pattern);
30213
+ logger.info(`Found ${files.length} command files`);
30214
+ for (const file of files) {
30215
+ try {
30216
+ const module = await import(file);
30217
+ if (module.default) {
30218
+ let command;
30219
+ if (typeof module.default === "function") {
30220
+ command = new module.default();
30221
+ } else {
30222
+ command = module.default;
30223
+ }
30224
+ if (this.isValidCommand(command)) {
30225
+ if (command.initialize) {
30226
+ await command.initialize();
30227
+ }
30228
+ this.register(command);
30229
+ } else {
30230
+ logger.warn(`Invalid command in ${file}`);
30231
+ }
30232
+ }
30233
+ for (const [key, value] of Object.entries(module)) {
30234
+ if (key !== "default" && this.isValidCommand(value)) {
30235
+ const command = value;
30236
+ if (command.initialize) {
30237
+ await command.initialize();
30238
+ }
30239
+ this.register(command);
30240
+ }
30241
+ }
30242
+ } catch (error) {
30243
+ logger.error(`Failed to load command from ${file}:`, error);
30244
+ }
30245
+ }
30246
+ this.initialized = true;
30247
+ logger.info(`Registered ${this.commands.size} commands total`);
30248
+ } catch (error) {
30249
+ logger.error("Auto-registration failed:", error);
30250
+ throw error;
30251
+ }
30252
+ }
30253
+ /**
30254
+ * Register a middleware
30255
+ */
30256
+ registerMiddleware(middleware) {
30257
+ this.middlewares.set(middleware.name, middleware);
30258
+ logger.info(`Registered middleware: ${middleware.name}`);
30259
+ }
30260
+ // Private helper methods
30261
+ setupDefaultMiddlewares() {
30262
+ this.registerMiddleware({
30263
+ name: "logging",
30264
+ priority: 0,
30265
+ async execute(command, args, context, next) {
30266
+ logger.debug(`Executing command: ${command.name}`, {
30267
+ args: args.raw,
30268
+ user: context.user?.id
30269
+ });
30270
+ return next();
30271
+ }
30272
+ });
30273
+ this.registerMiddleware({
30274
+ name: "error-handler",
30275
+ priority: 1,
30276
+ async execute(_command, _args, _context, next) {
30277
+ try {
30278
+ return await next();
30279
+ } catch (error) {
30280
+ logger.error(`Command ${_command.name} failed:`, error);
30281
+ throw error;
30282
+ }
30283
+ }
30284
+ });
30285
+ }
30286
+ parseArguments(raw) {
30287
+ const args = {
30288
+ raw,
30289
+ parsed: {},
30290
+ flags: {},
30291
+ options: {}
30292
+ };
30293
+ const positional = [];
30294
+ for (let i = 0; i < raw.length; i++) {
30295
+ const arg = raw[i];
30296
+ if (!arg) continue;
30297
+ if (arg.startsWith("--")) {
30298
+ const key = arg.slice(2);
30299
+ const nextArg = raw[i + 1];
30300
+ if (nextArg && !nextArg.startsWith("-")) {
30301
+ args.options[key] = nextArg;
30302
+ i++;
30303
+ } else {
30304
+ args.flags[key] = true;
30305
+ }
30306
+ } else if (arg && arg.startsWith("-") && arg.length === 2) {
30307
+ args.flags[arg.slice(1)] = true;
30308
+ } else if (arg) {
30309
+ positional.push(arg);
30310
+ }
30311
+ }
30312
+ if (positional.length > 0) {
30313
+ args.parsed["positional"] = positional;
30314
+ }
30315
+ return args;
30316
+ }
30317
+ async checkPermissions(command, context) {
30318
+ if (!command.permissions) {
30319
+ return { success: true, message: "" };
30320
+ }
30321
+ const { requiresAuth, role } = command.permissions;
30322
+ if (requiresAuth && !context.user) {
30323
+ return {
30324
+ success: false,
30325
+ message: "Authentication required",
30326
+ data: { suggestions: ["Run /login to authenticate"] }
30327
+ };
30328
+ }
30329
+ if (role && context.user?.role !== role) {
30330
+ return {
30331
+ success: false,
30332
+ message: `Insufficient permissions. Required role: ${role}`
30333
+ };
30334
+ }
30335
+ return { success: true, message: "" };
30336
+ }
30337
+ checkRateLimit(command, context) {
30338
+ if (!command.rateLimit) {
30339
+ return { success: true, message: "" };
30340
+ }
30341
+ const userId = context.user?.id || "anonymous";
30342
+ const commandLimits = this.rateLimits.get(command.name) || /* @__PURE__ */ new Map();
30343
+ const userLimit = commandLimits.get(userId);
30344
+ const now = Date.now();
30345
+ const windowMs = this.parseWindow(command.rateLimit.window);
30346
+ if (!userLimit || userLimit.resetAt < now) {
30347
+ commandLimits.set(userId, {
30348
+ count: 1,
30349
+ resetAt: now + windowMs
30350
+ });
30351
+ this.rateLimits.set(command.name, commandLimits);
30352
+ return { success: true, message: "" };
30353
+ }
30354
+ if (userLimit.count >= command.rateLimit.requests) {
30355
+ const retryAfter = Math.ceil((userLimit.resetAt - now) / 1e3);
30356
+ return {
30357
+ success: false,
30358
+ message: `Rate limit exceeded. Try again in ${retryAfter} seconds`,
30359
+ data: { retryAfter }
30360
+ };
30361
+ }
30362
+ userLimit.count++;
30363
+ return { success: true, message: "" };
30364
+ }
30365
+ parseWindow(window) {
30366
+ const match = window.match(/^(\d+)([smhd])$/);
30367
+ if (!match) {
30368
+ return 6e4;
30369
+ }
30370
+ const [, num, unit] = match;
30371
+ const value = parseInt(num || "60", 10);
30372
+ switch (unit) {
30373
+ case "s":
30374
+ return value * 1e3;
30375
+ case "m":
30376
+ return value * 60 * 1e3;
30377
+ case "h":
30378
+ return value * 60 * 60 * 1e3;
30379
+ case "d":
30380
+ return value * 24 * 60 * 60 * 1e3;
30381
+ default:
30382
+ return 6e4;
30383
+ }
30384
+ }
30385
+ async runMiddlewareChain(command, args, context, execute) {
30386
+ const middlewareNames = command.middleware || [];
30387
+ const middlewares = middlewareNames.map((name) => this.middlewares.get(name)).filter(Boolean);
30388
+ middlewares.sort((a, b) => (a.priority || 0) - (b.priority || 0));
30389
+ let index = 0;
30390
+ const next = /* @__PURE__ */ __name(async () => {
30391
+ if (index < middlewares.length) {
30392
+ const middleware = middlewares[index++];
30393
+ return middleware ? middleware.execute(command, args, context, next) : execute();
30394
+ }
30395
+ return execute();
30396
+ }, "next");
30397
+ return next();
30398
+ }
30399
+ getSuggestions(input) {
30400
+ const suggestions = [];
30401
+ const cleanInput = input.replace("/", "").toLowerCase();
30402
+ for (const [name] of this.commands) {
30403
+ if (name.toLowerCase().includes(cleanInput) || cleanInput.includes(name.toLowerCase())) {
30404
+ suggestions.push(`/${name}`);
30405
+ }
30406
+ }
30407
+ for (const [alias] of this.aliases) {
30408
+ if (alias.toLowerCase().includes(cleanInput) || cleanInput.includes(alias.toLowerCase())) {
30409
+ suggestions.push(`/${alias}`);
30410
+ }
30411
+ }
30412
+ return suggestions.slice(0, 5);
30413
+ }
30414
+ isValidCommand(obj) {
30415
+ if (!obj || typeof obj !== "object") {
30416
+ return false;
30417
+ }
30418
+ const cmd = obj;
30419
+ return typeof cmd.name === "string" && typeof cmd.category === "string" && typeof cmd.description === "string" && typeof cmd.execute === "function";
30420
+ }
30421
+ logExecution(command, args, context, result) {
30422
+ const logData = {
30423
+ command: command.name,
30424
+ args: args.raw,
30425
+ user: context.user?.id,
30426
+ success: result.success,
30427
+ executionTime: result.metadata?.executionTime
30428
+ };
30429
+ if (result.success) {
30430
+ logger.info("Command executed", logData);
30431
+ } else {
30432
+ logger.error("Command failed", { ...logData, error: result.message });
30433
+ }
30434
+ }
30435
+ };
30436
+ var commandRegistry = new CommandRegistry();
30437
+
30438
+ // src/slash-commands/index.ts
30439
+ init_auth();
30440
+ init_validation();
30441
+ init_rate_limit();
30442
+ init_logging();
30443
+ init_clear_command();
30444
+ async function initializeSlashCommands() {
30445
+ const { authMiddleware: authMiddleware2 } = await Promise.resolve().then(() => (init_auth(), auth_exports));
30446
+ const { validationMiddleware: validationMiddleware2 } = await Promise.resolve().then(() => (init_validation(), validation_exports));
30447
+ const { rateLimitMiddleware: rateLimitMiddleware2 } = await Promise.resolve().then(() => (init_rate_limit(), rate_limit_exports));
30448
+ const { loggingMiddleware: loggingMiddleware2 } = await Promise.resolve().then(() => (init_logging(), logging_exports));
30449
+ commandRegistry.registerMiddleware(loggingMiddleware2);
30450
+ commandRegistry.registerMiddleware(authMiddleware2);
30451
+ commandRegistry.registerMiddleware(rateLimitMiddleware2);
30452
+ commandRegistry.registerMiddleware(validationMiddleware2);
30453
+ await registerBuiltInCommands();
30454
+ console.log(`\u2705 Initialized ${commandRegistry.getAll().length} slash commands`);
30455
+ }
30456
+ __name(initializeSlashCommands, "initializeSlashCommands");
30457
+ async function registerBuiltInCommands() {
30458
+ try {
30459
+ const { ClearCommand: ClearCommand2 } = await Promise.resolve().then(() => (init_clear_command(), clear_command_exports));
30460
+ const clearCommand = new ClearCommand2();
30461
+ if (clearCommand.initialize) {
30462
+ await clearCommand.initialize();
30463
+ }
30464
+ commandRegistry.register(clearCommand);
30465
+ const setupCommandModule = await Promise.resolve().then(() => (init_setup_command(), setup_command_exports));
30466
+ const setupCommand = setupCommandModule.default;
30467
+ if (setupCommand) {
30468
+ if (setupCommand.initialize) {
30469
+ await setupCommand.initialize();
30470
+ }
30471
+ commandRegistry.register(setupCommand);
30472
+ }
30473
+ } catch (error) {
30474
+ console.error("Failed to register built-in commands:", error);
30475
+ }
30476
+ }
30477
+ __name(registerBuiltInCommands, "registerBuiltInCommands");
30478
+ function getCommandSuggestions(input) {
30479
+ const commands = commandRegistry.getAll();
30480
+ const suggestions = [];
30481
+ const cleanInput = input.replace("/", "").toLowerCase();
30482
+ for (const command of commands) {
30483
+ if (command.name.toLowerCase().startsWith(cleanInput)) {
30484
+ suggestions.push({ command: `/${command.name}`, score: 1e3, type: "name" });
30485
+ } else if (command.name.toLowerCase().includes(cleanInput)) {
30486
+ suggestions.push({ command: `/${command.name}`, score: 800, type: "name" });
30487
+ } else if (command.description.toLowerCase().includes(cleanInput)) {
30488
+ suggestions.push({ command: `/${command.name}`, score: 600, type: "description" });
30489
+ }
30490
+ if (command.aliases) {
30491
+ for (const alias of command.aliases) {
30492
+ if (alias.toLowerCase().startsWith(cleanInput)) {
30493
+ suggestions.push({ command: `/${alias}`, score: 950, type: "alias" });
30494
+ } else if (alias.toLowerCase().includes(cleanInput)) {
30495
+ suggestions.push({ command: `/${alias}`, score: 750, type: "alias" });
30496
+ }
30497
+ }
30498
+ }
30499
+ }
30500
+ return suggestions.sort((a, b) => b.score - a.score).slice(0, 10).map((s) => s.command);
30501
+ }
30502
+ __name(getCommandSuggestions, "getCommandSuggestions");
30503
+ function getCommandsByCategory2() {
30504
+ const commands = commandRegistry.getAll();
30505
+ const grouped = {};
30506
+ for (const command of commands) {
30507
+ if (!grouped[command.category]) {
30508
+ grouped[command.category] = [];
30509
+ }
30510
+ grouped[command.category].push(command);
30511
+ }
30512
+ return grouped;
30513
+ }
30514
+ __name(getCommandsByCategory2, "getCommandsByCategory");
30515
+
28574
30516
  // src/index.ts
30517
+ init_base_command();
28575
30518
  var VERSION = "1.1.0";
28576
30519
 
28577
30520
  exports.DualMemoryEngine = DualMemoryEngine;
@@ -28580,7 +30523,11 @@ exports.MemoryCoordinator = MemoryCoordinator;
28580
30523
  exports.System1Memory = System1MemoryManager;
28581
30524
  exports.System2Memory = System2MemoryManager;
28582
30525
  exports.VERSION = VERSION;
30526
+ exports.commandRegistry = commandRegistry;
28583
30527
  exports.createCLI = createCLI;
30528
+ exports.getCommandSuggestions = getCommandSuggestions;
30529
+ exports.getCommandsByCategory = getCommandsByCategory2;
28584
30530
  exports.getInternalModeService = getInternalModeService2;
30531
+ exports.initializeSlashCommands = initializeSlashCommands;
28585
30532
  //# sourceMappingURL=index.js.map
28586
30533
  //# sourceMappingURL=index.js.map