@bonginkan/maria 4.4.1 → 4.4.3

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,10 +8794,10 @@ 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"], {
8800
+ const _child = spawn5(_lmsPath, ["server", "start"], {
8801
8801
  stdio: "ignore",
8802
8802
  detached: true
8803
8803
  });
@@ -26067,8 +26067,8 @@ var require_package = __commonJS({
26067
26067
  "package.json"(exports, module) {
26068
26068
  module.exports = {
26069
26069
  name: "@bonginkan/maria",
26070
- version: "4.4.1",
26071
- description: "\u{1F680} MARIA v4.4.1 - 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.",
26070
+ version: "4.4.3",
26071
+ description: "\u{1F680} MARIA v4.4.3 - 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
26072
  keywords: [
26073
26073
  "ai",
26074
26074
  "cli",
@@ -27046,6 +27046,10 @@ ${authUrl}
27046
27046
  });
27047
27047
 
27048
27048
  // src/services/cli-auth/MariaAPIClient.ts
27049
+ var MariaAPIClient_exports = {};
27050
+ __export(MariaAPIClient_exports, {
27051
+ MariaAPIClient: () => MariaAPIClient
27052
+ });
27049
27053
  var MariaAPIClient;
27050
27054
  var init_MariaAPIClient = __esm({
27051
27055
  "src/services/cli-auth/MariaAPIClient.ts"() {
@@ -27069,12 +27073,36 @@ var init_MariaAPIClient = __esm({
27069
27073
  "Content-Type": "application/json"
27070
27074
  };
27071
27075
  if (requiresAuth2) {
27072
- const token = await this.authClient.getAccessToken();
27076
+ let token = await this.authClient.getAccessToken();
27077
+ if (!token) {
27078
+ try {
27079
+ const stored = await this.authClient.loadStoredTokens();
27080
+ if (stored?.refreshToken) {
27081
+ await this.authClient.refreshAccessToken(stored.refreshToken);
27082
+ token = await this.authClient.getAccessToken();
27083
+ }
27084
+ } catch (e2) {
27085
+ if (process.env.MARIA_DEBUG === "1") {
27086
+ console.error("[MARIA DEBUG] Token refresh preflight failed", String(e2?.message || e2));
27087
+ }
27088
+ }
27089
+ }
27073
27090
  if (!token) {
27074
27091
  throw new Error('Authentication required. Please run "maria /login" first.');
27075
27092
  }
27076
27093
  headers["Authorization"] = `Bearer ${token}`;
27077
27094
  }
27095
+ if (process.env.MARIA_DEBUG === "1") {
27096
+ try {
27097
+ console.error("[MARIA DEBUG] API request start", {
27098
+ method,
27099
+ url: url2,
27100
+ requiresAuth: requiresAuth2,
27101
+ hasAuthHeader: Boolean(headers["Authorization"])
27102
+ });
27103
+ } catch {
27104
+ }
27105
+ }
27078
27106
  let lastError = null;
27079
27107
  for (let attempt = 1; attempt <= (this.config.retryAttempts || 3); attempt++) {
27080
27108
  try {
@@ -27089,26 +27117,52 @@ var init_MariaAPIClient = __esm({
27089
27117
  clearTimeout(timeoutId);
27090
27118
  const responseData = await response.json();
27091
27119
  if (!response.ok) {
27092
- if (response.status === 401) {
27120
+ if (response.status === 401 && requiresAuth2) {
27093
27121
  const tokens2 = await this.authClient.loadStoredTokens();
27094
27122
  if (tokens2?.refreshToken) {
27095
27123
  try {
27124
+ if (process.env.MARIA_DEBUG === "1") {
27125
+ try {
27126
+ console.error("[MARIA DEBUG] 401 received, attempting token refresh");
27127
+ } catch {
27128
+ }
27129
+ }
27096
27130
  await this.authClient.refreshAccessToken(tokens2.refreshToken);
27131
+ const refreshedToken = await this.authClient.getAccessToken();
27132
+ if (refreshedToken) {
27133
+ headers["Authorization"] = `Bearer ${refreshedToken}`;
27134
+ }
27135
+ if (process.env.MARIA_DEBUG === "1") {
27136
+ try {
27137
+ console.error("[MARIA DEBUG] Token refresh completed", { hasAuthHeader: Boolean(headers["Authorization"]) });
27138
+ } catch {
27139
+ }
27140
+ }
27097
27141
  continue;
27098
27142
  } catch {
27099
- throw new Error("Session expired. Please login again.");
27100
27143
  }
27101
27144
  }
27102
- throw new Error(responseData.hint || "Authentication failed");
27145
+ throw new Error(responseData?.hint || "Authentication failed");
27103
27146
  }
27104
27147
  if (response.status === 429) {
27105
27148
  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));
27149
+ const delay2 = retryAfter ? parseInt(retryAfter) * 1e3 : 5e3;
27150
+ console.log(`\u23F3 Rate limited. Waiting ${delay2}ms before retry...`);
27151
+ await new Promise((resolve19) => setTimeout(resolve19, delay2));
27109
27152
  continue;
27110
27153
  }
27111
- throw new Error(responseData.error || `Request failed: ${response.status}`);
27154
+ const details = {
27155
+ status: response.status,
27156
+ endpoint: url2,
27157
+ method,
27158
+ attempt,
27159
+ response: responseData
27160
+ };
27161
+ if (process.env.MARIA_DEBUG === "1") {
27162
+ console.error("[MARIA DEBUG] API request failed", details);
27163
+ }
27164
+ const msg = responseData && (responseData.error || responseData.message) || `Request failed: ${response.status}`;
27165
+ throw new Error(msg);
27112
27166
  }
27113
27167
  return responseData;
27114
27168
  } catch (error2) {
@@ -27117,11 +27171,17 @@ var init_MariaAPIClient = __esm({
27117
27171
  console.error(`Request timeout after ${this.config.timeout}ms`);
27118
27172
  }
27119
27173
  if (attempt < (this.config.retryAttempts || 3)) {
27174
+ if (process.env.MARIA_DEBUG === "1") {
27175
+ console.error("[MARIA DEBUG] API error on attempt", { method, endpoint: url2, attempt, error: String(error2?.message || error2) });
27176
+ }
27120
27177
  console.log(`\u{1F504} Retrying request (attempt ${attempt + 1}/${this.config.retryAttempts})...`);
27121
27178
  await new Promise((resolve19) => setTimeout(resolve19, 1e3 * attempt));
27122
27179
  }
27123
27180
  }
27124
27181
  }
27182
+ if (process.env.MARIA_DEBUG === "1") {
27183
+ console.error("[MARIA DEBUG] API request exhausted retries", { method, endpoint: url2, error: String(lastError?.message || lastError) });
27184
+ }
27125
27185
  throw lastError || new Error("Request failed after all retries");
27126
27186
  }
27127
27187
  /**
@@ -27166,6 +27226,33 @@ var init_MariaAPIClient = __esm({
27166
27226
  async getAPIInfo() {
27167
27227
  return this.request("GET", "/api/v1", null, false);
27168
27228
  }
27229
+ /**
27230
+ * Create Stripe checkout session for a target plan
27231
+ */
27232
+ async createCheckoutSession(planId, options) {
27233
+ try {
27234
+ return await this.request("POST", "/api/stripe/create-checkout-session", {
27235
+ planId,
27236
+ isAnnual: Boolean(options?.isAnnual)
27237
+ });
27238
+ } catch (e2) {
27239
+ return await this.request("POST", "/api/create-checkout-session", {
27240
+ planId,
27241
+ isAnnual: Boolean(options?.isAnnual)
27242
+ });
27243
+ }
27244
+ }
27245
+ /**
27246
+ * Create Stripe customer portal session
27247
+ */
27248
+ async createPortalSession(returnUrl) {
27249
+ const body = { returnUrl: returnUrl || (process.env.MARIA_RETURN_URL || "https://maria-code.ai/manage") };
27250
+ try {
27251
+ return await this.request("POST", "/api/stripe/create-portal-session", body);
27252
+ } catch (e2) {
27253
+ return await this.request("POST", "/api/create-portal-session", body);
27254
+ }
27255
+ }
27169
27256
  /**
27170
27257
  * Health check
27171
27258
  */
@@ -27237,7 +27324,7 @@ var init_MariaAPIClient = __esm({
27237
27324
  });
27238
27325
  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
27326
  } catch (error2) {
27240
- console.error("Failed to fetch usage stats:", error2.message);
27327
+ console.error("Failed to fetch usage stats:", error2?.message || String(error2));
27241
27328
  }
27242
27329
  }
27243
27330
  /**
@@ -27954,6 +28041,12 @@ var init_AuthSecretManager = __esm({
27954
28041
  new AuthSecretManager();
27955
28042
  }
27956
28043
  });
28044
+
28045
+ // src/utils/open-url.ts
28046
+ var open_url_exports = {};
28047
+ __export(open_url_exports, {
28048
+ openUrl: () => openUrl
28049
+ });
27957
28050
  async function openUrl(url2) {
27958
28051
  if (process.env.CI === "true" || process.env.SSH_CONNECTION || process.env.CONTAINER === "true") {
27959
28052
  throw new Error("Headless environment");
@@ -28131,7 +28224,7 @@ var init_AuthenticationManager = __esm({
28131
28224
  const response = await fetch(`${this.apiBase}/api/user/profile`, {
28132
28225
  headers: {
28133
28226
  "Authorization": `Bearer ${tokens2.accessToken}`,
28134
- "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.4.1"}`
28227
+ "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.4.3"}`
28135
28228
  }
28136
28229
  });
28137
28230
  if (response.status === 401) {
@@ -28785,7 +28878,7 @@ async function callApi(path66, init3 = {}) {
28785
28878
  "Authorization": `Bearer ${token}`,
28786
28879
  "X-Device-Id": getDeviceId(),
28787
28880
  "X-Session-Id": getSessionId() || "",
28788
- "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.4.1"}`,
28881
+ "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.4.3"}`,
28789
28882
  "Content-Type": init3.headers?.["Content-Type"] || "application/json"
28790
28883
  });
28791
28884
  const doFetch = async (token) => {
@@ -29050,6 +29143,273 @@ var init_choice_memory = __esm({
29050
29143
  }
29051
29144
  });
29052
29145
 
29146
+ // src/services/local-llm-manager.ts
29147
+ var local_llm_manager_exports = {};
29148
+ __export(local_llm_manager_exports, {
29149
+ ensureLocalProviderUp: () => ensureLocalProviderUp,
29150
+ generateViaCli: () => generateViaCli,
29151
+ selectLocalProviderAndModel: () => selectLocalProviderAndModel
29152
+ });
29153
+ function debugLog(...args2) {
29154
+ if (process.env.MARIA_DEBUG === "1") {
29155
+ try {
29156
+ console.log("[DEBUG/local-llm]", ...args2);
29157
+ } catch {
29158
+ }
29159
+ }
29160
+ }
29161
+ async function isUp(provider) {
29162
+ const res = await discoverLocalProvider(provider, { timeoutMs: 600, nearbyScan: true });
29163
+ return res?.base || null;
29164
+ }
29165
+ async function tryStartLMStudio() {
29166
+ child_process.spawn("lms", ["server", "start"], { stdio: "ignore", detached: true }).unref();
29167
+ }
29168
+ async function tryStartOllama() {
29169
+ child_process.spawn("ollama", ["serve"], { stdio: "ignore", detached: true }).unref();
29170
+ }
29171
+ async function waitUntilUp(provider, timeoutMs = 15e3) {
29172
+ const start = Date.now();
29173
+ while (Date.now() - start < timeoutMs) {
29174
+ const base = await isUp(provider);
29175
+ if (base) return base;
29176
+ await promises.setTimeout(500);
29177
+ }
29178
+ return null;
29179
+ }
29180
+ async function ensureLocalProviderUp(preferredOrder = ["lmstudio", "ollama"]) {
29181
+ for (const p of preferredOrder) {
29182
+ const up = await isUp(p);
29183
+ if (up) {
29184
+ debugLog("provider up", p, up);
29185
+ return { provider: p, baseUrl: up, started: false };
29186
+ }
29187
+ try {
29188
+ debugLog("attempting autostart", p);
29189
+ if (p === "lmstudio") await tryStartLMStudio();
29190
+ else await tryStartOllama();
29191
+ const providerTimeout = p === "lmstudio" ? parseInt(process.env.LMSTUDIO_STARTUP_TIMEOUT_MS || "") || 9e4 : parseInt(process.env.OLLAMA_STARTUP_TIMEOUT_MS || "") || 2e4;
29192
+ const base = await waitUntilUp(p, providerTimeout);
29193
+ if (base) {
29194
+ debugLog("provider started", p, base);
29195
+ return { provider: p, baseUrl: base, started: true };
29196
+ }
29197
+ debugLog("autostart failed or timed out", p);
29198
+ } catch (e2) {
29199
+ debugLog("autostart error", p, e2?.message || String(e2));
29200
+ }
29201
+ }
29202
+ debugLog("no preferred providers available");
29203
+ return null;
29204
+ }
29205
+ function parseModelId(id) {
29206
+ const s2 = id.toLowerCase();
29207
+ const afterSlash = s2.includes("/") ? s2.split("/").pop() || s2 : s2;
29208
+ const m1 = afterSlash.match(/^(gpt-oss|gemma|llama|magistral)[-:]?(\d+(?:\.\d+)?)?([a-z]*)?[:\-]?(\d+)?([a-z]*)?$/);
29209
+ if (m1) {
29210
+ const fam = m1[1];
29211
+ const verToken = m1[2] || null;
29212
+ const lastNum = m1[4] || null;
29213
+ const sizeToken = (m1[3] || m1[5] || "").toLowerCase();
29214
+ const version = verToken ? Number(verToken) : null;
29215
+ const size = lastNum ? Number(lastNum) : sizeToken.includes("b") ? Number(sizeToken.replace(/[^0-9]/g, "")) : null;
29216
+ return { family: fam, version, size };
29217
+ }
29218
+ const m2 = afterSlash.match(/^(gpt-oss|gemma|llama|magistral)[^-:]*[:](\d+)([a-z])$/);
29219
+ if (m2) {
29220
+ return { family: m2[1], version: null, size: Number(m2[2]) };
29221
+ }
29222
+ return { family: s2.split(/[-:]/)[0], version: null, size: null };
29223
+ }
29224
+ function pickBestModel(models, prefs) {
29225
+ if (!models.length) return null;
29226
+ if (prefs.explicitModel) {
29227
+ const exact = models.find((m2) => m2.toLowerCase() === prefs.explicitModel.toLowerCase());
29228
+ if (exact) return exact;
29229
+ const family = prefs.explicitModel.split(/[:\-]/)[0].toLowerCase();
29230
+ const famMs = models.filter((m2) => m2.toLowerCase().startsWith(family));
29231
+ if (famMs.length) models = famMs;
29232
+ }
29233
+ const familyRank = (id) => {
29234
+ const fam = parseModelId(id).family;
29235
+ const idx = FAMILY_ORDER.indexOf(fam);
29236
+ return idx === -1 ? 999 : idx;
29237
+ };
29238
+ const score = (id) => {
29239
+ const { version, size } = parseModelId(id);
29240
+ return [-(version || 0), -(size || 0)];
29241
+ };
29242
+ const sorted = [...models].sort((a, b) => {
29243
+ const fa = familyRank(a);
29244
+ const fb = familyRank(b);
29245
+ if (fa !== fb) return fa - fb;
29246
+ const [va, sa] = score(a);
29247
+ const [vb, sb] = score(b);
29248
+ if (va !== vb) return va - vb;
29249
+ return sa - sb;
29250
+ });
29251
+ return sorted[0] || null;
29252
+ }
29253
+ async function listModels(provider, baseUrl) {
29254
+ const viaCli = await listModelsViaCli(provider).catch(() => []);
29255
+ if (viaCli.length) return viaCli;
29256
+ try {
29257
+ const url2 = provider === "ollama" ? `${baseUrl}/api/tags` : `${baseUrl}/models`;
29258
+ const res = await fetch(url2);
29259
+ if (!res.ok) return [];
29260
+ const body = await res.json().catch(() => ({}));
29261
+ if (provider === "ollama") {
29262
+ const arr2 = Array.isArray(body.models) ? body.models : body.data || [];
29263
+ return arr2.map((m2) => m2?.name).filter(Boolean);
29264
+ }
29265
+ const arr = Array.isArray(body.data) ? body.data : Array.isArray(body._data) ? body._data : [];
29266
+ return arr.map((m2) => m2?.id).filter(Boolean);
29267
+ } catch {
29268
+ return [];
29269
+ }
29270
+ }
29271
+ async function ensureBaselineModel(provider) {
29272
+ if (provider === "lmstudio") {
29273
+ child_process.spawn("lms", ["model", "download", "openai/gpt-oss-20b"], { stdio: "ignore", detached: true }).unref();
29274
+ return;
29275
+ }
29276
+ child_process.spawn("ollama", ["pull", "gpt-oss:latest"], { stdio: "ignore", detached: true }).unref();
29277
+ }
29278
+ async function selectLocalProviderAndModel(prefs = {}) {
29279
+ const order = prefs.explicitProvider ? [
29280
+ prefs.explicitProvider,
29281
+ ...prefs.explicitProvider === "lmstudio" ? ["ollama"] : ["lmstudio"]
29282
+ ] : ["lmstudio", "ollama"];
29283
+ const up = await ensureLocalProviderUp(order);
29284
+ if (!up) return null;
29285
+ let models = await listModels(up.provider, up.baseUrl);
29286
+ if (process.env.MARIA_DEBUG === "1") {
29287
+ try {
29288
+ console.log("[DEBUG/local-llm] models.list", up.provider, models.slice(0, 20));
29289
+ } catch {
29290
+ }
29291
+ }
29292
+ if (!models.length) {
29293
+ await ensureBaselineModel(up.provider);
29294
+ await promises.setTimeout(2e3);
29295
+ models = await listModels(up.provider, up.baseUrl);
29296
+ }
29297
+ if (up.provider === "lmstudio") {
29298
+ const hasPreferred = models.some((m2) => parseModelId(m2).family === "gpt-oss");
29299
+ if (!hasPreferred) {
29300
+ await ensureBaselineModel("lmstudio");
29301
+ await promises.setTimeout(3e3);
29302
+ models = await listModels(up.provider, up.baseUrl);
29303
+ if (process.env.MARIA_DEBUG === "1") {
29304
+ try {
29305
+ console.log("[DEBUG/local-llm] models.relist.after-download", models.slice(0, 20));
29306
+ } catch {
29307
+ }
29308
+ }
29309
+ }
29310
+ }
29311
+ const chosen = pickBestModel(models, prefs) || (up.provider === "lmstudio" ? "openai/gpt-oss-20b" : "gpt-oss:latest");
29312
+ debugLog("selected provider/model", up.provider, chosen);
29313
+ return { provider: up.provider, baseUrl: up.baseUrl, model: chosen };
29314
+ }
29315
+ function runCommand(cmd, args2, input3, timeoutMs = 3e5) {
29316
+ return new Promise((resolve19) => {
29317
+ const child = child_process.spawn(cmd, args2, { stdio: ["pipe", "pipe", "pipe"] });
29318
+ let stdout2 = "";
29319
+ let stderr = "";
29320
+ const timer = setTimeout(() => {
29321
+ try {
29322
+ child.kill("SIGKILL");
29323
+ } catch {
29324
+ }
29325
+ }, timeoutMs);
29326
+ child.stdout?.on("data", (d) => {
29327
+ stdout2 += d.toString();
29328
+ });
29329
+ child.stderr?.on("data", (d) => {
29330
+ stderr += d.toString();
29331
+ });
29332
+ child.on("exit", (code) => {
29333
+ clearTimeout(timer);
29334
+ resolve19({ code, stdout: stdout2, stderr });
29335
+ });
29336
+ if (input3 && child.stdin) {
29337
+ child.stdin.write(input3);
29338
+ child.stdin.end();
29339
+ }
29340
+ });
29341
+ }
29342
+ async function listModelsViaCli(provider) {
29343
+ try {
29344
+ if (provider === "lmstudio") {
29345
+ const res2 = await runCommand("lms", ["ls", "--json"]);
29346
+ if (res2.code === 0) {
29347
+ try {
29348
+ const j = JSON.parse(res2.stdout);
29349
+ const arr = Array.isArray(j?.models) ? j.models : Array.isArray(j?.data) ? j.data : [];
29350
+ return arr.map((m2) => m2?.id || m2?.name).filter(Boolean);
29351
+ } catch {
29352
+ }
29353
+ }
29354
+ const res22 = await runCommand("lms", ["ls"]);
29355
+ if (res22.code === 0) {
29356
+ return res22.stdout.split(/\r?\n/).map((s2) => s2.trim()).filter(Boolean);
29357
+ }
29358
+ return [];
29359
+ }
29360
+ const res = await runCommand("ollama", ["list"]);
29361
+ if (res.code === 0) {
29362
+ const lines = res.stdout.split(/\r?\n/).slice(1).filter(Boolean);
29363
+ const names = lines.map((l) => l.split(/\s+/)[0]).filter(Boolean);
29364
+ return names;
29365
+ }
29366
+ return [];
29367
+ } catch {
29368
+ return [];
29369
+ }
29370
+ }
29371
+ async function generateViaCli(provider, model, prompt) {
29372
+ try {
29373
+ if (provider === "lmstudio") {
29374
+ const args2 = ["chat", model, "-p", prompt, "--yes", "--offline", "--ttl", "2"];
29375
+ if (process.env.MARIA_DEBUG === "1") {
29376
+ try {
29377
+ console.log("[DEBUG/local][lmstudio-cli] args", args2);
29378
+ } catch {
29379
+ }
29380
+ }
29381
+ const exec2 = await runCommand("lms", args2);
29382
+ if (process.env.MARIA_DEBUG === "1") {
29383
+ try {
29384
+ console.log("[DEBUG/local][lmstudio-cli] exit", exec2.code, "stdout.len:", exec2.stdout.length, "stderr.len:", exec2.stderr.length);
29385
+ } catch {
29386
+ }
29387
+ }
29388
+ if (exec2.code === 0) {
29389
+ const out = exec2.stdout.trim();
29390
+ if (out) return out;
29391
+ const err = exec2.stderr.trim();
29392
+ if (err) return err;
29393
+ }
29394
+ return null;
29395
+ }
29396
+ const res = await runCommand("ollama", ["run", model], prompt);
29397
+ if (res.code === 0) return res.stdout.trim();
29398
+ const res2 = await runCommand("ollama", ["run", model, prompt]);
29399
+ if (res2.code === 0) return res2.stdout.trim();
29400
+ return null;
29401
+ } catch {
29402
+ return null;
29403
+ }
29404
+ }
29405
+ var FAMILY_ORDER;
29406
+ var init_local_llm_manager = __esm({
29407
+ "src/services/local-llm-manager.ts"() {
29408
+ init_llm_endpoint_discovery();
29409
+ FAMILY_ORDER = ["gpt-oss", "gemma", "llama", "magistral"];
29410
+ }
29411
+ });
29412
+
29053
29413
  // src/services/cli-auth/api-caller.ts
29054
29414
  var api_caller_exports = {};
29055
29415
  __export(api_caller_exports, {
@@ -29059,6 +29419,44 @@ __export(api_caller_exports, {
29059
29419
  executeChat: () => executeChat,
29060
29420
  executeCode: () => executeCode
29061
29421
  });
29422
+ function sanitizeLocalOutputText(raw) {
29423
+ let t2 = (raw || "").toString();
29424
+ const marker = "<|channel|>final<|message|>";
29425
+ const idx = t2.lastIndexOf(marker);
29426
+ if (idx >= 0) {
29427
+ let body = t2.substring(idx + marker.length);
29428
+ const endIdx = body.indexOf("<|end|>");
29429
+ if (endIdx >= 0) body = body.substring(0, endIdx);
29430
+ return body.trim();
29431
+ }
29432
+ return t2.replace(/<\|[^>]+?\|>/g, "").trim();
29433
+ }
29434
+ async function getEnterpriseFlag() {
29435
+ if (cachedEnterprise !== null) return cachedEnterprise;
29436
+ try {
29437
+ const tokens2 = await authManager2.getValidTokens();
29438
+ if (!tokens2) return false;
29439
+ const apiBase = process.env.MARIA_API_BASE || "https://api.maria-code.ai";
29440
+ const ctl = new AbortController();
29441
+ const to = setTimeout(() => ctl.abort(), 3e3);
29442
+ const r2 = await fetch(`${apiBase}/api/user/profile`, {
29443
+ method: "GET",
29444
+ headers: { "Authorization": `Bearer ${tokens2.accessToken}` }
29445
+ });
29446
+ clearTimeout(to);
29447
+ if (!r2.ok) {
29448
+ cachedEnterprise = false;
29449
+ return false;
29450
+ }
29451
+ const prof = await r2.json().catch(() => ({}));
29452
+ const plan = String((prof?.plan || "").toString()).toLowerCase();
29453
+ cachedEnterprise = plan === "enterprise";
29454
+ return cachedEnterprise;
29455
+ } catch {
29456
+ cachedEnterprise = false;
29457
+ return false;
29458
+ }
29459
+ }
29062
29460
  async function callAPI(endpoint, options = {}) {
29063
29461
  const tokens2 = await authManager2.getValidTokens();
29064
29462
  if (!tokens2) {
@@ -29066,6 +29464,93 @@ async function callAPI(endpoint, options = {}) {
29066
29464
  }
29067
29465
  const apiBase = process.env.MARIA_API_BASE || "https://api.maria-code.ai";
29068
29466
  const url2 = `${apiBase}${endpoint}`;
29467
+ try {
29468
+ const isLocalMode = process.env.LOCAL_MODE === "1";
29469
+ const isAiProxy = endpoint === "/v1/ai-proxy" && (options.method || "GET") === "POST";
29470
+ if (isAiProxy && (isLocalMode || true)) {
29471
+ const isEnterprisePlan = await getEnterpriseFlag().catch(() => false) || String(process.env.PLAN || "").toLowerCase() === "enterprise";
29472
+ if (!isLocalMode && !isEnterprisePlan) {
29473
+ } else {
29474
+ const payload = options.body || {};
29475
+ const reqProvider = String(payload?.provider || "").toLowerCase();
29476
+ if (isEnterprisePlan && reqProvider && !["lmstudio", "ollama"].includes(reqProvider)) {
29477
+ throw new Error("Enterprise policy requires local LLM only");
29478
+ }
29479
+ const explicitModel = typeof payload?.model === "string" ? payload.model : void 0;
29480
+ let effectivePrompt = void 0;
29481
+ if (typeof payload?.prompt === "string" && payload.prompt.trim()) {
29482
+ effectivePrompt = String(payload.prompt).trim();
29483
+ } else if (Array.isArray(payload?.messages)) {
29484
+ try {
29485
+ const lastUser = [...payload.messages].reverse().find((m2) => (m2?.role || "").toLowerCase() === "user");
29486
+ effectivePrompt = lastUser?.content && String(lastUser.content) || payload.messages.map((m2) => String(m2?.content || "")).filter(Boolean).join("\n");
29487
+ } catch {
29488
+ }
29489
+ }
29490
+ if (effectivePrompt && (!reqProvider || ["lmstudio", "ollama"].includes(reqProvider))) {
29491
+ try {
29492
+ let inlineProvider;
29493
+ let inlineModel;
29494
+ {
29495
+ const provMatch = /\s--provider=([a-zA-Z0-9_-]+)/i.exec(effectivePrompt);
29496
+ if (provMatch) inlineProvider = provMatch[1].toLowerCase();
29497
+ const modelMatch = /\s--model=([^\s]+)/i.exec(effectivePrompt);
29498
+ if (modelMatch) inlineModel = modelMatch[1];
29499
+ if (inlineProvider || inlineModel) {
29500
+ effectivePrompt = effectivePrompt.replace(/\s--provider=[^\s]+/ig, "").replace(/\s--model=[^\s]+/ig, "").trim();
29501
+ }
29502
+ }
29503
+ const { selectLocalProviderAndModel: selectLocalProviderAndModel2, generateViaCli: generateViaCli2 } = await Promise.resolve().then(() => (init_local_llm_manager(), local_llm_manager_exports));
29504
+ const sel = await selectLocalProviderAndModel2({ explicitModel: inlineModel || explicitModel, explicitProvider: inlineProvider });
29505
+ if (process.env.MARIA_DEBUG === "1" && sel) {
29506
+ try {
29507
+ console.log("[DEBUG/local] provider:", sel.provider, "model:", sel.model);
29508
+ } catch {
29509
+ }
29510
+ }
29511
+ if (sel) {
29512
+ const out = await generateViaCli2(sel.provider, sel.model, effectivePrompt);
29513
+ if (typeof out === "string" && out.length > 0) {
29514
+ const finalText = sanitizeLocalOutputText(out);
29515
+ if (process.env.MARIA_DEBUG === "1") {
29516
+ try {
29517
+ console.log("[DEBUG/local] sanitize", { inLen: out.length, outLen: finalText.length, changed: finalText.length !== out.length });
29518
+ } catch {
29519
+ }
29520
+ }
29521
+ try {
29522
+ const ctl = new AbortController();
29523
+ const to = setTimeout(() => ctl.abort(), 1500);
29524
+ await fetch(`${apiBase}/api/v1/usage`, {
29525
+ method: "POST",
29526
+ headers: {
29527
+ "Authorization": `Bearer ${tokens2.accessToken}`,
29528
+ "Content-Type": "application/json",
29529
+ "Idempotency-Key": `cli_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`
29530
+ },
29531
+ body: JSON.stringify({ consumption: { requests: 1 } }),
29532
+ signal: ctl.signal
29533
+ }).catch(() => null);
29534
+ clearTimeout(to);
29535
+ } catch {
29536
+ }
29537
+ return { data: { content: finalText, routedModel: { vendor: "local", family: sel.provider, name: sel.model, reason: isEnterprisePlan ? "enterprise" : "local_mode" } } };
29538
+ }
29539
+ }
29540
+ if (isEnterprisePlan) {
29541
+ throw new Error("Enterprise policy requires local LLM. Local execution failed or unavailable.");
29542
+ }
29543
+ } catch (e2) {
29544
+ if (isEnterprisePlan) throw e2;
29545
+ }
29546
+ } else if (isEnterprisePlan) {
29547
+ throw new Error("Enterprise policy requires local LLM only");
29548
+ }
29549
+ }
29550
+ }
29551
+ } catch (e2) {
29552
+ if (String(process.env.PLAN || "").toLowerCase() === "enterprise") throw e2;
29553
+ }
29069
29554
  const controller = new AbortController();
29070
29555
  const defaultMs = 6e5;
29071
29556
  const envMs = Number(process.env.MARIA_API_TIMEOUT_MS || process.env.MARIA_CODE_TIMEOUT_MS || defaultMs);
@@ -29225,12 +29710,13 @@ async function executeAIProxy(provider, model, messages, options) {
29225
29710
  body: { provider, model, messages, options }
29226
29711
  });
29227
29712
  }
29228
- var authManager2, RateLimitError;
29713
+ var authManager2, cachedEnterprise, RateLimitError;
29229
29714
  var init_api_caller = __esm({
29230
29715
  "src/services/cli-auth/api-caller.ts"() {
29231
29716
  init_AuthenticationManager();
29232
29717
  new https__default.default.Agent({ keepAlive: true });
29233
29718
  authManager2 = new AuthenticationManager();
29719
+ cachedEnterprise = null;
29234
29720
  RateLimitError = class extends Error {
29235
29721
  constructor(message, retryAfter) {
29236
29722
  super(message);
@@ -38009,7 +38495,23 @@ var init_telemetry_helper = __esm({
38009
38495
 
38010
38496
  // src/services/subscription/subscription-manager.ts
38011
38497
  async function getUserPlan() {
38012
- return "free";
38498
+ try {
38499
+ const { cliAuth: cliAuth2 } = await Promise.resolve().then(() => (init_CLIAuthService(), CLIAuthService_exports));
38500
+ const api = cliAuth2.getAPIClient();
38501
+ const usage = await api.getUsage();
38502
+ const raw = String(usage?.planCode || usage?.planName || "").toUpperCase();
38503
+ const normalized = raw.replace(/[-_](ANNUAL|MONTHLY|YEARLY)$/i, "").toUpperCase();
38504
+ try {
38505
+ process.env.MARIA_PLAN = raw;
38506
+ } catch {
38507
+ }
38508
+ if (normalized === "ENTERPRISE" || normalized === "ULTRA") return "ultra";
38509
+ if (normalized === "PRO") return "pro";
38510
+ if (normalized === "STARTER") return "starter";
38511
+ return "free";
38512
+ } catch {
38513
+ return "free";
38514
+ }
38013
38515
  }
38014
38516
  var init_subscription_manager = __esm({
38015
38517
  "src/services/subscription/subscription-manager.ts"() {
@@ -39105,16 +39607,7 @@ var init_HelpCommand = __esm({
39105
39607
  async showCommandHelp(commandName) {
39106
39608
  const command = await this.readyService.getCommand(commandName);
39107
39609
  if (!command) {
39108
- const searchResults = await this.readyService.searchCommands(commandName, 3);
39109
- const suggestions = searchResults.map((r2) => `/${r2.command.name}`);
39110
- return this.error(
39111
- `READY command not found: /${commandName}`,
39112
- "COMMAND_NOT_FOUND",
39113
- {
39114
- suggestions,
39115
- tip: "Only contract-validated READY commands are shown"
39116
- }
39117
- );
39610
+ return await this.showGeneralHelp();
39118
39611
  }
39119
39612
  const lines = this.formatMinimalUsage(command);
39120
39613
  return this.success(lines);
@@ -40649,18 +41142,18 @@ var init_StatusCommand = __esm({
40649
41142
  );
40650
41143
  if (process.env.NODE_ENV === "test") {
40651
41144
  if (timeoutMs < 200 || options.signal) {
40652
- const delay = Math.max(75, timeoutMs + 50);
41145
+ const delay2 = Math.max(75, timeoutMs + 50);
40653
41146
  systemHealthPromise = Promise.all([
40654
41147
  systemHealthPromise,
40655
- this.createCancellableDelay(delay, options.signal)
41148
+ this.createCancellableDelay(delay2, options.signal)
40656
41149
  ]).then(([health]) => health);
40657
41150
  } else {
40658
41151
  systemHealthPromise = systemHealthPromise.then((health) => {
40659
41152
  return new Promise((resolve19) => {
40660
41153
  if (!globalThis._statusCommandTestCounter)
40661
41154
  globalThis._statusCommandTestCounter = 0;
40662
- const delay = ++globalThis._statusCommandTestCounter % 2 === 1 ? 3 : 1;
40663
- setTimeout(() => resolve19(health), delay);
41155
+ const delay2 = ++globalThis._statusCommandTestCounter % 2 === 1 ? 3 : 1;
41156
+ setTimeout(() => resolve19(health), delay2);
40664
41157
  });
40665
41158
  });
40666
41159
  }
@@ -48095,6 +48588,94 @@ var init_ImageArgumentInference = __esm({
48095
48588
  init_api_caller();
48096
48589
  }
48097
48590
  });
48591
+
48592
+ // src/services/media-orchestrator/VideoArgumentInference.ts
48593
+ function extractFirstJson4(text) {
48594
+ const matches = text.match(/[\[{][\s\S]*[\]}]/g) || [];
48595
+ for (const cand of matches) {
48596
+ try {
48597
+ JSON.parse(cand);
48598
+ return cand;
48599
+ } catch {
48600
+ }
48601
+ }
48602
+ return null;
48603
+ }
48604
+ function parseSizeAny2(x2) {
48605
+ if (!x2) return void 0;
48606
+ const s2 = String(x2).trim().toLowerCase().replace(/p$/, "");
48607
+ const m2 = /^(\d{2,4})x(\d{2,4})$/.exec(s2);
48608
+ if (m2) {
48609
+ const w = Number(m2[1]);
48610
+ const h2 = Number(m2[2]);
48611
+ if (Number.isFinite(w) && Number.isFinite(h2) && w >= 256 && h2 >= 256 && w <= 4096 && h2 <= 4096) return [w, h2];
48612
+ return void 0;
48613
+ }
48614
+ if (s2 === "720") return [1280, 720];
48615
+ if (s2 === "1080") return [1920, 1080];
48616
+ return void 0;
48617
+ }
48618
+ async function inferVideoArgsLLM(promptText) {
48619
+ const system = [
48620
+ "You extract video generation options from user natural language.",
48621
+ 'Return JSON only with keys: { "model"?: "sora-2"|"veo-3.1-generate-preview", "duration"?: number, "aspect"?: "16:9"|"9:16", "size"?: "WIDTHxHEIGHT"|"720"|"1080" }.',
48622
+ "Rules:",
48623
+ '- If user mentions OpenAI Sora, choose model "sora-2". If Google Veo, choose "veo-3.1-generate-preview".',
48624
+ "- Duration options differ: for Sora use one of 4, 8, 12; for Veo prefer 4, 6, 8 (1080p fixed 8).",
48625
+ "- If user says 10 seconds, map to closest allowed (e.g., 8 for Sora/Veo).",
48626
+ '- Aspect: map "portrait"/"vertical" to 9:16, "landscape"/"wide" to 16:9. If square mentioned, prefer 1:1 but output closest supported by providers (choose 16:9).',
48627
+ '- Size: if 720p or 1080p mentioned, return "720" or "1080". If explicit WxH, return as is if within 256..4096 per side.',
48628
+ "Do not add explanations; JSON only."
48629
+ ].join("\n");
48630
+ let explicitModel;
48631
+ let explicitProvider;
48632
+ try {
48633
+ const { extractExplicitModel: extractExplicitModel2, extractExplicitProvider: extractExplicitProvider2, providerFromModel: providerFromModel2 } = await Promise.resolve().then(() => (init_llm_flags(), llm_flags_exports));
48634
+ explicitModel = extractExplicitModel2(promptText);
48635
+ explicitProvider = extractExplicitProvider2(promptText) || providerFromModel2(explicitModel);
48636
+ } catch {
48637
+ }
48638
+ let attachments = [];
48639
+ try {
48640
+ const { collectFileAttachmentsFromText: collectFileAttachmentsFromText2 } = await Promise.resolve().then(() => (init_attachment_utils(), attachment_utils_exports));
48641
+ attachments = await collectFileAttachmentsFromText2(promptText, process.cwd(), { maxBytes: 12 * 1024 * 1024 });
48642
+ } catch {
48643
+ }
48644
+ const resp = await callAPI("/v1/ai-proxy", {
48645
+ method: "POST",
48646
+ body: {
48647
+ ...explicitProvider ? { provider: explicitProvider } : {},
48648
+ ...explicitModel ? { model: explicitModel } : {},
48649
+ prompt: `${system}
48650
+
48651
+ ---
48652
+
48653
+ ${promptText}`,
48654
+ taskType: "media",
48655
+ ...attachments.length ? { metadata: { attachments } } : {}
48656
+ }
48657
+ });
48658
+ const raw = (resp?.data?.content || resp?.output || "").trim();
48659
+ const jsonText = extractFirstJson4(raw) || raw;
48660
+ let parsed;
48661
+ try {
48662
+ parsed = JSON.parse(jsonText);
48663
+ } catch {
48664
+ return {};
48665
+ }
48666
+ const out = {};
48667
+ if (typeof parsed?.model === "string" && parsed.model.trim()) out.model = String(parsed.model).trim();
48668
+ if (Number.isFinite(Number(parsed?.duration))) out.duration = Math.max(1, Math.floor(Number(parsed.duration)));
48669
+ if (parsed?.aspect === "16:9" || parsed?.aspect === "9:16") out.aspect = parsed.aspect;
48670
+ const size = parseSizeAny2(parsed?.size);
48671
+ if (size) out.size = size;
48672
+ return out;
48673
+ }
48674
+ var init_VideoArgumentInference = __esm({
48675
+ "src/services/media-orchestrator/VideoArgumentInference.ts"() {
48676
+ init_api_caller();
48677
+ }
48678
+ });
48098
48679
  function parseSize(value) {
48099
48680
  const m2 = /^\s*(\d{2,4})x(\d{2,4})\s*$/i.exec(value || "");
48100
48681
  if (!m2) throw new Error(`invalid size: ${value}`);
@@ -48314,6 +48895,15 @@ function normalizeVideoArgs(raw, root) {
48314
48895
  break;
48315
48896
  }
48316
48897
  }
48898
+ try {
48899
+ if (String(process.env.MARIA_USE_LLM_INFER || "1") === "1") {
48900
+ global.__MARIA_VIDEO_LLM_INFER__ = async () => {
48901
+ const llm = await inferVideoArgsLLM(prompt);
48902
+ return llm;
48903
+ };
48904
+ }
48905
+ } catch {
48906
+ }
48317
48907
  if (!out.apply && !out.planOnly && !out.dryRun) {
48318
48908
  out.apply = true;
48319
48909
  }
@@ -48353,6 +48943,7 @@ var init_Normalizer = __esm({
48353
48943
  init_types4();
48354
48944
  init_NLInference();
48355
48945
  init_ImageArgumentInference();
48946
+ init_VideoArgumentInference();
48356
48947
  }
48357
48948
  });
48358
48949
  function ensureDirSync(p) {
@@ -48524,13 +49115,13 @@ async function withRetry429(fn, opts) {
48524
49115
  const kind = classify(e2);
48525
49116
  if (!kind) throw e2;
48526
49117
  if (i2 === opts.retries) break;
48527
- const delay = backoffDelay(i2, opts);
49118
+ const delay2 = backoffDelay(i2, opts);
48528
49119
  try {
48529
- process.stderr.write(`WARN: ${kind} retry in ${delay}ms (attempt ${i2 + 1}/${opts.retries})
49120
+ process.stderr.write(`WARN: ${kind} retry in ${delay2}ms (attempt ${i2 + 1}/${opts.retries})
48530
49121
  `);
48531
49122
  } catch {
48532
49123
  }
48533
- await sleep2(delay);
49124
+ await sleep2(delay2);
48534
49125
  }
48535
49126
  }
48536
49127
  throw lastErr;
@@ -49568,7 +50159,39 @@ var init_video_command = __esm({
49568
50159
  try {
49569
50160
  const root = context2.environment.cwd;
49570
50161
  const cli = normalizeVideoArgs(args2.raw, root);
49571
- cli.duration = 8;
50162
+ try {
50163
+ const hook = global.__MARIA_VIDEO_LLM_INFER__;
50164
+ if (hook) {
50165
+ const llm = await hook();
50166
+ if (llm) {
50167
+ if (llm.model && typeof llm.model === "string") cli.model = llm.model;
50168
+ if (Number.isFinite(Number(llm.duration))) {
50169
+ const d = Math.floor(Number(llm.duration));
50170
+ cli.duration = Math.max(1, Math.min(60, d));
50171
+ }
50172
+ if (llm.aspect === "16:9" || llm.aspect === "9:16") {
50173
+ cli.aspect = llm.aspect;
50174
+ const [w, h2] = cli.size;
50175
+ if (llm.size && Array.isArray(llm.size) && llm.size.length === 2) {
50176
+ cli.size = llm.size;
50177
+ } else if (w === 1280 && h2 === 720 || w === 720 && h2 === 1280 || w === 1920 && h2 === 1080 || w === 1080 && h2 === 1920) {
50178
+ if (llm.aspect === "9:16") {
50179
+ if (h2 === 720) cli.size = [720, 1280];
50180
+ else if (h2 === 1080) cli.size = [1080, 1920];
50181
+ } else {
50182
+ if (w === 720) cli.size = [1280, 720];
50183
+ else if (w === 1080) cli.size = [1920, 1080];
50184
+ if (w === 1080 && h2 === 1920) cli.size = [1920, 1080];
50185
+ }
50186
+ }
50187
+ } else if (llm.size && Array.isArray(llm.size) && llm.size.length === 2) {
50188
+ cli.size = llm.size;
50189
+ cli.aspect = cli.size[0] >= cli.size[1] ? "16:9" : "9:16";
50190
+ }
50191
+ }
50192
+ }
50193
+ } catch {
50194
+ }
49572
50195
  if (cli.planOnly || cli.dryRun || !cli.apply) {
49573
50196
  const line = `Plan: video ${cli.duration}s @${cli.fps}fps ${cli.size[0]}x${cli.size[1]} ${cli.format} model=${cli.model || "auto"} concurrency=${cli.concurrency} retry=${cli.retry}`;
49574
50197
  const next = `Next: /video "${cli.prompt}" --duration ${cli.duration} --fps ${cli.fps} --res ${cli.size[0]}x${cli.size[1]} --apply`;
@@ -51384,7 +52007,7 @@ var init_about_command = __esm({
51384
52007
  async execute(args2, context2) {
51385
52008
  const output3 = [];
51386
52009
  output3.push("");
51387
- output3.push(chalk14__default.default.cyan.bold("About MARIA v4.4.1"));
52010
+ output3.push(chalk14__default.default.cyan.bold("About MARIA v4.4.3"));
51388
52011
  output3.push(chalk14__default.default.gray("\u2550".repeat(40)));
51389
52012
  output3.push("");
51390
52013
  output3.push(chalk14__default.default.white.bold("MARIA - Minimal API, Maximum Power"));
@@ -54693,7 +55316,7 @@ var init_code_utils = __esm({
54693
55316
  });
54694
55317
 
54695
55318
  // src/services/creative/NovelArgumentInference.ts
54696
- function extractFirstJson4(text) {
55319
+ function extractFirstJson5(text) {
54697
55320
  if (!text) return null;
54698
55321
  const start = text.indexOf("{");
54699
55322
  const end = text.lastIndexOf("}");
@@ -54744,7 +55367,7 @@ ${rawText}`,
54744
55367
  }
54745
55368
  });
54746
55369
  const raw = (resp?.data?.content || resp?.output || "").trim();
54747
- const jsonText = extractFirstJson4(raw) || raw;
55370
+ const jsonText = extractFirstJson5(raw) || raw;
54748
55371
  let parsed = {};
54749
55372
  try {
54750
55373
  parsed = JSON.parse(jsonText);
@@ -55146,7 +55769,7 @@ var init_rate_limit_handler = __esm({
55146
55769
  });
55147
55770
 
55148
55771
  // src/services/code-orchestrator/ArgumentInference.ts
55149
- function extractFirstJson5(text) {
55772
+ function extractFirstJson6(text) {
55150
55773
  const fence = /```json\r?\n([\s\S]*?)```/i.exec(text);
55151
55774
  if (fence) return fence[1];
55152
55775
  const start = text.indexOf("{");
@@ -55198,7 +55821,7 @@ ${rawText}`,
55198
55821
  }
55199
55822
  });
55200
55823
  const raw = (resp?.data?.content || resp?.output || "").trim();
55201
- const jsonText = extractFirstJson5(raw) || raw;
55824
+ const jsonText = extractFirstJson6(raw) || raw;
55202
55825
  let parsed = {};
55203
55826
  try {
55204
55827
  parsed = JSON.parse(jsonText);
@@ -55796,16 +56419,16 @@ function countRemainingLines(hunks, startHunkIdx, currentPart, currentLine) {
55796
56419
  }
55797
56420
  function colorGreen(s2) {
55798
56421
  try {
55799
- const chalk44 = __require("chalk");
55800
- return chalk44.green(s2);
56422
+ const chalk46 = __require("chalk");
56423
+ return chalk46.green(s2);
55801
56424
  } catch {
55802
56425
  return s2;
55803
56426
  }
55804
56427
  }
55805
56428
  function colorRed(s2) {
55806
56429
  try {
55807
- const chalk44 = __require("chalk");
55808
- return chalk44.red(s2);
56430
+ const chalk46 = __require("chalk");
56431
+ return chalk46.red(s2);
55809
56432
  } catch {
55810
56433
  return s2;
55811
56434
  }
@@ -57294,9 +57917,9 @@ function emitTelemetry(ev) {
57294
57917
  }
57295
57918
  async function assertCleanWorkingTree() {
57296
57919
  try {
57297
- const { spawn: spawn4 } = await import('child_process');
57920
+ const { spawn: spawn5 } = await import('child_process');
57298
57921
  const run = (cmd, args2) => new Promise((resolve19) => {
57299
- const p = spawn4(cmd, args2, { stdio: "ignore" });
57922
+ const p = spawn5(cmd, args2, { stdio: "ignore" });
57300
57923
  p.on("close", (code) => resolve19(code ?? 0));
57301
57924
  p.on("error", () => resolve19(1));
57302
57925
  });
@@ -57311,15 +57934,15 @@ async function assertCleanWorkingTree() {
57311
57934
  }
57312
57935
  async function gitSingleCommit(appliedCount, opts) {
57313
57936
  try {
57314
- const { spawn: spawn4 } = await import('child_process');
57937
+ const { spawn: spawn5 } = await import('child_process');
57315
57938
  const run = (cmd, args2) => new Promise((resolve19) => {
57316
- const p = spawn4(cmd, args2, { stdio: "ignore" });
57939
+ const p = spawn5(cmd, args2, { stdio: "ignore" });
57317
57940
  p.on("close", (code2) => resolve19(code2 ?? 0));
57318
57941
  p.on("error", () => resolve19(1));
57319
57942
  });
57320
57943
  const runOut = (cmd, args2) => new Promise((resolve19) => {
57321
57944
  const chunks = [];
57322
- const p = spawn4(cmd, args2, { stdio: ["ignore", "pipe", "ignore"] });
57945
+ const p = spawn5(cmd, args2, { stdio: ["ignore", "pipe", "ignore"] });
57323
57946
  p.stdout.on("data", (c) => chunks.push(c));
57324
57947
  p.on("close", () => resolve19(Buffer.concat(chunks).toString().trim()));
57325
57948
  p.on("error", () => resolve19(""));
@@ -57357,10 +57980,10 @@ async function gitSingleCommit(appliedCount, opts) {
57357
57980
  }
57358
57981
  async function buildAutoTag(prefix) {
57359
57982
  try {
57360
- const { spawn: spawn4 } = await import('child_process');
57983
+ const { spawn: spawn5 } = await import('child_process');
57361
57984
  const runOut = (cmd, args2) => new Promise((resolve19) => {
57362
57985
  const chunks = [];
57363
- const p = spawn4(cmd, args2, { stdio: ["ignore", "pipe", "ignore"] });
57986
+ const p = spawn5(cmd, args2, { stdio: ["ignore", "pipe", "ignore"] });
57364
57987
  p.stdout.on("data", (c) => chunks.push(c));
57365
57988
  p.on("close", () => resolve19(Buffer.concat(chunks).toString().trim()));
57366
57989
  p.on("error", () => resolve19(""));
@@ -58186,7 +58809,7 @@ ${user}`
58186
58809
  } catch {
58187
58810
  }
58188
58811
  const content = (resp?.data?.content || resp?.content || "").trim();
58189
- const extractFirstJson7 = (text) => {
58812
+ const extractFirstJson8 = (text) => {
58190
58813
  const fence = /```\s*json\s*\r?\n([\s\S]*?)```/i.exec(text);
58191
58814
  if (fence) return fence[1];
58192
58815
  const generic = /```\s*\r?\n([\s\S]*?)```/i.exec(text);
@@ -58209,7 +58832,7 @@ ${user}`
58209
58832
  }
58210
58833
  return null;
58211
58834
  };
58212
- const jsonText = extractFirstJson7(content) || content;
58835
+ const jsonText = extractFirstJson8(content) || content;
58213
58836
  let parsed = {};
58214
58837
  try {
58215
58838
  parsed = JSON.parse(jsonText);
@@ -59468,12 +60091,12 @@ async function scanRoot(opts) {
59468
60091
  const filepath = path12__namespace.join(cwd2, name2);
59469
60092
  const result = await safeRead(filepath, 512 * 1024, maxLines, signal);
59470
60093
  if (result.head || result.meta) {
59471
- let meta27 = result.meta || object;
60094
+ let meta28 = result.meta || object;
59472
60095
  if (name2 === "package.json" && result.head) {
59473
60096
  try {
59474
60097
  const pkg = JSON.parse(result.head);
59475
- meta27 = {
59476
- ...meta27,
60098
+ meta28 = {
60099
+ ...meta28,
59477
60100
  name: pkg.name,
59478
60101
  version: pkg.version,
59479
60102
  type: pkg.type,
@@ -59486,14 +60109,14 @@ async function scanRoot(opts) {
59486
60109
  workspaces: pkg.workspaces
59487
60110
  };
59488
60111
  } catch (e2) {
59489
- meta27.parseError = true;
60112
+ meta28.parseError = true;
59490
60113
  }
59491
60114
  }
59492
60115
  findings.push({
59493
60116
  file: name2,
59494
60117
  kind: "read",
59495
60118
  head: result.head,
59496
- meta: meta27,
60119
+ meta: meta28,
59497
60120
  truncated: result.truncated
59498
60121
  });
59499
60122
  }
@@ -59831,19 +60454,19 @@ function extractPackageInfo(findings) {
59831
60454
  hasPostinstall: false
59832
60455
  };
59833
60456
  }
59834
- const meta27 = pkgFinding.meta;
60457
+ const meta28 = pkgFinding.meta;
59835
60458
  return {
59836
- name: meta27.name,
59837
- version: meta27.version,
59838
- type: meta27.type,
59839
- scripts: meta27.scripts ? Object.keys(meta27.scripts) : [],
59840
- hasPostinstall: !!meta27.scripts?.postinstall,
59841
- bin: meta27.bin,
59842
- main: meta27.main,
59843
- exports: meta27.exports,
59844
- dependencies: meta27.dependencies || [],
59845
- devDependencies: meta27.devDependencies || [],
59846
- workspaces: meta27.workspaces
60459
+ name: meta28.name,
60460
+ version: meta28.version,
60461
+ type: meta28.type,
60462
+ scripts: meta28.scripts ? Object.keys(meta28.scripts) : [],
60463
+ hasPostinstall: !!meta28.scripts?.postinstall,
60464
+ bin: meta28.bin,
60465
+ main: meta28.main,
60466
+ exports: meta28.exports,
60467
+ dependencies: meta28.dependencies || [],
60468
+ devDependencies: meta28.devDependencies || [],
60469
+ workspaces: meta28.workspaces
59847
60470
  };
59848
60471
  }
59849
60472
  function collectWarnings(pkg, findings, cwd2) {
@@ -59994,9 +60617,9 @@ function calculateMetrics(findings, startTime) {
59994
60617
  }
59995
60618
  function renderFinding(f3) {
59996
60619
  const title = `### ${f3.kind.toUpperCase()} \u2014 ${f3.file}`;
59997
- let meta27 = "";
60620
+ let meta28 = "";
59998
60621
  if (f3.meta && Object.keys(f3.meta).length > 0) {
59999
- meta27 = `
60622
+ meta28 = `
60000
60623
  <details><summary>meta</summary>
60001
60624
 
60002
60625
  \`\`\`json
@@ -60017,7 +60640,7 @@ ${f3.head.trim()}
60017
60640
  }
60018
60641
  const truncInfo = f3.truncated ? `
60019
60642
  > _truncated preview_` : "";
60020
- return [title, meta27, content, truncInfo, ""].join("\n");
60643
+ return [title, meta28, content, truncInfo, ""].join("\n");
60021
60644
  }
60022
60645
  function safeJsonStringify(obj) {
60023
60646
  try {
@@ -70732,11 +71355,11 @@ var init_search_command = __esm({
70732
71355
  * Calculate processing delay for simulation
70733
71356
  */
70734
71357
  calculateProcessingDelay(options) {
70735
- let delay = 100;
70736
- if (options.kgBoost) delay += 50;
70737
- if (options.rerank) delay += 100;
70738
- if (options.explain) delay += 30;
70739
- return delay + Math.random() * 50;
71358
+ let delay2 = 100;
71359
+ if (options.kgBoost) delay2 += 50;
71360
+ if (options.rerank) delay2 += 100;
71361
+ if (options.explain) delay2 += 30;
71362
+ return delay2 + Math.random() * 50;
70740
71363
  }
70741
71364
  /**
70742
71365
  * Generate mock search results
@@ -72814,6 +73437,592 @@ var init_gpu_command = __esm({
72814
73437
  gpu_command_default = GPUCommand;
72815
73438
  }
72816
73439
  });
73440
+ function renderFeatureComparison() {
73441
+ const lines = [];
73442
+ const COLS = {
73443
+ feature: 28,
73444
+ free: 9,
73445
+ starter: 15,
73446
+ pro: 20,
73447
+ ultra: 20
73448
+ };
73449
+ const stripAnsi2 = (s2) => s2.replace(/\x1B\[[0-9;]*m/g, "");
73450
+ const padAnsi = (s2, width) => {
73451
+ const len = stripAnsi2(s2).length;
73452
+ return s2 + " ".repeat(Math.max(0, width - len));
73453
+ };
73454
+ lines.push("");
73455
+ lines.push(chalk14__default.default.bold.white("\u{1F4CA} Plan Comparison"));
73456
+ lines.push("");
73457
+ lines.push(chalk14__default.default.gray("\u2500".repeat(60)));
73458
+ lines.push("");
73459
+ lines.push(
73460
+ " " + 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)
73461
+ );
73462
+ lines.push("");
73463
+ const features = [
73464
+ // LP-aligned buckets
73465
+ ["Code Generation/month", "40", "300", "1,200", "5,000"],
73466
+ ["File Analysis/month", "5", "50", "200", "500"],
73467
+ ["AI Models", "3 models", "4 models", "6 models", "12 models"],
73468
+ ["Support", "Community", "Community", "Community", "Priority"]
73469
+ ];
73470
+ for (const [feature, free, starter, pro, ultra] of features) {
73471
+ 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);
73472
+ lines.push(line);
73473
+ }
73474
+ lines.push("");
73475
+ lines.push(chalk14__default.default.gray("\u2500".repeat(60)));
73476
+ lines.push("");
73477
+ lines.push(chalk14__default.default.cyan(" \u{1F48E} Upgrade: /upgrade"));
73478
+ lines.push("");
73479
+ return lines.join("\n");
73480
+ }
73481
+ function formatValue(value, color) {
73482
+ if (value === "\u274C") return chalk14__default.default.red(value);
73483
+ if (value === "\u2705") return chalk14__default.default.green(value);
73484
+ if (value === "Unlimited") {
73485
+ return color === "magenta" ? chalk14__default.default.magenta.bold(value) : chalk14__default.default.bold(value);
73486
+ }
73487
+ switch (color) {
73488
+ case "blue":
73489
+ return chalk14__default.default.blue(value);
73490
+ case "yellow":
73491
+ return chalk14__default.default.yellow(value);
73492
+ case "magenta":
73493
+ return chalk14__default.default.magenta(value);
73494
+ default:
73495
+ return chalk14__default.default.white(value);
73496
+ }
73497
+ }
73498
+ var init_plan_aware_ui = __esm({
73499
+ "src/ui/components/plan-aware-ui.ts"() {
73500
+ }
73501
+ });
73502
+
73503
+ // src/slash-commands/categories/system/upgrade.command.ts
73504
+ var upgrade_command_exports = {};
73505
+ __export(upgrade_command_exports, {
73506
+ UpgradeCommand: () => UpgradeCommand,
73507
+ meta: () => meta26
73508
+ });
73509
+ var UpgradeCommand, meta26;
73510
+ var init_upgrade_command = __esm({
73511
+ "src/slash-commands/categories/system/upgrade.command.ts"() {
73512
+ init_base_command();
73513
+ init_plan_aware_ui();
73514
+ init_subscription_manager();
73515
+ UpgradeCommand = class extends BaseCommand {
73516
+ name = "upgrade";
73517
+ description = "Upgrade your subscription plan";
73518
+ category = "system";
73519
+ aliases = ["pro", "ultra", "premium", "subscribe"];
73520
+ async execute(args2, context2) {
73521
+ Array.isArray(args2?.raw) ? args2.raw : [];
73522
+ const positional = args2?.parsed?.positional;
73523
+ const firstPositional = Array.isArray(positional) && positional.length > 0 ? positional[0] : void 0;
73524
+ const planOpt = args2?.options?.plan;
73525
+ const compareFlag = Boolean(args2?.flags?.compare);
73526
+ const plan = (planOpt || firstPositional)?.trim();
73527
+ const contextPlan = String(context2?.user?.plan || "").toUpperCase();
73528
+ const mappedFromContext = this.mapContextPlanToInternal(contextPlan);
73529
+ let currentPlan = mappedFromContext || await getUserPlan();
73530
+ if (compareFlag) {
73531
+ return {
73532
+ success: true,
73533
+ message: renderFeatureComparison(),
73534
+ requiresInput: false,
73535
+ autoRetry: false
73536
+ };
73537
+ }
73538
+ if (!plan) {
73539
+ return this.showInteractiveUpgrade(currentPlan, contextPlan);
73540
+ }
73541
+ let isAuthenticated = Boolean(context2?.user);
73542
+ try {
73543
+ if (!isAuthenticated) {
73544
+ const { cliAuth: cliAuth2 } = await Promise.resolve().then(() => (init_CLIAuthService(), CLIAuthService_exports));
73545
+ isAuthenticated = await cliAuth2.getAuthClient().isAuthenticated();
73546
+ }
73547
+ } catch {
73548
+ }
73549
+ if (!isAuthenticated) {
73550
+ return {
73551
+ success: false,
73552
+ message: "\u{1F510} Authentication required \xB7 Run: /login",
73553
+ requiresInput: false,
73554
+ autoRetry: false
73555
+ };
73556
+ }
73557
+ const normalizedPlan = plan.trim().toLowerCase();
73558
+ if (!["starter", "pro", "ultra"].includes(normalizedPlan)) {
73559
+ return {
73560
+ success: false,
73561
+ message: `Invalid plan: ${plan}. Choose 'starter', 'pro' or 'ultra'.`,
73562
+ requiresInput: false,
73563
+ autoRetry: false
73564
+ };
73565
+ }
73566
+ return this.processUpgrade(currentPlan, normalizedPlan, contextPlan, isAuthenticated, context2);
73567
+ }
73568
+ mapContextPlanToInternal(contextPlanUpper) {
73569
+ const code = contextPlanUpper.replace(/[-_](ANNUAL|MONTHLY|YEARLY)$/i, "").toUpperCase();
73570
+ if (code.includes("ENTERPRISE")) return "ultra";
73571
+ if (code.includes("ULTRA")) return "ultra";
73572
+ if (code.includes("PRO")) return "pro";
73573
+ if (code.includes("STARTER")) return "starter";
73574
+ if (code.includes("FREE")) return "free";
73575
+ return void 0;
73576
+ }
73577
+ async showInteractiveUpgrade(currentPlan, contextPlanUpper) {
73578
+ const output3 = [];
73579
+ output3.push("");
73580
+ output3.push(chalk14__default.default.bold.cyan("\u{1F48E} Upgrade Your Plan"));
73581
+ output3.push("");
73582
+ output3.push(chalk14__default.default.gray("Current Plan: ") + this.getCurrentPlanLabel(currentPlan, contextPlanUpper));
73583
+ output3.push("");
73584
+ output3.push(chalk14__default.default.gray("\u2500".repeat(60)));
73585
+ output3.push("");
73586
+ if (currentPlan === "free") {
73587
+ output3.push(chalk14__default.default.bold.white("\u{1F539} STARTER - $20/month"));
73588
+ output3.push(chalk14__default.default.gray("For individual developers"));
73589
+ output3.push("");
73590
+ output3.push(" \u2705 Advanced AI Chat");
73591
+ output3.push(" \u2705 Code Generation (300/month)");
73592
+ output3.push(" \u2705 50 file analysis/month");
73593
+ output3.push(" \u2705 4 AI models");
73594
+ output3.push(" \u2705 Community support");
73595
+ output3.push("");
73596
+ output3.push(chalk14__default.default.cyan(" Upgrade: /upgrade starter"));
73597
+ output3.push("");
73598
+ output3.push(chalk14__default.default.gray("\u2500".repeat(60)));
73599
+ output3.push("");
73600
+ output3.push(chalk14__default.default.bold.yellow("\u{1F31F} PRO - $39/month"));
73601
+ output3.push(chalk14__default.default.gray("For serious developers"));
73602
+ output3.push("");
73603
+ output3.push(" \u2705 Pro AI Chat");
73604
+ output3.push(" \u2705 Advanced Code Generation (1,200/month)");
73605
+ output3.push(" \u2705 200 file analysis/month");
73606
+ output3.push(" \u2705 6 AI models");
73607
+ output3.push(" \u2705 Community support");
73608
+ output3.push(" \u2705 API Access");
73609
+ output3.push("");
73610
+ output3.push(chalk14__default.default.cyan(" Upgrade: /upgrade pro"));
73611
+ output3.push("");
73612
+ output3.push(chalk14__default.default.gray("\u2500".repeat(60)));
73613
+ output3.push("");
73614
+ output3.push(chalk14__default.default.bold.magenta("\u{1F680} ULTRA - $99/month"));
73615
+ output3.push(chalk14__default.default.gray("For power users and teams"));
73616
+ output3.push("");
73617
+ output3.push(" \u2705 Executive AI Chat");
73618
+ output3.push(" \u2705 Professional Code Generation (5,000/month)");
73619
+ output3.push(" \u2705 500 file analysis/month");
73620
+ output3.push(" \u2705 12 AI models");
73621
+ output3.push(" \u2705 Priority support");
73622
+ output3.push(" \u2705 API Access");
73623
+ output3.push("");
73624
+ output3.push(chalk14__default.default.cyan(" Upgrade: /upgrade ultra"));
73625
+ } else if (currentPlan === "starter") {
73626
+ output3.push(chalk14__default.default.bold.yellow("\u{1F31F} Upgrade to PRO - $39/month"));
73627
+ output3.push("");
73628
+ output3.push(" \u2705 Pro AI Chat");
73629
+ output3.push(" \u2705 Advanced Code Generation (1,200/month)");
73630
+ output3.push(" \u2705 200 file analysis/month");
73631
+ output3.push(" \u2705 6 AI models");
73632
+ output3.push(" \u2705 Community support");
73633
+ output3.push(" \u2705 API Access");
73634
+ output3.push("");
73635
+ output3.push(chalk14__default.default.cyan(" Upgrade: /upgrade pro"));
73636
+ output3.push("");
73637
+ output3.push(chalk14__default.default.gray("\u2500".repeat(60)));
73638
+ output3.push("");
73639
+ output3.push(chalk14__default.default.bold.magenta("\u{1F680} Upgrade to ULTRA - $99/month"));
73640
+ output3.push("");
73641
+ output3.push(" \u2705 Executive AI Chat");
73642
+ output3.push(" \u2705 Professional Code Generation (5,000/month)");
73643
+ output3.push(" \u2705 500 file analysis/month");
73644
+ output3.push(" \u2705 12 AI models");
73645
+ output3.push(" \u2705 Priority support");
73646
+ output3.push(" \u2705 API Access");
73647
+ output3.push("");
73648
+ output3.push(chalk14__default.default.cyan(" Upgrade: /upgrade ultra"));
73649
+ } else if (currentPlan === "pro") {
73650
+ output3.push(chalk14__default.default.bold.magenta("\u{1F680} Upgrade to ULTRA - $99/month"));
73651
+ output3.push("");
73652
+ output3.push(" \u2705 Executive AI Chat");
73653
+ output3.push(" \u2705 Professional Code Generation (5,000/month)");
73654
+ output3.push(" \u2705 500 file analysis/month");
73655
+ output3.push(" \u2705 12 AI models + Local LLM");
73656
+ output3.push(" \u2705 Priority support");
73657
+ output3.push("");
73658
+ output3.push(chalk14__default.default.cyan(" Upgrade: /upgrade ultra"));
73659
+ } else {
73660
+ output3.push(chalk14__default.default.green(`\u2728 You have the ${this.getTopTierLabel(contextPlanUpper)} plan!`));
73661
+ output3.push("");
73662
+ output3.push("You already have access to all features:");
73663
+ output3.push(" \u2022 Maximum rate limits");
73664
+ output3.push(" \u2022 All premium features");
73665
+ output3.push(" \u2022 Priority support");
73666
+ }
73667
+ output3.push("");
73668
+ output3.push(chalk14__default.default.gray("\u2500".repeat(60)));
73669
+ output3.push("");
73670
+ output3.push(chalk14__default.default.gray("Compare all plans: /upgrade --compare"));
73671
+ output3.push("");
73672
+ return {
73673
+ success: true,
73674
+ message: output3.join("\n"),
73675
+ requiresInput: false,
73676
+ autoRetry: false
73677
+ };
73678
+ }
73679
+ async processUpgrade(currentPlan, targetPlan, contextPlanUpper, isAuthenticated, context2) {
73680
+ const output3 = [];
73681
+ const planHierarchy = {
73682
+ free: 0,
73683
+ starter: 1,
73684
+ pro: 2,
73685
+ ultra: 3
73686
+ };
73687
+ if (planHierarchy[targetPlan] <= planHierarchy[currentPlan]) {
73688
+ output3.push("");
73689
+ output3.push(chalk14__default.default.yellow("\u26A0\uFE0F Invalid Upgrade"));
73690
+ output3.push("");
73691
+ output3.push(`You already have the ${this.getCurrentPlanLabel(currentPlan, contextPlanUpper)} plan.`);
73692
+ if (currentPlan === "ultra" || String(contextPlanUpper || "").toUpperCase() === "ENTERPRISE") {
73693
+ output3.push("You have access to all features!");
73694
+ } else {
73695
+ output3.push(`Consider upgrading to ${targetPlan === "pro" ? "ULTRA" : "a higher plan"} for more features.`);
73696
+ }
73697
+ output3.push("");
73698
+ return {
73699
+ success: true,
73700
+ message: output3.join("\n"),
73701
+ requiresInput: false,
73702
+ autoRetry: false
73703
+ };
73704
+ }
73705
+ output3.push("");
73706
+ output3.push(chalk14__default.default.cyan("\u{1F504} Processing upgrade..."));
73707
+ output3.push("");
73708
+ output3.push(`From: ${this.getPlanBadge(currentPlan)}`);
73709
+ output3.push(`To: ${this.getPlanBadge(targetPlan)}`);
73710
+ output3.push("");
73711
+ output3.push(chalk14__default.default.gray("Opening browser for billing..."));
73712
+ output3.push("");
73713
+ let upgraded = false;
73714
+ let changedTo = null;
73715
+ try {
73716
+ const base = process.env.MARIA_API_URL || "https://maria-code.ai";
73717
+ const startCliReturnServer = async () => {
73718
+ const callbackPort = 65434;
73719
+ const callbackPath = "/cli-return";
73720
+ const http4 = await import('http');
73721
+ return new Promise((resolve19) => {
73722
+ let finished = false;
73723
+ const server = http4.createServer(async (req, res) => {
73724
+ try {
73725
+ const method = (req.method || "GET").toUpperCase();
73726
+ let status;
73727
+ let plan;
73728
+ const urlStr = `http://localhost${req.url || ""}`;
73729
+ const u = new URL(urlStr);
73730
+ if (u.pathname === callbackPath) {
73731
+ status = u.searchParams.get("status") || void 0;
73732
+ plan = u.searchParams.get("plan") || void 0;
73733
+ if (method === "POST") {
73734
+ const chunks = [];
73735
+ await new Promise((r2) => {
73736
+ req.on("data", (c) => {
73737
+ if (chunks.join("").length < 8192) chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(String(c)));
73738
+ });
73739
+ req.on("end", () => r2());
73740
+ });
73741
+ const body = Buffer.concat(chunks).toString("utf8");
73742
+ try {
73743
+ const params2 = new URLSearchParams(body);
73744
+ status = params2.get("status") || status;
73745
+ plan = params2.get("plan") || plan;
73746
+ } catch {
73747
+ }
73748
+ }
73749
+ if (process.env.MARIA_DEBUG === "1") {
73750
+ try {
73751
+ console.error("[MARIA DEBUG] CLI return inbound", { method, status, plan });
73752
+ } catch {
73753
+ }
73754
+ }
73755
+ res.writeHead(200, { "Content-Type": "text/html" });
73756
+ res.end('<html><body style="font-family:system-ui;padding:24px;text-align:center">OK. You can close this window.</body></html>');
73757
+ if (!finished && status === "success") {
73758
+ finished = true;
73759
+ setTimeout(() => {
73760
+ try {
73761
+ server.close();
73762
+ } catch {
73763
+ }
73764
+ resolve19({ status, plan });
73765
+ }, 10);
73766
+ }
73767
+ return;
73768
+ }
73769
+ } catch {
73770
+ }
73771
+ res.statusCode = 404;
73772
+ res.end("");
73773
+ });
73774
+ const timer = setTimeout(() => {
73775
+ if (!finished) {
73776
+ finished = true;
73777
+ try {
73778
+ server.close();
73779
+ } catch {
73780
+ }
73781
+ resolve19(null);
73782
+ }
73783
+ }, 18e4);
73784
+ server.listen(callbackPort, "127.0.0.1", () => {
73785
+ if (process.env.MARIA_DEBUG === "1") {
73786
+ try {
73787
+ console.error("[MARIA DEBUG] CLI return server listening", { port: callbackPort, path: callbackPath });
73788
+ } catch {
73789
+ }
73790
+ }
73791
+ });
73792
+ server.on("close", () => {
73793
+ clearTimeout(timer);
73794
+ });
73795
+ });
73796
+ };
73797
+ const cliReturnUrl = `http://localhost:65434/cli-return`;
73798
+ const targetUrl = `${base}/manage?upgrade=${encodeURIComponent(targetPlan)}&auto=1&cliReturn=${encodeURIComponent(cliReturnUrl)}`;
73799
+ const { openUrl: openUrl2 } = await Promise.resolve().then(() => (init_open_url(), open_url_exports));
73800
+ if (process.env.MARIA_DEBUG === "1") {
73801
+ console.error("[MARIA DEBUG] Open manage URL", { url: targetUrl });
73802
+ }
73803
+ const cliReturnPromise = startCliReturnServer();
73804
+ await openUrl2(targetUrl);
73805
+ try {
73806
+ const cb = await cliReturnPromise;
73807
+ if (cb && (cb.status === "success" || cb.status === "scheduled")) {
73808
+ const p = String(cb.plan || "").toLowerCase();
73809
+ if (p === "starter" || p === "pro" || p === "ultra") {
73810
+ if (cb.status === "success") {
73811
+ changedTo = p;
73812
+ upgraded = true;
73813
+ } else {
73814
+ changedTo = p;
73815
+ }
73816
+ if (process.env.MARIA_DEBUG === "1") {
73817
+ try {
73818
+ console.error("[MARIA DEBUG] LP callback received", { plan: p, status: cb.status });
73819
+ } catch {
73820
+ }
73821
+ }
73822
+ }
73823
+ }
73824
+ } catch {
73825
+ }
73826
+ try {
73827
+ const { cliAuth: cliAuth2 } = await Promise.resolve().then(() => (init_CLIAuthService(), CLIAuthService_exports));
73828
+ const { MariaAPIClient: MariaAPIClient2 } = await Promise.resolve().then(() => (init_MariaAPIClient(), MariaAPIClient_exports));
73829
+ const api = new MariaAPIClient2({
73830
+ baseUrl: "https://api.maria-code.ai",
73831
+ timeout: 3e4,
73832
+ retryAttempts: 3
73833
+ }, cliAuth2.getAuthClient());
73834
+ if (!isAuthenticated || upgraded) {
73835
+ if (process.env.MARIA_DEBUG === "1") {
73836
+ console.error("[MARIA DEBUG] Skip plan polling (no context.user)");
73837
+ }
73838
+ throw new Error("SKIP_POLLING_UNAUTHENTICATED");
73839
+ }
73840
+ const normalize3 = (v) => String(v).toLowerCase().replace(/-annual|-monthly|-yearly$/i, "");
73841
+ const targetNorm = normalize3(targetPlan);
73842
+ const initialNorm = normalize3(currentPlan);
73843
+ const start = Date.now();
73844
+ const timeoutMs = 6e5;
73845
+ const intervalMs = 3e3;
73846
+ while (Date.now() - start < timeoutMs) {
73847
+ await new Promise((r2) => setTimeout(r2, intervalMs));
73848
+ try {
73849
+ const usage = await api.getUsage();
73850
+ const code = String(usage?.planCode || usage?.planName || "").toLowerCase();
73851
+ const norm = normalize3(code);
73852
+ if (process.env.MARIA_DEBUG === "1") {
73853
+ try {
73854
+ console.error("[MARIA DEBUG] Poll tick", { endpoint: "GET /api/v1/usage", planCode: usage?.planCode, planName: usage?.planName, norm, initialNorm, targetNorm });
73855
+ } catch {
73856
+ }
73857
+ }
73858
+ if (norm !== initialNorm) {
73859
+ if (norm === "starter" || norm === "pro" || norm === "ultra") {
73860
+ changedTo = norm;
73861
+ } else {
73862
+ if (norm.includes("enterprise")) changedTo = "ultra";
73863
+ }
73864
+ if (changedTo) {
73865
+ upgraded = true;
73866
+ if (process.env.MARIA_DEBUG === "1") {
73867
+ try {
73868
+ console.error("[MARIA DEBUG] Plan change detected", { changedTo });
73869
+ } catch {
73870
+ }
73871
+ }
73872
+ break;
73873
+ }
73874
+ }
73875
+ } catch (pollErr) {
73876
+ if (process.env.MARIA_DEBUG === "1") {
73877
+ const e2 = pollErr;
73878
+ try {
73879
+ console.error("[MARIA DEBUG] Plan poll failed", { error: String(e2?.message || e2), stack: e2?.stack, name: e2?.name });
73880
+ } catch {
73881
+ }
73882
+ }
73883
+ const msg = String(pollErr?.message || pollErr);
73884
+ if (msg.includes("Authentication required")) {
73885
+ if (process.env.MARIA_DEBUG === "1") {
73886
+ try {
73887
+ console.error("[MARIA DEBUG] Stop polling due to auth error");
73888
+ } catch {
73889
+ }
73890
+ }
73891
+ break;
73892
+ }
73893
+ }
73894
+ }
73895
+ } catch (pollSetupErr) {
73896
+ const msg = String(pollSetupErr?.message || pollSetupErr);
73897
+ if (process.env.MARIA_DEBUG === "1" && msg !== "SKIP_POLLING_UNAUTHENTICATED") {
73898
+ console.error("[MARIA DEBUG] Plan polling setup failed", { error: msg });
73899
+ }
73900
+ }
73901
+ } catch (e2) {
73902
+ if (process.env.MARIA_DEBUG === "1") {
73903
+ console.error("[MARIA DEBUG] Failed to open manage URL", { error: String(e2?.message || e2) });
73904
+ }
73905
+ upgraded = false;
73906
+ }
73907
+ if (upgraded && changedTo) {
73908
+ output3.push(chalk14__default.default.green("\u2705 Upgrade Successful!"));
73909
+ output3.push("");
73910
+ output3.push(`Welcome to ${this.getPlanBadge(changedTo)}!`);
73911
+ output3.push("");
73912
+ const planToDescribe = changedTo;
73913
+ if (planToDescribe === "starter") {
73914
+ output3.push("You now have access to:");
73915
+ output3.push(" \u2022 Advanced AI Chat");
73916
+ output3.push(" \u2022 Code Generation (300/month)");
73917
+ output3.push(" \u2022 50 file analysis/month");
73918
+ output3.push(" \u2022 4 AI models");
73919
+ output3.push(" \u2022 Community support");
73920
+ } else if (planToDescribe === "pro") {
73921
+ output3.push("You now have access to:");
73922
+ output3.push(" \u2022 Pro AI Chat");
73923
+ output3.push(" \u2022 Advanced Code Generation (1,200/month)");
73924
+ output3.push(" \u2022 200 file analysis/month");
73925
+ output3.push(" \u2022 6 AI models");
73926
+ output3.push(" \u2022 Community support");
73927
+ output3.push(" \u2022 API Access");
73928
+ } else if (planToDescribe === "ultra") {
73929
+ output3.push("You now have access to:");
73930
+ output3.push(" \u2022 Executive AI Chat");
73931
+ output3.push(" \u2022 Professional Code Generation (5,000/month)");
73932
+ output3.push(" \u2022 500 file analysis/month");
73933
+ output3.push(" \u2022 12 AI models");
73934
+ output3.push(" \u2022 Priority support");
73935
+ output3.push(" \u2022 API Access");
73936
+ }
73937
+ output3.push("");
73938
+ output3.push(chalk14__default.default.cyan("Try your new features (after billing completes):"));
73939
+ output3.push(' /code "Refactor module"');
73940
+ output3.push(' /image "logo in matrix style"');
73941
+ output3.push(' /video "product teaser"');
73942
+ output3.push("");
73943
+ } else {
73944
+ output3.push(chalk14__default.default.yellow("\u23F3 Billing in progress"));
73945
+ output3.push("");
73946
+ output3.push("The billing portal or checkout was opened in your browser.");
73947
+ output3.push("We did not detect a plan change yet. Complete the process and run /whoami to verify.");
73948
+ }
73949
+ try {
73950
+ const { WhoAmICommand: WhoAmICommand2 } = await Promise.resolve().then(() => (init_WhoAmICommand(), WhoAmICommand_exports));
73951
+ const whoami = new WhoAmICommand2();
73952
+ const who = await whoami.execute({}, context2);
73953
+ if (who?.message) {
73954
+ output3.push("");
73955
+ output3.push(chalk14__default.default.gray("\u2500".repeat(60)));
73956
+ output3.push("");
73957
+ output3.push(chalk14__default.default.cyan("Current account status"));
73958
+ output3.push(who.message);
73959
+ }
73960
+ } catch {
73961
+ }
73962
+ return {
73963
+ success: upgraded,
73964
+ message: output3.join("\n"),
73965
+ requiresInput: false,
73966
+ autoRetry: false
73967
+ };
73968
+ }
73969
+ getPlanBadge(plan) {
73970
+ const badges = {
73971
+ free: chalk14__default.default.gray("[FREE]"),
73972
+ starter: chalk14__default.default.bgBlue.black(" STARTER "),
73973
+ pro: chalk14__default.default.bgYellow.black(" PRO "),
73974
+ ultra: chalk14__default.default.bgMagenta.white(" ULTRA ")
73975
+ };
73976
+ return badges[plan];
73977
+ }
73978
+ getCurrentPlanLabel(plan, contextPlanUpper) {
73979
+ try {
73980
+ if (String(contextPlanUpper || "").toUpperCase() === "ENTERPRISE") {
73981
+ return chalk14__default.default.bgMagenta.white(" ENTERPRISE ");
73982
+ }
73983
+ const envPlan = String(process.env.MARIA_PLAN || "").toUpperCase();
73984
+ if (envPlan === "ENTERPRISE") return chalk14__default.default.bgMagenta.white(" ENTERPRISE ");
73985
+ } catch {
73986
+ }
73987
+ return this.getPlanBadge(plan);
73988
+ }
73989
+ getTopTierLabel(contextPlanUpper) {
73990
+ try {
73991
+ if (String(contextPlanUpper || "").toUpperCase() === "ENTERPRISE") {
73992
+ return "ENTERPRISE";
73993
+ }
73994
+ const envPlan = String(process.env.MARIA_PLAN || "").toUpperCase();
73995
+ if (envPlan === "ENTERPRISE") return "ENTERPRISE";
73996
+ } catch {
73997
+ }
73998
+ return "ULTRA";
73999
+ }
74000
+ async handleError(error2) {
74001
+ return {
74002
+ success: false,
74003
+ message: `Failed to process upgrade: ${error2.message}`,
74004
+ requiresInput: false,
74005
+ autoRetry: false
74006
+ };
74007
+ }
74008
+ };
74009
+ meta26 = {
74010
+ name: "upgrade",
74011
+ category: "system",
74012
+ description: "Upgrade your subscription plan",
74013
+ aliases: ["pro", "ultra", "premium", "subscribe"],
74014
+ usage: "/upgrade [starter|pro|ultra] [--compare]",
74015
+ examples: [
74016
+ "/upgrade",
74017
+ "/upgrade starter",
74018
+ "/upgrade pro",
74019
+ "/upgrade ultra",
74020
+ "/upgrade --compare"
74021
+ ],
74022
+ deps: []
74023
+ };
74024
+ }
74025
+ });
72817
74026
  var CriteriaManager;
72818
74027
  var init_CriteriaManager = __esm({
72819
74028
  "src/services/evaluation/CriteriaManager.ts"() {
@@ -73229,7 +74438,7 @@ ${user}`,
73229
74438
  };
73230
74439
  }
73231
74440
  });
73232
- function extractFirstJson6(text) {
74441
+ function extractFirstJson7(text) {
73233
74442
  const fence = /```json\r?\n([\s\S]*?)```/i.exec(text);
73234
74443
  if (fence) return fence[1];
73235
74444
  const start = text.indexOf("{");
@@ -73291,7 +74500,7 @@ ${user}`,
73291
74500
  }
73292
74501
  });
73293
74502
  const raw = (response?.data?.content || response?.output || "").trim();
73294
- const jsonText = extractFirstJson6(raw) || raw;
74503
+ const jsonText = extractFirstJson7(raw) || raw;
73295
74504
  let parsed = {};
73296
74505
  try {
73297
74506
  parsed = JSON.parse(jsonText);
@@ -73325,9 +74534,9 @@ var evaluate_command_exports = {};
73325
74534
  __export(evaluate_command_exports, {
73326
74535
  EvaluateCommand: () => EvaluateCommand,
73327
74536
  default: () => evaluate_command_default,
73328
- meta: () => meta26
74537
+ meta: () => meta27
73329
74538
  });
73330
- var EvaluateCommand, meta26, evaluate_command_default;
74539
+ var EvaluateCommand, meta27, evaluate_command_default;
73331
74540
  var init_evaluate_command = __esm({
73332
74541
  "src/slash-commands/categories/evaluation/evaluate.command.ts"() {
73333
74542
  init_base_command();
@@ -74053,7 +75262,7 @@ ${content}` : content;
74053
75262
  return { success: true };
74054
75263
  }
74055
75264
  };
74056
- meta26 = {
75265
+ meta27 = {
74057
75266
  name: "evaluate",
74058
75267
  category: "evaluation",
74059
75268
  description: "A/B testing and quality evaluation framework",
@@ -74504,15 +75713,22 @@ async function registerBuiltInCommands() {
74504
75713
  initialize: async () => {
74505
75714
  }
74506
75715
  });
74507
- commandRegistry.register({
74508
- name: "upgrade",
74509
- category: "system",
74510
- description: "Upgrade MARIA",
74511
- aliases: [],
74512
- execute: async () => shield2({ message: "\u{1F512} Coming soon", showWaitlist: true }),
74513
- initialize: async () => {
74514
- }
74515
- });
75716
+ try {
75717
+ const { UpgradeCommand: UpgradeCommand2 } = await Promise.resolve().then(() => (init_upgrade_command(), upgrade_command_exports));
75718
+ const upgrade = new UpgradeCommand2();
75719
+ if (upgrade.initialize) await upgrade.initialize();
75720
+ commandRegistry.register(upgrade);
75721
+ } catch {
75722
+ commandRegistry.register({
75723
+ name: "upgrade",
75724
+ category: "system",
75725
+ description: "Upgrade your subscription plan",
75726
+ aliases: ["pro", "ultra", "premium", "subscribe"],
75727
+ execute: async () => shield2({ message: "\u{1F512} Coming soon", showWaitlist: true }),
75728
+ initialize: async () => {
75729
+ }
75730
+ });
75731
+ }
74516
75732
  } catch (error2) {
74517
75733
  console.error("Failed to register system _commands:", error2);
74518
75734
  }
@@ -77204,13 +78420,13 @@ ${options.map((opt, i2) => `${i2 + 1}) ${opt}`).join("\n")}`;
77204
78420
  const lines = response.split("\n");
77205
78421
  for (let i2 = 0; i2 < lines.length; i2++) {
77206
78422
  callback(lines[i2]);
77207
- let delay = 40;
78423
+ let delay2 = 40;
77208
78424
  const line = lines[i2];
77209
- if (line.trim().length === 0) delay = 20;
77210
- else if (line.includes("```")) delay = 60;
77211
- else if (/[.!?]$/.test(line)) delay = 80;
78425
+ if (line.trim().length === 0) delay2 = 20;
78426
+ else if (line.includes("```")) delay2 = 60;
78427
+ else if (/[.!?]$/.test(line)) delay2 = 80;
77212
78428
  if (i2 < lines.length - 1)
77213
- await new Promise((r2) => setTimeout(r2, delay));
78429
+ await new Promise((r2) => setTimeout(r2, delay2));
77214
78430
  }
77215
78431
  }
77216
78432
  };
@@ -78009,8 +79225,8 @@ async function runServerMode() {
78009
79225
  console.error(chalk14__default.default.white("Searched dirs: " + candidateDirs.join(" | ")));
78010
79226
  process.exit(1);
78011
79227
  }
78012
- const { spawn: spawn4 } = await import('child_process');
78013
- const serverProcess = spawn4("node", [serverPath], {
79228
+ const { spawn: spawn5 } = await import('child_process');
79229
+ const serverProcess = spawn5("node", [serverPath], {
78014
79230
  stdio: "inherit",
78015
79231
  env: process.env,
78016
79232
  cwd: path12__namespace.dirname(serverPath)