@bonginkan/maria 3.6.3 → 3.6.4

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/cli.cjs CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- var fs4 = require('fs');
5
- var path6 = require('path');
4
+ var fs6 = require('fs');
5
+ var path8 = require('path');
6
6
  var os2 = require('os');
7
7
  var events = require('events');
8
- var fs6 = require('fs/promises');
8
+ var fs8 = require('fs/promises');
9
9
  var Stream = require('stream');
10
10
  var util = require('util');
11
11
  var buffer = require('buffer');
@@ -15,6 +15,7 @@ var url = require('url');
15
15
  var https = require('https');
16
16
  var zlib = require('zlib');
17
17
  var chalk13 = require('chalk');
18
+ var child_process = require('child_process');
18
19
  var readline = require('readline');
19
20
  var dotenv = require('dotenv');
20
21
  var OpenAI = require('openai');
@@ -50,10 +51,10 @@ function _interopNamespace(e) {
50
51
  return Object.freeze(n);
51
52
  }
52
53
 
53
- var fs4__namespace = /*#__PURE__*/_interopNamespace(fs4);
54
- var path6__namespace = /*#__PURE__*/_interopNamespace(path6);
55
- var os2__namespace = /*#__PURE__*/_interopNamespace(os2);
56
54
  var fs6__namespace = /*#__PURE__*/_interopNamespace(fs6);
55
+ var path8__namespace = /*#__PURE__*/_interopNamespace(path8);
56
+ var os2__namespace = /*#__PURE__*/_interopNamespace(os2);
57
+ var fs8__namespace = /*#__PURE__*/_interopNamespace(fs8);
57
58
  var Stream__default = /*#__PURE__*/_interopDefault(Stream);
58
59
  var http__default = /*#__PURE__*/_interopDefault(http);
59
60
  var https__default = /*#__PURE__*/_interopDefault(https);
@@ -115,8 +116,8 @@ var init_conversation_persistence = __esm({
115
116
  autoSaveInterval = null;
116
117
  pendingWrites = [];
117
118
  constructor(maxHistorySize = 100) {
118
- const configDir = path6__namespace.join(os2__namespace.homedir(), ".maria");
119
- this.sessionFile = path6__namespace.join(configDir, "conversation-history.json");
119
+ const configDir = path8__namespace.join(os2__namespace.homedir(), ".maria");
120
+ this.sessionFile = path8__namespace.join(configDir, "conversation-history.json");
120
121
  this.maxHistorySize = maxHistorySize;
121
122
  this.ensureConfigDir();
122
123
  this.startAutoSave();
@@ -126,8 +127,8 @@ var init_conversation_persistence = __esm({
126
127
  */
127
128
  async ensureConfigDir() {
128
129
  try {
129
- const configDir = path6__namespace.dirname(this.sessionFile);
130
- await fs4.promises.mkdir(configDir, { recursive: true });
130
+ const configDir = path8__namespace.dirname(this.sessionFile);
131
+ await fs6.promises.mkdir(configDir, { recursive: true });
131
132
  } catch (error) {
132
133
  console.warn("Failed to create config directory:", error);
133
134
  }
@@ -137,7 +138,7 @@ var init_conversation_persistence = __esm({
137
138
  */
138
139
  async loadHistory() {
139
140
  try {
140
- const data2 = await fs4.promises.readFile(this.sessionFile, "utf-8");
141
+ const data2 = await fs6.promises.readFile(this.sessionFile, "utf-8");
141
142
  const session = JSON.parse(data2);
142
143
  const messages = session.messages.map((msg) => ({
143
144
  ...msg,
@@ -175,7 +176,7 @@ var init_conversation_persistence = __esm({
175
176
  model: messages[messages.length - 1]?.model
176
177
  }
177
178
  };
178
- await fs4.promises.writeFile(this.sessionFile, JSON.stringify(session, null, 2));
179
+ await fs6.promises.writeFile(this.sessionFile, JSON.stringify(session, null, 2));
179
180
  } catch (error) {
180
181
  console.warn("Failed to save conversation history:", error);
181
182
  }
@@ -185,7 +186,7 @@ var init_conversation_persistence = __esm({
185
186
  */
186
187
  async clearHistory() {
187
188
  try {
188
- await fs4.promises.unlink(this.sessionFile);
189
+ await fs6.promises.unlink(this.sessionFile);
189
190
  } catch (innerError) {
190
191
  }
191
192
  this.pendingWrites = [];
@@ -196,7 +197,7 @@ var init_conversation_persistence = __esm({
196
197
  async getStats() {
197
198
  try {
198
199
  const messages = await this.loadHistory();
199
- const stats = await fs4.promises.stat(this.sessionFile);
200
+ const stats = await fs6.promises.stat(this.sessionFile);
200
201
  return {
201
202
  totalMessages: messages.length,
202
203
  oldestMessage: messages[0]?.timestamp,
@@ -266,7 +267,7 @@ var init_chat_context_service = __esm({
266
267
  maxTokens: config2?.maxTokens || 128e3,
267
268
  compressionThreshold: config2?.compressionThreshold || 0.8,
268
269
  summaryTokenLimit: config2?.summaryTokenLimit || 2e3,
269
- persistPath: config2?.persistPath || path6__namespace.join(process.env["HOME"] || "", ".maria", "context")
270
+ persistPath: config2?.persistPath || path8__namespace.join(process.env["HOME"] || "", ".maria", "context")
270
271
  };
271
272
  this.sessionId = this.generateSessionId();
272
273
  }
@@ -385,8 +386,8 @@ var init_chat_context_service = __esm({
385
386
  async persistSession() {
386
387
  if (!this.config.persistPath) return;
387
388
  try {
388
- await fs6__namespace.mkdir(this.config.persistPath, { recursive: true });
389
- const sessionFile = path6__namespace.join(
389
+ await fs8__namespace.mkdir(this.config.persistPath, { recursive: true });
390
+ const sessionFile = path8__namespace.join(
390
391
  this.config.persistPath,
391
392
  `${this.sessionId}.json`
392
393
  );
@@ -398,7 +399,7 @@ var init_chat_context_service = __esm({
398
399
  fullHistory: this.fullHistory,
399
400
  compressionCount: this.compressionCount
400
401
  };
401
- await fs6__namespace.writeFile(sessionFile, JSON.stringify(sessionData, null, 2));
402
+ await fs8__namespace.writeFile(sessionFile, JSON.stringify(sessionData, null, 2));
402
403
  this.emit("session-persisted", sessionFile);
403
404
  } catch (error) {
404
405
  this.emit(
@@ -1401,7 +1402,7 @@ var require_ponyfill_es2018 = __commonJS({
1401
1402
  return new originalPromise(executor);
1402
1403
  }
1403
1404
  function promiseResolvedWith(value) {
1404
- return newPromise((resolve2) => resolve2(value));
1405
+ return newPromise((resolve4) => resolve4(value));
1405
1406
  }
1406
1407
  function promiseRejectedWith(reason) {
1407
1408
  return originalPromiseReject(reason);
@@ -1571,8 +1572,8 @@ var require_ponyfill_es2018 = __commonJS({
1571
1572
  return new TypeError("Cannot " + name2 + " a stream using a released reader");
1572
1573
  }
1573
1574
  function defaultReaderClosedPromiseInitialize(reader2) {
1574
- reader2._closedPromise = newPromise((resolve2, reject) => {
1575
- reader2._closedPromise_resolve = resolve2;
1575
+ reader2._closedPromise = newPromise((resolve4, reject) => {
1576
+ reader2._closedPromise_resolve = resolve4;
1576
1577
  reader2._closedPromise_reject = reject;
1577
1578
  });
1578
1579
  }
@@ -1623,11 +1624,11 @@ var require_ponyfill_es2018 = __commonJS({
1623
1624
  throw new TypeError(`${context2} is not a function.`);
1624
1625
  }
1625
1626
  }
1626
- function isObject(x2) {
1627
+ function isObject2(x2) {
1627
1628
  return typeof x2 === "object" && x2 !== null || typeof x2 === "function";
1628
1629
  }
1629
1630
  function assertObject(x2, context2) {
1630
- if (!isObject(x2)) {
1631
+ if (!isObject2(x2)) {
1631
1632
  throw new TypeError(`${context2} is not an object.`);
1632
1633
  }
1633
1634
  }
@@ -1746,8 +1747,8 @@ var require_ponyfill_es2018 = __commonJS({
1746
1747
  }
1747
1748
  let resolvePromise;
1748
1749
  let rejectPromise;
1749
- const promise = newPromise((resolve2, reject) => {
1750
- resolvePromise = resolve2;
1750
+ const promise = newPromise((resolve4, reject) => {
1751
+ resolvePromise = resolve4;
1751
1752
  rejectPromise = reject;
1752
1753
  });
1753
1754
  const readRequest = {
@@ -1852,8 +1853,8 @@ var require_ponyfill_es2018 = __commonJS({
1852
1853
  const reader2 = this._reader;
1853
1854
  let resolvePromise;
1854
1855
  let rejectPromise;
1855
- const promise = newPromise((resolve2, reject) => {
1856
- resolvePromise = resolve2;
1856
+ const promise = newPromise((resolve4, reject) => {
1857
+ resolvePromise = resolve4;
1857
1858
  rejectPromise = reject;
1858
1859
  });
1859
1860
  const readRequest = {
@@ -2872,8 +2873,8 @@ var require_ponyfill_es2018 = __commonJS({
2872
2873
  }
2873
2874
  let resolvePromise;
2874
2875
  let rejectPromise;
2875
- const promise = newPromise((resolve2, reject) => {
2876
- resolvePromise = resolve2;
2876
+ const promise = newPromise((resolve4, reject) => {
2877
+ resolvePromise = resolve4;
2877
2878
  rejectPromise = reject;
2878
2879
  });
2879
2880
  const readIntoRequest = {
@@ -3185,10 +3186,10 @@ var require_ponyfill_es2018 = __commonJS({
3185
3186
  wasAlreadyErroring = true;
3186
3187
  reason = void 0;
3187
3188
  }
3188
- const promise = newPromise((resolve2, reject) => {
3189
+ const promise = newPromise((resolve4, reject) => {
3189
3190
  stream._pendingAbortRequest = {
3190
3191
  _promise: void 0,
3191
- _resolve: resolve2,
3192
+ _resolve: resolve4,
3192
3193
  _reject: reject,
3193
3194
  _reason: reason,
3194
3195
  _wasAlreadyErroring: wasAlreadyErroring
@@ -3205,9 +3206,9 @@ var require_ponyfill_es2018 = __commonJS({
3205
3206
  if (state === "closed" || state === "errored") {
3206
3207
  return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));
3207
3208
  }
3208
- const promise = newPromise((resolve2, reject) => {
3209
+ const promise = newPromise((resolve4, reject) => {
3209
3210
  const closeRequest = {
3210
- _resolve: resolve2,
3211
+ _resolve: resolve4,
3211
3212
  _reject: reject
3212
3213
  };
3213
3214
  stream._closeRequest = closeRequest;
@@ -3220,9 +3221,9 @@ var require_ponyfill_es2018 = __commonJS({
3220
3221
  return promise;
3221
3222
  }
3222
3223
  function WritableStreamAddWriteRequest(stream) {
3223
- const promise = newPromise((resolve2, reject) => {
3224
+ const promise = newPromise((resolve4, reject) => {
3224
3225
  const writeRequest = {
3225
- _resolve: resolve2,
3226
+ _resolve: resolve4,
3226
3227
  _reject: reject
3227
3228
  };
3228
3229
  stream._writeRequests.push(writeRequest);
@@ -3838,8 +3839,8 @@ var require_ponyfill_es2018 = __commonJS({
3838
3839
  return new TypeError("Cannot " + name2 + " a stream using a released writer");
3839
3840
  }
3840
3841
  function defaultWriterClosedPromiseInitialize(writer) {
3841
- writer._closedPromise = newPromise((resolve2, reject) => {
3842
- writer._closedPromise_resolve = resolve2;
3842
+ writer._closedPromise = newPromise((resolve4, reject) => {
3843
+ writer._closedPromise_resolve = resolve4;
3843
3844
  writer._closedPromise_reject = reject;
3844
3845
  writer._closedPromiseState = "pending";
3845
3846
  });
@@ -3875,8 +3876,8 @@ var require_ponyfill_es2018 = __commonJS({
3875
3876
  writer._closedPromiseState = "resolved";
3876
3877
  }
3877
3878
  function defaultWriterReadyPromiseInitialize(writer) {
3878
- writer._readyPromise = newPromise((resolve2, reject) => {
3879
- writer._readyPromise_resolve = resolve2;
3879
+ writer._readyPromise = newPromise((resolve4, reject) => {
3880
+ writer._readyPromise_resolve = resolve4;
3880
3881
  writer._readyPromise_reject = reject;
3881
3882
  });
3882
3883
  writer._readyPromiseState = "pending";
@@ -3963,7 +3964,7 @@ var require_ponyfill_es2018 = __commonJS({
3963
3964
  source._disturbed = true;
3964
3965
  let shuttingDown = false;
3965
3966
  let currentWrite = promiseResolvedWith(void 0);
3966
- return newPromise((resolve2, reject) => {
3967
+ return newPromise((resolve4, reject) => {
3967
3968
  let abortAlgorithm;
3968
3969
  if (signal !== void 0) {
3969
3970
  abortAlgorithm = () => {
@@ -4108,7 +4109,7 @@ var require_ponyfill_es2018 = __commonJS({
4108
4109
  if (isError) {
4109
4110
  reject(error);
4110
4111
  } else {
4111
- resolve2(void 0);
4112
+ resolve4(void 0);
4112
4113
  }
4113
4114
  return null;
4114
4115
  }
@@ -4389,8 +4390,8 @@ var require_ponyfill_es2018 = __commonJS({
4389
4390
  let branch1;
4390
4391
  let branch2;
4391
4392
  let resolveCancelPromise;
4392
- const cancelPromise = newPromise((resolve2) => {
4393
- resolveCancelPromise = resolve2;
4393
+ const cancelPromise = newPromise((resolve4) => {
4394
+ resolveCancelPromise = resolve4;
4394
4395
  });
4395
4396
  function pullAlgorithm() {
4396
4397
  if (reading) {
@@ -4481,8 +4482,8 @@ var require_ponyfill_es2018 = __commonJS({
4481
4482
  let branch1;
4482
4483
  let branch2;
4483
4484
  let resolveCancelPromise;
4484
- const cancelPromise = newPromise((resolve2) => {
4485
- resolveCancelPromise = resolve2;
4485
+ const cancelPromise = newPromise((resolve4) => {
4486
+ resolveCancelPromise = resolve4;
4486
4487
  });
4487
4488
  function forwardReaderError(thisReader) {
4488
4489
  uponRejection(thisReader._closedPromise, (r2) => {
@@ -5262,8 +5263,8 @@ var require_ponyfill_es2018 = __commonJS({
5262
5263
  const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
5263
5264
  const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
5264
5265
  let startPromise_resolve;
5265
- const startPromise = newPromise((resolve2) => {
5266
- startPromise_resolve = resolve2;
5266
+ const startPromise = newPromise((resolve4) => {
5267
+ startPromise_resolve = resolve4;
5267
5268
  });
5268
5269
  InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
5269
5270
  SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
@@ -5356,8 +5357,8 @@ var require_ponyfill_es2018 = __commonJS({
5356
5357
  if (stream._backpressureChangePromise !== void 0) {
5357
5358
  stream._backpressureChangePromise_resolve();
5358
5359
  }
5359
- stream._backpressureChangePromise = newPromise((resolve2) => {
5360
- stream._backpressureChangePromise_resolve = resolve2;
5360
+ stream._backpressureChangePromise = newPromise((resolve4) => {
5361
+ stream._backpressureChangePromise_resolve = resolve4;
5361
5362
  });
5362
5363
  stream._backpressure = backpressure;
5363
5364
  }
@@ -5525,8 +5526,8 @@ var require_ponyfill_es2018 = __commonJS({
5525
5526
  return controller._finishPromise;
5526
5527
  }
5527
5528
  const readable = stream._readable;
5528
- controller._finishPromise = newPromise((resolve2, reject) => {
5529
- controller._finishPromise_resolve = resolve2;
5529
+ controller._finishPromise = newPromise((resolve4, reject) => {
5530
+ controller._finishPromise_resolve = resolve4;
5530
5531
  controller._finishPromise_reject = reject;
5531
5532
  });
5532
5533
  const cancelPromise = controller._cancelAlgorithm(reason);
@@ -5552,8 +5553,8 @@ var require_ponyfill_es2018 = __commonJS({
5552
5553
  return controller._finishPromise;
5553
5554
  }
5554
5555
  const readable = stream._readable;
5555
- controller._finishPromise = newPromise((resolve2, reject) => {
5556
- controller._finishPromise_resolve = resolve2;
5556
+ controller._finishPromise = newPromise((resolve4, reject) => {
5557
+ controller._finishPromise_resolve = resolve4;
5557
5558
  controller._finishPromise_reject = reject;
5558
5559
  });
5559
5560
  const flushPromise = controller._flushAlgorithm();
@@ -5583,8 +5584,8 @@ var require_ponyfill_es2018 = __commonJS({
5583
5584
  return controller._finishPromise;
5584
5585
  }
5585
5586
  const writable = stream._writable;
5586
- controller._finishPromise = newPromise((resolve2, reject) => {
5587
- controller._finishPromise_resolve = resolve2;
5587
+ controller._finishPromise = newPromise((resolve4, reject) => {
5588
+ controller._finishPromise_resolve = resolve4;
5588
5589
  controller._finishPromise_reject = reject;
5589
5590
  });
5590
5591
  const cancelPromise = controller._cancelAlgorithm(reason);
@@ -6126,23 +6127,23 @@ var init_from = __esm({
6126
6127
  import_node_domexception = __toESM(require_node_domexception());
6127
6128
  init_file();
6128
6129
  init_fetch_blob();
6129
- ({ stat } = fs4.promises);
6130
- blobFromSync = (path7, type) => fromBlob(fs4.statSync(path7), path7, type);
6131
- blobFrom = (path7, type) => stat(path7).then((stat2) => fromBlob(stat2, path7, type));
6132
- fileFrom = (path7, type) => stat(path7).then((stat2) => fromFile(stat2, path7, type));
6133
- fileFromSync = (path7, type) => fromFile(fs4.statSync(path7), path7, type);
6134
- fromBlob = (stat2, path7, type = "") => new fetch_blob_default([new BlobDataItem({
6135
- path: path7,
6130
+ ({ stat } = fs6.promises);
6131
+ blobFromSync = (path9, type) => fromBlob(fs6.statSync(path9), path9, type);
6132
+ blobFrom = (path9, type) => stat(path9).then((stat2) => fromBlob(stat2, path9, type));
6133
+ fileFrom = (path9, type) => stat(path9).then((stat2) => fromFile(stat2, path9, type));
6134
+ fileFromSync = (path9, type) => fromFile(fs6.statSync(path9), path9, type);
6135
+ fromBlob = (stat2, path9, type = "") => new fetch_blob_default([new BlobDataItem({
6136
+ path: path9,
6136
6137
  size: stat2.size,
6137
6138
  lastModified: stat2.mtimeMs,
6138
6139
  start: 0
6139
6140
  })], { type });
6140
- fromFile = (stat2, path7, type = "") => new file_default([new BlobDataItem({
6141
- path: path7,
6141
+ fromFile = (stat2, path9, type = "") => new file_default([new BlobDataItem({
6142
+ path: path9,
6142
6143
  size: stat2.size,
6143
6144
  lastModified: stat2.mtimeMs,
6144
6145
  start: 0
6145
- })], path6.basename(path7), { type, lastModified: stat2.mtimeMs });
6146
+ })], path8.basename(path9), { type, lastModified: stat2.mtimeMs });
6146
6147
  BlobDataItem = class _BlobDataItem {
6147
6148
  #path;
6148
6149
  #start;
@@ -6169,7 +6170,7 @@ var init_from = __esm({
6169
6170
  if (mtimeMs > this.lastModified) {
6170
6171
  throw new import_node_domexception.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.", "NotReadableError");
6171
6172
  }
6172
- yield* fs4.createReadStream(this.#path, {
6173
+ yield* fs6.createReadStream(this.#path, {
6173
6174
  start: this.#start,
6174
6175
  end: this.#start + this.size - 1
6175
6176
  });
@@ -7506,7 +7507,7 @@ __export(src_exports, {
7506
7507
  isRedirect: () => isRedirect
7507
7508
  });
7508
7509
  async function fetch2(url, options_) {
7509
- return new Promise((resolve2, reject) => {
7510
+ return new Promise((resolve4, reject) => {
7510
7511
  const request = new Request(url, options_);
7511
7512
  const { parsedURL, options } = getNodeRequestOptions(request);
7512
7513
  if (!supportedSchemas.has(parsedURL.protocol)) {
@@ -7515,7 +7516,7 @@ async function fetch2(url, options_) {
7515
7516
  if (parsedURL.protocol === "data:") {
7516
7517
  const data2 = dist_default(request.url);
7517
7518
  const response3 = new Response(data2, { headers: { "Content-Type": data2.typeFull } });
7518
- resolve2(response3);
7519
+ resolve4(response3);
7519
7520
  return;
7520
7521
  }
7521
7522
  const send = (parsedURL.protocol === "https:" ? https__default.default : http__default.default).request;
@@ -7637,7 +7638,7 @@ async function fetch2(url, options_) {
7637
7638
  if (responseReferrerPolicy) {
7638
7639
  requestOptions.referrerPolicy = responseReferrerPolicy;
7639
7640
  }
7640
- resolve2(fetch2(new Request(locationURL, requestOptions)));
7641
+ resolve4(fetch2(new Request(locationURL, requestOptions)));
7641
7642
  finalize();
7642
7643
  return;
7643
7644
  }
@@ -7670,7 +7671,7 @@ async function fetch2(url, options_) {
7670
7671
  const codings = headers.get("Content-Encoding");
7671
7672
  if (!request.compress || request.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {
7672
7673
  response2 = new Response(body, responseOptions);
7673
- resolve2(response2);
7674
+ resolve4(response2);
7674
7675
  return;
7675
7676
  }
7676
7677
  const zlibOptions = {
@@ -7684,7 +7685,7 @@ async function fetch2(url, options_) {
7684
7685
  }
7685
7686
  });
7686
7687
  response2 = new Response(body, responseOptions);
7687
- resolve2(response2);
7688
+ resolve4(response2);
7688
7689
  return;
7689
7690
  }
7690
7691
  if (codings === "deflate" || codings === "x-deflate") {
@@ -7708,12 +7709,12 @@ async function fetch2(url, options_) {
7708
7709
  });
7709
7710
  }
7710
7711
  response2 = new Response(body, responseOptions);
7711
- resolve2(response2);
7712
+ resolve4(response2);
7712
7713
  });
7713
7714
  raw.once("end", () => {
7714
7715
  if (!response2) {
7715
7716
  response2 = new Response(body, responseOptions);
7716
- resolve2(response2);
7717
+ resolve4(response2);
7717
7718
  }
7718
7719
  });
7719
7720
  return;
@@ -7725,11 +7726,11 @@ async function fetch2(url, options_) {
7725
7726
  }
7726
7727
  });
7727
7728
  response2 = new Response(body, responseOptions);
7728
- resolve2(response2);
7729
+ resolve4(response2);
7729
7730
  return;
7730
7731
  }
7731
7732
  response2 = new Response(body, responseOptions);
7732
- resolve2(response2);
7733
+ resolve4(response2);
7733
7734
  });
7734
7735
  writeToStream(request_, request).catch(reject);
7735
7736
  });
@@ -7923,7 +7924,7 @@ var init_base_provider = __esm({
7923
7924
  }
7924
7925
  if (attempt < maxRetries - 1) {
7925
7926
  const delay = Math.pow(2, attempt) * 1e3;
7926
- await new Promise((resolve2) => setTimeout(resolve2, delay));
7927
+ await new Promise((resolve4) => setTimeout(resolve4, delay));
7927
7928
  }
7928
7929
  }
7929
7930
  }
@@ -9468,7 +9469,7 @@ I'm here to assist you effectively!`;
9468
9469
  delay = 80;
9469
9470
  }
9470
9471
  if (i2 < lines.length - 1) {
9471
- await new Promise((resolve2) => setTimeout(resolve2, delay));
9472
+ await new Promise((resolve4) => setTimeout(resolve4, delay));
9472
9473
  }
9473
9474
  }
9474
9475
  }
@@ -9569,52 +9570,1754 @@ var init_SlashCommandHandler = __esm({
9569
9570
  const resolvedName = this.aliases.get(name2) || name2;
9570
9571
  return this.commands.get(resolvedName);
9571
9572
  }
9572
- /**
9573
- * Search commands by pattern
9574
- */
9575
- searchCommands(pattern2) {
9576
- const lowercasePattern = pattern2.toLowerCase();
9577
- return this.listCommands().filter(
9578
- (cmd) => cmd.name.toLowerCase().includes(lowercasePattern) || cmd.description.toLowerCase().includes(lowercasePattern)
9579
- );
9573
+ /**
9574
+ * Search commands by pattern
9575
+ */
9576
+ searchCommands(pattern2) {
9577
+ const lowercasePattern = pattern2.toLowerCase();
9578
+ return this.listCommands().filter(
9579
+ (cmd) => cmd.name.toLowerCase().includes(lowercasePattern) || cmd.description.toLowerCase().includes(lowercasePattern)
9580
+ );
9581
+ }
9582
+ /**
9583
+ * Get commands by category
9584
+ */
9585
+ getCommandsByCategory(category) {
9586
+ return this.listCommands().filter((cmd) => cmd.category === category);
9587
+ }
9588
+ /**
9589
+ * Get all categories
9590
+ */
9591
+ getCategories() {
9592
+ const categories = /* @__PURE__ */ new Set();
9593
+ for (const command of this.commands.values()) {
9594
+ categories.add(command.category);
9595
+ }
9596
+ return Array.from(categories);
9597
+ }
9598
+ /**
9599
+ * Validate command arguments
9600
+ */
9601
+ validateArgs(commandName, args) {
9602
+ const command = this.getCommand(commandName);
9603
+ if (!command) return false;
9604
+ return true;
9605
+ }
9606
+ /**
9607
+ * Create a helper context for testing
9608
+ */
9609
+ static createTestContext(deps, overrides) {
9610
+ return {
9611
+ command: "test",
9612
+ args: [],
9613
+ options: {},
9614
+ deps,
9615
+ signal: void 0,
9616
+ ...overrides
9617
+ };
9618
+ }
9619
+ };
9620
+ }
9621
+ });
9622
+ var LogLevel, Logger, logger, envLogLevel;
9623
+ var init_logger = __esm({
9624
+ "src/utils/logger.ts"() {
9625
+ LogLevel = /* @__PURE__ */ ((LogLevel2) => {
9626
+ LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
9627
+ LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
9628
+ LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
9629
+ LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
9630
+ LogLevel2[LogLevel2["NONE"] = 4] = "NONE";
9631
+ return LogLevel2;
9632
+ })(LogLevel || {});
9633
+ Logger = class {
9634
+ level = 2 /* WARN */;
9635
+ // Default to WARN to reduce noise
9636
+ prefix = "[MARIA CODE]";
9637
+ setLevel(level) {
9638
+ this.level = level;
9639
+ }
9640
+ debug(...args) {
9641
+ if (this.level <= 0 /* DEBUG */) {
9642
+ console.log(chalk13__default.default.magenta(`${this.prefix} [DEBUG]`), ...args);
9643
+ }
9644
+ }
9645
+ info(...args) {
9646
+ if (this.level <= 1 /* INFO */) {
9647
+ console.log(chalk13__default.default.bold.magenta(`${this.prefix} [INFO]`), ...args);
9648
+ }
9649
+ }
9650
+ warn(...args) {
9651
+ if (this.level <= 2 /* WARN */) {
9652
+ console.warn(chalk13__default.default.bold.magenta(`${this.prefix} [WARN]`), ...args);
9653
+ }
9654
+ }
9655
+ error(...args) {
9656
+ if (this.level <= 3 /* ERROR */) {
9657
+ console.error(chalk13__default.default.bold.magenta(`${this.prefix} [ERROR]`), ...args);
9658
+ }
9659
+ }
9660
+ success(...args) {
9661
+ if (this.level <= 1 /* INFO */) {
9662
+ console.log(chalk13__default.default.bold.magenta(`${this.prefix} [SUCCESS]`), ...args);
9663
+ }
9664
+ }
9665
+ task(taskName, status, message) {
9666
+ if (this.level > 1 /* INFO */) {
9667
+ return;
9668
+ }
9669
+ const statusIcons = {
9670
+ start: "\u{1F680}",
9671
+ progress: "\u23F3",
9672
+ complete: "\u2705",
9673
+ error: "\u274C"
9674
+ };
9675
+ const statusColors = {
9676
+ start: chalk13__default.default.bold.magenta,
9677
+ progress: chalk13__default.default.magenta,
9678
+ complete: chalk13__default.default.bold.magenta,
9679
+ error: chalk13__default.default.bold.magenta
9680
+ };
9681
+ const icon = statusIcons[status];
9682
+ const color = statusColors[status];
9683
+ const formattedMessage = message ? `: ${message}` : "";
9684
+ console.log(color(`${this.prefix} ${icon} ${taskName}${formattedMessage}`));
9685
+ }
9686
+ table(data2) {
9687
+ if (this.level > 1 /* INFO */) {
9688
+ return;
9689
+ }
9690
+ console.table(data2);
9691
+ }
9692
+ json(obj, pretty = true) {
9693
+ if (this.level > 0 /* DEBUG */) {
9694
+ return;
9695
+ }
9696
+ console.log(chalk13__default.default.magenta(`${this.prefix} [JSON]`));
9697
+ console.log(pretty ? JSON.stringify(obj, null, 2) : JSON.stringify(obj));
9698
+ }
9699
+ divider() {
9700
+ if (this.level > 1 /* INFO */) {
9701
+ return;
9702
+ }
9703
+ console.log(chalk13__default.default.magenta("\u2500".repeat(60)));
9704
+ }
9705
+ clear() {
9706
+ console.clear();
9707
+ }
9708
+ /**
9709
+ * プログレスバーを表示
9710
+ */
9711
+ progress(current, total, label) {
9712
+ if (this.level > 1 /* INFO */) {
9713
+ return;
9714
+ }
9715
+ const percentage = Math.round(current / total * 100);
9716
+ const barLength = 30;
9717
+ const filled = Math.round(percentage / 100 * barLength);
9718
+ const empty = barLength - filled;
9719
+ const bar = "\u2588".repeat(filled) + "\u2591".repeat(empty);
9720
+ const progressText = `${current}/${total}`;
9721
+ const labelText = label ? ` ${label}` : "";
9722
+ process.stdout.write(
9723
+ `\r${chalk13__default.default.bold.magenta(bar)} ${percentage}% ${progressText}${labelText}`
9724
+ );
9725
+ if (current === total) {
9726
+ process.stdout.write("\n");
9727
+ }
9728
+ }
9729
+ };
9730
+ logger = new Logger();
9731
+ envLogLevel = process.env["MARIA_LOG_LEVEL"]?.toUpperCase();
9732
+ if (envLogLevel && LogLevel[envLogLevel] !== void 0) {
9733
+ logger.setLevel(LogLevel[envLogLevel]);
9734
+ }
9735
+ }
9736
+ });
9737
+
9738
+ // src/slash-commands/base-command.ts
9739
+ var BaseCommand;
9740
+ var init_base_command = __esm({
9741
+ "src/slash-commands/base-command.ts"() {
9742
+ init_logger();
9743
+ BaseCommand = class {
9744
+ // Optional properties with defaults
9745
+ aliases = [];
9746
+ usage = "";
9747
+ examples = [];
9748
+ permissions;
9749
+ middleware = [];
9750
+ rateLimit;
9751
+ // Metadata with defaults
9752
+ metadata = {
9753
+ version: "1.0.0",
9754
+ author: "MARIA Team",
9755
+ deprecated: false,
9756
+ experimental: false
9757
+ };
9758
+ // Cache for frequently used data
9759
+ cache = /* @__PURE__ */ new Map();
9760
+ /**
9761
+ * Initialize the command (called once when registered)
9762
+ */
9763
+ async initialize() {
9764
+ logger.debug(`Initializing command: ${this.name}`);
9765
+ }
9766
+ /**
9767
+ * Validate command arguments
9768
+ */
9769
+ async validate(_args) {
9770
+ return { success: true };
9771
+ }
9772
+ /**
9773
+ * Cleanup resources (called when command is unregistered)
9774
+ */
9775
+ async cleanup() {
9776
+ this.cache.clear();
9777
+ logger.debug(`Cleanup command: ${this.name}`);
9778
+ }
9779
+ /**
9780
+ * Rollback on error - override for custom rollback logic
9781
+ */
9782
+ async rollback(_context, error) {
9783
+ logger.error(`Rollback for ${this.name}:`, error);
9784
+ }
9785
+ // Helper methods for subclasses
9786
+ /**
9787
+ * Parse command arguments into structured format
9788
+ */
9789
+ parseArgs(raw) {
9790
+ const args = {
9791
+ raw,
9792
+ parsed: Record,
9793
+ flags: Record,
9794
+ options: Record
9795
+ };
9796
+ for (let i2 = 0; i2 < raw.length; i2++) {
9797
+ const _arg = raw[i2];
9798
+ if (!_arg) {
9799
+ continue;
9800
+ }
9801
+ if (_arg.startsWith("--")) {
9802
+ const _key = _arg.slice(2);
9803
+ const _nextArg = raw[i2 + 1];
9804
+ if (_nextArg && !_nextArg.startsWith("-")) {
9805
+ args.options[_key] = _nextArg;
9806
+ i2++;
9807
+ } else {
9808
+ args.flags[_key] = true;
9809
+ }
9810
+ } else if (_arg && _arg.startsWith("-") && _arg.length === 2) {
9811
+ args.flags[_arg.slice(1)] = true;
9812
+ } else {
9813
+ if (!args.parsed["positional"]) {
9814
+ args.parsed["positional"] = [];
9815
+ }
9816
+ args.parsed["positional"].push(_arg);
9817
+ }
9818
+ }
9819
+ return args;
9820
+ }
9821
+ /**
9822
+ * Create a success response
9823
+ */
9824
+ success(message, data2, metadata) {
9825
+ return {
9826
+ success: true,
9827
+ message,
9828
+ data: data2,
9829
+ metadata: {
9830
+ executionTime: Date.now(),
9831
+ commandVersion: this.metadata.version,
9832
+ ...metadata
9833
+ }
9834
+ };
9835
+ }
9836
+ /**
9837
+ * Create an error response
9838
+ */
9839
+ error(message, code, details) {
9840
+ return {
9841
+ success: false,
9842
+ message,
9843
+ data: { code, details },
9844
+ metadata: {
9845
+ executionTime: Date.now(),
9846
+ commandVersion: this.metadata.version
9847
+ }
9848
+ };
9849
+ }
9850
+ /**
9851
+ * Cache data with TTL
9852
+ */
9853
+ setCache(_key, data2, ttlSeconds = 60) {
9854
+ this.cache.set(_key, {
9855
+ data: data2,
9856
+ expires: Date.now() + ttlSeconds * 1e3
9857
+ });
9858
+ }
9859
+ /**
9860
+ * Get _cached data
9861
+ */
9862
+ getCache(_key) {
9863
+ const _cached = this.cache.get(_key);
9864
+ if (!_cached) {
9865
+ return null;
9866
+ }
9867
+ if (_cached.expires < Date.now()) {
9868
+ this.cache.delete(_key);
9869
+ return null;
9870
+ }
9871
+ return _cached.data;
9872
+ }
9873
+ /**
9874
+ * Check if user has required permissions
9875
+ */
9876
+ async checkPermissions(context2) {
9877
+ if (!this.permissions) {
9878
+ return { success: true };
9879
+ }
9880
+ const { requiresAuth, requiresPremium, role } = this.permissions;
9881
+ if (requiresAuth && !context2.user) {
9882
+ return {
9883
+ success: false,
9884
+ error: "Authentication required",
9885
+ suggestions: ["Run /login to authenticate"]
9886
+ };
9887
+ }
9888
+ if (role && context2.user?.role !== role) {
9889
+ return {
9890
+ success: false,
9891
+ error: `Required role: ${role}`,
9892
+ suggestions: [`Contact admin for ${role} access`]
9893
+ };
9894
+ }
9895
+ if (requiresPremium) {
9896
+ logger.warn("Premium check not implemented");
9897
+ }
9898
+ return { success: true };
9899
+ }
9900
+ /**
9901
+ * Format help text for this command
9902
+ */
9903
+ formatHelp() {
9904
+ const lines = [];
9905
+ lines.push(`\u{1F4D8} ${this.name.toUpperCase()}`);
9906
+ lines.push("\u2500".repeat(40));
9907
+ lines.push(`
9908
+ ${this.description}
9909
+ `);
9910
+ if (this.usage) {
9911
+ lines.push("**Usage:**");
9912
+ lines.push(` /${this.name} ${this.usage}
9913
+ `);
9914
+ }
9915
+ if (this.aliases && this.aliases.length > 0) {
9916
+ lines.push("**Aliases:**");
9917
+ lines.push(` ${this.aliases.map((a2) => `/${a2}`).join(", ")}
9918
+ `);
9919
+ }
9920
+ if (this.examples.length > 0) {
9921
+ lines.push("**Examples:**");
9922
+ this.examples.forEach((ex) => {
9923
+ lines.push(` ${ex.input}`);
9924
+ lines.push(` ${ex.description}`);
9925
+ if (ex.output) {
9926
+ lines.push(` \u2192 ${ex.output}`);
9927
+ }
9928
+ });
9929
+ lines.push("");
9930
+ }
9931
+ if (this.permissions) {
9932
+ lines.push("**Requirements:**");
9933
+ if (this.permissions.requiresAuth) {
9934
+ lines.push(" \u2022 Authentication required");
9935
+ }
9936
+ if (this.permissions.role) {
9937
+ lines.push(` \u2022 Role: ${this.permissions.role}`);
9938
+ }
9939
+ if (this.permissions.requiresPremium) {
9940
+ lines.push(" \u2022 Premium subscription");
9941
+ }
9942
+ lines.push("");
9943
+ }
9944
+ if (this.metadata.experimental) {
9945
+ lines.push("\u26A0\uFE0F **Experimental Feature**");
9946
+ }
9947
+ if (this.metadata.deprecated) {
9948
+ lines.push(
9949
+ `\u26A0\uFE0F **Deprecated** - Use ${this.metadata.replacedBy || "alternative"} instead`
9950
+ );
9951
+ }
9952
+ return lines.join("\n");
9953
+ }
9954
+ /**
9955
+ * Log command execution
9956
+ */
9957
+ logExecution(args, context2, result) {
9958
+ const _logData = {
9959
+ command: this.name,
9960
+ args: args.raw,
9961
+ user: context2.user?.id,
9962
+ success: result.success,
9963
+ executionTime: result.metadata?.executionTime
9964
+ };
9965
+ if (result.success) {
9966
+ logger.info("Command executed", _logData);
9967
+ } else {
9968
+ logger.error("Command failed", { ..._logData, error: result.message });
9969
+ }
9970
+ }
9971
+ };
9972
+ }
9973
+ });
9974
+
9975
+ // src/slash-commands/help/metadata-validator.ts
9976
+ function validateHelpMetadata(container, opts = {}) {
9977
+ const errors = [];
9978
+ const warnings = [];
9979
+ if (!isObject(container)) {
9980
+ return fail("container is not an object");
9981
+ }
9982
+ const c = container;
9983
+ if (!isInt(c.schemaVersion)) errors.push("schemaVersion must be an integer");
9984
+ if (!isISO(c.generatedAt)) errors.push("generatedAt must be ISO-8601 string");
9985
+ if (!Array.isArray(c.commands)) errors.push("commands must be an array");
9986
+ const expected = opts.expectedSchemaVersion;
9987
+ if (expected != null && c.schemaVersion !== expected) {
9988
+ warnings.push(
9989
+ `schemaVersion mismatch: meta=${c.schemaVersion}, expected=${expected}`
9990
+ );
9991
+ }
9992
+ if (errors.length) {
9993
+ return {
9994
+ ok: false,
9995
+ errors,
9996
+ warnings,
9997
+ counts: { commands: 0, categories: 0 }
9998
+ };
9999
+ }
10000
+ const cmds = c.commands;
10001
+ if (cmds.length === 0) errors.push("commands array is empty");
10002
+ const nameSet = /* @__PURE__ */ new Set();
10003
+ const aliasSet = /* @__PURE__ */ new Set();
10004
+ const categorySet = /* @__PURE__ */ new Set();
10005
+ for (const m2 of cmds) {
10006
+ if (!m2 || !isObject(m2)) {
10007
+ errors.push("command entry is not an object");
10008
+ continue;
10009
+ }
10010
+ if (!isString(m2.name) || !m2.name.startsWith("/")) {
10011
+ errors.push(`invalid name: ${JSON.stringify(m2?.name)}`);
10012
+ } else if (nameSet.has(m2.name)) {
10013
+ errors.push(`duplicated name: ${m2.name}`);
10014
+ } else {
10015
+ nameSet.add(m2.name);
10016
+ }
10017
+ if (!isString(m2.category) || !m2.category.trim()) {
10018
+ errors.push(`invalid category for ${m2.name}`);
10019
+ } else {
10020
+ categorySet.add(m2.category);
10021
+ }
10022
+ if (!ALLOWED_LEVEL.includes(m2.level)) {
10023
+ errors.push(`invalid level for ${m2.name}: ${m2.level}`);
10024
+ }
10025
+ if (m2.tags) {
10026
+ for (const t2 of m2.tags) {
10027
+ if (!ALLOWED_TAGS.includes(t2)) {
10028
+ errors.push(`invalid tag "${t2}" on ${m2.name}`);
10029
+ }
10030
+ }
10031
+ }
10032
+ if (m2.usage) {
10033
+ if (m2.usage.count != null && (!isInt(m2.usage.count) || m2.usage.count < 0)) {
10034
+ errors.push(`usage.count must be non-negative int on ${m2.name}`);
10035
+ }
10036
+ if (m2.usage.frequency != null && !(typeof m2.usage.frequency === "number" && m2.usage.frequency >= 0)) {
10037
+ errors.push(`usage.frequency must be non-negative number on ${m2.name}`);
10038
+ }
10039
+ if (m2.usage.lastUsed != null && !isISO(m2.usage.lastUsed)) {
10040
+ errors.push(`usage.lastUsed must be ISO-8601 on ${m2.name}`);
10041
+ }
10042
+ }
10043
+ if (m2.aliases) {
10044
+ for (const a2 of m2.aliases) {
10045
+ if (!isString(a2) || !a2.startsWith("/")) {
10046
+ errors.push(
10047
+ `invalid alias "${a2}" on ${m2.name} (must start with "/")`
10048
+ );
10049
+ continue;
10050
+ }
10051
+ if (nameSet.has(a2)) {
10052
+ errors.push(`alias conflicts with existing name: ${a2} on ${m2.name}`);
10053
+ continue;
10054
+ }
10055
+ if (aliasSet.has(a2)) {
10056
+ errors.push(`duplicated alias across commands: ${a2} on ${m2.name}`);
10057
+ continue;
10058
+ }
10059
+ aliasSet.add(a2);
10060
+ }
10061
+ }
10062
+ }
10063
+ const byName = new Map(cmds.map((m2) => [m2.name, m2]));
10064
+ for (const m2 of cmds) {
10065
+ if (m2.parent) {
10066
+ if (!byName.has(m2.parent)) {
10067
+ errors.push(`parent not found: ${m2.name} \u2192 ${m2.parent}`);
10068
+ }
10069
+ const computedDepth = computeDepth(m2, byName, errors);
10070
+ if (m2.depth != null && m2.depth !== computedDepth) {
10071
+ warnings.push(
10072
+ `depth mismatch on ${m2.name}: meta=${m2.depth} computed=${computedDepth}`
10073
+ );
10074
+ }
10075
+ if (opts.maxDepth != null && computedDepth > opts.maxDepth) {
10076
+ warnings.push(
10077
+ `depth exceeds maxDepth on ${m2.name}: ${computedDepth} > ${opts.maxDepth}`
10078
+ );
10079
+ }
10080
+ if (m2.level === "primary") {
10081
+ warnings.push(`command marked primary but has parent: ${m2.name}`);
10082
+ }
10083
+ } else {
10084
+ if (m2.depth != null && m2.depth !== 0) {
10085
+ warnings.push(`root command depth should be 0 on ${m2.name}`);
10086
+ }
10087
+ }
10088
+ }
10089
+ const seenGlobal = /* @__PURE__ */ new Set();
10090
+ for (const m2 of cmds) {
10091
+ if (seenGlobal.has(m2.name)) continue;
10092
+ const cycle = detectCycle(m2, byName);
10093
+ if (cycle) {
10094
+ errors.push(`cycle detected: ${cycle.join(" -> ")}`);
10095
+ }
10096
+ seenGlobal.add(m2.name);
10097
+ }
10098
+ if (c.stats) {
10099
+ if (c.stats.totalCommands != null && c.stats.totalCommands !== cmds.length) {
10100
+ warnings.push(
10101
+ `stats.totalCommands mismatch: meta=${c.stats.totalCommands} actual=${cmds.length}`
10102
+ );
10103
+ }
10104
+ if (c.stats.totalCategories != null && c.stats.totalCategories !== categorySet.size) {
10105
+ warnings.push(
10106
+ `stats.totalCategories mismatch: meta=${c.stats.totalCategories} actual=${categorySet.size}`
10107
+ );
10108
+ }
10109
+ if (c.stats.lastUpdated && !isISO(c.stats.lastUpdated)) {
10110
+ warnings.push(`stats.lastUpdated must be ISO-8601`);
10111
+ }
10112
+ }
10113
+ return {
10114
+ ok: errors.length === 0,
10115
+ errors,
10116
+ warnings,
10117
+ counts: {
10118
+ commands: cmds.length,
10119
+ categories: categorySet.size
10120
+ }
10121
+ };
10122
+ function fail(msg) {
10123
+ return {
10124
+ ok: false,
10125
+ errors: [msg],
10126
+ warnings: [],
10127
+ counts: { commands: 0, categories: 0 }
10128
+ };
10129
+ }
10130
+ }
10131
+ function isObject(x2) {
10132
+ return !!x2 && typeof x2 === "object";
10133
+ }
10134
+ function isString(x2) {
10135
+ return typeof x2 === "string";
10136
+ }
10137
+ function isInt(x2) {
10138
+ return typeof x2 === "number" && Number.isInteger(x2);
10139
+ }
10140
+ function isISO(x2) {
10141
+ if (typeof x2 !== "string") return false;
10142
+ const d = new Date(x2);
10143
+ return !Number.isNaN(d.getTime()) && /^\d{4}-\d{2}-\d{2}T/.test(x2);
10144
+ }
10145
+ function computeDepth(node2, byName, errors) {
10146
+ let depth = 0;
10147
+ const visited2 = /* @__PURE__ */ new Set();
10148
+ let cur = node2;
10149
+ while (cur?.parent) {
10150
+ if (visited2.has(cur.name)) {
10151
+ errors.push(`cycle while computing depth at ${cur.name}`);
10152
+ break;
10153
+ }
10154
+ visited2.add(cur.name);
10155
+ const p = byName.get(cur.parent);
10156
+ if (!p) break;
10157
+ depth++;
10158
+ cur = p;
10159
+ if (depth > 1e3) {
10160
+ errors.push(`depth overflow at ${node2.name}`);
10161
+ break;
10162
+ }
10163
+ }
10164
+ return depth;
10165
+ }
10166
+ function detectCycle(start, byName) {
10167
+ const stack = [];
10168
+ const visiting = /* @__PURE__ */ new Set();
10169
+ let cur = start;
10170
+ while (cur) {
10171
+ if (visiting.has(cur.name)) {
10172
+ const idx = stack.indexOf(cur.name);
10173
+ return idx >= 0 ? stack.slice(idx).concat(cur.name) : [cur.name, cur.name];
10174
+ }
10175
+ visiting.add(cur.name);
10176
+ stack.push(cur.name);
10177
+ if (!cur.parent) break;
10178
+ cur = byName.get(cur.parent);
10179
+ }
10180
+ return null;
10181
+ }
10182
+ var ALLOWED_LEVEL, ALLOWED_TAGS;
10183
+ var init_metadata_validator = __esm({
10184
+ "src/slash-commands/help/metadata-validator.ts"() {
10185
+ ALLOWED_LEVEL = ["primary", "secondary", "hidden"];
10186
+ ALLOWED_TAGS = ["core", "advanced", "experimental", "deprecated"];
10187
+ }
10188
+ });
10189
+ var MetadataManager;
10190
+ var init_metadata_manager = __esm({
10191
+ "src/slash-commands/help/metadata-manager.ts"() {
10192
+ init_metadata_validator();
10193
+ MetadataManager = class {
10194
+ cache;
10195
+ cacheTime;
10196
+ CACHE_TTL = 5 * 60 * 1e3;
10197
+ // 5 minutes
10198
+ STALE_WARNING_MS = 7 * 864e5;
10199
+ // 7 days
10200
+ metaPath;
10201
+ constructor(metaPath) {
10202
+ this.metaPath = metaPath ?? path8__namespace.resolve("src/slash-commands/help/command-meta.json");
10203
+ }
10204
+ async load() {
10205
+ if (this.cache && this.cacheTime && Date.now() - this.cacheTime < this.CACHE_TTL) {
10206
+ return this.cache;
10207
+ }
10208
+ try {
10209
+ const meta = await this.loadFromDisk();
10210
+ const validation = validateHelpMetadata(meta, {
10211
+ expectedSchemaVersion: 1
10212
+ });
10213
+ if (!validation.ok) {
10214
+ console.error("[help] Metadata validation failed:", validation.errors);
10215
+ throw new Error("Invalid metadata structure");
10216
+ }
10217
+ if (validation.warnings.length > 0) {
10218
+ for (const warning of validation.warnings) {
10219
+ console.warn(`[help] Warning: ${warning}`);
10220
+ }
10221
+ }
10222
+ const age = Date.now() - new Date(meta.generatedAt).getTime();
10223
+ if (age > this.STALE_WARNING_MS) {
10224
+ console.warn(
10225
+ "[help] Metadata stale (7d+), consider running: npx tsx scripts/generate-help-meta.ts"
10226
+ );
10227
+ this.triggerBackgroundRegeneration();
10228
+ }
10229
+ this.cache = meta;
10230
+ this.cacheTime = Date.now();
10231
+ return meta;
10232
+ } catch (error) {
10233
+ console.error("[help] Failed to load metadata:", error);
10234
+ throw new Error(
10235
+ `Metadata loading failed: ${error instanceof Error ? error.message : error}`
10236
+ );
10237
+ }
10238
+ }
10239
+ async loadFromDisk() {
10240
+ const text = await fs8__namespace.readFile(this.metaPath, "utf8");
10241
+ const data2 = JSON.parse(text);
10242
+ if (Array.isArray(data2)) {
10243
+ return {
10244
+ schemaVersion: 1,
10245
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
10246
+ generatorVersion: "legacy",
10247
+ commands: data2,
10248
+ stats: {
10249
+ totalCommands: data2.length,
10250
+ totalCategories: new Set(data2.map((c) => c.category)).size,
10251
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
10252
+ }
10253
+ };
10254
+ }
10255
+ return data2;
10256
+ }
10257
+ hasStaleCache() {
10258
+ return !!this.cache;
10259
+ }
10260
+ getStaleCache() {
10261
+ return this.cache;
10262
+ }
10263
+ triggerBackgroundRegeneration() {
10264
+ try {
10265
+ const child2 = child_process.spawn("npx", ["tsx", "scripts/generate-help-meta.ts"], {
10266
+ detached: true,
10267
+ stdio: "ignore"
10268
+ });
10269
+ child2.unref();
10270
+ console.log("[help] Background metadata regeneration triggered");
10271
+ } catch (error) {
10272
+ console.warn("[help] Failed to trigger background regeneration:", error);
10273
+ }
10274
+ }
10275
+ /**
10276
+ * Build compact JSON for non-TTY output
10277
+ */
10278
+ buildCompactJson(metas) {
10279
+ const byCat = /* @__PURE__ */ new Map();
10280
+ for (const m2 of metas) {
10281
+ if (m2.level === "hidden") continue;
10282
+ const arr = byCat.get(m2.category) || [];
10283
+ arr.push(m2);
10284
+ byCat.set(m2.category, arr);
10285
+ }
10286
+ const categories = [];
10287
+ for (const [cat, arr] of byCat) {
10288
+ const primaries = arr.filter((x2) => x2.level === "primary" && !x2.parent).sort(
10289
+ (a2, b) => (a2.rank ?? 1e9) - (b.rank ?? 1e9) || a2.name.localeCompare(b.name)
10290
+ );
10291
+ const top = primaries.slice(0, 3).map((p) => ({
10292
+ name: p.name,
10293
+ title: p.title
10294
+ }));
10295
+ const more = Math.max(0, primaries.length - top.length);
10296
+ categories.push({
10297
+ category: cat,
10298
+ total: arr.length,
10299
+ top,
10300
+ more
10301
+ });
10302
+ }
10303
+ categories.sort((a2, b) => a2.category.localeCompare(b.category));
10304
+ return {
10305
+ mode: "compact-json",
10306
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
10307
+ categories
10308
+ };
10309
+ }
10310
+ };
10311
+ }
10312
+ });
10313
+
10314
+ // src/slash-commands/help/renderers/compact-renderer.ts
10315
+ function renderCompactHelp(metas, opts = {}) {
10316
+ const {
10317
+ maxPrimaryPerCategory = 3,
10318
+ maxCategories = 16,
10319
+ showAdvanced = false,
10320
+ twoColumnThreshold = 100,
10321
+ categoryOrder,
10322
+ heading = "\u{1F4D6} MARIA Commands (compact \u2022 primary only)"
10323
+ } = opts;
10324
+ const visible = metas.filter((m2) => showAdvanced || m2.level !== "hidden");
10325
+ const byCat = /* @__PURE__ */ new Map();
10326
+ for (const m2 of visible) {
10327
+ const arr = byCat.get(m2.category) || [];
10328
+ arr.push(m2);
10329
+ byCat.set(m2.category, arr);
10330
+ }
10331
+ const compact = Array.from(byCat.entries()).map(([cat, arr]) => {
10332
+ const primary = arr.filter((m2) => m2.level === "primary").sort(sorter2);
10333
+ const total = arr.length;
10334
+ const items = primary.slice(0, maxPrimaryPerCategory);
10335
+ const more = Math.max(0, total - items.length);
10336
+ return { category: cat, items, total, more };
10337
+ });
10338
+ compact.sort(
10339
+ (a2, b) => categoryIndex(a2.category) - categoryIndex(b.category) || a2.category.localeCompare(b.category)
10340
+ );
10341
+ const limitedCompact = compact.slice(0, maxCategories);
10342
+ const remainingCats = compact.length - limitedCompact.length;
10343
+ const width = process.stdout.columns || 80;
10344
+ const twoCol = width >= twoColumnThreshold && compact.length > 6;
10345
+ const colPad = twoCol ? Math.floor(width / 2) : width;
10346
+ const lines = [];
10347
+ lines.push(heading, "");
10348
+ let buffer = [];
10349
+ function flushRow() {
10350
+ if (!twoCol) {
10351
+ lines.push(...buffer);
10352
+ buffer = [];
10353
+ return;
10354
+ }
10355
+ for (let i2 = 0; i2 < buffer.length; i2 += 2) {
10356
+ const left = buffer[i2] ?? "";
10357
+ const right = buffer[i2 + 1] ?? "";
10358
+ const paddedLeft = left.padEnd(colPad - 1, " ");
10359
+ lines.push(paddedLeft + right);
10360
+ }
10361
+ buffer = [];
10362
+ }
10363
+ for (const block of limitedCompact) {
10364
+ const head = formatCategoryHeader(
10365
+ block.category,
10366
+ block.items.length,
10367
+ block.total
10368
+ );
10369
+ const body = [
10370
+ ...block.items.map(
10371
+ (it) => ` ${padCmd3(it.name, 20)} ${truncate3(it.title ?? "", colPad - 24)}`
10372
+ ),
10373
+ block.more > 0 ? ` +${block.more} more \u2192 /help ${block.category}` : ""
10374
+ ].filter(Boolean);
10375
+ const segment = [head, ...body, ""].join("\n");
10376
+ if (twoCol) {
10377
+ buffer.push(segment);
10378
+ if (buffer.length === 2) flushRow();
10379
+ } else {
10380
+ lines.push(segment);
10381
+ }
10382
+ }
10383
+ if (buffer.length) flushRow();
10384
+ const totalCmds = metas.length;
10385
+ const totalCats = byCat.size;
10386
+ const footerLines = [
10387
+ `Tip: /help <category> \u3067\u5C55\u958B, /help --search <kw>, /help --all${showAdvanced ? "" : ", /help --advanced"}`,
10388
+ `Total: ${totalCmds} cmds / ${totalCats} cats (showing ${limitedCompact.length}/${totalCats} categories)`
10389
+ ];
10390
+ if (remainingCats > 0) {
10391
+ footerLines.push(
10392
+ `${remainingCats} more categories available with /help --all`
10393
+ );
10394
+ }
10395
+ lines.push(...footerLines);
10396
+ return lines.join("\n");
10397
+ function sorter2(a2, b) {
10398
+ if ((a2.rank ?? 999999) !== (b.rank ?? 999999))
10399
+ return (a2.rank ?? 999999) - (b.rank ?? 999999);
10400
+ return a2.name.localeCompare(b.name);
10401
+ }
10402
+ function categoryIndex(cat) {
10403
+ if (!categoryOrder) return 0;
10404
+ const idx = categoryOrder.indexOf(cat);
10405
+ return idx === -1 ? 9999 : idx;
10406
+ }
10407
+ function formatCategoryHeader(cat, shown, total) {
10408
+ const label = beautifyCategory3(cat);
10409
+ return `${label} (${shown} of ${total})`;
10410
+ }
10411
+ function beautifyCategory3(cat) {
10412
+ const map = {
10413
+ core: "\u{1F4DD} Core",
10414
+ generation: "\u{1F680} Content Generation",
10415
+ analysis: "\u{1F50D} Analysis & Review",
10416
+ quality: "\u{1F6E1}\uFE0F Code Quality",
10417
+ development: "\u2699\uFE0F Development Tools",
10418
+ workflow: "\u{1F504} Workflow Automation",
10419
+ configuration: "\u{1F4CB} Configuration",
10420
+ auth: "\u{1F510} Authentication",
10421
+ media: "\u{1F3A8} Media Generation",
10422
+ integration: "\u{1F517} Integration",
10423
+ system: "\u{1F3E5} System & Diagnostics",
10424
+ optimization: "\u26A1 Performance Optimization",
10425
+ creative: "\u{1F3A8} Creative Tools",
10426
+ implementation: "\u{1F527} Implementation Utilities",
10427
+ evolution: "\u{1F9E0} RL Evolution",
10428
+ ai: "\u{1F916} AI & GPU Operations",
10429
+ monitoring: "\u{1F4CA} Real-time Monitoring",
10430
+ file: "\u{1F4BE} File Operations",
10431
+ "coding-agent": "\u{1F916} AI Coding Agent",
10432
+ business: "\u{1F4BC} Business Operations"
10433
+ };
10434
+ return map[cat] ?? cat.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
10435
+ }
10436
+ function padCmd3(cmd, len) {
10437
+ return cmd.padEnd(len, " ");
10438
+ }
10439
+ function truncate3(s2, max) {
10440
+ if (s2.length <= max) return s2;
10441
+ return s2.slice(0, Math.max(0, max - 1)) + "\u2026";
10442
+ }
10443
+ }
10444
+ var init_compact_renderer = __esm({
10445
+ "src/slash-commands/help/renderers/compact-renderer.ts"() {
10446
+ }
10447
+ });
10448
+
10449
+ // src/slash-commands/help/renderers/detail-renderer.ts
10450
+ function sorter(a2, b) {
10451
+ if ((a2.rank ?? 999999) !== (b.rank ?? 999999))
10452
+ return (a2.rank ?? 999999) - (b.rank ?? 999999);
10453
+ return a2.name.localeCompare(b.name);
10454
+ }
10455
+ function beautifyCategory(cat) {
10456
+ const map = {
10457
+ core: "\u{1F4DD} Core",
10458
+ generation: "\u{1F680} Content Generation",
10459
+ analysis: "\u{1F50D} Analysis & Review",
10460
+ quality: "\u{1F6E1}\uFE0F Code Quality",
10461
+ development: "\u2699\uFE0F Development Tools",
10462
+ workflow: "\u{1F504} Workflow Automation",
10463
+ configuration: "\u{1F4CB} Configuration",
10464
+ auth: "\u{1F510} Authentication",
10465
+ media: "\u{1F3A8} Media Generation",
10466
+ integration: "\u{1F517} Integration",
10467
+ system: "\u{1F3E5} System & Diagnostics",
10468
+ optimization: "\u26A1 Performance Optimization",
10469
+ creative: "\u{1F3A8} Creative Tools",
10470
+ implementation: "\u{1F527} Implementation Utilities",
10471
+ evolution: "\u{1F9E0} RL Evolution",
10472
+ ai: "\u{1F916} AI & GPU Operations",
10473
+ monitoring: "\u{1F4CA} Real-time Monitoring",
10474
+ file: "\u{1F4BE} File Operations",
10475
+ "coding-agent": "\u{1F916} AI Coding Agent",
10476
+ business: "\u{1F4BC} Business Operations"
10477
+ };
10478
+ return map[cat] ?? cat.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
10479
+ }
10480
+ function padCmd(cmd, len) {
10481
+ return cmd.padEnd(len, " ");
10482
+ }
10483
+ function truncate(s2, max) {
10484
+ if (s2.length <= max) return s2;
10485
+ return s2.slice(0, Math.max(0, max - 1)) + "\u2026";
10486
+ }
10487
+ function formatTags(m2) {
10488
+ if (!m2.tags || m2.tags.length === 0) return "";
10489
+ return " [" + m2.tags.join(",") + "]";
10490
+ }
10491
+ function renderCategoryHelp(metas, category, opts = {}) {
10492
+ const width = opts.width ?? process.stdout.columns ?? 80;
10493
+ const colCmd = Math.min(24, Math.max(16, Math.floor(width * 0.28)));
10494
+ const advanced = !!opts.advanced;
10495
+ let target = metas.filter((m2) => m2.category === category);
10496
+ if (!advanced) target = target.filter((m2) => m2.level !== "hidden");
10497
+ const primary = target.filter((m2) => !m2.parent && m2.level !== "hidden" && m2.level !== "secondary").sort(sorter);
10498
+ const secondaries = target.filter((m2) => m2.parent || m2.level === "secondary").sort(sorter);
10499
+ const byParent = /* @__PURE__ */ new Map();
10500
+ for (const s2 of secondaries) {
10501
+ const p = s2.parent ?? "(misc)";
10502
+ const arr = byParent.get(p) || [];
10503
+ arr.push(s2);
10504
+ byParent.set(p, arr);
10505
+ }
10506
+ const lines = [];
10507
+ lines.push(
10508
+ opts.heading ?? `\u{1F4D6} ${beautifyCategory(category)} \u2014 All Commands`,
10509
+ ""
10510
+ );
10511
+ if (primary.length) {
10512
+ lines.push("Primary:");
10513
+ for (const p of primary) {
10514
+ const alias = opts.showAliases && p.aliases?.length ? ` (aka: ${p.aliases.join(", ")})` : "";
10515
+ const tags = formatTags(p);
10516
+ lines.push(
10517
+ ` ${padCmd(p.name, colCmd)} ${truncate((p.title ?? "") + alias + tags, width - colCmd - 4)}`
10518
+ );
10519
+ }
10520
+ lines.push("");
10521
+ }
10522
+ const parentsSorted = Array.from(byParent.keys()).sort();
10523
+ for (const parent of parentsSorted) {
10524
+ const children = byParent.get(parent).sort(sorter);
10525
+ const parentHead = parent !== "(misc)" ? parent : "Subcommands";
10526
+ lines.push(`${parentHead}:`);
10527
+ for (const c of children) {
10528
+ const alias = opts.showAliases && c.aliases?.length ? ` (aka: ${c.aliases.join(", ")})` : "";
10529
+ const tags = formatTags(c);
10530
+ lines.push(
10531
+ ` ${padCmd(c.name, colCmd)} ${truncate((c.title ?? "") + alias + tags, width - colCmd - 4)}`
10532
+ );
10533
+ }
10534
+ lines.push("");
10535
+ }
10536
+ if (!primary.length && byParent.size === 0) {
10537
+ lines.push("(No commands found in this category)");
10538
+ lines.push("");
10539
+ }
10540
+ lines.push(
10541
+ `Tip: /help --search <kw>, /help --all${advanced ? "" : ", /help --advanced"}`
10542
+ );
10543
+ return lines.join("\n");
10544
+ }
10545
+ function renderSearchHelp(metas, query, opts = {}) {
10546
+ const width = opts.width ?? process.stdout.columns ?? 80;
10547
+ const colCmd = Math.min(24, Math.max(16, Math.floor(width * 0.28)));
10548
+ const advanced = !!opts.advanced;
10549
+ const matchMode = opts.matchMode ?? "any";
10550
+ const q = query.trim().toLowerCase();
10551
+ if (!q) return "Please provide a search keyword.\n";
10552
+ const pool = advanced ? metas : metas.filter((m2) => m2.level !== "hidden");
10553
+ const matches2 = pool.map((m2) => ({ meta: m2, score: fuzzyScore(m2, q, matchMode) })).filter((x2) => x2.score > 0).sort(
10554
+ (a2, b) => b.score - a2.score || (a2.meta.rank ?? 999999) - (b.meta.rank ?? 999999)
10555
+ ).slice(0, 50);
10556
+ const lines = [];
10557
+ lines.push(`\u{1F50E} Search: "${query}" (${matches2.length} results)`, "");
10558
+ if (matches2.length === 0) {
10559
+ lines.push(
10560
+ "No matches. Try another keyword or use --match all for stricter matching."
10561
+ );
10562
+ return lines.join("\n");
10563
+ }
10564
+ const byCat = /* @__PURE__ */ new Map();
10565
+ for (const m2 of matches2) {
10566
+ const arr = byCat.get(m2.meta.category) || [];
10567
+ arr.push(m2);
10568
+ byCat.set(m2.meta.category, arr);
10569
+ }
10570
+ const cats = Array.from(byCat.keys()).sort();
10571
+ for (const cat of cats) {
10572
+ lines.push(`${beautifyCategory(cat)}:`);
10573
+ const arr = byCat.get(cat).sort((a2, b) => b.score - a2.score || sorter(a2.meta, b.meta));
10574
+ for (const { meta } of arr) {
10575
+ const alias = opts.showAliases && meta.aliases?.length ? ` (aka: ${meta.aliases.join(", ")})` : "";
10576
+ const tags = formatTags(meta);
10577
+ const badge = meta.level === "secondary" ? "\xB7 " : "";
10578
+ lines.push(
10579
+ ` ${badge}${padCmd(meta.name, colCmd)} ${truncate((meta.title ?? "") + alias + tags, width - colCmd - 6)}`
10580
+ );
10581
+ }
10582
+ lines.push("");
10583
+ }
10584
+ lines.push(
10585
+ `Tip: /help <category> \u3067\u8A72\u5F53\u30AB\u30C6\u30B4\u30EA\u3092\u5C55\u958B, /help --all${advanced ? "" : ", /help --advanced"}`
10586
+ );
10587
+ return lines.join("\n");
10588
+ function fuzzyScore(m2, q2, mode) {
10589
+ const tokens = q2.split(/\s+/).filter(Boolean);
10590
+ [
10591
+ m2.name.toLowerCase(),
10592
+ (m2.title ?? "").toLowerCase(),
10593
+ m2.category.toLowerCase(),
10594
+ ...(m2.aliases ?? []).map((a2) => a2.toLowerCase())
10595
+ ].join(" | ");
10596
+ let totalScore = 0;
10597
+ let matchedTokens = 0;
10598
+ for (const token of tokens) {
10599
+ let tokenScore = 0;
10600
+ if (m2.name.toLowerCase() === token || m2.name.toLowerCase() === "/" + token) {
10601
+ tokenScore = 1e4;
10602
+ } else if (m2.aliases?.some(
10603
+ (a2) => a2.toLowerCase() === token || a2.toLowerCase() === "/" + token
10604
+ )) {
10605
+ tokenScore = 8e3;
10606
+ } else if (m2.name.toLowerCase().startsWith("/" + token)) {
10607
+ tokenScore = 5e3;
10608
+ } else if (m2.name.toLowerCase().includes(token)) {
10609
+ tokenScore = 3e3;
10610
+ } else if (m2.name.split(/[\s\/]+/).some((w) => w.toLowerCase().startsWith(token))) {
10611
+ tokenScore = 2e3;
10612
+ } else if (m2.title?.toLowerCase().includes(token)) {
10613
+ tokenScore = 1e3;
10614
+ } else if (m2.category.toLowerCase().includes(token)) {
10615
+ tokenScore = 500;
10616
+ }
10617
+ if (tokenScore > 0) {
10618
+ matchedTokens++;
10619
+ totalScore += tokenScore;
10620
+ }
10621
+ }
10622
+ if (mode === "all" && matchedTokens < tokens.length) {
10623
+ return 0;
10624
+ }
10625
+ if (mode === "any" && matchedTokens === 0) {
10626
+ return 0;
10627
+ }
10628
+ if (m2.usage?.frequency) {
10629
+ totalScore *= 1 + Math.min(m2.usage.frequency / 100, 2);
10630
+ }
10631
+ if (m2.tags?.includes("deprecated")) totalScore *= 0.5;
10632
+ if (m2.tags?.includes("experimental")) totalScore *= 0.8;
10633
+ return totalScore;
10634
+ }
10635
+ }
10636
+ var init_detail_renderer = __esm({
10637
+ "src/slash-commands/help/renderers/detail-renderer.ts"() {
10638
+ }
10639
+ });
10640
+
10641
+ // src/slash-commands/help/renderers/full-renderer.ts
10642
+ function renderFullHelp(metas, opts = {}) {
10643
+ const {
10644
+ advanced = false,
10645
+ showAliases = false,
10646
+ categoryOrder,
10647
+ heading = "\u{1F4D6} MARIA Commands \u2014 Full Listing"
10648
+ } = opts;
10649
+ const width = opts.width ?? process.stdout.columns ?? 80;
10650
+ const colCmd = Math.min(28, Math.max(16, Math.floor(width * 0.3)));
10651
+ const visible = advanced ? metas : metas.filter((m2) => m2.level !== "hidden");
10652
+ const byCat = /* @__PURE__ */ new Map();
10653
+ for (const m2 of visible) {
10654
+ const arr = byCat.get(m2.category) || [];
10655
+ arr.push(m2);
10656
+ byCat.set(m2.category, arr);
10657
+ }
10658
+ const cats = Array.from(byCat.keys()).sort(
10659
+ (a2, b) => categoryIndex(a2) - categoryIndex(b) || a2.localeCompare(b)
10660
+ );
10661
+ const out = [];
10662
+ out.push(heading, "");
10663
+ for (const cat of cats) {
10664
+ const list = (byCat.get(cat) || []).slice().sort(sorter2);
10665
+ const primaries = list.filter((m2) => m2.level === "primary" && !m2.parent);
10666
+ const secondaries = list.filter((m2) => m2.level !== "primary" || m2.parent);
10667
+ out.push(`${beautifyCategory3(cat)} (${list.length})`, "");
10668
+ if (primaries.length) {
10669
+ out.push("Primary:");
10670
+ for (const p of primaries) {
10671
+ out.push(` ${padCmd3(p.name, colCmd)} ${fmtDesc(p)}`);
10672
+ }
10673
+ out.push("");
10674
+ }
10675
+ if (secondaries.length) {
10676
+ const byParent = /* @__PURE__ */ new Map();
10677
+ for (const s2 of secondaries) {
10678
+ const k = s2.parent ?? "(misc)";
10679
+ const arr = byParent.get(k) || [];
10680
+ arr.push(s2);
10681
+ byParent.set(k, arr);
10682
+ }
10683
+ const parents = Array.from(byParent.keys()).sort();
10684
+ for (const parent of parents) {
10685
+ const label = parent !== "(misc)" ? parent : "Subcommands";
10686
+ out.push(`${label}:`);
10687
+ const children = (byParent.get(parent) || []).slice().sort(sorter2);
10688
+ for (const c of children) {
10689
+ out.push(` ${padCmd3(c.name, colCmd)} ${fmtDesc(c)}`);
10690
+ }
10691
+ out.push("");
10692
+ }
10693
+ }
10694
+ out.push("");
10695
+ }
10696
+ out.push(
10697
+ `Tip: /help <category> \u3067\u30AB\u30C6\u30B4\u30EA\u5225\u3001/help --search <kw> \u3067\u7D5E\u308A\u8FBC\u307F\u3001/help \u3067\u30B3\u30F3\u30D1\u30AF\u30C8\u8868\u793A`,
10698
+ `Total: ${metas.length} commands across ${cats.length} categories${advanced ? " (advanced shown)" : ""}`
10699
+ );
10700
+ return out.join("\n");
10701
+ function sorter2(a2, b) {
10702
+ if ((a2.rank ?? 999999) !== (b.rank ?? 999999))
10703
+ return (a2.rank ?? 999999) - (b.rank ?? 999999);
10704
+ return a2.name.localeCompare(b.name);
10705
+ }
10706
+ function categoryIndex(cat) {
10707
+ if (!categoryOrder) return 0;
10708
+ const i2 = categoryOrder.indexOf(cat);
10709
+ return i2 === -1 ? 9999 : i2;
10710
+ }
10711
+ function beautifyCategory3(cat) {
10712
+ const map = {
10713
+ core: "\u{1F4DD} Core",
10714
+ generation: "\u{1F680} Content Generation",
10715
+ analysis: "\u{1F50D} Analysis & Review",
10716
+ quality: "\u{1F6E1}\uFE0F Code Quality",
10717
+ development: "\u2699\uFE0F Development Tools",
10718
+ workflow: "\u{1F504} Workflow Automation",
10719
+ configuration: "\u{1F4CB} Configuration",
10720
+ auth: "\u{1F510} Authentication",
10721
+ media: "\u{1F3A8} Media Generation",
10722
+ integration: "\u{1F517} Integration",
10723
+ system: "\u{1F3E5} System & Diagnostics",
10724
+ optimization: "\u26A1 Performance Optimization",
10725
+ creative: "\u{1F3A8} Creative Tools",
10726
+ implementation: "\u{1F527} Implementation Utilities",
10727
+ evolution: "\u{1F9E0} RL Evolution",
10728
+ ai: "\u{1F916} AI & GPU Operations",
10729
+ monitoring: "\u{1F4CA} Real-time Monitoring",
10730
+ file: "\u{1F4BE} File Operations",
10731
+ "coding-agent": "\u{1F916} AI Coding Agent",
10732
+ business: "\u{1F4BC} Business Operations"
10733
+ };
10734
+ return map[cat] ?? cat.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
10735
+ }
10736
+ function padCmd3(cmd, len) {
10737
+ return cmd.padEnd(len, " ");
10738
+ }
10739
+ function truncate3(s2, max) {
10740
+ if (s2.length <= max) return s2;
10741
+ return s2.slice(0, Math.max(0, max - 1)) + "\u2026";
10742
+ }
10743
+ function fmtDesc(m2) {
10744
+ const alias = showAliases && m2.aliases?.length ? ` (aka: ${m2.aliases.join(", ")})` : "";
10745
+ const tags = m2.tags && m2.tags.length ? ` [${m2.tags.join(",")}]` : "";
10746
+ const text = ((m2.title ?? "") + alias + tags).trim();
10747
+ return truncate3(text, Math.max(8, width - colCmd - 4));
10748
+ }
10749
+ }
10750
+ var init_full_renderer = __esm({
10751
+ "src/slash-commands/help/renderers/full-renderer.ts"() {
10752
+ }
10753
+ });
10754
+ async function runInteractiveHelp(opts = {}) {
10755
+ const metaPath = opts.metaPath ?? path8__namespace.resolve("src/slash-commands/help/command-meta.json");
10756
+ let container;
10757
+ try {
10758
+ const text = await fs8__namespace.readFile(metaPath, "utf8");
10759
+ container = JSON.parse(text);
10760
+ } catch (error) {
10761
+ throw new Error(`Failed to load metadata: ${error}`);
10762
+ }
10763
+ const metas = Array.isArray(container) ? container : container.commands;
10764
+ if (!Array.isArray(metas) || metas.length === 0) {
10765
+ throw new Error("help meta not found or empty");
10766
+ }
10767
+ const state = buildState(
10768
+ metas,
10769
+ !!opts.showAdvancedDefault,
10770
+ opts.heading ?? "\u{1F4D6} MARIA Commands \u2014 Interactive"
10771
+ );
10772
+ const term = new Terminal();
10773
+ try {
10774
+ if (!process.stdout.isTTY || process.env.NO_ALT_SCREEN) {
10775
+ throw new Error("Interactive mode requires TTY with alt screen support");
10776
+ }
10777
+ term.enterAlt();
10778
+ term.hideCursor();
10779
+ term.enableRaw();
10780
+ render(term, state);
10781
+ await loop(term, state);
10782
+ } finally {
10783
+ term.disableRaw();
10784
+ term.showCursor();
10785
+ term.leaveAlt();
10786
+ }
10787
+ }
10788
+ function buildState(metas, showAdvanced, heading) {
10789
+ const width = process.stdout.columns || 80;
10790
+ const height = process.stdout.rows || 24;
10791
+ const visible = showAdvanced ? metas : metas.filter((m2) => m2.level !== "hidden");
10792
+ const byCat = /* @__PURE__ */ new Map();
10793
+ for (const m2 of visible) {
10794
+ const arr = byCat.get(m2.category) || [];
10795
+ arr.push(m2);
10796
+ byCat.set(m2.category, arr);
10797
+ }
10798
+ const blocks = [];
10799
+ for (const [cat, arr] of byCat) {
10800
+ const sorted = arr.slice().sort(sorter2);
10801
+ const primaries = sorted.filter((m2) => m2.level === "primary" && !m2.parent);
10802
+ const secondaries = sorted.filter((m2) => m2.level !== "primary" || m2.parent);
10803
+ blocks.push({
10804
+ key: cat,
10805
+ label: beautifyCategory2(cat),
10806
+ total: sorted.length,
10807
+ primaries,
10808
+ secondaries
10809
+ });
10810
+ }
10811
+ const order = blocks.map((b) => b.key).sort((a2, b) => a2.localeCompare(b));
10812
+ return {
10813
+ heading,
10814
+ width,
10815
+ height,
10816
+ categories: blocks,
10817
+ order,
10818
+ selected: 0,
10819
+ expanded: /* @__PURE__ */ new Set(),
10820
+ scrollTop: 0,
10821
+ showAdvanced
10822
+ };
10823
+ function sorter2(a2, b) {
10824
+ if ((a2.rank ?? 999999) !== (b.rank ?? 999999))
10825
+ return (a2.rank ?? 999999) - (b.rank ?? 999999);
10826
+ return a2.name.localeCompare(b.name);
10827
+ }
10828
+ }
10829
+ function beautifyCategory2(cat) {
10830
+ const map = {
10831
+ core: "\u{1F4DD} Core",
10832
+ generation: "\u{1F680} Content Generation",
10833
+ analysis: "\u{1F50D} Analysis & Review",
10834
+ quality: "\u{1F6E1}\uFE0F Code Quality",
10835
+ development: "\u2699\uFE0F Development Tools",
10836
+ workflow: "\u{1F504} Workflow Automation",
10837
+ configuration: "\u{1F4CB} Configuration",
10838
+ auth: "\u{1F510} Authentication",
10839
+ media: "\u{1F3A8} Media Generation",
10840
+ integration: "\u{1F517} Integration",
10841
+ system: "\u{1F3E5} System & Diagnostics",
10842
+ optimization: "\u26A1 Performance Optimization",
10843
+ creative: "\u{1F3A8} Creative Tools",
10844
+ implementation: "\u{1F527} Implementation Utilities",
10845
+ evolution: "\u{1F9E0} RL Evolution",
10846
+ ai: "\u{1F916} AI & GPU Operations",
10847
+ monitoring: "\u{1F4CA} Real-time Monitoring",
10848
+ file: "\u{1F4BE} File Operations",
10849
+ "coding-agent": "\u{1F916} AI Coding Agent",
10850
+ business: "\u{1F4BC} Business Operations"
10851
+ };
10852
+ return map[cat] ?? cat.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
10853
+ }
10854
+ async function loop(term, s2) {
10855
+ let last = 0;
10856
+ const onKey = async (buf) => {
10857
+ const now = Date.now();
10858
+ if (now - last < 25) return;
10859
+ last = now;
10860
+ const str = buf.toString();
10861
+ if (str === KEY.UP) {
10862
+ s2.selected = Math.max(0, s2.selected - 1);
10863
+ ensureVisible(s2);
10864
+ render(term, s2);
10865
+ return;
10866
+ }
10867
+ if (str === KEY.DOWN) {
10868
+ s2.selected = Math.min(s2.order.length - 1, s2.selected + 1);
10869
+ ensureVisible(s2);
10870
+ render(term, s2);
10871
+ return;
10872
+ }
10873
+ if (str === KEY.RIGHT || str === KEY.ENTER) {
10874
+ toggleExpand(s2, true);
10875
+ ensureVisible(s2);
10876
+ render(term, s2);
10877
+ return;
10878
+ }
10879
+ if (str === KEY.LEFT) {
10880
+ toggleExpand(s2, false);
10881
+ ensureVisible(s2);
10882
+ render(term, s2);
10883
+ return;
10884
+ }
10885
+ if (str.toLowerCase() === KEY.A) {
10886
+ s2.showAdvanced = !s2.showAdvanced;
10887
+ render(term, s2);
10888
+ return;
10889
+ }
10890
+ if (str.toLowerCase() === KEY.D) {
10891
+ await showCategoryDetail(term, s2);
10892
+ render(term, s2);
10893
+ return;
10894
+ }
10895
+ if (str.toLowerCase() === KEY.F) {
10896
+ await showFullDetail(term, s2);
10897
+ render(term, s2);
10898
+ return;
10899
+ }
10900
+ if (str === KEY.ESC || str.toLowerCase() === KEY.Q) {
10901
+ term.writeAt(1, 1, "");
10902
+ throw new ExitSignal();
10903
+ }
10904
+ };
10905
+ try {
10906
+ await term.onKey(onKey);
10907
+ } catch (e2) {
10908
+ if (!(e2 instanceof ExitSignal)) throw e2;
10909
+ }
10910
+ }
10911
+ function toggleExpand(s2, open) {
10912
+ const cat = s2.order[s2.selected];
10913
+ if (!cat) return;
10914
+ const isOpen = s2.expanded.has(cat);
10915
+ if (open && !isOpen) s2.expanded.add(cat);
10916
+ if (!open && isOpen) s2.expanded.delete(cat);
10917
+ }
10918
+ function ensureVisible(s2) {
10919
+ materializeLines(s2);
10920
+ const indexLine = findCategoryTopLine(s2, s2.order[s2.selected]);
10921
+ const top = s2.scrollTop;
10922
+ const bottom = s2.scrollTop + (s2.height - 4);
10923
+ if (indexLine < top) s2.scrollTop = indexLine;
10924
+ else if (indexLine > bottom - 3) s2.scrollTop = indexLine - (s2.height - 4) + 3;
10925
+ if (s2.scrollTop < 0) s2.scrollTop = 0;
10926
+ }
10927
+ function render(term, s2) {
10928
+ const lines = materializeLines(s2);
10929
+ const maxLines = s2.height - 2;
10930
+ term.clearAll();
10931
+ term.moveTo(1, 1);
10932
+ term.write(`${s2.heading} ${s2.showAdvanced ? "[ADVANCED: ON]" : ""}`);
10933
+ term.write("\n");
10934
+ const start = s2.scrollTop;
10935
+ const end = Math.min(lines.length, start + maxLines - 2);
10936
+ for (let i2 = start; i2 < end; i2++) {
10937
+ term.write(lines[i2] + "\n");
10938
+ }
10939
+ const footer = "\u2191/\u2193 Move \u2192/Enter Expand \u2190 Collapse [A]dvanced [D]etail [F]ull [Q/Esc] Quit";
10940
+ term.write(truncateWidth(footer, s2.width));
10941
+ }
10942
+ function materializeLines(s2) {
10943
+ const lines = [];
10944
+ const selCat = s2.order[s2.selected];
10945
+ for (const key2 of s2.order) {
10946
+ const block = s2.categories.find((b) => b.key === key2);
10947
+ const isOpen = s2.expanded.has(key2);
10948
+ const isSel = key2 === selCat;
10949
+ const head = `${isOpen ? "\u25BC" : "\u25B6"} ${block.label} (${block.primaries.length + block.secondaries.length})`;
10950
+ lines.push(colorize(isSel, head));
10951
+ if (isOpen) {
10952
+ for (const p of block.primaries) {
10953
+ lines.push(
10954
+ " " + padCmd2(p.name, 24) + " " + truncate2(p.title ?? "", 80)
10955
+ );
10956
+ }
10957
+ const byParent = /* @__PURE__ */ new Map();
10958
+ for (const sc of block.secondaries) {
10959
+ const parent = sc.parent ?? "(misc)";
10960
+ const arr = byParent.get(parent) || [];
10961
+ arr.push(sc);
10962
+ byParent.set(parent, arr);
10963
+ }
10964
+ const parents = Array.from(byParent.keys()).sort();
10965
+ for (const parent of parents) {
10966
+ lines.push(` ${parent !== "(misc)" ? parent : "Subcommands"}:`);
10967
+ const children = (byParent.get(parent) || []).slice().sort(
10968
+ (a2, b) => (a2.rank ?? 999999) - (b.rank ?? 999999) || a2.name.localeCompare(b.name)
10969
+ );
10970
+ for (const c of children) {
10971
+ lines.push(
10972
+ " " + padCmd2(c.name, 24) + " " + truncate2(c.title ?? "", 76)
10973
+ );
10974
+ }
10975
+ }
10976
+ lines.push("");
10977
+ }
10978
+ }
10979
+ return lines;
10980
+ }
10981
+ function findCategoryTopLine(s2, cat, lines) {
10982
+ let cursor = 0;
10983
+ for (const key2 of s2.order) {
10984
+ if (key2 === cat) return cursor;
10985
+ cursor++;
10986
+ const isOpen = s2.expanded.has(key2);
10987
+ if (isOpen) {
10988
+ const b = s2.categories.find((x2) => x2.key === key2);
10989
+ cursor += b.primaries.length;
10990
+ const byParent = /* @__PURE__ */ new Map();
10991
+ for (const sc of b.secondaries) {
10992
+ const parent = sc.parent ?? "(misc)";
10993
+ const arr = byParent.get(parent) || [];
10994
+ arr.push(sc);
10995
+ byParent.set(parent, arr);
10996
+ }
10997
+ cursor += byParent.size;
10998
+ for (const arr of byParent.values()) {
10999
+ cursor += arr.length;
11000
+ }
11001
+ cursor += 1;
11002
+ }
11003
+ }
11004
+ return 0;
11005
+ }
11006
+ function padCmd2(cmd, len) {
11007
+ return cmd.padEnd(len, " ");
11008
+ }
11009
+ function truncate2(s2, max) {
11010
+ if (s2.length <= max) return s2;
11011
+ return s2.slice(0, Math.max(0, max - 1)) + "\u2026";
11012
+ }
11013
+ function truncateWidth(s2, width) {
11014
+ return s2.length <= width ? s2 : s2.slice(0, width - 1) + "\u2026";
11015
+ }
11016
+ function colorize(selected, text) {
11017
+ if (process.env.NO_COLOR) return selected ? `> ${text}` : ` ${text}`;
11018
+ const B = "\x1B[1m", R = "\x1B[0m", C = selected ? "\x1B[36m" : "";
11019
+ return selected ? `${B}${C}> ${text}${R}` : ` ${text}`;
11020
+ }
11021
+ async function showCategoryDetail(term, s2) {
11022
+ const cat = s2.order[s2.selected];
11023
+ if (!cat) return;
11024
+ const metas = s2.showAdvanced ? collectAll(s2, cat) : collectAll(s2, cat).filter((m2) => m2.level !== "hidden");
11025
+ const txt = renderCategoryHelp(metas, cat, {
11026
+ advanced: s2.showAdvanced,
11027
+ showAliases: false,
11028
+ width: s2.width
11029
+ });
11030
+ term.clearAll();
11031
+ term.moveTo(1, 1);
11032
+ term.write(txt + "\n\n");
11033
+ term.write("Press any key to return...");
11034
+ await term.waitKey();
11035
+ }
11036
+ async function showFullDetail(term, s2) {
11037
+ const metas = s2.showAdvanced ? collectAll(s2) : collectAll(s2).filter((m2) => m2.level !== "hidden");
11038
+ const txt = renderFullHelp(metas, {
11039
+ advanced: s2.showAdvanced,
11040
+ showAliases: false,
11041
+ heading: "\u{1F4D6} Full Listing",
11042
+ width: s2.width
11043
+ });
11044
+ term.clearAll();
11045
+ term.moveTo(1, 1);
11046
+ term.write(txt + "\n\n");
11047
+ term.write("Press any key to return...");
11048
+ await term.waitKey();
11049
+ }
11050
+ function collectAll(s2, onlyCat) {
11051
+ const arr = [];
11052
+ for (const key2 of s2.order) {
11053
+ if (onlyCat && key2 !== onlyCat) continue;
11054
+ const b = s2.categories.find((x2) => x2.key === key2);
11055
+ arr.push(...b.primaries, ...b.secondaries);
11056
+ }
11057
+ return arr;
11058
+ }
11059
+ var KEY, ExitSignal, Terminal;
11060
+ var init_interactive_help = __esm({
11061
+ "src/slash-commands/help/interactive-help.ts"() {
11062
+ init_detail_renderer();
11063
+ init_full_renderer();
11064
+ KEY = {
11065
+ UP: "\x1B[A",
11066
+ DOWN: "\x1B[B",
11067
+ RIGHT: "\x1B[C",
11068
+ LEFT: "\x1B[D",
11069
+ ENTER: "\r",
11070
+ ESC: "\x1B",
11071
+ Q: "q",
11072
+ A: "a",
11073
+ D: "d",
11074
+ F: "f"
11075
+ };
11076
+ ExitSignal = class extends Error {
11077
+ };
11078
+ Terminal = class {
11079
+ keyHandler;
11080
+ enterAlt() {
11081
+ this.write("\x1B[?1049h");
11082
+ }
11083
+ leaveAlt() {
11084
+ this.write("\x1B[?1049l");
11085
+ }
11086
+ hideCursor() {
11087
+ this.write("\x1B[?25l");
11088
+ }
11089
+ showCursor() {
11090
+ this.write("\x1B[?25h");
11091
+ }
11092
+ enableRaw() {
11093
+ if (process.stdin.isTTY) {
11094
+ process.stdin.setRawMode(true);
11095
+ process.stdin.resume();
11096
+ }
11097
+ }
11098
+ disableRaw() {
11099
+ try {
11100
+ if (process.stdin.isTTY) {
11101
+ process.stdin.setRawMode(false);
11102
+ process.stdin.pause();
11103
+ }
11104
+ } catch {
11105
+ }
11106
+ }
11107
+ clearAll() {
11108
+ this.write("\x1B[2J\x1B[H");
11109
+ }
11110
+ moveTo(row, col) {
11111
+ this.write(`\x1B[${row};${col}H`);
11112
+ }
11113
+ write(s2) {
11114
+ process.stdout.write(s2);
9580
11115
  }
9581
- /**
9582
- * Get commands by category
9583
- */
9584
- getCommandsByCategory(category) {
9585
- return this.listCommands().filter((cmd) => cmd.category === category);
11116
+ writeAt(row, col, s2) {
11117
+ this.moveTo(row, col);
11118
+ this.write(s2);
9586
11119
  }
9587
- /**
9588
- * Get all categories
9589
- */
9590
- getCategories() {
9591
- const categories = /* @__PURE__ */ new Set();
9592
- for (const command of this.commands.values()) {
9593
- categories.add(command.category);
9594
- }
9595
- return Array.from(categories);
11120
+ async onKey(handler) {
11121
+ this.keyHandler = handler;
11122
+ return new Promise((resolve4, reject) => {
11123
+ const onData = (b) => handler(b);
11124
+ const onErr = (e2) => reject(e2);
11125
+ process.stdin.on("data", onData);
11126
+ process.stdin.on("error", onErr);
11127
+ const cleanup = () => {
11128
+ process.stdin.off("data", onData);
11129
+ process.stdin.off("error", onErr);
11130
+ };
11131
+ this._cleanup = cleanup;
11132
+ });
9596
11133
  }
9597
- /**
9598
- * Validate command arguments
9599
- */
9600
- validateArgs(commandName, args) {
9601
- const command = this.getCommand(commandName);
9602
- if (!command) return false;
9603
- return true;
11134
+ async waitKey() {
11135
+ return new Promise((res) => {
11136
+ const handler = (b) => {
11137
+ process.stdin.off("data", handler);
11138
+ res();
11139
+ };
11140
+ process.stdin.on("data", handler);
11141
+ });
9604
11142
  }
9605
- /**
9606
- * Create a helper context for testing
9607
- */
9608
- static createTestContext(deps, overrides) {
11143
+ };
11144
+ }
11145
+ });
11146
+
11147
+ // src/slash-commands/help/HelpCommand.ts
11148
+ var HelpCommandV2;
11149
+ var init_HelpCommand = __esm({
11150
+ "src/slash-commands/help/HelpCommand.ts"() {
11151
+ init_base_command();
11152
+ init_metadata_manager();
11153
+ init_compact_renderer();
11154
+ init_detail_renderer();
11155
+ init_full_renderer();
11156
+ init_interactive_help();
11157
+ HelpCommandV2 = class extends BaseCommand {
11158
+ name = "help";
11159
+ category = "core";
11160
+ description = "Show help information and command list with progressive disclosure";
11161
+ aliases = ["h", "?"];
11162
+ usage = "[<category>] [--search <kw>] [--all] [--advanced] [--interactive] [--json]";
11163
+ examples = [
11164
+ { input: "/help", description: "Compact view (Top 3 per category)" },
11165
+ { input: "/help business", description: "Category expansion" },
11166
+ { input: "/help --search sow", description: "Search across categories" },
11167
+ { input: "/help --all", description: "Full listing" },
11168
+ {
11169
+ input: "/help --interactive",
11170
+ description: "TUI mode with arrow navigation"
11171
+ },
11172
+ { input: "/help --json", description: "JSON output for automation" }
11173
+ ];
11174
+ metadataManager = new MetadataManager();
11175
+ async execute(args, _context) {
11176
+ const flags = this.parseFlags(args);
11177
+ try {
11178
+ const container = await this.metadataManager.load();
11179
+ const metas = container.commands;
11180
+ const isTTY = !!(process.stdout.isTTY && process.stdin.isTTY);
11181
+ if ((!isTTY || flags.json) && !flags.interactive) {
11182
+ const payload = this.metadataManager.buildCompactJson(metas);
11183
+ return this.success(JSON.stringify(payload, null, 2));
11184
+ }
11185
+ if (flags.interactive) {
11186
+ try {
11187
+ await runInteractiveHelp({
11188
+ showAdvancedDefault: flags.advanced
11189
+ });
11190
+ return this.success("");
11191
+ } catch (error) {
11192
+ if (error.message?.includes("TTY")) {
11193
+ return this.error(
11194
+ "Interactive mode requires a TTY terminal",
11195
+ "HELP_NO_TTY"
11196
+ );
11197
+ }
11198
+ return this.error(
11199
+ "Interactive help failed",
11200
+ "HELP_INTERACTIVE_ERROR",
11201
+ error?.message
11202
+ );
11203
+ }
11204
+ }
11205
+ let output3 = "";
11206
+ if (flags.search) {
11207
+ output3 = renderSearchHelp(metas, flags.search, {
11208
+ advanced: flags.advanced,
11209
+ showAliases: flags.aliases,
11210
+ matchMode: flags.matchMode || "any"
11211
+ });
11212
+ } else if (flags.category) {
11213
+ output3 = renderCategoryHelp(metas, flags.category, {
11214
+ advanced: flags.advanced,
11215
+ showAliases: flags.aliases
11216
+ });
11217
+ } else if (flags.all) {
11218
+ output3 = renderFullHelp(metas, {
11219
+ advanced: flags.advanced,
11220
+ showAliases: flags.aliases,
11221
+ heading: "\u{1F4D6} MARIA Commands \u2014 Full Listing"
11222
+ });
11223
+ } else {
11224
+ output3 = renderCompactHelp(metas, {
11225
+ maxPrimaryPerCategory: 3,
11226
+ showAdvanced: flags.advanced,
11227
+ twoColumnThreshold: 100,
11228
+ heading: "\u{1F4D6} MARIA Commands (compact \u2022 primary only)"
11229
+ });
11230
+ }
11231
+ return this.success(output3);
11232
+ } catch (error) {
11233
+ return this.handleError(error);
11234
+ }
11235
+ }
11236
+ parseFlags(args) {
11237
+ const { parsed, options, flags } = args;
11238
+ const positional = parsed?.positional || [];
11239
+ const category = positional[0] && !positional[0].startsWith("-") ? positional[0] : void 0;
9609
11240
  return {
9610
- command: "test",
9611
- args: [],
9612
- options: {},
9613
- deps,
9614
- signal: void 0,
9615
- ...overrides
11241
+ category,
11242
+ search: this.getStringOption(options, "search"),
11243
+ all: this.getBoolFlag(options, flags, "all"),
11244
+ advanced: this.getBoolFlag(options, flags, "advanced"),
11245
+ aliases: this.getBoolFlag(options, flags, "aliases"),
11246
+ interactive: this.getBoolFlag(options, flags, "interactive"),
11247
+ json: this.getBoolFlag(options, flags, "json"),
11248
+ matchMode: this.getStringOption(options, "match") || "any"
9616
11249
  };
9617
11250
  }
11251
+ getBoolFlag(options, flags, key2) {
11252
+ const optValue = options?.[key2];
11253
+ const flagValue = flags?.[key2];
11254
+ if (typeof optValue === "boolean") return optValue;
11255
+ if (typeof flagValue === "boolean") return flagValue;
11256
+ if (typeof optValue === "string")
11257
+ return optValue === "true" || optValue === "";
11258
+ if (typeof flagValue === "string")
11259
+ return flagValue === "true" || flagValue === "";
11260
+ return !!optValue || !!flagValue;
11261
+ }
11262
+ getStringOption(options, key2) {
11263
+ const value = options?.[key2];
11264
+ return typeof value === "string" ? value : void 0;
11265
+ }
11266
+ handleError(error) {
11267
+ console.error("[help] Command failed:", error);
11268
+ if (this.metadataManager.hasStaleCache()) {
11269
+ console.warn("[help] Using stale cache as fallback");
11270
+ try {
11271
+ const staleContainer = this.metadataManager.getStaleCache();
11272
+ if (staleContainer) {
11273
+ const output3 = renderCompactHelp(staleContainer.commands, {
11274
+ heading: "\u{1F4D6} MARIA Commands (using cached data - may be outdated)"
11275
+ });
11276
+ return this.success(
11277
+ output3 + "\n\n\u26A0\uFE0F Using stale cache. Run: npx tsx scripts/generate-help-meta.ts"
11278
+ );
11279
+ }
11280
+ } catch (fallbackError) {
11281
+ console.error("[help] Stale cache fallback failed:", fallbackError);
11282
+ }
11283
+ }
11284
+ const fallbackHelp = [
11285
+ "\u{1F4D6} MARIA Commands",
11286
+ "",
11287
+ "Help metadata unavailable.",
11288
+ `Reason: ${error?.message || error}`,
11289
+ "",
11290
+ "Try:",
11291
+ " \u2022 npx tsx scripts/generate-help-meta.ts",
11292
+ " \u2022 Check that command-meta.json exists and is valid",
11293
+ "",
11294
+ "For immediate help, use individual command --help flags.",
11295
+ ""
11296
+ ].join("\n");
11297
+ return this.success(fallbackHelp);
11298
+ }
11299
+ async validate(args) {
11300
+ const flags = this.parseFlags(args);
11301
+ if (flags.search !== void 0 && (flags.search === "" || flags.search.length < 2)) {
11302
+ return {
11303
+ success: false,
11304
+ error: "Search term must be at least 2 characters long"
11305
+ };
11306
+ }
11307
+ if (flags.matchMode && !["any", "all"].includes(flags.matchMode)) {
11308
+ return {
11309
+ success: false,
11310
+ error: 'Match mode must be either "any" or "all"'
11311
+ };
11312
+ }
11313
+ if (flags.interactive && !process.stdout.isTTY) {
11314
+ return {
11315
+ success: false,
11316
+ error: "Interactive mode requires a TTY terminal"
11317
+ };
11318
+ }
11319
+ return { success: true };
11320
+ }
9618
11321
  };
9619
11322
  }
9620
11323
  });
@@ -9624,6 +11327,7 @@ var LegacySlashCommandAdapter, SlashCommandHandler2;
9624
11327
  var init_LegacySlashCommandAdapter = __esm({
9625
11328
  "src/shared/adapters/LegacySlashCommandAdapter.ts"() {
9626
11329
  init_SlashCommandHandler();
11330
+ init_HelpCommand();
9627
11331
  LegacySlashCommandAdapter = class _LegacySlashCommandAdapter {
9628
11332
  static instance = null;
9629
11333
  handler;
@@ -9635,6 +11339,7 @@ var init_LegacySlashCommandAdapter = __esm({
9635
11339
  ui: null
9636
11340
  };
9637
11341
  this.handler = new SlashCommandHandlerV2(deps);
11342
+ this.registerEssentialCommands();
9638
11343
  }
9639
11344
  /**
9640
11345
  * Legacy getInstance method for backward compatibility
@@ -9694,6 +11399,48 @@ var init_LegacySlashCommandAdapter = __esm({
9694
11399
  };
9695
11400
  this.handler.register(newCommand);
9696
11401
  }
11402
+ /**
11403
+ * Register essential commands that should be available in legacy sessions
11404
+ */
11405
+ registerEssentialCommands() {
11406
+ try {
11407
+ const helpCommand = new HelpCommandV2();
11408
+ const helpCommandV2 = {
11409
+ name: "help",
11410
+ aliases: ["h", "?"],
11411
+ description: helpCommand.description,
11412
+ category: helpCommand.category,
11413
+ execute: async (context2) => {
11414
+ try {
11415
+ const result = await helpCommand.execute({
11416
+ raw: context2.args?.join(" ") || "",
11417
+ parsed: {
11418
+ positional: context2.args || [],
11419
+ named: {},
11420
+ flags: {}
11421
+ },
11422
+ options: {},
11423
+ flags: {}
11424
+ }, context2);
11425
+ return {
11426
+ success: result.success,
11427
+ messages: [{ role: "assistant", content: result.message || result.data || "" }],
11428
+ error: result.error
11429
+ };
11430
+ } catch (error) {
11431
+ return {
11432
+ success: false,
11433
+ error: error instanceof Error ? error.message : "Help command failed",
11434
+ messages: []
11435
+ };
11436
+ }
11437
+ }
11438
+ };
11439
+ this.handler.register(helpCommandV2);
11440
+ } catch (error) {
11441
+ console.warn("Failed to register essential commands:", error);
11442
+ }
11443
+ }
9697
11444
  /**
9698
11445
  * Get the underlying SlashCommandHandlerV2 instance
9699
11446
  */
@@ -11000,10 +12747,10 @@ var init_interactive_cli = __esm({
11000
12747
  this.selectedIndex = 0;
11001
12748
  this.isShowingSuggestions = false;
11002
12749
  process.stdout.write(prompt);
11003
- return new Promise((resolve2) => {
12750
+ return new Promise((resolve4) => {
11004
12751
  const handler = (input4) => {
11005
12752
  this.rl.removeListener("line", handler);
11006
- resolve2(input4);
12753
+ resolve4(input4);
11007
12754
  };
11008
12755
  this.rl.on("line", handler);
11009
12756
  });
@@ -11038,8 +12785,8 @@ var init_interactive_cli = __esm({
11038
12785
  }
11039
12786
  });
11040
12787
  function loadEnvironmentVariables() {
11041
- const _envPath = path6__namespace.join(process.cwd(), ".env");
11042
- if (fs4__namespace.existsSync(_envPath)) {
12788
+ const _envPath = path8__namespace.join(process.cwd(), ".env");
12789
+ if (fs6__namespace.existsSync(_envPath)) {
11043
12790
  const _result = dotenv__namespace.config({ path: _envPath });
11044
12791
  if (_result.error) {
11045
12792
  console.warn("Error loading .env:", _result.error);
@@ -11047,8 +12794,8 @@ function loadEnvironmentVariables() {
11047
12794
  console.log("\u2705 Loaded environment from .env");
11048
12795
  }
11049
12796
  }
11050
- const _lmstudioEnvPath = path6__namespace.join(process.cwd(), ".env.lmstudio");
11051
- if (fs4__namespace.existsSync(_lmstudioEnvPath)) {
12797
+ const _lmstudioEnvPath = path8__namespace.join(process.cwd(), ".env.lmstudio");
12798
+ if (fs6__namespace.existsSync(_lmstudioEnvPath)) {
11052
12799
  const _result = dotenv__namespace.config({ path: _lmstudioEnvPath, override: false });
11053
12800
  if (_result.error) {
11054
12801
  console.warn("Error loading .env.lmstudio:", _result.error);
@@ -11079,25 +12826,25 @@ function getPackageJson() {
11079
12826
  try {
11080
12827
  const possiblePaths = [
11081
12828
  // When running from built dist/
11082
- path6.join(__dirname, "../../package.json"),
12829
+ path8.join(__dirname, "../../package.json"),
11083
12830
  // When running from source
11084
- path6.join(__dirname, "../../../package.json"),
12831
+ path8.join(__dirname, "../../../package.json"),
11085
12832
  // Current working directory
11086
- path6.join(process.cwd(), "package.json"),
12833
+ path8.join(process.cwd(), "package.json"),
11087
12834
  // One level up from current working directory
11088
- path6.join(process.cwd(), "../package.json"),
12835
+ path8.join(process.cwd(), "../package.json"),
11089
12836
  // For globally installed packages
11090
- path6.join(__dirname, "../../../../package.json"),
11091
- path6.join(__dirname, "../../../../../package.json"),
12837
+ path8.join(__dirname, "../../../../package.json"),
12838
+ path8.join(__dirname, "../../../../../package.json"),
11092
12839
  // npm global install locations
11093
12840
  "/usr/local/lib/node_modules/@bonginkan/maria/package.json",
11094
12841
  "/usr/lib/node_modules/@bonginkan/maria/package.json",
11095
12842
  // User home npm global
11096
- path6.join(
12843
+ path8.join(
11097
12844
  process.env.HOME || "",
11098
12845
  ".npm-global/lib/node_modules/@bonginkan/maria/package.json"
11099
12846
  ),
11100
- path6.join(
12847
+ path8.join(
11101
12848
  process.env.HOME || "",
11102
12849
  ".nvm/versions/node",
11103
12850
  process.version,
@@ -11105,13 +12852,13 @@ function getPackageJson() {
11105
12852
  )
11106
12853
  ];
11107
12854
  let packageJsonPath = null;
11108
- for (const path7 of possiblePaths) {
11109
- if (fs4.existsSync(path7)) {
12855
+ for (const path9 of possiblePaths) {
12856
+ if (fs6.existsSync(path9)) {
11110
12857
  try {
11111
- const content = fs4.readFileSync(path7, "utf-8");
12858
+ const content = fs6.readFileSync(path9, "utf-8");
11112
12859
  const parsed = JSON.parse(content);
11113
12860
  if (parsed.name === "@bonginkan/maria") {
11114
- packageJsonPath = path7;
12861
+ packageJsonPath = path9;
11115
12862
  break;
11116
12863
  }
11117
12864
  } catch {
@@ -11122,7 +12869,7 @@ function getPackageJson() {
11122
12869
  if (!packageJsonPath) {
11123
12870
  throw new Error("package.json not found in any expected location");
11124
12871
  }
11125
- const packageJsonContent = fs4.readFileSync(packageJsonPath, "utf-8");
12872
+ const packageJsonContent = fs6.readFileSync(packageJsonPath, "utf-8");
11126
12873
  _cachedPackageJson = JSON.parse(packageJsonContent);
11127
12874
  return _cachedPackageJson;
11128
12875
  } catch (error) {
@@ -11137,121 +12884,6 @@ var init_version = __esm({
11137
12884
  getVersion();
11138
12885
  }
11139
12886
  });
11140
- var LogLevel, Logger, logger, envLogLevel;
11141
- var init_logger = __esm({
11142
- "src/utils/logger.ts"() {
11143
- LogLevel = /* @__PURE__ */ ((LogLevel2) => {
11144
- LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
11145
- LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
11146
- LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
11147
- LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
11148
- LogLevel2[LogLevel2["NONE"] = 4] = "NONE";
11149
- return LogLevel2;
11150
- })(LogLevel || {});
11151
- Logger = class {
11152
- level = 2 /* WARN */;
11153
- // Default to WARN to reduce noise
11154
- prefix = "[MARIA CODE]";
11155
- setLevel(level) {
11156
- this.level = level;
11157
- }
11158
- debug(...args) {
11159
- if (this.level <= 0 /* DEBUG */) {
11160
- console.log(chalk13__default.default.magenta(`${this.prefix} [DEBUG]`), ...args);
11161
- }
11162
- }
11163
- info(...args) {
11164
- if (this.level <= 1 /* INFO */) {
11165
- console.log(chalk13__default.default.bold.magenta(`${this.prefix} [INFO]`), ...args);
11166
- }
11167
- }
11168
- warn(...args) {
11169
- if (this.level <= 2 /* WARN */) {
11170
- console.warn(chalk13__default.default.bold.magenta(`${this.prefix} [WARN]`), ...args);
11171
- }
11172
- }
11173
- error(...args) {
11174
- if (this.level <= 3 /* ERROR */) {
11175
- console.error(chalk13__default.default.bold.magenta(`${this.prefix} [ERROR]`), ...args);
11176
- }
11177
- }
11178
- success(...args) {
11179
- if (this.level <= 1 /* INFO */) {
11180
- console.log(chalk13__default.default.bold.magenta(`${this.prefix} [SUCCESS]`), ...args);
11181
- }
11182
- }
11183
- task(taskName, status, message) {
11184
- if (this.level > 1 /* INFO */) {
11185
- return;
11186
- }
11187
- const statusIcons = {
11188
- start: "\u{1F680}",
11189
- progress: "\u23F3",
11190
- complete: "\u2705",
11191
- error: "\u274C"
11192
- };
11193
- const statusColors = {
11194
- start: chalk13__default.default.bold.magenta,
11195
- progress: chalk13__default.default.magenta,
11196
- complete: chalk13__default.default.bold.magenta,
11197
- error: chalk13__default.default.bold.magenta
11198
- };
11199
- const icon = statusIcons[status];
11200
- const color = statusColors[status];
11201
- const formattedMessage = message ? `: ${message}` : "";
11202
- console.log(color(`${this.prefix} ${icon} ${taskName}${formattedMessage}`));
11203
- }
11204
- table(data2) {
11205
- if (this.level > 1 /* INFO */) {
11206
- return;
11207
- }
11208
- console.table(data2);
11209
- }
11210
- json(obj, pretty = true) {
11211
- if (this.level > 0 /* DEBUG */) {
11212
- return;
11213
- }
11214
- console.log(chalk13__default.default.magenta(`${this.prefix} [JSON]`));
11215
- console.log(pretty ? JSON.stringify(obj, null, 2) : JSON.stringify(obj));
11216
- }
11217
- divider() {
11218
- if (this.level > 1 /* INFO */) {
11219
- return;
11220
- }
11221
- console.log(chalk13__default.default.magenta("\u2500".repeat(60)));
11222
- }
11223
- clear() {
11224
- console.clear();
11225
- }
11226
- /**
11227
- * プログレスバーを表示
11228
- */
11229
- progress(current, total, label) {
11230
- if (this.level > 1 /* INFO */) {
11231
- return;
11232
- }
11233
- const percentage = Math.round(current / total * 100);
11234
- const barLength = 30;
11235
- const filled = Math.round(percentage / 100 * barLength);
11236
- const empty = barLength - filled;
11237
- const bar = "\u2588".repeat(filled) + "\u2591".repeat(empty);
11238
- const progressText = `${current}/${total}`;
11239
- const labelText = label ? ` ${label}` : "";
11240
- process.stdout.write(
11241
- `\r${chalk13__default.default.bold.magenta(bar)} ${percentage}% ${progressText}${labelText}`
11242
- );
11243
- if (current === total) {
11244
- process.stdout.write("\n");
11245
- }
11246
- }
11247
- };
11248
- logger = new Logger();
11249
- envLogLevel = process.env["MARIA_LOG_LEVEL"]?.toUpperCase();
11250
- if (envLogLevel && LogLevel[envLogLevel] !== void 0) {
11251
- logger.setLevel(LogLevel[envLogLevel]);
11252
- }
11253
- }
11254
- });
11255
12887
 
11256
12888
  // src/providers/ai-provider.ts
11257
12889
  var BaseAIProvider;
@@ -11797,7 +13429,7 @@ var init_lmstudio_provider = __esm({
11797
13429
  throw _error;
11798
13430
  }
11799
13431
  await new Promise(
11800
- (resolve2) => setTimeout(resolve2, this.retryDelay * Math.pow(2, i2))
13432
+ (resolve4) => setTimeout(resolve4, this.retryDelay * Math.pow(2, i2))
11801
13433
  );
11802
13434
  }
11803
13435
  }
@@ -12708,23 +14340,23 @@ var init_default_provider = __esm({
12708
14340
  function loadConfig() {
12709
14341
  let currentDir = process.cwd();
12710
14342
  while (currentDir !== "/") {
12711
- const _configPath = path6.join(currentDir, _CONFIG_FILE);
12712
- if (fs4.existsSync(_configPath)) {
14343
+ const _configPath = path8.join(currentDir, _CONFIG_FILE);
14344
+ if (fs6.existsSync(_configPath)) {
12713
14345
  try {
12714
- const _content = fs4.readFileSync(_configPath, "utf-8");
14346
+ const _content = fs6.readFileSync(_configPath, "utf-8");
12715
14347
  return toml.parse(_content);
12716
14348
  } catch {
12717
14349
  }
12718
14350
  }
12719
- const _parentDir = path6.join(currentDir, "..");
14351
+ const _parentDir = path8.join(currentDir, "..");
12720
14352
  if (_parentDir === currentDir) {
12721
14353
  break;
12722
14354
  }
12723
14355
  currentDir = _parentDir;
12724
14356
  }
12725
- if (fs4.existsSync(_GLOBAL_CONFIG_PATH)) {
14357
+ if (fs6.existsSync(_GLOBAL_CONFIG_PATH)) {
12726
14358
  try {
12727
- const _content = fs4.readFileSync(_GLOBAL_CONFIG_PATH, "utf-8");
14359
+ const _content = fs6.readFileSync(_GLOBAL_CONFIG_PATH, "utf-8");
12728
14360
  return toml.parse(_content);
12729
14361
  } catch {
12730
14362
  }
@@ -12765,7 +14397,7 @@ var _CONFIG_FILE, _GLOBAL_CONFIG_PATH;
12765
14397
  var init_config2 = __esm({
12766
14398
  "src/utils/config.ts"() {
12767
14399
  _CONFIG_FILE = ".maria-code.toml";
12768
- _GLOBAL_CONFIG_PATH = path6.join(os2.homedir(), ".maria-code", "_config.toml");
14400
+ _GLOBAL_CONFIG_PATH = path8.join(os2.homedir(), ".maria-code", "_config.toml");
12769
14401
  }
12770
14402
  });
12771
14403
 
@@ -13283,7 +14915,7 @@ Include: function descriptions, parameter explanations, return values, usage exa
13283
14915
  // Helper methods
13284
14916
  async detectFramework() {
13285
14917
  try {
13286
- const _packageJson = await fs6__namespace.readFile("package.json", "utf-8");
14918
+ const _packageJson = await fs8__namespace.readFile("package.json", "utf-8");
13287
14919
  const _pkg = JSON.parse(_packageJson);
13288
14920
  if (_pkg.dependencies?.react || _pkg.devDependencies?.react) {
13289
14921
  return "React";
@@ -13309,7 +14941,7 @@ Include: function descriptions, parameter explanations, return values, usage exa
13309
14941
  }
13310
14942
  async detectProjectType() {
13311
14943
  try {
13312
- const _files = await fs6__namespace.readdir(process.cwd());
14944
+ const _files = await fs8__namespace.readdir(process.cwd());
13313
14945
  if (_files.includes("package.json")) {
13314
14946
  return "Node.js";
13315
14947
  }
@@ -13332,7 +14964,7 @@ Include: function descriptions, parameter explanations, return values, usage exa
13332
14964
  async detectTestFramework(_context) {
13333
14965
  if (_context.language === "javascript" || _context.language === "typescript") {
13334
14966
  try {
13335
- const _packageJson = await fs6__namespace.readFile("package.json", "utf-8");
14967
+ const _packageJson = await fs8__namespace.readFile("package.json", "utf-8");
13336
14968
  const _pkg = JSON.parse(_packageJson);
13337
14969
  if (_pkg.devDependencies?.jest) {
13338
14970
  return "Jest";
@@ -13379,7 +15011,7 @@ Include: function descriptions, parameter explanations, return values, usage exa
13379
15011
  };
13380
15012
  LanguageDetector = class {
13381
15013
  async detectFromFile(_filePath) {
13382
- const _ext = path6__namespace.extname(_filePath).toLowerCase();
15014
+ const _ext = path8__namespace.extname(_filePath).toLowerCase();
13383
15015
  const languageMap = {
13384
15016
  ".js": "javascript",
13385
15017
  ".jsx": "javascript",
@@ -13848,21 +15480,21 @@ var init_llm_health_checker = __esm({
13848
15480
  }
13849
15481
  async startLMStudio() {
13850
15482
  try {
13851
- const { spawn } = await import('child_process');
15483
+ const { spawn: spawn2 } = await import('child_process');
13852
15484
  const _lmsPath = "/Users/bongin_max/.lmstudio/bin/lms";
13853
- return new Promise((resolve2) => {
13854
- const _child = spawn(_lmsPath, ["server", "start"], {
15485
+ return new Promise((resolve4) => {
15486
+ const _child = spawn2(_lmsPath, ["server", "start"], {
13855
15487
  stdio: "ignore",
13856
15488
  detached: true
13857
15489
  });
13858
15490
  child.on("_error", () => {
13859
- resolve2(false);
15491
+ resolve4(false);
13860
15492
  });
13861
15493
  _child.on("spawn", () => {
13862
15494
  child.unref();
13863
15495
  setTimeout(async () => {
13864
15496
  const _status = await this.checkService("LM Studio");
13865
- resolve2(_status.isRunning);
15497
+ resolve4(_status.isRunning);
13866
15498
  }, 3e3);
13867
15499
  });
13868
15500
  });
@@ -13876,18 +15508,15 @@ var init_llm_health_checker = __esm({
13876
15508
  var ProviderSelector;
13877
15509
  var init_provider_selector = __esm({
13878
15510
  "src/services/provider-selector.ts"() {
13879
- init_providers();
13880
15511
  ProviderSelector = class {
13881
15512
  config;
13882
- modernProviderManager;
13883
- legacyProviderManager;
15513
+ providerManager;
13884
15514
  constructor(_config) {
13885
15515
  this.config = _config;
13886
- this.modernProviderManager = new UnifiedAIProviderManager();
13887
- this.legacyProviderManager = new UnifiedAIProviderManager2(_config);
15516
+ this.providerManager = new UnifiedAIProviderManager();
13888
15517
  }
13889
15518
  async initialize() {
13890
- await this.modernProviderManager.initialize();
15519
+ await this.providerManager.initialize();
13891
15520
  }
13892
15521
  async selectProvider() {
13893
15522
  const providers = await this.getAvailableProviders();
@@ -17601,12 +19230,12 @@ var init_errors = __esm({
17601
19230
  });
17602
19231
 
17603
19232
  // src/services/interactive-session/core/SessionManager.ts
17604
- var SessionManager2;
19233
+ var SessionManager;
17605
19234
  var init_SessionManager = __esm({
17606
19235
  "src/services/interactive-session/core/SessionManager.ts"() {
17607
19236
  init_SessionStateMachine();
17608
19237
  init_errors();
17609
- SessionManager2 = class {
19238
+ SessionManager = class {
17610
19239
  constructor(input4, display, command, options = {}) {
17611
19240
  this.input = input4;
17612
19241
  this.display = display;
@@ -17851,11 +19480,11 @@ var init_InputController = __esm({
17851
19480
  try {
17852
19481
  this.enableRawMode(true);
17853
19482
  await this.installKeypress();
17854
- const line = await new Promise((resolve2) => {
19483
+ const line = await new Promise((resolve4) => {
17855
19484
  const onKey = (str, key2) => {
17856
19485
  if (key2?.name === "escape" && this.opts.escCancels)
17857
- return resolve2(null);
17858
- if (key2?.ctrl && key2?.name === "c") return resolve2(null);
19486
+ return resolve4(null);
19487
+ if (key2?.ctrl && key2?.name === "c") return resolve4(null);
17859
19488
  if (key2?.name === "return" || key2?.name === "enter") {
17860
19489
  return;
17861
19490
  }
@@ -17864,7 +19493,7 @@ var init_InputController = __esm({
17864
19493
  process$1.stdin.on("keypress", onKey);
17865
19494
  this.rl.question("", (answer) => {
17866
19495
  process$1.stdin.off("keypress", onKey);
17867
- resolve2(answer.trim());
19496
+ resolve4(answer.trim());
17868
19497
  });
17869
19498
  });
17870
19499
  this.lastSubmitAt = Date.now();
@@ -17913,11 +19542,11 @@ var init_InputController = __esm({
17913
19542
  };
17914
19543
  }
17915
19544
  });
17916
- var ReadlineAdapter2;
19545
+ var ReadlineAdapter;
17917
19546
  var init_ReadlineAdapter = __esm({
17918
19547
  "src/services/interactive-session/adapters/ReadlineAdapter.ts"() {
17919
19548
  init_InputController();
17920
- ReadlineAdapter2 = class {
19549
+ ReadlineAdapter = class {
17921
19550
  rl;
17922
19551
  inputController;
17923
19552
  constructor() {
@@ -17933,10 +19562,10 @@ var init_ReadlineAdapter = __esm({
17933
19562
  }
17934
19563
  async readline(signal) {
17935
19564
  if (signal?.aborted) return null;
17936
- return new Promise((resolve2) => {
17937
- const abortHandler = () => resolve2(null);
19565
+ return new Promise((resolve4) => {
19566
+ const abortHandler = () => resolve4(null);
17938
19567
  signal?.addEventListener("abort", abortHandler, { once: true });
17939
- this.inputController.readline().then(resolve2).catch(() => resolve2(null)).finally(() => {
19568
+ this.inputController.readline().then(resolve4).catch(() => resolve4(null)).finally(() => {
17940
19569
  signal?.removeEventListener("abort", abortHandler);
17941
19570
  });
17942
19571
  });
@@ -17962,10 +19591,10 @@ var init_ReadlineAdapter = __esm({
17962
19591
  };
17963
19592
  }
17964
19593
  });
17965
- var ChalkAdapter2;
19594
+ var ChalkAdapter;
17966
19595
  var init_ChalkAdapter = __esm({
17967
19596
  "src/services/interactive-session/adapters/ChalkAdapter.ts"() {
17968
- ChalkAdapter2 = class {
19597
+ ChalkAdapter = class {
17969
19598
  spinners = /* @__PURE__ */ new Map();
17970
19599
  spinnerId = 0;
17971
19600
  async showWelcome() {
@@ -20398,11 +22027,11 @@ var init_ConfigService = __esm({
20398
22027
  _saveDebounceTimer = null;
20399
22028
  _isDirty = false;
20400
22029
  constructor(configDir = process.env.MARIA_CONFIG_DIR || "~/.maria") {
20401
- this._configPath = path6__namespace.join(
22030
+ this._configPath = path8__namespace.join(
20402
22031
  this.expandHome(configDir),
20403
22032
  "session.config.json"
20404
22033
  );
20405
- this._userConfigPath = path6__namespace.join(
22034
+ this._userConfigPath = path8__namespace.join(
20406
22035
  this.expandHome(configDir),
20407
22036
  "user.config.json"
20408
22037
  );
@@ -20423,7 +22052,7 @@ var init_ConfigService = __esm({
20423
22052
  */
20424
22053
  async loadSystemConfig() {
20425
22054
  try {
20426
- const configFile = await fs6__namespace.readFile(this._configPath, "utf-8");
22055
+ const configFile = await fs8__namespace.readFile(this._configPath, "utf-8");
20427
22056
  return JSON.parse(configFile);
20428
22057
  } catch (error) {
20429
22058
  return {};
@@ -20434,7 +22063,7 @@ var init_ConfigService = __esm({
20434
22063
  */
20435
22064
  async loadUserConfig() {
20436
22065
  try {
20437
- const configFile = await fs6__namespace.readFile(this._userConfigPath, "utf-8");
22066
+ const configFile = await fs8__namespace.readFile(this._userConfigPath, "utf-8");
20438
22067
  return JSON.parse(configFile);
20439
22068
  } catch (error) {
20440
22069
  return {};
@@ -20477,8 +22106,8 @@ var init_ConfigService = __esm({
20477
22106
  /**
20478
22107
  * ネストされた設定値の取得
20479
22108
  */
20480
- getNestedValue(path7) {
20481
- const keys = path7.split(".");
22109
+ getNestedValue(path9) {
22110
+ const keys = path9.split(".");
20482
22111
  let value = this._config;
20483
22112
  for (const key2 of keys) {
20484
22113
  if (value && typeof value === "object" && key2 in value) {
@@ -20508,8 +22137,8 @@ var init_ConfigService = __esm({
20508
22137
  /**
20509
22138
  * ネストされた設定値の更新
20510
22139
  */
20511
- async setNestedValue(path7, value) {
20512
- const keys = path7.split(".");
22140
+ async setNestedValue(path9, value) {
22141
+ const keys = path9.split(".");
20513
22142
  const lastKey = keys.pop();
20514
22143
  let target = this._config;
20515
22144
  for (const key2 of keys) {
@@ -20522,7 +22151,7 @@ var init_ConfigService = __esm({
20522
22151
  target[lastKey] = value;
20523
22152
  this.validateConfig();
20524
22153
  this.emitChange({
20525
- path: path7,
22154
+ path: path9,
20526
22155
  oldValue,
20527
22156
  newValue: value,
20528
22157
  timestamp: /* @__PURE__ */ new Date()
@@ -20536,9 +22165,9 @@ var init_ConfigService = __esm({
20536
22165
  async save() {
20537
22166
  if (!this._isDirty) return;
20538
22167
  try {
20539
- const configDir = path6__namespace.dirname(this._userConfigPath);
20540
- await fs6__namespace.mkdir(configDir, { recursive: true });
20541
- await fs6__namespace.writeFile(
22168
+ const configDir = path8__namespace.dirname(this._userConfigPath);
22169
+ await fs8__namespace.mkdir(configDir, { recursive: true });
22170
+ await fs8__namespace.writeFile(
20542
22171
  this._userConfigPath,
20543
22172
  JSON.stringify(this._config, null, 2),
20544
22173
  "utf-8"
@@ -20567,8 +22196,8 @@ var init_ConfigService = __esm({
20567
22196
  setupAutoSave() {
20568
22197
  process.on("exit", () => {
20569
22198
  if (this._isDirty) {
20570
- const fs7 = __require("fs");
20571
- fs7.writeFileSync(
22199
+ const fs9 = __require("fs");
22200
+ fs9.writeFileSync(
20572
22201
  this._userConfigPath,
20573
22202
  JSON.stringify(this._config, null, 2),
20574
22203
  "utf-8"
@@ -20579,13 +22208,13 @@ var init_ConfigService = __esm({
20579
22208
  /**
20580
22209
  * 変更リスナーの登録
20581
22210
  */
20582
- onChange(path7, listener) {
20583
- if (!this._listeners.has(path7)) {
20584
- this._listeners.set(path7, []);
22211
+ onChange(path9, listener) {
22212
+ if (!this._listeners.has(path9)) {
22213
+ this._listeners.set(path9, []);
20585
22214
  }
20586
- this._listeners.get(path7).push(listener);
22215
+ this._listeners.get(path9).push(listener);
20587
22216
  return () => {
20588
- const listeners = this._listeners.get(path7);
22217
+ const listeners = this._listeners.get(path9);
20589
22218
  if (listeners) {
20590
22219
  const index = listeners.indexOf(listener);
20591
22220
  if (index !== -1) {
@@ -20615,7 +22244,7 @@ var init_ConfigService = __esm({
20615
22244
  * 設定のエクスポート
20616
22245
  */
20617
22246
  async export(filePath) {
20618
- await fs6__namespace.writeFile(
22247
+ await fs8__namespace.writeFile(
20619
22248
  filePath,
20620
22249
  JSON.stringify(this._config, null, 2),
20621
22250
  "utf-8"
@@ -20625,7 +22254,7 @@ var init_ConfigService = __esm({
20625
22254
  * 設定のインポート
20626
22255
  */
20627
22256
  async import(filePath) {
20628
- const configFile = await fs6__namespace.readFile(filePath, "utf-8");
22257
+ const configFile = await fs8__namespace.readFile(filePath, "utf-8");
20629
22258
  const importedConfig = JSON.parse(configFile);
20630
22259
  this._config = SessionConfigSchema.parse(importedConfig);
20631
22260
  this._isDirty = true;
@@ -20636,7 +22265,7 @@ var init_ConfigService = __esm({
20636
22265
  */
20637
22266
  expandHome(filePath) {
20638
22267
  if (filePath.startsWith("~/")) {
20639
- return path6__namespace.join(process.env.HOME || "", filePath.slice(2));
22268
+ return path8__namespace.join(process.env.HOME || "", filePath.slice(2));
20640
22269
  }
20641
22270
  return filePath;
20642
22271
  }
@@ -21074,7 +22703,7 @@ var init_ValidationService = __esm({
21074
22703
  );
21075
22704
  this._schemas.set(
21076
22705
  "filePath",
21077
- zod.z.string().min(1).max(this._config.maxFilePathLength).refine((path7) => !this.containsPathTraversal(path7), {
22706
+ zod.z.string().min(1).max(this._config.maxFilePathLength).refine((path9) => !this.containsPathTraversal(path9), {
21078
22707
  message: "Path traversal detected"
21079
22708
  })
21080
22709
  );
@@ -21213,11 +22842,11 @@ var init_ValidationService = __esm({
21213
22842
  /**
21214
22843
  * ファイルパス検証
21215
22844
  */
21216
- validateFilePath(path7) {
22845
+ validateFilePath(path9) {
21217
22846
  try {
21218
22847
  const schema = this._schemas.get("filePath");
21219
- const result = schema.parse(path7);
21220
- if (this.isSystemPath(path7)) {
22848
+ const result = schema.parse(path9);
22849
+ if (this.isSystemPath(path9)) {
21221
22850
  return {
21222
22851
  valid: false,
21223
22852
  errors: [
@@ -21363,8 +22992,8 @@ var init_ValidationService = __esm({
21363
22992
  /**
21364
22993
  * パストラバーサルの検出
21365
22994
  */
21366
- containsPathTraversal(path7) {
21367
- return /\.\.[/\\]/.test(path7) || path7.includes("..\\") || path7.includes("../");
22995
+ containsPathTraversal(path9) {
22996
+ return /\.\.[/\\]/.test(path9) || path9.includes("..\\") || path9.includes("../");
21368
22997
  }
21369
22998
  /**
21370
22999
  * 危険なコマンドの判定
@@ -21391,7 +23020,7 @@ var init_ValidationService = __esm({
21391
23020
  /**
21392
23021
  * システムパスの判定
21393
23022
  */
21394
- isSystemPath(path7) {
23023
+ isSystemPath(path9) {
21395
23024
  const systemPaths = [
21396
23025
  "/etc",
21397
23026
  "/sys",
@@ -21405,7 +23034,7 @@ var init_ValidationService = __esm({
21405
23034
  "/sbin"
21406
23035
  ];
21407
23036
  return systemPaths.some(
21408
- (sysPath) => path7.toLowerCase().startsWith(sysPath.toLowerCase())
23037
+ (sysPath) => path9.toLowerCase().startsWith(sysPath.toLowerCase())
21409
23038
  );
21410
23039
  }
21411
23040
  /**
@@ -22829,20 +24458,20 @@ var init_ApprovalEngine = __esm({
22829
24458
  );
22830
24459
  this.pendingRequests.set(_request.id, _request);
22831
24460
  this.emit("approval-requested", _request);
22832
- return new Promise((resolve2) => {
24461
+ return new Promise((resolve4) => {
22833
24462
  if (this.config.autoApprovalTimeout > 0 && _riskAssessment.overallRisk === "low") {
22834
24463
  setTimeout(() => {
22835
24464
  if (this.pendingRequests.has(_request.id)) {
22836
24465
  this.pendingRequests.delete(_request.id);
22837
24466
  this.emit("approval-timeout", { requestId: _request.id });
22838
- resolve2(this.createAutoApprovalResponse("Timeout auto-approval"));
24467
+ resolve4(this.createAutoApprovalResponse("Timeout auto-approval"));
22839
24468
  }
22840
24469
  }, this.config.autoApprovalTimeout);
22841
24470
  }
22842
24471
  this.once(
22843
24472
  `approval-response-${_request.id}`,
22844
24473
  (_response) => {
22845
- resolve2(_response);
24474
+ resolve4(_response);
22846
24475
  }
22847
24476
  );
22848
24477
  });
@@ -24719,7 +26348,7 @@ var init_DisplayManager = __esm({
24719
26348
  for (const frame of frames) {
24720
26349
  this.clearLine();
24721
26350
  this.write(frame);
24722
- await new Promise((resolve2) => setTimeout(resolve2, intervalMs));
26351
+ await new Promise((resolve4) => setTimeout(resolve4, intervalMs));
24723
26352
  }
24724
26353
  this.writeLine();
24725
26354
  }
@@ -26048,8 +27677,8 @@ var init_SessionOrchestrator = __esm({
26048
27677
  * UIサービスの初期化
26049
27678
  */
26050
27679
  async initializeUIServices() {
26051
- this._readlineAdapter = new ReadlineAdapter2();
26052
- this._chalkAdapter = new ChalkAdapter2();
27680
+ this._readlineAdapter = new ReadlineAdapter();
27681
+ this._chalkAdapter = new ChalkAdapter();
26053
27682
  this._displayManager = new DisplayManager();
26054
27683
  this._spinnerManager = SpinnerManager.getInstance();
26055
27684
  this._statusDisplay = new StatusDisplay();
@@ -26128,7 +27757,7 @@ var init_SessionOrchestrator = __esm({
26128
27757
  if (!this._inputController || !this._displayManager || !this._commandRegistry || !this._stateMachine) {
26129
27758
  throw new Error("Required components not initialized");
26130
27759
  }
26131
- this._sessionManager = new SessionManager2(
27760
+ this._sessionManager = new SessionManager(
26132
27761
  this._inputController,
26133
27762
  this._displayManager,
26134
27763
  this._commandRegistry,
@@ -26212,15 +27841,15 @@ var init_SessionOrchestrator = __esm({
26212
27841
  /**
26213
27842
  * 設定の取得
26214
27843
  */
26215
- getConfig(path7) {
26216
- return this._configService?.getNestedValue(path7);
27844
+ getConfig(path9) {
27845
+ return this._configService?.getNestedValue(path9);
26217
27846
  }
26218
27847
  /**
26219
27848
  * 設定の更新
26220
27849
  */
26221
- async setConfig(path7, value) {
27850
+ async setConfig(path9, value) {
26222
27851
  if (this._configService) {
26223
- await this._configService.setNestedValue(path7, value);
27852
+ await this._configService.setNestedValue(path9, value);
26224
27853
  }
26225
27854
  }
26226
27855
  /**
@@ -26315,91 +27944,11 @@ function createInteractiveSession(maria, config2) {
26315
27944
  const orchestrator = new SessionOrchestrator(context2, config2);
26316
27945
  return new RefactoredInteractiveSession(orchestrator);
26317
27946
  }
26318
- var CommandAdapter, RefactoredInteractiveSession;
27947
+ var RefactoredInteractiveSession;
26319
27948
  var init_interactive_session = __esm({
26320
27949
  "src/services/interactive-session/index.ts"() {
26321
27950
  init_SessionOrchestrator();
26322
27951
  init_errors();
26323
- CommandAdapter = class {
26324
- constructor(maria) {
26325
- this.maria = maria;
26326
- }
26327
- async execute(command, context2) {
26328
- try {
26329
- switch (command) {
26330
- case "/help":
26331
- return {
26332
- ok: true,
26333
- message: `\u{1F4D6} Available Commands:
26334
- \u2022 /help - Show this help message
26335
- \u2022 /clear - Clear the context
26336
- \u2022 /status - Show system status
26337
- \u2022 /model - Manage AI models
26338
- \u2022 /code - Generate code
26339
- \u2022 /exit - Exit the session`
26340
- };
26341
- case "/clear":
26342
- return {
26343
- ok: true,
26344
- message: "\u{1F9F9} Context cleared"
26345
- };
26346
- case "/status":
26347
- return {
26348
- ok: true,
26349
- message: "\u2705 System is operational"
26350
- };
26351
- default:
26352
- return {
26353
- ok: false,
26354
- message: `Command ${command} is being migrated to the new system`
26355
- };
26356
- }
26357
- } catch (error) {
26358
- return {
26359
- ok: false,
26360
- message: `Error executing command: ${error}`
26361
- };
26362
- }
26363
- }
26364
- exists(command) {
26365
- const knownCommands = [
26366
- "/help",
26367
- "/clear",
26368
- "/status",
26369
- "/model",
26370
- "/code",
26371
- "/exit",
26372
- "/memory",
26373
- "/test",
26374
- "/review"
26375
- ];
26376
- return knownCommands.includes(command.toLowerCase());
26377
- }
26378
- getAvailableCommands() {
26379
- return [
26380
- "/help",
26381
- "/clear",
26382
- "/status",
26383
- "/model",
26384
- "/code",
26385
- "/exit",
26386
- "/memory",
26387
- "/test",
26388
- "/review"
26389
- ];
26390
- }
26391
- getHelp(command) {
26392
- const helpTexts = {
26393
- "/help": "Show available commands",
26394
- "/clear": "Clear the conversation context",
26395
- "/status": "Show system status",
26396
- "/model": "Select or view AI models",
26397
- "/code": "Generate code from a description",
26398
- "/exit": "Exit the session"
26399
- };
26400
- return helpTexts[command.toLowerCase()] || null;
26401
- }
26402
- };
26403
27952
  RefactoredInteractiveSession = class {
26404
27953
  orchestrator;
26405
27954
  constructor(orchestrator) {
@@ -26418,20 +27967,13 @@ var init_interactive_session = __esm({
26418
27967
  getStats() {
26419
27968
  return this.orchestrator.getSessionStats();
26420
27969
  }
26421
- getConfig(path7) {
26422
- return this.orchestrator.getConfig(path7);
27970
+ getConfig(path9) {
27971
+ return this.orchestrator.getConfig(path9);
26423
27972
  }
26424
- async setConfig(path7, value) {
26425
- await this.orchestrator.setConfig(path7, value);
27973
+ async setConfig(path9, value) {
27974
+ await this.orchestrator.setConfig(path9, value);
26426
27975
  }
26427
27976
  };
26428
- ({
26429
- SessionManager,
26430
- ReadlineAdapter,
26431
- ChalkAdapter,
26432
- CommandAdapter,
26433
- SessionOrchestrator
26434
- });
26435
27977
  }
26436
27978
  });
26437
27979
 
@@ -26441,7 +27983,7 @@ var init_package = __esm({
26441
27983
  "package.json"() {
26442
27984
  package_default = {
26443
27985
  name: "@bonginkan/maria",
26444
- version: "3.6.3",
27986
+ version: "3.6.4",
26445
27987
  description: "\u{1F680} MARIA v3.6.0 - Premier Enterprise AI Development Platform. Revolutionary multimodal intelligence featuring advanced orchestration, production-grade telemetry, and sophisticated workflow templates. Delivers 93% performance enhancement with real-time TUI monitoring, ML-powered model selection, quantum-resistant security architecture, and comprehensive observability. Battle-tested for enterprise deployment with exceptional reliability.",
26446
27988
  keywords: [
26447
27989
  "ai",
@@ -27024,7 +28566,7 @@ async function generateAIResponse(userInput) {
27024
28566
  }
27025
28567
  async function streamAIResponse(userInput) {
27026
28568
  const thinkingInterval = startThinkingAnimation();
27027
- await new Promise((resolve2) => setTimeout(resolve2, 200));
28569
+ await new Promise((resolve4) => setTimeout(resolve4, 200));
27028
28570
  clearInterval(thinkingInterval);
27029
28571
  process.stdout.write("\r" + " ".repeat(50) + "\r");
27030
28572
  const response2 = await generateAIResponse(userInput);
@@ -27197,6 +28739,36 @@ async function startInteractiveSession() {
27197
28739
  // wrapped for reference safety
27198
28740
  }))
27199
28741
  };
28742
+ if (command === "/help" || command === "help") {
28743
+ console.log(`
28744
+ \u{1F4D6} MARIA Commands (Basic Help)
28745
+
28746
+ \u{1F680} Core Commands:
28747
+ /help - Show this help message
28748
+ /clear - Clear conversation context
28749
+ /exit - Exit MARIA
28750
+ /status - Show system status
28751
+ /config - Show configuration
28752
+ /model - Select AI model
28753
+
28754
+ \u{1F3A8} Generation:
28755
+ /code - Generate/fix code
28756
+ /test - Generate tests
28757
+ /review - Review code
28758
+
28759
+ For full help, run: pnpm build and check documentation.
28760
+ `);
28761
+ continue;
28762
+ }
28763
+ if (command === "/code" || command === "code") {
28764
+ if (args.length === 0) {
28765
+ console.log("\u274C Please provide a code request. Example: /code create a REST API");
28766
+ continue;
28767
+ }
28768
+ console.log("\u{1F680} Processing code request...");
28769
+ console.log("\u26A0\uFE0F Note: /code command functionality is being restored. Please try the legacy command system or check back after further updates.");
28770
+ continue;
28771
+ }
27200
28772
  try {
27201
28773
  const result = await slashCommandHandler.handleCommand(
27202
28774
  command,
@@ -27284,6 +28856,7 @@ async function startInteractiveSession() {
27284
28856
  function createCLI2() {
27285
28857
  const program2 = new commander.Command();
27286
28858
  program2.name("maria").description(`\u{1F680} MARIA v${packageJson.version} - Intelligent AI Assistant`).version(packageJson.version).option("--v3-session", "Use v3 session architecture").option("--no-interactive", "Disable interactive mode for CI/CD").action(async (options) => {
28859
+ loadEnvironmentVariables();
27287
28860
  const { displayFinalStartupScreen: displayFinalStartupScreen2 } = await Promise.resolve().then(() => (init_startup_display(), startup_display_exports));
27288
28861
  displayFinalStartupScreen2();
27289
28862
  const useV3 = options.v3Session || process.env.MARIA_USE_V3_SESSION === "1";