@bonginkan/maria 4.4.2 → 4.4.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.
@@ -23,9 +23,9 @@ var crypto6 = require('crypto');
23
23
  var perf_hooks = require('perf_hooks');
24
24
  var dotenv = require('dotenv');
25
25
  var child_process = require('child_process');
26
+ var promises = require('timers/promises');
26
27
  var string_decoder = require('string_decoder');
27
28
  var fs9 = require('fs-extra');
28
- var promises = require('timers/promises');
29
29
  var dns = require('dns/promises');
30
30
  var yaml = require('js-yaml');
31
31
  var neo4j = require('neo4j-driver');
@@ -526,22 +526,22 @@ function dataUriToBuffer(uri) {
526
526
  if (firstComma === -1 || firstComma <= 4) {
527
527
  throw new TypeError("malformed data: URI");
528
528
  }
529
- const meta27 = uri.substring(5, firstComma).split(";");
529
+ const meta28 = uri.substring(5, firstComma).split(";");
530
530
  let charset = "";
531
531
  let base64 = false;
532
- const type = meta27[0] || "text/plain";
532
+ const type = meta28[0] || "text/plain";
533
533
  let typeFull = type;
534
- for (let i2 = 1; i2 < meta27.length; i2++) {
535
- if (meta27[i2] === "base64") {
534
+ for (let i2 = 1; i2 < meta28.length; i2++) {
535
+ if (meta28[i2] === "base64") {
536
536
  base64 = true;
537
- } else if (meta27[i2]) {
538
- typeFull += `;${meta27[i2]}`;
539
- if (meta27[i2].indexOf("charset=") === 0) {
540
- charset = meta27[i2].substring(8);
537
+ } else if (meta28[i2]) {
538
+ typeFull += `;${meta28[i2]}`;
539
+ if (meta28[i2].indexOf("charset=") === 0) {
540
+ charset = meta28[i2].substring(8);
541
541
  }
542
542
  }
543
543
  }
544
- if (!meta27[0] && !charset.length) {
544
+ if (!meta28[0] && !charset.length) {
545
545
  typeFull += ";charset=US-ASCII";
546
546
  charset = "US-ASCII";
547
547
  }
@@ -7110,8 +7110,8 @@ var init_base_provider = __esm({
7110
7110
  throw error2;
7111
7111
  }
7112
7112
  if (attempt < maxRetries - 1) {
7113
- const delay = Math.pow(2, attempt) * 1e3;
7114
- await new Promise((resolve19) => setTimeout(resolve19, delay));
7113
+ const delay2 = Math.pow(2, attempt) * 1e3;
7114
+ await new Promise((resolve19) => setTimeout(resolve19, delay2));
7115
7115
  }
7116
7116
  }
7117
7117
  }
@@ -7517,8 +7517,8 @@ var init_SecretManagerIntegration = __esm({
7517
7517
  return payload.toString();
7518
7518
  } catch (e2) {
7519
7519
  if (attempt === this.MAX_RETRIES - 1) break;
7520
- const delay = this.BASE_DELAY_MS * Math.pow(2, attempt);
7521
- await new Promise((r2) => setTimeout(r2, delay));
7520
+ const delay2 = this.BASE_DELAY_MS * Math.pow(2, attempt);
7521
+ await new Promise((r2) => setTimeout(r2, delay2));
7522
7522
  }
7523
7523
  }
7524
7524
  return void 0;
@@ -8794,18 +8794,41 @@ var init_llm_health_checker = __esm({
8794
8794
  }
8795
8795
  async startLMStudio() {
8796
8796
  try {
8797
- const { spawn: spawn4 } = await import('child_process');
8797
+ const { spawn: spawn5 } = await import('child_process');
8798
8798
  const _lmsPath = "/Users/bongin_max/.lmstudio/bin/lms";
8799
8799
  return new Promise((resolve19) => {
8800
- const _child = spawn4(_lmsPath, ["server", "start"], {
8801
- stdio: "ignore",
8802
- detached: true
8800
+ const _child = spawn5(_lmsPath, ["server", "start"], {
8801
+ stdio: ["ignore", "pipe", "pipe"],
8802
+ detached: true,
8803
+ env: { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0" }
8803
8804
  });
8804
- _child.on("_error", () => {
8805
+ _child.on("error", () => {
8805
8806
  resolve19(false);
8806
8807
  });
8808
+ try {
8809
+ _child.stdout?.on("data", (d) => {
8810
+ if (process.env.MARIA_DEBUG === "1") {
8811
+ try {
8812
+ console.log("[DEBUG/lms][server]", String(d));
8813
+ } catch {
8814
+ }
8815
+ }
8816
+ });
8817
+ _child.stderr?.on("data", (d) => {
8818
+ if (process.env.MARIA_DEBUG === "1") {
8819
+ try {
8820
+ console.log("[DEBUG/lms][server][err]", String(d));
8821
+ } catch {
8822
+ }
8823
+ }
8824
+ });
8825
+ } catch {
8826
+ }
8807
8827
  _child.on("spawn", () => {
8808
- _child.unref();
8828
+ try {
8829
+ _child.unref();
8830
+ } catch {
8831
+ }
8809
8832
  setTimeout(async () => {
8810
8833
  const _status = await this.checkService("LM Studio");
8811
8834
  resolve19(_status.isRunning);
@@ -26067,8 +26090,8 @@ var require_package = __commonJS({
26067
26090
  "package.json"(exports, module) {
26068
26091
  module.exports = {
26069
26092
  name: "@bonginkan/maria",
26070
- version: "4.4.2",
26071
- description: "\u{1F680} MARIA v4.4.2 - Enterprise AI Development Platform with identity system and character voice implementation. Features 74 production-ready commands with comprehensive fallback implementation, local LLM support, and zero external dependencies. Includes natural language coding, AI safety evaluation, intelligent evolution system, episodic memory with PII masking, and real-time monitoring dashboard. Built with TypeScript AST-powered code generation, OAuth2.0 + PKCE authentication, quantum-resistant cryptography, and enterprise-grade performance.",
26093
+ version: "4.4.4",
26094
+ description: "\u{1F680} MARIA v4.4.4 - Enterprise AI Development Platform with identity system and character voice implementation. Features 74 production-ready commands with comprehensive fallback implementation, local LLM support, and zero external dependencies. Includes natural language coding, AI safety evaluation, intelligent evolution system, episodic memory with PII masking, and real-time monitoring dashboard. Built with TypeScript AST-powered code generation, OAuth2.0 + PKCE authentication, quantum-resistant cryptography, and enterprise-grade performance.",
26072
26095
  keywords: [
26073
26096
  "ai",
26074
26097
  "cli",
@@ -27046,6 +27069,10 @@ ${authUrl}
27046
27069
  });
27047
27070
 
27048
27071
  // src/services/cli-auth/MariaAPIClient.ts
27072
+ var MariaAPIClient_exports = {};
27073
+ __export(MariaAPIClient_exports, {
27074
+ MariaAPIClient: () => MariaAPIClient
27075
+ });
27049
27076
  var MariaAPIClient;
27050
27077
  var init_MariaAPIClient = __esm({
27051
27078
  "src/services/cli-auth/MariaAPIClient.ts"() {
@@ -27069,12 +27096,36 @@ var init_MariaAPIClient = __esm({
27069
27096
  "Content-Type": "application/json"
27070
27097
  };
27071
27098
  if (requiresAuth2) {
27072
- const token = await this.authClient.getAccessToken();
27099
+ let token = await this.authClient.getAccessToken();
27100
+ if (!token) {
27101
+ try {
27102
+ const stored = await this.authClient.loadStoredTokens();
27103
+ if (stored?.refreshToken) {
27104
+ await this.authClient.refreshAccessToken(stored.refreshToken);
27105
+ token = await this.authClient.getAccessToken();
27106
+ }
27107
+ } catch (e2) {
27108
+ if (process.env.MARIA_DEBUG === "1") {
27109
+ console.error("[MARIA DEBUG] Token refresh preflight failed", String(e2?.message || e2));
27110
+ }
27111
+ }
27112
+ }
27073
27113
  if (!token) {
27074
27114
  throw new Error('Authentication required. Please run "maria /login" first.');
27075
27115
  }
27076
27116
  headers["Authorization"] = `Bearer ${token}`;
27077
27117
  }
27118
+ if (process.env.MARIA_DEBUG === "1") {
27119
+ try {
27120
+ console.error("[MARIA DEBUG] API request start", {
27121
+ method,
27122
+ url: url2,
27123
+ requiresAuth: requiresAuth2,
27124
+ hasAuthHeader: Boolean(headers["Authorization"])
27125
+ });
27126
+ } catch {
27127
+ }
27128
+ }
27078
27129
  let lastError = null;
27079
27130
  for (let attempt = 1; attempt <= (this.config.retryAttempts || 3); attempt++) {
27080
27131
  try {
@@ -27089,26 +27140,52 @@ var init_MariaAPIClient = __esm({
27089
27140
  clearTimeout(timeoutId);
27090
27141
  const responseData = await response.json();
27091
27142
  if (!response.ok) {
27092
- if (response.status === 401) {
27143
+ if (response.status === 401 && requiresAuth2) {
27093
27144
  const tokens2 = await this.authClient.loadStoredTokens();
27094
27145
  if (tokens2?.refreshToken) {
27095
27146
  try {
27147
+ if (process.env.MARIA_DEBUG === "1") {
27148
+ try {
27149
+ console.error("[MARIA DEBUG] 401 received, attempting token refresh");
27150
+ } catch {
27151
+ }
27152
+ }
27096
27153
  await this.authClient.refreshAccessToken(tokens2.refreshToken);
27154
+ const refreshedToken = await this.authClient.getAccessToken();
27155
+ if (refreshedToken) {
27156
+ headers["Authorization"] = `Bearer ${refreshedToken}`;
27157
+ }
27158
+ if (process.env.MARIA_DEBUG === "1") {
27159
+ try {
27160
+ console.error("[MARIA DEBUG] Token refresh completed", { hasAuthHeader: Boolean(headers["Authorization"]) });
27161
+ } catch {
27162
+ }
27163
+ }
27097
27164
  continue;
27098
27165
  } catch {
27099
- throw new Error("Session expired. Please login again.");
27100
27166
  }
27101
27167
  }
27102
- throw new Error(responseData.hint || "Authentication failed");
27168
+ throw new Error(responseData?.hint || "Authentication failed");
27103
27169
  }
27104
27170
  if (response.status === 429) {
27105
27171
  const retryAfter = response.headers.get("Retry-After");
27106
- const delay = retryAfter ? parseInt(retryAfter) * 1e3 : 5e3;
27107
- console.log(`\u23F3 Rate limited. Waiting ${delay}ms before retry...`);
27108
- await new Promise((resolve19) => setTimeout(resolve19, delay));
27172
+ const delay2 = retryAfter ? parseInt(retryAfter) * 1e3 : 5e3;
27173
+ console.log(`\u23F3 Rate limited. Waiting ${delay2}ms before retry...`);
27174
+ await new Promise((resolve19) => setTimeout(resolve19, delay2));
27109
27175
  continue;
27110
27176
  }
27111
- throw new Error(responseData.error || `Request failed: ${response.status}`);
27177
+ const details = {
27178
+ status: response.status,
27179
+ endpoint: url2,
27180
+ method,
27181
+ attempt,
27182
+ response: responseData
27183
+ };
27184
+ if (process.env.MARIA_DEBUG === "1") {
27185
+ console.error("[MARIA DEBUG] API request failed", details);
27186
+ }
27187
+ const msg = responseData && (responseData.error || responseData.message) || `Request failed: ${response.status}`;
27188
+ throw new Error(msg);
27112
27189
  }
27113
27190
  return responseData;
27114
27191
  } catch (error2) {
@@ -27117,11 +27194,17 @@ var init_MariaAPIClient = __esm({
27117
27194
  console.error(`Request timeout after ${this.config.timeout}ms`);
27118
27195
  }
27119
27196
  if (attempt < (this.config.retryAttempts || 3)) {
27197
+ if (process.env.MARIA_DEBUG === "1") {
27198
+ console.error("[MARIA DEBUG] API error on attempt", { method, endpoint: url2, attempt, error: String(error2?.message || error2) });
27199
+ }
27120
27200
  console.log(`\u{1F504} Retrying request (attempt ${attempt + 1}/${this.config.retryAttempts})...`);
27121
27201
  await new Promise((resolve19) => setTimeout(resolve19, 1e3 * attempt));
27122
27202
  }
27123
27203
  }
27124
27204
  }
27205
+ if (process.env.MARIA_DEBUG === "1") {
27206
+ console.error("[MARIA DEBUG] API request exhausted retries", { method, endpoint: url2, error: String(lastError?.message || lastError) });
27207
+ }
27125
27208
  throw lastError || new Error("Request failed after all retries");
27126
27209
  }
27127
27210
  /**
@@ -27166,6 +27249,33 @@ var init_MariaAPIClient = __esm({
27166
27249
  async getAPIInfo() {
27167
27250
  return this.request("GET", "/api/v1", null, false);
27168
27251
  }
27252
+ /**
27253
+ * Create Stripe checkout session for a target plan
27254
+ */
27255
+ async createCheckoutSession(planId, options) {
27256
+ try {
27257
+ return await this.request("POST", "/api/stripe/create-checkout-session", {
27258
+ planId,
27259
+ isAnnual: Boolean(options?.isAnnual)
27260
+ });
27261
+ } catch (e2) {
27262
+ return await this.request("POST", "/api/create-checkout-session", {
27263
+ planId,
27264
+ isAnnual: Boolean(options?.isAnnual)
27265
+ });
27266
+ }
27267
+ }
27268
+ /**
27269
+ * Create Stripe customer portal session
27270
+ */
27271
+ async createPortalSession(returnUrl) {
27272
+ const body = { returnUrl: returnUrl || (process.env.MARIA_RETURN_URL || "https://maria-code.ai/manage") };
27273
+ try {
27274
+ return await this.request("POST", "/api/stripe/create-portal-session", body);
27275
+ } catch (e2) {
27276
+ return await this.request("POST", "/api/create-portal-session", body);
27277
+ }
27278
+ }
27169
27279
  /**
27170
27280
  * Health check
27171
27281
  */
@@ -27237,7 +27347,7 @@ var init_MariaAPIClient = __esm({
27237
27347
  });
27238
27348
  console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\n");
27239
27349
  } catch (error2) {
27240
- console.error("Failed to fetch usage stats:", error2.message);
27350
+ console.error("Failed to fetch usage stats:", error2?.message || String(error2));
27241
27351
  }
27242
27352
  }
27243
27353
  /**
@@ -27954,6 +28064,12 @@ var init_AuthSecretManager = __esm({
27954
28064
  new AuthSecretManager();
27955
28065
  }
27956
28066
  });
28067
+
28068
+ // src/utils/open-url.ts
28069
+ var open_url_exports = {};
28070
+ __export(open_url_exports, {
28071
+ openUrl: () => openUrl
28072
+ });
27957
28073
  async function openUrl(url2) {
27958
28074
  if (process.env.CI === "true" || process.env.SSH_CONNECTION || process.env.CONTAINER === "true") {
27959
28075
  throw new Error("Headless environment");
@@ -28131,7 +28247,7 @@ var init_AuthenticationManager = __esm({
28131
28247
  const response = await fetch(`${this.apiBase}/api/user/profile`, {
28132
28248
  headers: {
28133
28249
  "Authorization": `Bearer ${tokens2.accessToken}`,
28134
- "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.4.2"}`
28250
+ "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.4.4"}`
28135
28251
  }
28136
28252
  });
28137
28253
  if (response.status === 401) {
@@ -28785,7 +28901,7 @@ async function callApi(path66, init3 = {}) {
28785
28901
  "Authorization": `Bearer ${token}`,
28786
28902
  "X-Device-Id": getDeviceId(),
28787
28903
  "X-Session-Id": getSessionId() || "",
28788
- "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.4.2"}`,
28904
+ "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.4.4"}`,
28789
28905
  "Content-Type": init3.headers?.["Content-Type"] || "application/json"
28790
28906
  });
28791
28907
  const doFetch = async (token) => {
@@ -29050,6 +29166,365 @@ var init_choice_memory = __esm({
29050
29166
  }
29051
29167
  });
29052
29168
 
29169
+ // src/services/local-llm-manager.ts
29170
+ var local_llm_manager_exports = {};
29171
+ __export(local_llm_manager_exports, {
29172
+ ensureLocalProviderUp: () => ensureLocalProviderUp,
29173
+ generateViaCli: () => generateViaCli,
29174
+ selectLocalProviderAndModel: () => selectLocalProviderAndModel
29175
+ });
29176
+ function debugLog(...args2) {
29177
+ if (process.env.MARIA_DEBUG === "1") {
29178
+ try {
29179
+ console.log("[DEBUG/local-llm]", ...args2);
29180
+ } catch {
29181
+ }
29182
+ }
29183
+ }
29184
+ async function isUp(provider) {
29185
+ if (provider === "lmstudio") {
29186
+ try {
29187
+ const r2 = await runCommand("lms", ["ls"], void 0, 4e3);
29188
+ if (r2.code === 0 && (r2.stdout.trim() || r2.stderr.trim())) {
29189
+ return "http://localhost:1234/v1";
29190
+ }
29191
+ } catch {
29192
+ }
29193
+ }
29194
+ const res = await discoverLocalProvider(provider, { timeoutMs: 600, nearbyScan: true });
29195
+ return res?.base || null;
29196
+ }
29197
+ async function tryStartLMStudio() {
29198
+ const child = child_process.spawn("lms", ["server", "start"], { stdio: ["ignore", "pipe", "pipe"], detached: true, env: { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0" } });
29199
+ try {
29200
+ child.stdout?.on("data", (d) => {
29201
+ if (process.env.MARIA_DEBUG === "1") {
29202
+ try {
29203
+ console.log("[DEBUG/lms][server]", String(d));
29204
+ } catch {
29205
+ }
29206
+ }
29207
+ });
29208
+ child.stderr?.on("data", (d) => {
29209
+ if (process.env.MARIA_DEBUG === "1") {
29210
+ try {
29211
+ console.log("[DEBUG/lms][server][err]", String(d));
29212
+ } catch {
29213
+ }
29214
+ }
29215
+ });
29216
+ } catch {
29217
+ }
29218
+ try {
29219
+ child.unref();
29220
+ } catch {
29221
+ }
29222
+ }
29223
+ async function tryStartOllama() {
29224
+ child_process.spawn("ollama", ["serve"], { stdio: "ignore", detached: true }).unref();
29225
+ }
29226
+ async function waitUntilUp(provider, timeoutMs = 15e3) {
29227
+ const start = Date.now();
29228
+ while (Date.now() - start < timeoutMs) {
29229
+ const base = await isUp(provider);
29230
+ if (base) return base;
29231
+ await promises.setTimeout(500);
29232
+ }
29233
+ return null;
29234
+ }
29235
+ async function ensureLocalProviderUp(preferredOrder = ["lmstudio", "ollama"]) {
29236
+ for (const p of preferredOrder) {
29237
+ const up = await isUp(p);
29238
+ if (up) {
29239
+ debugLog("provider up", p, up);
29240
+ return { provider: p, baseUrl: up, started: false };
29241
+ }
29242
+ try {
29243
+ debugLog("attempting autostart", p);
29244
+ if (p === "lmstudio") await tryStartLMStudio();
29245
+ else await tryStartOllama();
29246
+ const providerTimeout = p === "lmstudio" ? parseInt(process.env.LMSTUDIO_STARTUP_TIMEOUT_MS || "") || 3e4 : parseInt(process.env.OLLAMA_STARTUP_TIMEOUT_MS || "") || 2e4;
29247
+ const base = await waitUntilUp(p, providerTimeout);
29248
+ if (base) {
29249
+ debugLog("provider started", p, base);
29250
+ return { provider: p, baseUrl: base, started: true };
29251
+ }
29252
+ debugLog("autostart failed or timed out", p);
29253
+ } catch (e2) {
29254
+ debugLog("autostart error", p, e2?.message || String(e2));
29255
+ }
29256
+ }
29257
+ debugLog("no preferred providers available");
29258
+ return null;
29259
+ }
29260
+ function parseModelId(id) {
29261
+ const s2 = id.toLowerCase();
29262
+ const afterSlash = s2.includes("/") ? s2.split("/").pop() || s2 : s2;
29263
+ const m1 = afterSlash.match(/^(gpt-oss|gemma|llama|magistral)[-:]?(\d+(?:\.\d+)?)?([a-z]*)?[:\-]?(\d+)?([a-z]*)?$/);
29264
+ if (m1) {
29265
+ const fam = m1[1];
29266
+ const verToken = m1[2] || null;
29267
+ const lastNum = m1[4] || null;
29268
+ const sizeToken = (m1[3] || m1[5] || "").toLowerCase();
29269
+ const version = verToken ? Number(verToken) : null;
29270
+ const size = lastNum ? Number(lastNum) : sizeToken.includes("b") ? Number(sizeToken.replace(/[^0-9]/g, "")) : null;
29271
+ return { family: fam, version, size };
29272
+ }
29273
+ const m2 = afterSlash.match(/^(gpt-oss|gemma|llama|magistral)[^-:]*[:](\d+)([a-z])$/);
29274
+ if (m2) {
29275
+ return { family: m2[1], version: null, size: Number(m2[2]) };
29276
+ }
29277
+ return { family: s2.split(/[-:]/)[0], version: null, size: null };
29278
+ }
29279
+ function pickBestModel(models, prefs) {
29280
+ if (!models.length) return null;
29281
+ if (prefs.explicitModel) {
29282
+ const exact = models.find((m2) => m2.toLowerCase() === prefs.explicitModel.toLowerCase());
29283
+ if (exact) return exact;
29284
+ const family = prefs.explicitModel.split(/[:\-]/)[0].toLowerCase();
29285
+ const famMs = models.filter((m2) => m2.toLowerCase().startsWith(family));
29286
+ if (famMs.length) models = famMs;
29287
+ }
29288
+ const familyRank = (id) => {
29289
+ const fam = parseModelId(id).family;
29290
+ const idx = FAMILY_ORDER.indexOf(fam);
29291
+ return idx === -1 ? 999 : idx;
29292
+ };
29293
+ const score = (id) => {
29294
+ const { version, size } = parseModelId(id);
29295
+ return [-(version || 0), -(size || 0)];
29296
+ };
29297
+ const sorted = [...models].sort((a, b) => {
29298
+ const fa = familyRank(a);
29299
+ const fb = familyRank(b);
29300
+ if (fa !== fb) return fa - fb;
29301
+ const [va, sa] = score(a);
29302
+ const [vb, sb] = score(b);
29303
+ if (va !== vb) return va - vb;
29304
+ return sa - sb;
29305
+ });
29306
+ return sorted[0] || null;
29307
+ }
29308
+ function extractTextFromResponsesApi(body) {
29309
+ try {
29310
+ const out = Array.isArray(body?.output) ? body.output : [];
29311
+ for (const item of out) {
29312
+ const contents = Array.isArray(item?.content) ? item.content : [];
29313
+ for (const c of contents) {
29314
+ if (typeof c?.text === "string" && c.text.trim()) return c.text.trim();
29315
+ }
29316
+ }
29317
+ if (typeof body?.text === "string" && body.text.trim()) return body.text.trim();
29318
+ if (typeof body?.content === "string" && body.content.trim()) return body.content.trim();
29319
+ } catch {
29320
+ }
29321
+ return null;
29322
+ }
29323
+ function supportsReasoningForLmStudioModel(modelId) {
29324
+ try {
29325
+ const fam = parseModelId(modelId).family.toLowerCase();
29326
+ return fam === "gpt-oss";
29327
+ } catch {
29328
+ return false;
29329
+ }
29330
+ }
29331
+ async function listModels(provider, baseUrl) {
29332
+ const viaCli = await listModelsViaCli(provider).catch(() => []);
29333
+ if (viaCli.length) return viaCli;
29334
+ try {
29335
+ const url2 = provider === "ollama" ? `${baseUrl}/api/tags` : `${baseUrl}/models`;
29336
+ const res = await fetch(url2);
29337
+ if (!res.ok) return [];
29338
+ const body = await res.json().catch(() => ({}));
29339
+ if (provider === "ollama") {
29340
+ const arr2 = Array.isArray(body.models) ? body.models : body.data || [];
29341
+ return arr2.map((m2) => m2?.name).filter(Boolean);
29342
+ }
29343
+ const arr = Array.isArray(body.data) ? body.data : Array.isArray(body._data) ? body._data : [];
29344
+ return arr.map((m2) => m2?.id).filter(Boolean);
29345
+ } catch {
29346
+ return [];
29347
+ }
29348
+ }
29349
+ async function ensureBaselineModel(provider) {
29350
+ if (provider === "lmstudio") {
29351
+ child_process.spawn("lms", ["get", "openai/gpt-oss-20b"], { stdio: "ignore", detached: true }).unref();
29352
+ return;
29353
+ }
29354
+ child_process.spawn("ollama", ["pull", "gpt-oss:latest"], { stdio: "ignore", detached: true }).unref();
29355
+ }
29356
+ async function selectLocalProviderAndModel(prefs = {}) {
29357
+ const order = prefs.explicitProvider ? [
29358
+ prefs.explicitProvider,
29359
+ ...prefs.explicitProvider === "lmstudio" ? ["ollama"] : ["lmstudio"]
29360
+ ] : ["lmstudio", "ollama"];
29361
+ const up = await ensureLocalProviderUp(order);
29362
+ if (!up) return null;
29363
+ let models = await listModels(up.provider, up.baseUrl);
29364
+ if (process.env.MARIA_DEBUG === "1") {
29365
+ try {
29366
+ console.log("[DEBUG/local-llm] models.list", up.provider, models.slice(0, 20));
29367
+ } catch {
29368
+ }
29369
+ }
29370
+ if (!models.length) {
29371
+ await ensureBaselineModel(up.provider);
29372
+ await promises.setTimeout(2e3);
29373
+ models = await listModels(up.provider, up.baseUrl);
29374
+ }
29375
+ if (up.provider === "lmstudio") {
29376
+ const hasPreferred = models.some((m2) => parseModelId(m2).family === "gpt-oss");
29377
+ if (!hasPreferred) {
29378
+ await ensureBaselineModel("lmstudio");
29379
+ await promises.setTimeout(3e3);
29380
+ models = await listModels(up.provider, up.baseUrl);
29381
+ if (process.env.MARIA_DEBUG === "1") {
29382
+ try {
29383
+ console.log("[DEBUG/local-llm] models.relist.after-download", models.slice(0, 20));
29384
+ } catch {
29385
+ }
29386
+ }
29387
+ }
29388
+ }
29389
+ const chosen = pickBestModel(models, prefs) || (up.provider === "lmstudio" ? "openai/gpt-oss-20b" : "gpt-oss:latest");
29390
+ debugLog("selected provider/model", up.provider, chosen);
29391
+ return { provider: up.provider, baseUrl: up.baseUrl, model: chosen };
29392
+ }
29393
+ function runCommand(cmd, args2, input3, timeoutMs = 3e5) {
29394
+ return new Promise((resolve19) => {
29395
+ const child = child_process.spawn(cmd, args2, {
29396
+ stdio: ["pipe", "pipe", "pipe"],
29397
+ env: { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0", CI: "1" }
29398
+ });
29399
+ let stdout2 = "";
29400
+ let stderr = "";
29401
+ const timer = setTimeout(() => {
29402
+ try {
29403
+ child.kill("SIGKILL");
29404
+ } catch {
29405
+ }
29406
+ }, timeoutMs);
29407
+ child.stdout?.on("data", (d) => {
29408
+ stdout2 += d.toString();
29409
+ });
29410
+ child.stderr?.on("data", (d) => {
29411
+ stderr += d.toString();
29412
+ });
29413
+ child.on("close", (code) => {
29414
+ clearTimeout(timer);
29415
+ resolve19({ code, stdout: stdout2, stderr });
29416
+ });
29417
+ child.on("error", () => {
29418
+ clearTimeout(timer);
29419
+ resolve19({ code: -1, stdout: stdout2, stderr });
29420
+ });
29421
+ if (input3 && child.stdin) {
29422
+ child.stdin.write(input3);
29423
+ child.stdin.end();
29424
+ }
29425
+ });
29426
+ }
29427
+ async function listModelsViaCli(provider) {
29428
+ try {
29429
+ if (provider === "lmstudio") {
29430
+ const res2 = await runCommand("lms", ["ls", "--json"]);
29431
+ if (res2.code === 0) {
29432
+ try {
29433
+ const j = JSON.parse(res2.stdout);
29434
+ const arr = Array.isArray(j?.models) ? j.models : Array.isArray(j?.data) ? j.data : [];
29435
+ return arr.map((m2) => m2?.id || m2?.name).filter(Boolean);
29436
+ } catch {
29437
+ }
29438
+ }
29439
+ const res22 = await runCommand("lms", ["ls"]);
29440
+ if (res22.code === 0) {
29441
+ return res22.stdout.split(/\r?\n/).map((s2) => s2.trim()).filter(Boolean);
29442
+ }
29443
+ return [];
29444
+ }
29445
+ const res = await runCommand("ollama", ["list"]);
29446
+ if (res.code === 0) {
29447
+ const lines = res.stdout.split(/\r?\n/).slice(1).filter(Boolean);
29448
+ const names = lines.map((l) => l.split(/\s+/)[0]).filter(Boolean);
29449
+ return names;
29450
+ }
29451
+ return [];
29452
+ } catch {
29453
+ return [];
29454
+ }
29455
+ }
29456
+ async function generateViaCli(provider, model, prompt, baseUrl) {
29457
+ try {
29458
+ if (provider === "lmstudio") {
29459
+ let lmsBase = baseUrl;
29460
+ if (!lmsBase) {
29461
+ const found = await discoverLocalProvider("lmstudio", { timeoutMs: 800, nearbyScan: true });
29462
+ lmsBase = found?.base || "http://localhost:1234/v1";
29463
+ }
29464
+ const endpoint = `${lmsBase.replace(/\/$/, "")}/responses`;
29465
+ const controller = new AbortController();
29466
+ const timer = setTimeout(() => controller.abort(), 6e4);
29467
+ try {
29468
+ const withReasoning = supportsReasoningForLmStudioModel(model);
29469
+ const r2 = await fetch(endpoint, {
29470
+ method: "POST",
29471
+ headers: { "Content-Type": "application/json" },
29472
+ body: JSON.stringify({
29473
+ model,
29474
+ input: prompt,
29475
+ ...withReasoning ? { reasoning: { effort: "high" } } : {}
29476
+ }),
29477
+ signal: controller.signal
29478
+ });
29479
+ if (r2.ok) {
29480
+ const body = await r2.json().catch(() => ({}));
29481
+ const text = extractTextFromResponsesApi(body);
29482
+ if (text) return text;
29483
+ }
29484
+ const r22 = await fetch(endpoint, {
29485
+ method: "POST",
29486
+ headers: { "Content-Type": "application/json" },
29487
+ body: JSON.stringify({
29488
+ model,
29489
+ messages: [{ role: "user", content: prompt }],
29490
+ ...withReasoning ? { reasoning: { effort: "high" } } : {}
29491
+ }),
29492
+ signal: controller.signal
29493
+ });
29494
+ if (r22.ok) {
29495
+ const body2 = await r22.json().catch(() => ({}));
29496
+ const text2 = extractTextFromResponsesApi(body2);
29497
+ if (text2) return text2;
29498
+ }
29499
+ } finally {
29500
+ clearTimeout(timer);
29501
+ }
29502
+ return null;
29503
+ }
29504
+ try {
29505
+ const res = await runCommand("ollama", ["run", "--keepalive", "0", model], prompt);
29506
+ if (res.code === 0) return res.stdout.trim();
29507
+ const res2 = await runCommand("ollama", ["run", "--keepalive", "0", model, prompt]);
29508
+ if (res2.code === 0) return res2.stdout.trim();
29509
+ return null;
29510
+ } finally {
29511
+ try {
29512
+ await runCommand("ollama", ["stop", model], void 0, 8e3);
29513
+ } catch {
29514
+ }
29515
+ }
29516
+ } catch {
29517
+ return null;
29518
+ }
29519
+ }
29520
+ var FAMILY_ORDER;
29521
+ var init_local_llm_manager = __esm({
29522
+ "src/services/local-llm-manager.ts"() {
29523
+ init_llm_endpoint_discovery();
29524
+ FAMILY_ORDER = ["gpt-oss", "gemma", "llama", "magistral"];
29525
+ }
29526
+ });
29527
+
29053
29528
  // src/services/cli-auth/api-caller.ts
29054
29529
  var api_caller_exports = {};
29055
29530
  __export(api_caller_exports, {
@@ -29059,6 +29534,44 @@ __export(api_caller_exports, {
29059
29534
  executeChat: () => executeChat,
29060
29535
  executeCode: () => executeCode
29061
29536
  });
29537
+ function sanitizeLocalOutputText(raw) {
29538
+ let t2 = (raw || "").toString();
29539
+ const marker = "<|channel|>final<|message|>";
29540
+ const idx = t2.lastIndexOf(marker);
29541
+ if (idx >= 0) {
29542
+ let body = t2.substring(idx + marker.length);
29543
+ const endIdx = body.indexOf("<|end|>");
29544
+ if (endIdx >= 0) body = body.substring(0, endIdx);
29545
+ return body.trim();
29546
+ }
29547
+ return t2.replace(/<\|[^>]+?\|>/g, "").trim();
29548
+ }
29549
+ async function getEnterpriseFlag() {
29550
+ if (cachedEnterprise !== null) return cachedEnterprise;
29551
+ try {
29552
+ const tokens2 = await authManager2.getValidTokens();
29553
+ if (!tokens2) return false;
29554
+ const apiBase = process.env.MARIA_API_BASE || "https://api.maria-code.ai";
29555
+ const ctl = new AbortController();
29556
+ const to = setTimeout(() => ctl.abort(), 3e3);
29557
+ const r2 = await fetch(`${apiBase}/api/user/profile`, {
29558
+ method: "GET",
29559
+ headers: { "Authorization": `Bearer ${tokens2.accessToken}` }
29560
+ });
29561
+ clearTimeout(to);
29562
+ if (!r2.ok) {
29563
+ cachedEnterprise = false;
29564
+ return false;
29565
+ }
29566
+ const prof = await r2.json().catch(() => ({}));
29567
+ const plan = String((prof?.plan || "").toString()).toLowerCase();
29568
+ cachedEnterprise = plan === "enterprise";
29569
+ return cachedEnterprise;
29570
+ } catch {
29571
+ cachedEnterprise = false;
29572
+ return false;
29573
+ }
29574
+ }
29062
29575
  async function callAPI(endpoint, options = {}) {
29063
29576
  const tokens2 = await authManager2.getValidTokens();
29064
29577
  if (!tokens2) {
@@ -29066,6 +29579,93 @@ async function callAPI(endpoint, options = {}) {
29066
29579
  }
29067
29580
  const apiBase = process.env.MARIA_API_BASE || "https://api.maria-code.ai";
29068
29581
  const url2 = `${apiBase}${endpoint}`;
29582
+ try {
29583
+ const isLocalMode = process.env.LOCAL_MODE === "1";
29584
+ const isAiProxy = endpoint === "/v1/ai-proxy" && (options.method || "GET") === "POST";
29585
+ if (isAiProxy && (isLocalMode || true)) {
29586
+ const isEnterprisePlan = await getEnterpriseFlag().catch(() => false) || String(process.env.PLAN || "").toLowerCase() === "enterprise";
29587
+ if (!isLocalMode && !isEnterprisePlan) {
29588
+ } else {
29589
+ const payload = options.body || {};
29590
+ const reqProvider = String(payload?.provider || "").toLowerCase();
29591
+ if (isEnterprisePlan && reqProvider && !["lmstudio", "ollama"].includes(reqProvider)) {
29592
+ throw new Error("Enterprise policy requires local LLM only");
29593
+ }
29594
+ const explicitModel = typeof payload?.model === "string" ? payload.model : void 0;
29595
+ let effectivePrompt = void 0;
29596
+ if (typeof payload?.prompt === "string" && payload.prompt.trim()) {
29597
+ effectivePrompt = String(payload.prompt).trim();
29598
+ } else if (Array.isArray(payload?.messages)) {
29599
+ try {
29600
+ const lastUser = [...payload.messages].reverse().find((m2) => (m2?.role || "").toLowerCase() === "user");
29601
+ effectivePrompt = lastUser?.content && String(lastUser.content) || payload.messages.map((m2) => String(m2?.content || "")).filter(Boolean).join("\n");
29602
+ } catch {
29603
+ }
29604
+ }
29605
+ if (effectivePrompt && (!reqProvider || ["lmstudio", "ollama"].includes(reqProvider))) {
29606
+ try {
29607
+ let inlineProvider;
29608
+ let inlineModel;
29609
+ {
29610
+ const provMatch = /(?:^|\s)--provider(?:=|\s+)([^\s]+)/i.exec(effectivePrompt);
29611
+ if (provMatch) inlineProvider = provMatch[1].toLowerCase();
29612
+ const modelMatch = /(?:^|\s)--model(?:=|\s+)([^\s]+)/i.exec(effectivePrompt);
29613
+ if (modelMatch) inlineModel = modelMatch[1];
29614
+ if (inlineProvider || inlineModel) {
29615
+ effectivePrompt = effectivePrompt.replace(/(?:^|\s)--provider(?:=|\s+)[^\s]+/ig, " ").replace(/(?:^|\s)--model(?:=|\s+)[^\s]+/ig, " ").replace(/\s{2,}/g, " ").trim();
29616
+ }
29617
+ }
29618
+ const { selectLocalProviderAndModel: selectLocalProviderAndModel2, generateViaCli: generateViaCli2 } = await Promise.resolve().then(() => (init_local_llm_manager(), local_llm_manager_exports));
29619
+ const sel = await selectLocalProviderAndModel2({ explicitModel: inlineModel || explicitModel, explicitProvider: inlineProvider });
29620
+ if (process.env.MARIA_DEBUG === "1" && sel) {
29621
+ try {
29622
+ console.log("[DEBUG/local] provider:", sel.provider, "model:", sel.model);
29623
+ } catch {
29624
+ }
29625
+ }
29626
+ if (sel) {
29627
+ const out = await generateViaCli2(sel.provider, sel.model, effectivePrompt);
29628
+ if (typeof out === "string" && out.length > 0) {
29629
+ const finalText = sanitizeLocalOutputText(out);
29630
+ if (process.env.MARIA_DEBUG === "1") {
29631
+ try {
29632
+ console.log("[DEBUG/local] sanitize", { inLen: out.length, outLen: finalText.length, changed: finalText.length !== out.length });
29633
+ } catch {
29634
+ }
29635
+ }
29636
+ try {
29637
+ const ctl = new AbortController();
29638
+ const to = setTimeout(() => ctl.abort(), 1500);
29639
+ await fetch(`${apiBase}/api/v1/usage`, {
29640
+ method: "POST",
29641
+ headers: {
29642
+ "Authorization": `Bearer ${tokens2.accessToken}`,
29643
+ "Content-Type": "application/json",
29644
+ "Idempotency-Key": `cli_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`
29645
+ },
29646
+ body: JSON.stringify({ consumption: { requests: 1 } }),
29647
+ signal: ctl.signal
29648
+ }).catch(() => null);
29649
+ clearTimeout(to);
29650
+ } catch {
29651
+ }
29652
+ return { data: { content: finalText, routedModel: { vendor: "local", family: sel.provider, name: sel.model, reason: isEnterprisePlan ? "enterprise" : "local_mode" } } };
29653
+ }
29654
+ }
29655
+ if (isEnterprisePlan) {
29656
+ throw new Error("Enterprise policy requires local LLM. Local execution failed or unavailable.");
29657
+ }
29658
+ } catch (e2) {
29659
+ if (isEnterprisePlan) throw e2;
29660
+ }
29661
+ } else if (isEnterprisePlan) {
29662
+ throw new Error("Enterprise policy requires local LLM only");
29663
+ }
29664
+ }
29665
+ }
29666
+ } catch (e2) {
29667
+ if (String(process.env.PLAN || "").toLowerCase() === "enterprise") throw e2;
29668
+ }
29069
29669
  const controller = new AbortController();
29070
29670
  const defaultMs = 6e5;
29071
29671
  const envMs = Number(process.env.MARIA_API_TIMEOUT_MS || process.env.MARIA_CODE_TIMEOUT_MS || defaultMs);
@@ -29225,12 +29825,13 @@ async function executeAIProxy(provider, model, messages, options) {
29225
29825
  body: { provider, model, messages, options }
29226
29826
  });
29227
29827
  }
29228
- var authManager2, RateLimitError;
29828
+ var authManager2, cachedEnterprise, RateLimitError;
29229
29829
  var init_api_caller = __esm({
29230
29830
  "src/services/cli-auth/api-caller.ts"() {
29231
29831
  init_AuthenticationManager();
29232
29832
  new https__default.default.Agent({ keepAlive: true });
29233
29833
  authManager2 = new AuthenticationManager();
29834
+ cachedEnterprise = null;
29234
29835
  RateLimitError = class extends Error {
29235
29836
  constructor(message, retryAfter) {
29236
29837
  super(message);
@@ -38009,7 +38610,23 @@ var init_telemetry_helper = __esm({
38009
38610
 
38010
38611
  // src/services/subscription/subscription-manager.ts
38011
38612
  async function getUserPlan() {
38012
- return "free";
38613
+ try {
38614
+ const { cliAuth: cliAuth2 } = await Promise.resolve().then(() => (init_CLIAuthService(), CLIAuthService_exports));
38615
+ const api = cliAuth2.getAPIClient();
38616
+ const usage = await api.getUsage();
38617
+ const raw = String(usage?.planCode || usage?.planName || "").toUpperCase();
38618
+ const normalized = raw.replace(/[-_](ANNUAL|MONTHLY|YEARLY)$/i, "").toUpperCase();
38619
+ try {
38620
+ process.env.MARIA_PLAN = raw;
38621
+ } catch {
38622
+ }
38623
+ if (normalized === "ENTERPRISE" || normalized === "ULTRA") return "ultra";
38624
+ if (normalized === "PRO") return "pro";
38625
+ if (normalized === "STARTER") return "starter";
38626
+ return "free";
38627
+ } catch {
38628
+ return "free";
38629
+ }
38013
38630
  }
38014
38631
  var init_subscription_manager = __esm({
38015
38632
  "src/services/subscription/subscription-manager.ts"() {
@@ -40640,18 +41257,18 @@ var init_StatusCommand = __esm({
40640
41257
  );
40641
41258
  if (process.env.NODE_ENV === "test") {
40642
41259
  if (timeoutMs < 200 || options.signal) {
40643
- const delay = Math.max(75, timeoutMs + 50);
41260
+ const delay2 = Math.max(75, timeoutMs + 50);
40644
41261
  systemHealthPromise = Promise.all([
40645
41262
  systemHealthPromise,
40646
- this.createCancellableDelay(delay, options.signal)
41263
+ this.createCancellableDelay(delay2, options.signal)
40647
41264
  ]).then(([health]) => health);
40648
41265
  } else {
40649
41266
  systemHealthPromise = systemHealthPromise.then((health) => {
40650
41267
  return new Promise((resolve19) => {
40651
41268
  if (!globalThis._statusCommandTestCounter)
40652
41269
  globalThis._statusCommandTestCounter = 0;
40653
- const delay = ++globalThis._statusCommandTestCounter % 2 === 1 ? 3 : 1;
40654
- setTimeout(() => resolve19(health), delay);
41270
+ const delay2 = ++globalThis._statusCommandTestCounter % 2 === 1 ? 3 : 1;
41271
+ setTimeout(() => resolve19(health), delay2);
40655
41272
  });
40656
41273
  });
40657
41274
  }
@@ -48613,13 +49230,13 @@ async function withRetry429(fn, opts) {
48613
49230
  const kind = classify(e2);
48614
49231
  if (!kind) throw e2;
48615
49232
  if (i2 === opts.retries) break;
48616
- const delay = backoffDelay(i2, opts);
49233
+ const delay2 = backoffDelay(i2, opts);
48617
49234
  try {
48618
- process.stderr.write(`WARN: ${kind} retry in ${delay}ms (attempt ${i2 + 1}/${opts.retries})
49235
+ process.stderr.write(`WARN: ${kind} retry in ${delay2}ms (attempt ${i2 + 1}/${opts.retries})
48619
49236
  `);
48620
49237
  } catch {
48621
49238
  }
48622
- await sleep2(delay);
49239
+ await sleep2(delay2);
48623
49240
  }
48624
49241
  }
48625
49242
  throw lastErr;
@@ -51505,7 +52122,7 @@ var init_about_command = __esm({
51505
52122
  async execute(args2, context2) {
51506
52123
  const output3 = [];
51507
52124
  output3.push("");
51508
- output3.push(chalk14__default.default.cyan.bold("About MARIA v4.4.2"));
52125
+ output3.push(chalk14__default.default.cyan.bold("About MARIA v4.4.4"));
51509
52126
  output3.push(chalk14__default.default.gray("\u2550".repeat(40)));
51510
52127
  output3.push("");
51511
52128
  output3.push(chalk14__default.default.white.bold("MARIA - Minimal API, Maximum Power"));
@@ -55917,16 +56534,16 @@ function countRemainingLines(hunks, startHunkIdx, currentPart, currentLine) {
55917
56534
  }
55918
56535
  function colorGreen(s2) {
55919
56536
  try {
55920
- const chalk44 = __require("chalk");
55921
- return chalk44.green(s2);
56537
+ const chalk46 = __require("chalk");
56538
+ return chalk46.green(s2);
55922
56539
  } catch {
55923
56540
  return s2;
55924
56541
  }
55925
56542
  }
55926
56543
  function colorRed(s2) {
55927
56544
  try {
55928
- const chalk44 = __require("chalk");
55929
- return chalk44.red(s2);
56545
+ const chalk46 = __require("chalk");
56546
+ return chalk46.red(s2);
55930
56547
  } catch {
55931
56548
  return s2;
55932
56549
  }
@@ -57415,9 +58032,9 @@ function emitTelemetry(ev) {
57415
58032
  }
57416
58033
  async function assertCleanWorkingTree() {
57417
58034
  try {
57418
- const { spawn: spawn4 } = await import('child_process');
58035
+ const { spawn: spawn5 } = await import('child_process');
57419
58036
  const run = (cmd, args2) => new Promise((resolve19) => {
57420
- const p = spawn4(cmd, args2, { stdio: "ignore" });
58037
+ const p = spawn5(cmd, args2, { stdio: "ignore" });
57421
58038
  p.on("close", (code) => resolve19(code ?? 0));
57422
58039
  p.on("error", () => resolve19(1));
57423
58040
  });
@@ -57432,15 +58049,15 @@ async function assertCleanWorkingTree() {
57432
58049
  }
57433
58050
  async function gitSingleCommit(appliedCount, opts) {
57434
58051
  try {
57435
- const { spawn: spawn4 } = await import('child_process');
58052
+ const { spawn: spawn5 } = await import('child_process');
57436
58053
  const run = (cmd, args2) => new Promise((resolve19) => {
57437
- const p = spawn4(cmd, args2, { stdio: "ignore" });
58054
+ const p = spawn5(cmd, args2, { stdio: "ignore" });
57438
58055
  p.on("close", (code2) => resolve19(code2 ?? 0));
57439
58056
  p.on("error", () => resolve19(1));
57440
58057
  });
57441
58058
  const runOut = (cmd, args2) => new Promise((resolve19) => {
57442
58059
  const chunks = [];
57443
- const p = spawn4(cmd, args2, { stdio: ["ignore", "pipe", "ignore"] });
58060
+ const p = spawn5(cmd, args2, { stdio: ["ignore", "pipe", "ignore"] });
57444
58061
  p.stdout.on("data", (c) => chunks.push(c));
57445
58062
  p.on("close", () => resolve19(Buffer.concat(chunks).toString().trim()));
57446
58063
  p.on("error", () => resolve19(""));
@@ -57478,10 +58095,10 @@ async function gitSingleCommit(appliedCount, opts) {
57478
58095
  }
57479
58096
  async function buildAutoTag(prefix) {
57480
58097
  try {
57481
- const { spawn: spawn4 } = await import('child_process');
58098
+ const { spawn: spawn5 } = await import('child_process');
57482
58099
  const runOut = (cmd, args2) => new Promise((resolve19) => {
57483
58100
  const chunks = [];
57484
- const p = spawn4(cmd, args2, { stdio: ["ignore", "pipe", "ignore"] });
58101
+ const p = spawn5(cmd, args2, { stdio: ["ignore", "pipe", "ignore"] });
57485
58102
  p.stdout.on("data", (c) => chunks.push(c));
57486
58103
  p.on("close", () => resolve19(Buffer.concat(chunks).toString().trim()));
57487
58104
  p.on("error", () => resolve19(""));
@@ -59589,12 +60206,12 @@ async function scanRoot(opts) {
59589
60206
  const filepath = path12__namespace.join(cwd2, name2);
59590
60207
  const result = await safeRead(filepath, 512 * 1024, maxLines, signal);
59591
60208
  if (result.head || result.meta) {
59592
- let meta27 = result.meta || object;
60209
+ let meta28 = result.meta || object;
59593
60210
  if (name2 === "package.json" && result.head) {
59594
60211
  try {
59595
60212
  const pkg = JSON.parse(result.head);
59596
- meta27 = {
59597
- ...meta27,
60213
+ meta28 = {
60214
+ ...meta28,
59598
60215
  name: pkg.name,
59599
60216
  version: pkg.version,
59600
60217
  type: pkg.type,
@@ -59607,14 +60224,14 @@ async function scanRoot(opts) {
59607
60224
  workspaces: pkg.workspaces
59608
60225
  };
59609
60226
  } catch (e2) {
59610
- meta27.parseError = true;
60227
+ meta28.parseError = true;
59611
60228
  }
59612
60229
  }
59613
60230
  findings.push({
59614
60231
  file: name2,
59615
60232
  kind: "read",
59616
60233
  head: result.head,
59617
- meta: meta27,
60234
+ meta: meta28,
59618
60235
  truncated: result.truncated
59619
60236
  });
59620
60237
  }
@@ -59952,19 +60569,19 @@ function extractPackageInfo(findings) {
59952
60569
  hasPostinstall: false
59953
60570
  };
59954
60571
  }
59955
- const meta27 = pkgFinding.meta;
60572
+ const meta28 = pkgFinding.meta;
59956
60573
  return {
59957
- name: meta27.name,
59958
- version: meta27.version,
59959
- type: meta27.type,
59960
- scripts: meta27.scripts ? Object.keys(meta27.scripts) : [],
59961
- hasPostinstall: !!meta27.scripts?.postinstall,
59962
- bin: meta27.bin,
59963
- main: meta27.main,
59964
- exports: meta27.exports,
59965
- dependencies: meta27.dependencies || [],
59966
- devDependencies: meta27.devDependencies || [],
59967
- workspaces: meta27.workspaces
60574
+ name: meta28.name,
60575
+ version: meta28.version,
60576
+ type: meta28.type,
60577
+ scripts: meta28.scripts ? Object.keys(meta28.scripts) : [],
60578
+ hasPostinstall: !!meta28.scripts?.postinstall,
60579
+ bin: meta28.bin,
60580
+ main: meta28.main,
60581
+ exports: meta28.exports,
60582
+ dependencies: meta28.dependencies || [],
60583
+ devDependencies: meta28.devDependencies || [],
60584
+ workspaces: meta28.workspaces
59968
60585
  };
59969
60586
  }
59970
60587
  function collectWarnings(pkg, findings, cwd2) {
@@ -60115,9 +60732,9 @@ function calculateMetrics(findings, startTime) {
60115
60732
  }
60116
60733
  function renderFinding(f3) {
60117
60734
  const title = `### ${f3.kind.toUpperCase()} \u2014 ${f3.file}`;
60118
- let meta27 = "";
60735
+ let meta28 = "";
60119
60736
  if (f3.meta && Object.keys(f3.meta).length > 0) {
60120
- meta27 = `
60737
+ meta28 = `
60121
60738
  <details><summary>meta</summary>
60122
60739
 
60123
60740
  \`\`\`json
@@ -60138,7 +60755,7 @@ ${f3.head.trim()}
60138
60755
  }
60139
60756
  const truncInfo = f3.truncated ? `
60140
60757
  > _truncated preview_` : "";
60141
- return [title, meta27, content, truncInfo, ""].join("\n");
60758
+ return [title, meta28, content, truncInfo, ""].join("\n");
60142
60759
  }
60143
60760
  function safeJsonStringify(obj) {
60144
60761
  try {
@@ -70853,11 +71470,11 @@ var init_search_command = __esm({
70853
71470
  * Calculate processing delay for simulation
70854
71471
  */
70855
71472
  calculateProcessingDelay(options) {
70856
- let delay = 100;
70857
- if (options.kgBoost) delay += 50;
70858
- if (options.rerank) delay += 100;
70859
- if (options.explain) delay += 30;
70860
- return delay + Math.random() * 50;
71473
+ let delay2 = 100;
71474
+ if (options.kgBoost) delay2 += 50;
71475
+ if (options.rerank) delay2 += 100;
71476
+ if (options.explain) delay2 += 30;
71477
+ return delay2 + Math.random() * 50;
70861
71478
  }
70862
71479
  /**
70863
71480
  * Generate mock search results
@@ -72935,6 +73552,592 @@ var init_gpu_command = __esm({
72935
73552
  gpu_command_default = GPUCommand;
72936
73553
  }
72937
73554
  });
73555
+ function renderFeatureComparison() {
73556
+ const lines = [];
73557
+ const COLS = {
73558
+ feature: 28,
73559
+ free: 9,
73560
+ starter: 15,
73561
+ pro: 20,
73562
+ ultra: 20
73563
+ };
73564
+ const stripAnsi2 = (s2) => s2.replace(/\x1B\[[0-9;]*m/g, "");
73565
+ const padAnsi = (s2, width) => {
73566
+ const len = stripAnsi2(s2).length;
73567
+ return s2 + " ".repeat(Math.max(0, width - len));
73568
+ };
73569
+ lines.push("");
73570
+ lines.push(chalk14__default.default.bold.white("\u{1F4CA} Plan Comparison"));
73571
+ lines.push("");
73572
+ lines.push(chalk14__default.default.gray("\u2500".repeat(60)));
73573
+ lines.push("");
73574
+ lines.push(
73575
+ " " + padAnsi(chalk14__default.default.gray.bold("Feature"), COLS.feature) + padAnsi(chalk14__default.default.bold("FREE"), COLS.free) + " " + padAnsi(chalk14__default.default.blue.bold("STARTER"), COLS.starter) + " " + padAnsi(chalk14__default.default.yellow.bold("PRO"), COLS.pro) + " " + padAnsi(chalk14__default.default.magenta.bold("ULTRA"), COLS.ultra)
73576
+ );
73577
+ lines.push("");
73578
+ const features = [
73579
+ // LP-aligned buckets
73580
+ ["Code Generation/month", "40", "300", "1,200", "5,000"],
73581
+ ["File Analysis/month", "5", "50", "200", "500"],
73582
+ ["AI Models", "3 models", "4 models", "6 models", "12 models"],
73583
+ ["Support", "Community", "Community", "Community", "Priority"]
73584
+ ];
73585
+ for (const [feature, free, starter, pro, ultra] of features) {
73586
+ const line = " " + padAnsi(feature, COLS.feature) + padAnsi(formatValue(free), COLS.free) + " " + padAnsi(formatValue(starter, "blue"), COLS.starter) + " " + padAnsi(formatValue(pro, "yellow"), COLS.pro) + " " + padAnsi(formatValue(ultra, "magenta"), COLS.ultra);
73587
+ lines.push(line);
73588
+ }
73589
+ lines.push("");
73590
+ lines.push(chalk14__default.default.gray("\u2500".repeat(60)));
73591
+ lines.push("");
73592
+ lines.push(chalk14__default.default.cyan(" \u{1F48E} Upgrade: /upgrade"));
73593
+ lines.push("");
73594
+ return lines.join("\n");
73595
+ }
73596
+ function formatValue(value, color) {
73597
+ if (value === "\u274C") return chalk14__default.default.red(value);
73598
+ if (value === "\u2705") return chalk14__default.default.green(value);
73599
+ if (value === "Unlimited") {
73600
+ return color === "magenta" ? chalk14__default.default.magenta.bold(value) : chalk14__default.default.bold(value);
73601
+ }
73602
+ switch (color) {
73603
+ case "blue":
73604
+ return chalk14__default.default.blue(value);
73605
+ case "yellow":
73606
+ return chalk14__default.default.yellow(value);
73607
+ case "magenta":
73608
+ return chalk14__default.default.magenta(value);
73609
+ default:
73610
+ return chalk14__default.default.white(value);
73611
+ }
73612
+ }
73613
+ var init_plan_aware_ui = __esm({
73614
+ "src/ui/components/plan-aware-ui.ts"() {
73615
+ }
73616
+ });
73617
+
73618
+ // src/slash-commands/categories/system/upgrade.command.ts
73619
+ var upgrade_command_exports = {};
73620
+ __export(upgrade_command_exports, {
73621
+ UpgradeCommand: () => UpgradeCommand,
73622
+ meta: () => meta26
73623
+ });
73624
+ var UpgradeCommand, meta26;
73625
+ var init_upgrade_command = __esm({
73626
+ "src/slash-commands/categories/system/upgrade.command.ts"() {
73627
+ init_base_command();
73628
+ init_plan_aware_ui();
73629
+ init_subscription_manager();
73630
+ UpgradeCommand = class extends BaseCommand {
73631
+ name = "upgrade";
73632
+ description = "Upgrade your subscription plan";
73633
+ category = "system";
73634
+ aliases = ["pro", "ultra", "premium", "subscribe"];
73635
+ async execute(args2, context2) {
73636
+ Array.isArray(args2?.raw) ? args2.raw : [];
73637
+ const positional = args2?.parsed?.positional;
73638
+ const firstPositional = Array.isArray(positional) && positional.length > 0 ? positional[0] : void 0;
73639
+ const planOpt = args2?.options?.plan;
73640
+ const compareFlag = Boolean(args2?.flags?.compare);
73641
+ const plan = (planOpt || firstPositional)?.trim();
73642
+ const contextPlan = String(context2?.user?.plan || "").toUpperCase();
73643
+ const mappedFromContext = this.mapContextPlanToInternal(contextPlan);
73644
+ let currentPlan = mappedFromContext || await getUserPlan();
73645
+ if (compareFlag) {
73646
+ return {
73647
+ success: true,
73648
+ message: renderFeatureComparison(),
73649
+ requiresInput: false,
73650
+ autoRetry: false
73651
+ };
73652
+ }
73653
+ if (!plan) {
73654
+ return this.showInteractiveUpgrade(currentPlan, contextPlan);
73655
+ }
73656
+ let isAuthenticated = Boolean(context2?.user);
73657
+ try {
73658
+ if (!isAuthenticated) {
73659
+ const { cliAuth: cliAuth2 } = await Promise.resolve().then(() => (init_CLIAuthService(), CLIAuthService_exports));
73660
+ isAuthenticated = await cliAuth2.getAuthClient().isAuthenticated();
73661
+ }
73662
+ } catch {
73663
+ }
73664
+ if (!isAuthenticated) {
73665
+ return {
73666
+ success: false,
73667
+ message: "\u{1F510} Authentication required \xB7 Run: /login",
73668
+ requiresInput: false,
73669
+ autoRetry: false
73670
+ };
73671
+ }
73672
+ const normalizedPlan = plan.trim().toLowerCase();
73673
+ if (!["starter", "pro", "ultra"].includes(normalizedPlan)) {
73674
+ return {
73675
+ success: false,
73676
+ message: `Invalid plan: ${plan}. Choose 'starter', 'pro' or 'ultra'.`,
73677
+ requiresInput: false,
73678
+ autoRetry: false
73679
+ };
73680
+ }
73681
+ return this.processUpgrade(currentPlan, normalizedPlan, contextPlan, isAuthenticated, context2);
73682
+ }
73683
+ mapContextPlanToInternal(contextPlanUpper) {
73684
+ const code = contextPlanUpper.replace(/[-_](ANNUAL|MONTHLY|YEARLY)$/i, "").toUpperCase();
73685
+ if (code.includes("ENTERPRISE")) return "ultra";
73686
+ if (code.includes("ULTRA")) return "ultra";
73687
+ if (code.includes("PRO")) return "pro";
73688
+ if (code.includes("STARTER")) return "starter";
73689
+ if (code.includes("FREE")) return "free";
73690
+ return void 0;
73691
+ }
73692
+ async showInteractiveUpgrade(currentPlan, contextPlanUpper) {
73693
+ const output3 = [];
73694
+ output3.push("");
73695
+ output3.push(chalk14__default.default.bold.cyan("\u{1F48E} Upgrade Your Plan"));
73696
+ output3.push("");
73697
+ output3.push(chalk14__default.default.gray("Current Plan: ") + this.getCurrentPlanLabel(currentPlan, contextPlanUpper));
73698
+ output3.push("");
73699
+ output3.push(chalk14__default.default.gray("\u2500".repeat(60)));
73700
+ output3.push("");
73701
+ if (currentPlan === "free") {
73702
+ output3.push(chalk14__default.default.bold.white("\u{1F539} STARTER - $20/month"));
73703
+ output3.push(chalk14__default.default.gray("For individual developers"));
73704
+ output3.push("");
73705
+ output3.push(" \u2705 Advanced AI Chat");
73706
+ output3.push(" \u2705 Code Generation (300/month)");
73707
+ output3.push(" \u2705 50 file analysis/month");
73708
+ output3.push(" \u2705 4 AI models");
73709
+ output3.push(" \u2705 Community support");
73710
+ output3.push("");
73711
+ output3.push(chalk14__default.default.cyan(" Upgrade: /upgrade starter"));
73712
+ output3.push("");
73713
+ output3.push(chalk14__default.default.gray("\u2500".repeat(60)));
73714
+ output3.push("");
73715
+ output3.push(chalk14__default.default.bold.yellow("\u{1F31F} PRO - $39/month"));
73716
+ output3.push(chalk14__default.default.gray("For serious developers"));
73717
+ output3.push("");
73718
+ output3.push(" \u2705 Pro AI Chat");
73719
+ output3.push(" \u2705 Advanced Code Generation (1,200/month)");
73720
+ output3.push(" \u2705 200 file analysis/month");
73721
+ output3.push(" \u2705 6 AI models");
73722
+ output3.push(" \u2705 Community support");
73723
+ output3.push(" \u2705 API Access");
73724
+ output3.push("");
73725
+ output3.push(chalk14__default.default.cyan(" Upgrade: /upgrade pro"));
73726
+ output3.push("");
73727
+ output3.push(chalk14__default.default.gray("\u2500".repeat(60)));
73728
+ output3.push("");
73729
+ output3.push(chalk14__default.default.bold.magenta("\u{1F680} ULTRA - $99/month"));
73730
+ output3.push(chalk14__default.default.gray("For power users and teams"));
73731
+ output3.push("");
73732
+ output3.push(" \u2705 Executive AI Chat");
73733
+ output3.push(" \u2705 Professional Code Generation (5,000/month)");
73734
+ output3.push(" \u2705 500 file analysis/month");
73735
+ output3.push(" \u2705 12 AI models");
73736
+ output3.push(" \u2705 Priority support");
73737
+ output3.push(" \u2705 API Access");
73738
+ output3.push("");
73739
+ output3.push(chalk14__default.default.cyan(" Upgrade: /upgrade ultra"));
73740
+ } else if (currentPlan === "starter") {
73741
+ output3.push(chalk14__default.default.bold.yellow("\u{1F31F} Upgrade to PRO - $39/month"));
73742
+ output3.push("");
73743
+ output3.push(" \u2705 Pro AI Chat");
73744
+ output3.push(" \u2705 Advanced Code Generation (1,200/month)");
73745
+ output3.push(" \u2705 200 file analysis/month");
73746
+ output3.push(" \u2705 6 AI models");
73747
+ output3.push(" \u2705 Community support");
73748
+ output3.push(" \u2705 API Access");
73749
+ output3.push("");
73750
+ output3.push(chalk14__default.default.cyan(" Upgrade: /upgrade pro"));
73751
+ output3.push("");
73752
+ output3.push(chalk14__default.default.gray("\u2500".repeat(60)));
73753
+ output3.push("");
73754
+ output3.push(chalk14__default.default.bold.magenta("\u{1F680} Upgrade to ULTRA - $99/month"));
73755
+ output3.push("");
73756
+ output3.push(" \u2705 Executive AI Chat");
73757
+ output3.push(" \u2705 Professional Code Generation (5,000/month)");
73758
+ output3.push(" \u2705 500 file analysis/month");
73759
+ output3.push(" \u2705 12 AI models");
73760
+ output3.push(" \u2705 Priority support");
73761
+ output3.push(" \u2705 API Access");
73762
+ output3.push("");
73763
+ output3.push(chalk14__default.default.cyan(" Upgrade: /upgrade ultra"));
73764
+ } else if (currentPlan === "pro") {
73765
+ output3.push(chalk14__default.default.bold.magenta("\u{1F680} Upgrade to ULTRA - $99/month"));
73766
+ output3.push("");
73767
+ output3.push(" \u2705 Executive AI Chat");
73768
+ output3.push(" \u2705 Professional Code Generation (5,000/month)");
73769
+ output3.push(" \u2705 500 file analysis/month");
73770
+ output3.push(" \u2705 12 AI models + Local LLM");
73771
+ output3.push(" \u2705 Priority support");
73772
+ output3.push("");
73773
+ output3.push(chalk14__default.default.cyan(" Upgrade: /upgrade ultra"));
73774
+ } else {
73775
+ output3.push(chalk14__default.default.green(`\u2728 You have the ${this.getTopTierLabel(contextPlanUpper)} plan!`));
73776
+ output3.push("");
73777
+ output3.push("You already have access to all features:");
73778
+ output3.push(" \u2022 Maximum rate limits");
73779
+ output3.push(" \u2022 All premium features");
73780
+ output3.push(" \u2022 Priority support");
73781
+ }
73782
+ output3.push("");
73783
+ output3.push(chalk14__default.default.gray("\u2500".repeat(60)));
73784
+ output3.push("");
73785
+ output3.push(chalk14__default.default.gray("Compare all plans: /upgrade --compare"));
73786
+ output3.push("");
73787
+ return {
73788
+ success: true,
73789
+ message: output3.join("\n"),
73790
+ requiresInput: false,
73791
+ autoRetry: false
73792
+ };
73793
+ }
73794
+ async processUpgrade(currentPlan, targetPlan, contextPlanUpper, isAuthenticated, context2) {
73795
+ const output3 = [];
73796
+ const planHierarchy = {
73797
+ free: 0,
73798
+ starter: 1,
73799
+ pro: 2,
73800
+ ultra: 3
73801
+ };
73802
+ if (planHierarchy[targetPlan] <= planHierarchy[currentPlan]) {
73803
+ output3.push("");
73804
+ output3.push(chalk14__default.default.yellow("\u26A0\uFE0F Invalid Upgrade"));
73805
+ output3.push("");
73806
+ output3.push(`You already have the ${this.getCurrentPlanLabel(currentPlan, contextPlanUpper)} plan.`);
73807
+ if (currentPlan === "ultra" || String(contextPlanUpper || "").toUpperCase() === "ENTERPRISE") {
73808
+ output3.push("You have access to all features!");
73809
+ } else {
73810
+ output3.push(`Consider upgrading to ${targetPlan === "pro" ? "ULTRA" : "a higher plan"} for more features.`);
73811
+ }
73812
+ output3.push("");
73813
+ return {
73814
+ success: true,
73815
+ message: output3.join("\n"),
73816
+ requiresInput: false,
73817
+ autoRetry: false
73818
+ };
73819
+ }
73820
+ output3.push("");
73821
+ output3.push(chalk14__default.default.cyan("\u{1F504} Processing upgrade..."));
73822
+ output3.push("");
73823
+ output3.push(`From: ${this.getPlanBadge(currentPlan)}`);
73824
+ output3.push(`To: ${this.getPlanBadge(targetPlan)}`);
73825
+ output3.push("");
73826
+ output3.push(chalk14__default.default.gray("Opening browser for billing..."));
73827
+ output3.push("");
73828
+ let upgraded = false;
73829
+ let changedTo = null;
73830
+ try {
73831
+ const base = process.env.MARIA_API_URL || "https://maria-code.ai";
73832
+ const startCliReturnServer = async () => {
73833
+ const callbackPort = 65434;
73834
+ const callbackPath = "/cli-return";
73835
+ const http4 = await import('http');
73836
+ return new Promise((resolve19) => {
73837
+ let finished = false;
73838
+ const server = http4.createServer(async (req, res) => {
73839
+ try {
73840
+ const method = (req.method || "GET").toUpperCase();
73841
+ let status;
73842
+ let plan;
73843
+ const urlStr = `http://localhost${req.url || ""}`;
73844
+ const u = new URL(urlStr);
73845
+ if (u.pathname === callbackPath) {
73846
+ status = u.searchParams.get("status") || void 0;
73847
+ plan = u.searchParams.get("plan") || void 0;
73848
+ if (method === "POST") {
73849
+ const chunks = [];
73850
+ await new Promise((r2) => {
73851
+ req.on("data", (c) => {
73852
+ if (chunks.join("").length < 8192) chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(String(c)));
73853
+ });
73854
+ req.on("end", () => r2());
73855
+ });
73856
+ const body = Buffer.concat(chunks).toString("utf8");
73857
+ try {
73858
+ const params2 = new URLSearchParams(body);
73859
+ status = params2.get("status") || status;
73860
+ plan = params2.get("plan") || plan;
73861
+ } catch {
73862
+ }
73863
+ }
73864
+ if (process.env.MARIA_DEBUG === "1") {
73865
+ try {
73866
+ console.error("[MARIA DEBUG] CLI return inbound", { method, status, plan });
73867
+ } catch {
73868
+ }
73869
+ }
73870
+ res.writeHead(200, { "Content-Type": "text/html" });
73871
+ res.end('<html><body style="font-family:system-ui;padding:24px;text-align:center">OK. You can close this window.</body></html>');
73872
+ if (!finished && status === "success") {
73873
+ finished = true;
73874
+ setTimeout(() => {
73875
+ try {
73876
+ server.close();
73877
+ } catch {
73878
+ }
73879
+ resolve19({ status, plan });
73880
+ }, 10);
73881
+ }
73882
+ return;
73883
+ }
73884
+ } catch {
73885
+ }
73886
+ res.statusCode = 404;
73887
+ res.end("");
73888
+ });
73889
+ const timer = setTimeout(() => {
73890
+ if (!finished) {
73891
+ finished = true;
73892
+ try {
73893
+ server.close();
73894
+ } catch {
73895
+ }
73896
+ resolve19(null);
73897
+ }
73898
+ }, 18e4);
73899
+ server.listen(callbackPort, "127.0.0.1", () => {
73900
+ if (process.env.MARIA_DEBUG === "1") {
73901
+ try {
73902
+ console.error("[MARIA DEBUG] CLI return server listening", { port: callbackPort, path: callbackPath });
73903
+ } catch {
73904
+ }
73905
+ }
73906
+ });
73907
+ server.on("close", () => {
73908
+ clearTimeout(timer);
73909
+ });
73910
+ });
73911
+ };
73912
+ const cliReturnUrl = `http://localhost:65434/cli-return`;
73913
+ const targetUrl = `${base}/manage?upgrade=${encodeURIComponent(targetPlan)}&auto=1&cliReturn=${encodeURIComponent(cliReturnUrl)}`;
73914
+ const { openUrl: openUrl2 } = await Promise.resolve().then(() => (init_open_url(), open_url_exports));
73915
+ if (process.env.MARIA_DEBUG === "1") {
73916
+ console.error("[MARIA DEBUG] Open manage URL", { url: targetUrl });
73917
+ }
73918
+ const cliReturnPromise = startCliReturnServer();
73919
+ await openUrl2(targetUrl);
73920
+ try {
73921
+ const cb = await cliReturnPromise;
73922
+ if (cb && (cb.status === "success" || cb.status === "scheduled")) {
73923
+ const p = String(cb.plan || "").toLowerCase();
73924
+ if (p === "starter" || p === "pro" || p === "ultra") {
73925
+ if (cb.status === "success") {
73926
+ changedTo = p;
73927
+ upgraded = true;
73928
+ } else {
73929
+ changedTo = p;
73930
+ }
73931
+ if (process.env.MARIA_DEBUG === "1") {
73932
+ try {
73933
+ console.error("[MARIA DEBUG] LP callback received", { plan: p, status: cb.status });
73934
+ } catch {
73935
+ }
73936
+ }
73937
+ }
73938
+ }
73939
+ } catch {
73940
+ }
73941
+ try {
73942
+ const { cliAuth: cliAuth2 } = await Promise.resolve().then(() => (init_CLIAuthService(), CLIAuthService_exports));
73943
+ const { MariaAPIClient: MariaAPIClient2 } = await Promise.resolve().then(() => (init_MariaAPIClient(), MariaAPIClient_exports));
73944
+ const api = new MariaAPIClient2({
73945
+ baseUrl: "https://api.maria-code.ai",
73946
+ timeout: 3e4,
73947
+ retryAttempts: 3
73948
+ }, cliAuth2.getAuthClient());
73949
+ if (!isAuthenticated || upgraded) {
73950
+ if (process.env.MARIA_DEBUG === "1") {
73951
+ console.error("[MARIA DEBUG] Skip plan polling (no context.user)");
73952
+ }
73953
+ throw new Error("SKIP_POLLING_UNAUTHENTICATED");
73954
+ }
73955
+ const normalize3 = (v) => String(v).toLowerCase().replace(/-annual|-monthly|-yearly$/i, "");
73956
+ const targetNorm = normalize3(targetPlan);
73957
+ const initialNorm = normalize3(currentPlan);
73958
+ const start = Date.now();
73959
+ const timeoutMs = 6e5;
73960
+ const intervalMs = 3e3;
73961
+ while (Date.now() - start < timeoutMs) {
73962
+ await new Promise((r2) => setTimeout(r2, intervalMs));
73963
+ try {
73964
+ const usage = await api.getUsage();
73965
+ const code = String(usage?.planCode || usage?.planName || "").toLowerCase();
73966
+ const norm = normalize3(code);
73967
+ if (process.env.MARIA_DEBUG === "1") {
73968
+ try {
73969
+ console.error("[MARIA DEBUG] Poll tick", { endpoint: "GET /api/v1/usage", planCode: usage?.planCode, planName: usage?.planName, norm, initialNorm, targetNorm });
73970
+ } catch {
73971
+ }
73972
+ }
73973
+ if (norm !== initialNorm) {
73974
+ if (norm === "starter" || norm === "pro" || norm === "ultra") {
73975
+ changedTo = norm;
73976
+ } else {
73977
+ if (norm.includes("enterprise")) changedTo = "ultra";
73978
+ }
73979
+ if (changedTo) {
73980
+ upgraded = true;
73981
+ if (process.env.MARIA_DEBUG === "1") {
73982
+ try {
73983
+ console.error("[MARIA DEBUG] Plan change detected", { changedTo });
73984
+ } catch {
73985
+ }
73986
+ }
73987
+ break;
73988
+ }
73989
+ }
73990
+ } catch (pollErr) {
73991
+ if (process.env.MARIA_DEBUG === "1") {
73992
+ const e2 = pollErr;
73993
+ try {
73994
+ console.error("[MARIA DEBUG] Plan poll failed", { error: String(e2?.message || e2), stack: e2?.stack, name: e2?.name });
73995
+ } catch {
73996
+ }
73997
+ }
73998
+ const msg = String(pollErr?.message || pollErr);
73999
+ if (msg.includes("Authentication required")) {
74000
+ if (process.env.MARIA_DEBUG === "1") {
74001
+ try {
74002
+ console.error("[MARIA DEBUG] Stop polling due to auth error");
74003
+ } catch {
74004
+ }
74005
+ }
74006
+ break;
74007
+ }
74008
+ }
74009
+ }
74010
+ } catch (pollSetupErr) {
74011
+ const msg = String(pollSetupErr?.message || pollSetupErr);
74012
+ if (process.env.MARIA_DEBUG === "1" && msg !== "SKIP_POLLING_UNAUTHENTICATED") {
74013
+ console.error("[MARIA DEBUG] Plan polling setup failed", { error: msg });
74014
+ }
74015
+ }
74016
+ } catch (e2) {
74017
+ if (process.env.MARIA_DEBUG === "1") {
74018
+ console.error("[MARIA DEBUG] Failed to open manage URL", { error: String(e2?.message || e2) });
74019
+ }
74020
+ upgraded = false;
74021
+ }
74022
+ if (upgraded && changedTo) {
74023
+ output3.push(chalk14__default.default.green("\u2705 Upgrade Successful!"));
74024
+ output3.push("");
74025
+ output3.push(`Welcome to ${this.getPlanBadge(changedTo)}!`);
74026
+ output3.push("");
74027
+ const planToDescribe = changedTo;
74028
+ if (planToDescribe === "starter") {
74029
+ output3.push("You now have access to:");
74030
+ output3.push(" \u2022 Advanced AI Chat");
74031
+ output3.push(" \u2022 Code Generation (300/month)");
74032
+ output3.push(" \u2022 50 file analysis/month");
74033
+ output3.push(" \u2022 4 AI models");
74034
+ output3.push(" \u2022 Community support");
74035
+ } else if (planToDescribe === "pro") {
74036
+ output3.push("You now have access to:");
74037
+ output3.push(" \u2022 Pro AI Chat");
74038
+ output3.push(" \u2022 Advanced Code Generation (1,200/month)");
74039
+ output3.push(" \u2022 200 file analysis/month");
74040
+ output3.push(" \u2022 6 AI models");
74041
+ output3.push(" \u2022 Community support");
74042
+ output3.push(" \u2022 API Access");
74043
+ } else if (planToDescribe === "ultra") {
74044
+ output3.push("You now have access to:");
74045
+ output3.push(" \u2022 Executive AI Chat");
74046
+ output3.push(" \u2022 Professional Code Generation (5,000/month)");
74047
+ output3.push(" \u2022 500 file analysis/month");
74048
+ output3.push(" \u2022 12 AI models");
74049
+ output3.push(" \u2022 Priority support");
74050
+ output3.push(" \u2022 API Access");
74051
+ }
74052
+ output3.push("");
74053
+ output3.push(chalk14__default.default.cyan("Try your new features (after billing completes):"));
74054
+ output3.push(' /code "Refactor module"');
74055
+ output3.push(' /image "logo in matrix style"');
74056
+ output3.push(' /video "product teaser"');
74057
+ output3.push("");
74058
+ } else {
74059
+ output3.push(chalk14__default.default.yellow("\u23F3 Billing in progress"));
74060
+ output3.push("");
74061
+ output3.push("The billing portal or checkout was opened in your browser.");
74062
+ output3.push("We did not detect a plan change yet. Complete the process and run /whoami to verify.");
74063
+ }
74064
+ try {
74065
+ const { WhoAmICommand: WhoAmICommand2 } = await Promise.resolve().then(() => (init_WhoAmICommand(), WhoAmICommand_exports));
74066
+ const whoami = new WhoAmICommand2();
74067
+ const who = await whoami.execute({}, context2);
74068
+ if (who?.message) {
74069
+ output3.push("");
74070
+ output3.push(chalk14__default.default.gray("\u2500".repeat(60)));
74071
+ output3.push("");
74072
+ output3.push(chalk14__default.default.cyan("Current account status"));
74073
+ output3.push(who.message);
74074
+ }
74075
+ } catch {
74076
+ }
74077
+ return {
74078
+ success: upgraded,
74079
+ message: output3.join("\n"),
74080
+ requiresInput: false,
74081
+ autoRetry: false
74082
+ };
74083
+ }
74084
+ getPlanBadge(plan) {
74085
+ const badges = {
74086
+ free: chalk14__default.default.gray("[FREE]"),
74087
+ starter: chalk14__default.default.bgBlue.black(" STARTER "),
74088
+ pro: chalk14__default.default.bgYellow.black(" PRO "),
74089
+ ultra: chalk14__default.default.bgMagenta.white(" ULTRA ")
74090
+ };
74091
+ return badges[plan];
74092
+ }
74093
+ getCurrentPlanLabel(plan, contextPlanUpper) {
74094
+ try {
74095
+ if (String(contextPlanUpper || "").toUpperCase() === "ENTERPRISE") {
74096
+ return chalk14__default.default.bgMagenta.white(" ENTERPRISE ");
74097
+ }
74098
+ const envPlan = String(process.env.MARIA_PLAN || "").toUpperCase();
74099
+ if (envPlan === "ENTERPRISE") return chalk14__default.default.bgMagenta.white(" ENTERPRISE ");
74100
+ } catch {
74101
+ }
74102
+ return this.getPlanBadge(plan);
74103
+ }
74104
+ getTopTierLabel(contextPlanUpper) {
74105
+ try {
74106
+ if (String(contextPlanUpper || "").toUpperCase() === "ENTERPRISE") {
74107
+ return "ENTERPRISE";
74108
+ }
74109
+ const envPlan = String(process.env.MARIA_PLAN || "").toUpperCase();
74110
+ if (envPlan === "ENTERPRISE") return "ENTERPRISE";
74111
+ } catch {
74112
+ }
74113
+ return "ULTRA";
74114
+ }
74115
+ async handleError(error2) {
74116
+ return {
74117
+ success: false,
74118
+ message: `Failed to process upgrade: ${error2.message}`,
74119
+ requiresInput: false,
74120
+ autoRetry: false
74121
+ };
74122
+ }
74123
+ };
74124
+ meta26 = {
74125
+ name: "upgrade",
74126
+ category: "system",
74127
+ description: "Upgrade your subscription plan",
74128
+ aliases: ["pro", "ultra", "premium", "subscribe"],
74129
+ usage: "/upgrade [starter|pro|ultra] [--compare]",
74130
+ examples: [
74131
+ "/upgrade",
74132
+ "/upgrade starter",
74133
+ "/upgrade pro",
74134
+ "/upgrade ultra",
74135
+ "/upgrade --compare"
74136
+ ],
74137
+ deps: []
74138
+ };
74139
+ }
74140
+ });
72938
74141
  var CriteriaManager;
72939
74142
  var init_CriteriaManager = __esm({
72940
74143
  "src/services/evaluation/CriteriaManager.ts"() {
@@ -73446,9 +74649,9 @@ var evaluate_command_exports = {};
73446
74649
  __export(evaluate_command_exports, {
73447
74650
  EvaluateCommand: () => EvaluateCommand,
73448
74651
  default: () => evaluate_command_default,
73449
- meta: () => meta26
74652
+ meta: () => meta27
73450
74653
  });
73451
- var EvaluateCommand, meta26, evaluate_command_default;
74654
+ var EvaluateCommand, meta27, evaluate_command_default;
73452
74655
  var init_evaluate_command = __esm({
73453
74656
  "src/slash-commands/categories/evaluation/evaluate.command.ts"() {
73454
74657
  init_base_command();
@@ -74174,7 +75377,7 @@ ${content}` : content;
74174
75377
  return { success: true };
74175
75378
  }
74176
75379
  };
74177
- meta26 = {
75380
+ meta27 = {
74178
75381
  name: "evaluate",
74179
75382
  category: "evaluation",
74180
75383
  description: "A/B testing and quality evaluation framework",
@@ -74625,15 +75828,22 @@ async function registerBuiltInCommands() {
74625
75828
  initialize: async () => {
74626
75829
  }
74627
75830
  });
74628
- commandRegistry.register({
74629
- name: "upgrade",
74630
- category: "system",
74631
- description: "Upgrade MARIA",
74632
- aliases: [],
74633
- execute: async () => shield2({ message: "\u{1F512} Coming soon", showWaitlist: true }),
74634
- initialize: async () => {
74635
- }
74636
- });
75831
+ try {
75832
+ const { UpgradeCommand: UpgradeCommand2 } = await Promise.resolve().then(() => (init_upgrade_command(), upgrade_command_exports));
75833
+ const upgrade = new UpgradeCommand2();
75834
+ if (upgrade.initialize) await upgrade.initialize();
75835
+ commandRegistry.register(upgrade);
75836
+ } catch {
75837
+ commandRegistry.register({
75838
+ name: "upgrade",
75839
+ category: "system",
75840
+ description: "Upgrade your subscription plan",
75841
+ aliases: ["pro", "ultra", "premium", "subscribe"],
75842
+ execute: async () => shield2({ message: "\u{1F512} Coming soon", showWaitlist: true }),
75843
+ initialize: async () => {
75844
+ }
75845
+ });
75846
+ }
74637
75847
  } catch (error2) {
74638
75848
  console.error("Failed to register system _commands:", error2);
74639
75849
  }
@@ -77325,13 +78535,13 @@ ${options.map((opt, i2) => `${i2 + 1}) ${opt}`).join("\n")}`;
77325
78535
  const lines = response.split("\n");
77326
78536
  for (let i2 = 0; i2 < lines.length; i2++) {
77327
78537
  callback(lines[i2]);
77328
- let delay = 40;
78538
+ let delay2 = 40;
77329
78539
  const line = lines[i2];
77330
- if (line.trim().length === 0) delay = 20;
77331
- else if (line.includes("```")) delay = 60;
77332
- else if (/[.!?]$/.test(line)) delay = 80;
78540
+ if (line.trim().length === 0) delay2 = 20;
78541
+ else if (line.includes("```")) delay2 = 60;
78542
+ else if (/[.!?]$/.test(line)) delay2 = 80;
77333
78543
  if (i2 < lines.length - 1)
77334
- await new Promise((r2) => setTimeout(r2, delay));
78544
+ await new Promise((r2) => setTimeout(r2, delay2));
77335
78545
  }
77336
78546
  }
77337
78547
  };
@@ -78130,8 +79340,8 @@ async function runServerMode() {
78130
79340
  console.error(chalk14__default.default.white("Searched dirs: " + candidateDirs.join(" | ")));
78131
79341
  process.exit(1);
78132
79342
  }
78133
- const { spawn: spawn4 } = await import('child_process');
78134
- const serverProcess = spawn4("node", [serverPath], {
79343
+ const { spawn: spawn5 } = await import('child_process');
79344
+ const serverProcess = spawn5("node", [serverPath], {
78135
79345
  stdio: "inherit",
78136
79346
  env: process.env,
78137
79347
  cwd: path12__namespace.dirname(serverPath)