@bonginkan/maria 4.3.36 → 4.3.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -12,6 +12,7 @@ var os10 = require('os');
12
12
  var child_process = require('child_process');
13
13
  var fsp = require('fs/promises');
14
14
  var secretManager = require('@google-cloud/secret-manager');
15
+ var https = require('https');
15
16
  var events = require('events');
16
17
  var Stream2 = require('stream');
17
18
  var string_decoder = require('string_decoder');
@@ -19,7 +20,6 @@ var fs6 = require('fs-extra');
19
20
  var util = require('util');
20
21
  var promises = require('timers/promises');
21
22
  var dns = require('dns/promises');
22
- var https = require('https');
23
23
  var zod = require('zod');
24
24
  var process6 = require('process');
25
25
  var readline = require('readline');
@@ -63,10 +63,10 @@ var http2__namespace = /*#__PURE__*/_interopNamespace(http2);
63
63
  var url__namespace = /*#__PURE__*/_interopNamespace(url);
64
64
  var os10__namespace = /*#__PURE__*/_interopNamespace(os10);
65
65
  var fsp__namespace = /*#__PURE__*/_interopNamespace(fsp);
66
+ var https__default = /*#__PURE__*/_interopDefault(https);
66
67
  var Stream2__default = /*#__PURE__*/_interopDefault(Stream2);
67
68
  var fs6__namespace = /*#__PURE__*/_interopNamespace(fs6);
68
69
  var dns__default = /*#__PURE__*/_interopDefault(dns);
69
- var https__default = /*#__PURE__*/_interopDefault(https);
70
70
  var process6__namespace = /*#__PURE__*/_interopNamespace(process6);
71
71
  var readline__namespace = /*#__PURE__*/_interopNamespace(readline);
72
72
  var zlib__default = /*#__PURE__*/_interopDefault(zlib);
@@ -1709,7 +1709,7 @@ var init_AuthenticationManager = __esm({
1709
1709
  const response = await fetch(`${this.apiBase}/api/user/profile`, {
1710
1710
  headers: {
1711
1711
  "Authorization": `Bearer ${tokens2.accessToken}`,
1712
- "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.3.36"}`
1712
+ "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.3.37"}`
1713
1713
  }
1714
1714
  });
1715
1715
  if (response.status === 401) {
@@ -2434,7 +2434,7 @@ async function callApi(path64, init3 = {}) {
2434
2434
  "Authorization": `Bearer ${token}`,
2435
2435
  "X-Device-Id": getDeviceId(),
2436
2436
  "X-Session-Id": getSessionId() || "",
2437
- "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.3.36"}`,
2437
+ "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.3.37"}`,
2438
2438
  "Content-Type": init3.headers?.["Content-Type"] || "application/json"
2439
2439
  });
2440
2440
  const doFetch = async (token) => {
@@ -3056,109 +3056,199 @@ var init_choice_memory = __esm({
3056
3056
  }
3057
3057
  });
3058
3058
 
3059
- // src/services/interactive/triage-orchestrator.ts
3060
- function getConfidenceBand(score) {
3061
- if (score >= TRIAGE_THRESHOLDS.high) {
3062
- return "high";
3059
+ // src/services/cli-auth/api-caller.ts
3060
+ var api_caller_exports = {};
3061
+ __export(api_caller_exports, {
3062
+ RateLimitError: () => RateLimitError,
3063
+ callAPI: () => callAPI,
3064
+ executeAIProxy: () => executeAIProxy,
3065
+ executeChat: () => executeChat,
3066
+ executeCode: () => executeCode
3067
+ });
3068
+ async function callAPI(endpoint, options = {}) {
3069
+ const tokens2 = await authManager2.getValidTokens();
3070
+ if (!tokens2) {
3071
+ throw new Error("Authentication required. Please run /login first.");
3063
3072
  }
3064
- if (score >= TRIAGE_THRESHOLDS.mid) {
3065
- return "mid";
3073
+ const apiBase = process.env.MARIA_API_BASE || "https://api.maria-code.ai";
3074
+ const url2 = `${apiBase}${endpoint}`;
3075
+ const controller = new AbortController();
3076
+ const defaultMs = 6e5;
3077
+ const envMs = Number(process.env.MARIA_API_TIMEOUT_MS || process.env.MARIA_CODE_TIMEOUT_MS || defaultMs);
3078
+ const timeoutMs = Number.isFinite(envMs) && envMs > 0 ? envMs : defaultMs;
3079
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
3080
+ try {
3081
+ const response = await fetch(url2, {
3082
+ method: options.method || "GET",
3083
+ headers: {
3084
+ "Authorization": `Bearer ${tokens2.accessToken}`,
3085
+ "Content-Type": "application/json",
3086
+ ...options.headers
3087
+ },
3088
+ body: options.body ? JSON.stringify(options.body) : void 0,
3089
+ // Note: fetch in Node doesn't accept 'agent' in our typing here; relying on global agent not necessary
3090
+ signal: controller.signal
3091
+ });
3092
+ clearTimeout(timeoutId);
3093
+ if (!response) {
3094
+ throw new Error("\u{1F310} Network error, check connection");
3095
+ }
3096
+ if (response.status === 401) {
3097
+ throw new Error("Session expired. Please run /login again.");
3098
+ }
3099
+ if (response.status === 402) {
3100
+ const data2 = await response.json().catch(() => ({}));
3101
+ throw new Error(`Quota exceeded: ${typeof data2?.message === "string" ? data2.message : "Please wait or /upgrade"}`);
3102
+ }
3103
+ if (response.status === 403) {
3104
+ const data2 = await response.json().catch(() => ({}));
3105
+ throw new Error(`Not available on Free plan: ${typeof data2?.message === "string" ? data2.message : "Run /upgrade"}`);
3106
+ }
3107
+ if (response.status === 429) {
3108
+ const h2 = response.headers;
3109
+ const ra = h2.get("Retry-After");
3110
+ const reset = h2.get("RateLimit-Reset") || h2.get("X-RateLimit-Reset");
3111
+ let waitSec = 3;
3112
+ if (ra && /^\d+$/.test(ra)) {
3113
+ waitSec = +ra;
3114
+ } else if (ra) {
3115
+ const t2 = Date.parse(ra);
3116
+ if (!isNaN(t2)) waitSec = Math.max(1, Math.ceil((t2 - Date.now()) / 1e3));
3117
+ } else if (reset) {
3118
+ waitSec = Math.max(1, Math.ceil((+reset - Date.now()) / 1e3));
3119
+ }
3120
+ throw new RateLimitError(`\u23F1 Wait ${waitSec}s`, waitSec);
3121
+ }
3122
+ if (!response.ok) {
3123
+ const data2 = await response.json().catch(() => ({}));
3124
+ const msg = typeof data2?.error === "string" ? data2.error : `Request failed: ${response.statusText}`;
3125
+ throw new Error(msg);
3126
+ }
3127
+ const data = await response.json();
3128
+ return data;
3129
+ } catch (error2) {
3130
+ clearTimeout(timeoutId);
3131
+ const err = error2;
3132
+ if (err && err.name === "AbortError") {
3133
+ throw new Error("\u{1F310} Network error, check connection");
3134
+ }
3135
+ throw err;
3066
3136
  }
3067
- return "low";
3068
3137
  }
3069
- async function triage(input3, ctx2 = {}) {
3070
- const question = (input3 || "").trim();
3071
- if (!question) {
3072
- return {
3073
- type: "simple",
3074
- confidence: 0.3,
3075
- rationale: ["empty"],
3076
- band: "low"
3077
- };
3138
+ async function executeChat(messages) {
3139
+ const response = await callAPI("/v1/chat", {
3140
+ method: "POST",
3141
+ body: { messages }
3142
+ });
3143
+ return response;
3144
+ }
3145
+ async function executeCode(input3) {
3146
+ const isOptions = typeof input3 === "object";
3147
+ const prompt = isOptions ? input3.prompt : input3;
3148
+ const provider = isOptions ? input3.provider : void 0;
3149
+ const model = isOptions ? input3.model : void 0;
3150
+ const attachments = isOptions ? input3.attachments : void 0;
3151
+ const body = { prompt, taskType: "code" };
3152
+ if (provider) body.provider = provider;
3153
+ if (model) body.model = model;
3154
+ if (attachments && attachments.length > 0) {
3155
+ body.metadata = { attachments };
3078
3156
  }
3079
- const lower2 = question.toLowerCase();
3080
- const rationale = [];
3081
- if (ctx2.recentCommands?.length) {
3082
- const last = ctx2.recentCommands[ctx2.recentCommands.length - 1];
3083
- if (typeof last === "string" && last.startsWith("/code")) {
3084
- rationale.push("recent:/code");
3085
- }
3157
+ const response = await callAPI("/v1/ai-proxy", {
3158
+ method: "POST",
3159
+ body
3160
+ });
3161
+ if (response.data?.routedModel) {
3162
+ response.routedModel = response.data.routedModel;
3086
3163
  }
3087
- if (IMAGE_REGEX.test(lower2)) {
3088
- rationale.push("match:image");
3089
- return {
3090
- type: "route-image",
3091
- confidence: 0.82,
3092
- rationale,
3093
- band: "high",
3094
- next: { route: "/image", args: [question] }
3095
- };
3164
+ if (response.data?.content) {
3165
+ response.output = response.data.content;
3096
3166
  }
3097
- if (VIDEO_REGEX.test(lower2)) {
3098
- rationale.push("match:video");
3099
- return {
3100
- type: "route-video",
3101
- confidence: 0.82,
3102
- rationale,
3103
- band: "high",
3104
- next: { route: "/video", args: [question] }
3167
+ return response;
3168
+ }
3169
+ async function executeAIProxy(provider, model, messages, options) {
3170
+ return callAPI("/v1/ai-proxy", {
3171
+ method: "POST",
3172
+ body: { provider, model, messages, options }
3173
+ });
3174
+ }
3175
+ var authManager2, RateLimitError;
3176
+ var init_api_caller = __esm({
3177
+ "src/services/cli-auth/api-caller.ts"() {
3178
+ init_AuthenticationManager();
3179
+ new https__default.default.Agent({ keepAlive: true });
3180
+ authManager2 = new AuthenticationManager();
3181
+ RateLimitError = class extends Error {
3182
+ constructor(message, retryAfter) {
3183
+ super(message);
3184
+ this.retryAfter = retryAfter;
3185
+ this.name = "RateLimitError";
3186
+ }
3105
3187
  };
3106
3188
  }
3107
- if (CODE_REGEX.test(lower2)) {
3108
- rationale.push("match:code");
3109
- const args2 = normalizeRouteArgs(["--plan-only", question]);
3110
- return {
3111
- type: "route-code",
3112
- confidence: 0.78,
3113
- rationale,
3114
- band: "high",
3115
- next: { route: "/code", args: args2 }
3116
- };
3189
+ });
3190
+
3191
+ // src/services/intelligent-router/LlmTopLevelRouter.ts
3192
+ function extractFirstJson(text) {
3193
+ const fence = /```json\r?\n([\s\S]*?)```/i.exec(text);
3194
+ if (fence) return fence[1];
3195
+ const start = text.indexOf("{");
3196
+ const end = text.lastIndexOf("}");
3197
+ if (start >= 0 && end > start) {
3198
+ const cand = text.slice(start, end + 1);
3199
+ try {
3200
+ JSON.parse(cand);
3201
+ return cand;
3202
+ } catch {
3203
+ }
3117
3204
  }
3118
- if (question.length > 220 || MULTI_SCOPE_REGEX.test(lower2) || /\b(ui|api|backend|database|テスト|設計|要件)\b/.test(lower2)) {
3119
- rationale.push("scope:multi");
3120
- const confidence = question.length > 220 ? 0.72 : 0.6;
3121
- return {
3122
- type: "complex",
3123
- confidence,
3124
- rationale,
3125
- band: getConfidenceBand(confidence)
3126
- };
3205
+ return null;
3206
+ }
3207
+ async function mapInputToTopLevelCommand(input3) {
3208
+ const system = [
3209
+ "You are a router for the MARIA CLI.",
3210
+ "Decide the best command for a single user input.",
3211
+ "Allowed commands: /help, /image, /code, /video, /whoami, /login, /logout, /evaluate, chat.",
3212
+ "Note that /image and /video are for generating them. If a path of a file is provided, you should double think why it's referenced (it may be for coding or chatting or other commands, regarding on the context).",
3213
+ 'Return JSON only with keys: { "command": string, "args"?: string[], "confidence": number }.',
3214
+ "Select chat when the input is a general question or conversation rather than a specific slash command.",
3215
+ "Make sure you set the confidence between 0 and 1.",
3216
+ "Only include args if necessary to pass user content to the command. Do not explain."
3217
+ ].join("\n");
3218
+ const resp = await callAPI("/v1/ai-proxy", {
3219
+ method: "POST",
3220
+ body: {
3221
+ prompt: `${system}
3222
+
3223
+ ---
3224
+
3225
+ ${input3}`,
3226
+ taskType: "routing"
3227
+ }
3228
+ });
3229
+ const raw = (resp?.data?.content || resp?.output || "").trim();
3230
+ const jsonText = extractFirstJson(raw) || raw;
3231
+ let parsed = {};
3232
+ try {
3233
+ parsed = JSON.parse(jsonText);
3234
+ } catch {
3235
+ return null;
3127
3236
  }
3128
- if (question.length <= 140 && QUESTION_REGEX.test(lower2)) {
3129
- rationale.push("short+qa");
3130
- const confidence = question.length < 80 ? 0.72 : 0.62;
3131
- return {
3132
- type: "simple",
3133
- confidence,
3134
- rationale,
3135
- band: getConfidenceBand(confidence)
3136
- };
3237
+ if (!parsed || typeof parsed.command !== "string") return null;
3238
+ const cmd = parsed.command;
3239
+ if (!["/help", "/image", "/code", "/video", "/whoami", "/login", "/logout", "/evaluate", "chat"].includes(cmd)) return null;
3240
+ const out = { command: cmd };
3241
+ if (Array.isArray(parsed.args)) {
3242
+ out.args = parsed.args.filter((a) => typeof a === "string" && a.trim()).map((s2) => s2.trim());
3137
3243
  }
3138
- rationale.push("default:complex");
3139
- const fallbackConfidence = question.length > 80 ? 0.5 : 0.4;
3140
- return {
3141
- type: "complex",
3142
- confidence: fallbackConfidence,
3143
- rationale,
3144
- band: getConfidenceBand(fallbackConfidence)
3145
- };
3146
- }
3147
- function normalizeRouteArgs(args2 = []) {
3148
- return args2.map((arg) => arg.trim()).filter((arg) => arg.length > 0);
3244
+ if (typeof parsed.confidence === "number") {
3245
+ out.confidence = Math.max(0, Math.min(1, parsed.confidence));
3246
+ }
3247
+ return out;
3149
3248
  }
3150
- var TRIAGE_THRESHOLDS, QUESTION_REGEX, CODE_REGEX, IMAGE_REGEX, VIDEO_REGEX, MULTI_SCOPE_REGEX;
3151
- var init_triage_orchestrator = __esm({
3152
- "src/services/interactive/triage-orchestrator.ts"() {
3153
- TRIAGE_THRESHOLDS = Object.freeze({
3154
- high: 0.7,
3155
- mid: 0.35
3156
- });
3157
- QUESTION_REGEX = /(how|what|why|when|どの|どう|なぜ|いつ|とは)\b/i;
3158
- CODE_REGEX = /(create|generate|add|refactor|fix|test|route|build|component|migration|implement|実装|生成|追加|修正)/i;
3159
- IMAGE_REGEX = /(image|画像|svg|png|webp|thumbnail|illustration|アート|描いて)/i;
3160
- VIDEO_REGEX = /(video|動画|mp4|webm|frames|storyboard|アニメーション)/i;
3161
- MULTI_SCOPE_REGEX = /(\band\b|\balso\b|\s+,+\s+)/i;
3249
+ var init_LlmTopLevelRouter = __esm({
3250
+ "src/services/intelligent-router/LlmTopLevelRouter.ts"() {
3251
+ init_api_caller();
3162
3252
  }
3163
3253
  });
3164
3254
 
@@ -3490,7 +3580,7 @@ var init_unknown_command = __esm({
3490
3580
  });
3491
3581
 
3492
3582
  // src/slash-commands/types.ts
3493
- var CommandError, ValidationError, PermissionError, RateLimitError;
3583
+ var CommandError, ValidationError, PermissionError, RateLimitError2;
3494
3584
  var init_types2 = __esm({
3495
3585
  "src/slash-commands/types.ts"() {
3496
3586
  CommandError = class extends Error {
@@ -3516,7 +3606,7 @@ var init_types2 = __esm({
3516
3606
  this.name = "PermissionError";
3517
3607
  }
3518
3608
  };
3519
- RateLimitError = class extends CommandError {
3609
+ RateLimitError2 = class extends CommandError {
3520
3610
  constructor(message, retryAfter) {
3521
3611
  super(message, "RATE_LIMIT_ERROR", 429);
3522
3612
  this.retryAfter = retryAfter;
@@ -10965,8 +11055,7 @@ var init_registry = __esm({
10965
11055
  const { ChatContextService: ChatContextService3 } = await Promise.resolve().then(() => (init_chat_context_service(), chat_context_service_exports));
10966
11056
  const ctxSvc = ChatContextService3.getInstance();
10967
11057
  const usageLine = ctxSvc.getSessionUsageLine();
10968
- const suffix = `
10969
- ${usageLine}`;
11058
+ const suffix = ``;
10970
11059
  result.message = (result.message || "").concat(suffix);
10971
11060
  } catch {
10972
11061
  }
@@ -11030,7 +11119,7 @@ ${usageLine}`;
11030
11119
  }
11031
11120
  }
11032
11121
  } catch (innerError) {
11033
- logger.error(`Failed to load command from ${file}:`, error);
11122
+ logger.error(`Failed to load command from ${file}:`, innerError);
11034
11123
  }
11035
11124
  }
11036
11125
  this.initialized = true;
@@ -11067,8 +11156,8 @@ ${usageLine}`;
11067
11156
  try {
11068
11157
  return await next();
11069
11158
  } catch (innerError) {
11070
- logger.error(`Command ${command.name} failed:`, error);
11071
- throw error;
11159
+ logger.error(`Command ${command.name} failed:`, innerError);
11160
+ throw innerError;
11072
11161
  }
11073
11162
  }
11074
11163
  });
@@ -12132,7 +12221,7 @@ var init_clear_auto_command = __esm({
12132
12221
  const args2 = mode === "display" ? ["--mode", "display"] : [];
12133
12222
  const res = await commandRegistry2.execute("/clear", args2, context2);
12134
12223
  const line = ctx2.getSessionUsageLine();
12135
- const banner = `Auto clear mode: ${mode} \xB7 ${line}`;
12224
+ const banner = `Auto clear mode: ${mode}`;
12136
12225
  if (res?.success) {
12137
12226
  return this.success(`${banner}
12138
12227
  ${res.message || ""}`.trim());
@@ -12798,6 +12887,69 @@ var init_ReadyCommandsService = __esm({
12798
12887
  }
12799
12888
  });
12800
12889
 
12890
+ // src/services/help/HelpArgumentInference.ts
12891
+ function extractFirstJson2(text) {
12892
+ const fence = /```json\r?\n([\s\S]*?)```/i.exec(text);
12893
+ if (fence) return fence[1];
12894
+ const start = text.indexOf("{");
12895
+ const end = text.lastIndexOf("}");
12896
+ if (start >= 0 && end > start) {
12897
+ const cand = text.slice(start, end + 1);
12898
+ try {
12899
+ JSON.parse(cand);
12900
+ return cand;
12901
+ } catch {
12902
+ }
12903
+ }
12904
+ return null;
12905
+ }
12906
+ async function inferHelpTarget(rawText, allowedCommands) {
12907
+ const allowList = allowedCommands.filter((n) => typeof n === "string" && n.trim()).map((n) => n.trim()).slice(0, 200);
12908
+ const system = [
12909
+ "You decide which help to show for the MARIA CLI.",
12910
+ 'Allowed results: { target: "general" } or { target: "command", commandName: <one of allowed> }.',
12911
+ 'Return JSON only with keys: { "target": "general"|"command", "commandName"?: string, "confidence": number }.',
12912
+ "If the user asks about a specific command (by name or description), select that command. Otherwise choose general.",
12913
+ "Use confidence between 0 and 1. Do not explain."
12914
+ ].join("\n");
12915
+ const user = [
12916
+ "User input:",
12917
+ rawText || "(empty)",
12918
+ "",
12919
+ "Allowed command names:",
12920
+ allowList.join(", ")
12921
+ ].join("\n");
12922
+ const resp = await callAPI("/v1/ai-proxy", {
12923
+ method: "POST",
12924
+ body: {
12925
+ prompt: `${system}
12926
+
12927
+ ---
12928
+
12929
+ ${user}`,
12930
+ taskType: "help"
12931
+ }
12932
+ });
12933
+ const raw = (resp?.data?.content || resp?.output || "").trim();
12934
+ const jsonText = extractFirstJson2(raw) || raw;
12935
+ let parsed = {};
12936
+ try {
12937
+ parsed = JSON.parse(jsonText);
12938
+ } catch {
12939
+ return {};
12940
+ }
12941
+ const out = {};
12942
+ if (parsed.target === "general" || parsed.target === "command") out.target = parsed.target;
12943
+ if (typeof parsed.commandName === "string" && parsed.commandName.trim()) out.commandName = parsed.commandName.trim();
12944
+ if (typeof parsed.confidence === "number") out.confidence = Math.max(0, Math.min(1, parsed.confidence));
12945
+ return out;
12946
+ }
12947
+ var init_HelpArgumentInference = __esm({
12948
+ "src/services/help/HelpArgumentInference.ts"() {
12949
+ init_api_caller();
12950
+ }
12951
+ });
12952
+
12801
12953
  // src/slash-commands/categories/core/handlers/HelpCommand.ts
12802
12954
  var HelpCommand_exports = {};
12803
12955
  __export(HelpCommand_exports, {
@@ -12811,6 +12963,8 @@ var init_HelpCommand = __esm({
12811
12963
  init_ReadyCommandsService();
12812
12964
  init_telemetry_helper();
12813
12965
  init_subscription_manager();
12966
+ init_HelpArgumentInference();
12967
+ init_animations();
12814
12968
  HelpCommand = class extends BaseCommand {
12815
12969
  name = "help";
12816
12970
  category = "core";
@@ -12859,6 +13013,26 @@ var init_HelpCommand = __esm({
12859
13013
  await this.trackSuccess(startTime, context2);
12860
13014
  return result2;
12861
13015
  }
13016
+ const text = (args2.raw || []).join(" ").trim();
13017
+ if (text) {
13018
+ const commandsList = (await this.readyService.getAllReadyCommands()).map((c) => c.name);
13019
+ const spin = new ProcessAnimation();
13020
+ spin.start();
13021
+ try {
13022
+ const inferred = await inferHelpTarget(text, commandsList);
13023
+ const threshold = Number(process.env.MARIA_HELP_CONFIDENCE || "0.7");
13024
+ if (inferred && inferred.target === "command" && inferred.commandName && (inferred.confidence ?? 1) >= threshold) {
13025
+ const result2 = await this.showCommandHelp(inferred.commandName);
13026
+ await this.trackSuccess(startTime, context2);
13027
+ return result2;
13028
+ }
13029
+ } finally {
13030
+ try {
13031
+ spin.stop();
13032
+ } catch {
13033
+ }
13034
+ }
13035
+ }
12862
13036
  if (_positional.length > 0) {
12863
13037
  const commandName = _positional[0];
12864
13038
  if (commandName) {
@@ -16208,8 +16382,8 @@ var require_package = __commonJS({
16208
16382
  "package.json"(exports, module) {
16209
16383
  module.exports = {
16210
16384
  name: "@bonginkan/maria",
16211
- version: "4.3.36",
16212
- description: "\u{1F680} MARIA v4.3.36 - 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.",
16385
+ version: "4.3.37",
16386
+ description: "\u{1F680} MARIA v4.3.37 - 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.",
16213
16387
  keywords: [
16214
16388
  "ai",
16215
16389
  "cli",
@@ -22402,140 +22576,8 @@ var init_NLInference = __esm({
22402
22576
  }
22403
22577
  });
22404
22578
 
22405
- // src/services/cli-auth/api-caller.ts
22406
- var api_caller_exports = {};
22407
- __export(api_caller_exports, {
22408
- RateLimitError: () => RateLimitError2,
22409
- callAPI: () => callAPI,
22410
- executeAIProxy: () => executeAIProxy,
22411
- executeChat: () => executeChat,
22412
- executeCode: () => executeCode
22413
- });
22414
- async function callAPI(endpoint, options = {}) {
22415
- const tokens2 = await authManager2.getValidTokens();
22416
- if (!tokens2) {
22417
- throw new Error("Authentication required. Please run /login first.");
22418
- }
22419
- const apiBase = process.env.MARIA_API_BASE || "https://api.maria-code.ai";
22420
- const url2 = `${apiBase}${endpoint}`;
22421
- const controller = new AbortController();
22422
- const defaultMs = 6e5;
22423
- const envMs = Number(process.env.MARIA_API_TIMEOUT_MS || process.env.MARIA_CODE_TIMEOUT_MS || defaultMs);
22424
- const timeoutMs = Number.isFinite(envMs) && envMs > 0 ? envMs : defaultMs;
22425
- const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
22426
- try {
22427
- const response = await fetch(url2, {
22428
- method: options.method || "GET",
22429
- headers: {
22430
- "Authorization": `Bearer ${tokens2.accessToken}`,
22431
- "Content-Type": "application/json",
22432
- ...options.headers
22433
- },
22434
- body: options.body ? JSON.stringify(options.body) : void 0,
22435
- // Note: fetch in Node doesn't accept 'agent' in our typing here; relying on global agent not necessary
22436
- signal: controller.signal
22437
- });
22438
- clearTimeout(timeoutId);
22439
- if (!response) {
22440
- throw new Error("\u{1F310} Network error, check connection");
22441
- }
22442
- if (response.status === 401) {
22443
- throw new Error("Session expired. Please run /login again.");
22444
- }
22445
- if (response.status === 402) {
22446
- const data2 = await response.json().catch(() => ({}));
22447
- throw new Error(`Quota exceeded: ${typeof data2?.message === "string" ? data2.message : "Please wait or /upgrade"}`);
22448
- }
22449
- if (response.status === 403) {
22450
- const data2 = await response.json().catch(() => ({}));
22451
- throw new Error(`Not available on Free plan: ${typeof data2?.message === "string" ? data2.message : "Run /upgrade"}`);
22452
- }
22453
- if (response.status === 429) {
22454
- const h2 = response.headers;
22455
- const ra = h2.get("Retry-After");
22456
- const reset = h2.get("RateLimit-Reset") || h2.get("X-RateLimit-Reset");
22457
- let waitSec = 3;
22458
- if (ra && /^\d+$/.test(ra)) {
22459
- waitSec = +ra;
22460
- } else if (ra) {
22461
- const t2 = Date.parse(ra);
22462
- if (!isNaN(t2)) waitSec = Math.max(1, Math.ceil((t2 - Date.now()) / 1e3));
22463
- } else if (reset) {
22464
- waitSec = Math.max(1, Math.ceil((+reset - Date.now()) / 1e3));
22465
- }
22466
- throw new RateLimitError2(`\u23F1 Wait ${waitSec}s`, waitSec);
22467
- }
22468
- if (!response.ok) {
22469
- const data2 = await response.json().catch(() => ({}));
22470
- const msg = typeof data2?.error === "string" ? data2.error : `Request failed: ${response.statusText}`;
22471
- throw new Error(msg);
22472
- }
22473
- const data = await response.json();
22474
- return data;
22475
- } catch (error2) {
22476
- clearTimeout(timeoutId);
22477
- const err = error2;
22478
- if (err && err.name === "AbortError") {
22479
- throw new Error("\u{1F310} Network error, check connection");
22480
- }
22481
- throw err;
22482
- }
22483
- }
22484
- async function executeChat(messages) {
22485
- const response = await callAPI("/v1/chat", {
22486
- method: "POST",
22487
- body: { messages }
22488
- });
22489
- return response;
22490
- }
22491
- async function executeCode(input3) {
22492
- const isOptions = typeof input3 === "object";
22493
- const prompt = isOptions ? input3.prompt : input3;
22494
- const provider = isOptions ? input3.provider : void 0;
22495
- const model = isOptions ? input3.model : void 0;
22496
- const attachments = isOptions ? input3.attachments : void 0;
22497
- const body = { prompt, taskType: "code" };
22498
- if (provider) body.provider = provider;
22499
- if (model) body.model = model;
22500
- if (attachments && attachments.length > 0) {
22501
- body.metadata = { attachments };
22502
- }
22503
- const response = await callAPI("/v1/ai-proxy", {
22504
- method: "POST",
22505
- body
22506
- });
22507
- if (response.data?.routedModel) {
22508
- response.routedModel = response.data.routedModel;
22509
- }
22510
- if (response.data?.content) {
22511
- response.output = response.data.content;
22512
- }
22513
- return response;
22514
- }
22515
- async function executeAIProxy(provider, model, messages, options) {
22516
- return callAPI("/v1/ai-proxy", {
22517
- method: "POST",
22518
- body: { provider, model, messages, options }
22519
- });
22520
- }
22521
- var authManager2, RateLimitError2;
22522
- var init_api_caller = __esm({
22523
- "src/services/cli-auth/api-caller.ts"() {
22524
- init_AuthenticationManager();
22525
- new https__default.default.Agent({ keepAlive: true });
22526
- authManager2 = new AuthenticationManager();
22527
- RateLimitError2 = class extends Error {
22528
- constructor(message, retryAfter) {
22529
- super(message);
22530
- this.retryAfter = retryAfter;
22531
- this.name = "RateLimitError";
22532
- }
22533
- };
22534
- }
22535
- });
22536
-
22537
22579
  // src/services/media-orchestrator/ImageArgumentInference.ts
22538
- function extractFirstJson(text) {
22580
+ function extractFirstJson3(text) {
22539
22581
  const fence = /```json\r?\n([\s\S]*?)```/i.exec(text);
22540
22582
  if (fence) return fence[1];
22541
22583
  const fencePlain = /```\s*\r?\n([\s\S]*?)```/i.exec(text);
@@ -22605,7 +22647,7 @@ ${user}`,
22605
22647
  }
22606
22648
  });
22607
22649
  const raw = (response?.data?.content || response?.output || "").trim();
22608
- const jsonText = extractFirstJson(raw) || raw;
22650
+ const jsonText = extractFirstJson3(raw) || raw;
22609
22651
  let parsed;
22610
22652
  try {
22611
22653
  parsed = JSON.parse(jsonText);
@@ -26347,7 +26389,7 @@ var init_about_command = __esm({
26347
26389
  async execute(args2, context2) {
26348
26390
  const output3 = [];
26349
26391
  output3.push("");
26350
- output3.push(chalk40__default.default.cyan.bold("\u{1F916} About MARIA v4.3.36"));
26392
+ output3.push(chalk40__default.default.cyan.bold("\u{1F916} About MARIA v4.3.37"));
26351
26393
  output3.push(chalk40__default.default.gray("\u2550".repeat(40)));
26352
26394
  output3.push("");
26353
26395
  output3.push(chalk40__default.default.white.bold("MARIA - Minimal API, Maximum Power"));
@@ -38499,6 +38541,62 @@ var init_code_utils = __esm({
38499
38541
  ]);
38500
38542
  }
38501
38543
  });
38544
+
38545
+ // src/services/code-orchestrator/ArgumentInference.ts
38546
+ function extractFirstJson4(text) {
38547
+ const fence = /```json\r?\n([\s\S]*?)```/i.exec(text);
38548
+ if (fence) return fence[1];
38549
+ const start = text.indexOf("{");
38550
+ const end = text.lastIndexOf("}");
38551
+ if (start >= 0 && end > start) {
38552
+ const cand = text.slice(start, end + 1);
38553
+ try {
38554
+ JSON.parse(cand);
38555
+ return cand;
38556
+ } catch {
38557
+ }
38558
+ }
38559
+ return null;
38560
+ }
38561
+ async function inferCodeArgs(rawText) {
38562
+ const system = [
38563
+ "You extract structured options for a code command.",
38564
+ 'Return JSON only with keys: { "planOnly"?: boolean, "dryRun"?: boolean, "output"?: "names"|"summary"|"detail", "previewLines"?: number }.',
38565
+ "Decide from the user text whether planOnly or dryRun should be true. Do not explain.",
38566
+ "Only include output if the user requests preview detail or summary mode. Only include previewLines if a specific number of lines is requested."
38567
+ ].join("\n");
38568
+ const resp = await callAPI("/v1/ai-proxy", {
38569
+ method: "POST",
38570
+ body: {
38571
+ prompt: `${system}
38572
+
38573
+ ---
38574
+
38575
+ ${rawText}`,
38576
+ taskType: "code"
38577
+ }
38578
+ });
38579
+ const raw = (resp?.data?.content || resp?.output || "").trim();
38580
+ const jsonText = extractFirstJson4(raw) || raw;
38581
+ let parsed = {};
38582
+ try {
38583
+ parsed = JSON.parse(jsonText);
38584
+ } catch {
38585
+ return {};
38586
+ }
38587
+ const out = {};
38588
+ if (typeof parsed.planOnly === "boolean") out.planOnly = parsed.planOnly;
38589
+ if (typeof parsed.dryRun === "boolean") out.dryRun = parsed.dryRun;
38590
+ if (typeof parsed.output === "string" && (parsed.output === "names" || parsed.output === "summary" || parsed.output === "detail")) out.output = parsed.output;
38591
+ if (typeof parsed.previewLines === "number" && Number.isFinite(parsed.previewLines) && parsed.previewLines > 0) out.previewLines = Math.min(2e3, Math.floor(parsed.previewLines));
38592
+ if (out.planOnly) out.dryRun = false;
38593
+ return out;
38594
+ }
38595
+ var init_ArgumentInference = __esm({
38596
+ "src/services/code-orchestrator/ArgumentInference.ts"() {
38597
+ init_api_caller();
38598
+ }
38599
+ });
38502
38600
  async function scanRepo(cwd2) {
38503
38601
  if (_cache && _cache.root === cwd2) return _cache;
38504
38602
  const root = cwd2;
@@ -39888,7 +39986,7 @@ function mapCodeErrorToReason(err) {
39888
39986
  const error2 = err;
39889
39987
  const message = typeof error2?.message === "string" ? error2.message.toLowerCase() : "";
39890
39988
  const code = typeof error2?.code === "string" ? error2.code.toLowerCase() : "";
39891
- if (error2 instanceof RateLimitError2 || message.includes("rate") && message.includes("limit")) {
39989
+ if (error2 instanceof RateLimitError || message.includes("rate") && message.includes("limit")) {
39892
39990
  return "rate-limit";
39893
39991
  }
39894
39992
  if (message.includes("timeout") || code === "etimedout") {
@@ -40365,6 +40463,7 @@ var init_code_command = __esm({
40365
40463
  init_rate_limit_handler();
40366
40464
  init_animations();
40367
40465
  init_code_utils();
40466
+ init_ArgumentInference();
40368
40467
  LANGUAGE_EXTENSIONS = {
40369
40468
  javascript: ".js",
40370
40469
  typescript: ".ts",
@@ -40404,6 +40503,35 @@ var init_code_command = __esm({
40404
40503
  }
40405
40504
  try {
40406
40505
  const opts = this.parseV2Options(commandArgs.raw);
40506
+ try {
40507
+ const rawText = commandArgs.raw.join(" ");
40508
+ const explicitPlan = commandArgs.raw.includes("--plan-only") || commandArgs.raw.includes("--sow");
40509
+ const explicitDry = commandArgs.raw.includes("--dry-run");
40510
+ const explicitOutput = commandArgs.raw.some((x2) => x2.startsWith("--output") || x2 === "--verbose" || x2 === "-v");
40511
+ const explicitPreview = commandArgs.raw.some((x2) => x2.startsWith("--preview-lines"));
40512
+ const preSpin = new ProcessAnimation();
40513
+ preSpin.start();
40514
+ let inferred = {};
40515
+ try {
40516
+ inferred = await inferCodeArgs(rawText);
40517
+ } finally {
40518
+ try {
40519
+ preSpin.stop();
40520
+ } catch {
40521
+ }
40522
+ }
40523
+ if (!explicitPlan && !explicitDry) {
40524
+ if (typeof inferred.planOnly === "boolean") opts.planOnly = inferred.planOnly;
40525
+ if (typeof inferred.dryRun === "boolean") opts.dryRun = inferred.dryRun;
40526
+ }
40527
+ if (!explicitOutput && inferred.output) {
40528
+ opts.output = inferred.output;
40529
+ }
40530
+ if (!explicitPreview && typeof inferred.previewLines === "number") {
40531
+ opts.previewLines = inferred.previewLines;
40532
+ }
40533
+ } catch {
40534
+ }
40407
40535
  if (opts.planOnly) {
40408
40536
  opts.apply = false;
40409
40537
  opts.dryRun = false;
@@ -40544,7 +40672,7 @@ ${user}`
40544
40672
  }
40545
40673
  });
40546
40674
  const content = (resp?.data?.content || resp?.content || "").trim();
40547
- const extractFirstJson3 = (text) => {
40675
+ const extractFirstJson6 = (text) => {
40548
40676
  const fence = /```\s*json\s*\r?\n([\s\S]*?)```/i.exec(text);
40549
40677
  if (fence) return fence[1];
40550
40678
  const generic = /```\s*\r?\n([\s\S]*?)```/i.exec(text);
@@ -40567,7 +40695,7 @@ ${user}`
40567
40695
  }
40568
40696
  return null;
40569
40697
  };
40570
- const jsonText = extractFirstJson3(content) || content;
40698
+ const jsonText = extractFirstJson6(content) || content;
40571
40699
  let parsed = {};
40572
40700
  try {
40573
40701
  parsed = JSON.parse(jsonText);
@@ -58441,7 +58569,7 @@ ${user}`,
58441
58569
  };
58442
58570
  }
58443
58571
  });
58444
- function extractFirstJson2(text) {
58572
+ function extractFirstJson5(text) {
58445
58573
  const fence = /```json\r?\n([\s\S]*?)```/i.exec(text);
58446
58574
  if (fence) return fence[1];
58447
58575
  const start = text.indexOf("{");
@@ -58488,7 +58616,7 @@ ${user}`,
58488
58616
  }
58489
58617
  });
58490
58618
  const raw = (response?.data?.content || response?.output || "").trim();
58491
- const jsonText = extractFirstJson2(raw) || raw;
58619
+ const jsonText = extractFirstJson5(raw) || raw;
58492
58620
  let parsed = {};
58493
58621
  try {
58494
58622
  parsed = JSON.parse(jsonText);
@@ -58509,7 +58637,7 @@ ${user}`,
58509
58637
  }
58510
58638
  return out;
58511
58639
  }
58512
- var init_ArgumentInference = __esm({
58640
+ var init_ArgumentInference2 = __esm({
58513
58641
  "src/services/evaluation/ArgumentInference.ts"() {
58514
58642
  init_api_caller();
58515
58643
  }
@@ -58530,7 +58658,7 @@ var init_evaluate_command = __esm({
58530
58658
  init_EvaluationOrchestrator();
58531
58659
  init_api_caller();
58532
58660
  init_animations();
58533
- init_ArgumentInference();
58661
+ init_ArgumentInference2();
58534
58662
  EvaluateCommand = class extends BaseCommand {
58535
58663
  name = "evaluate";
58536
58664
  category = "evaluation";
@@ -59213,7 +59341,7 @@ __export(slash_commands_exports, {
59213
59341
  MemoryStatusCommand: () => MemoryStatusCommand,
59214
59342
  PermissionError: () => PermissionError,
59215
59343
  PlanCommand: () => PlanCommand,
59216
- RateLimitError: () => RateLimitError,
59344
+ RateLimitError: () => RateLimitError2,
59217
59345
  RateLimitMiddleware: () => RateLimitMiddleware,
59218
59346
  RecallCommand: () => RecallCommand,
59219
59347
  RememberCommand: () => RememberCommand,
@@ -76640,47 +76768,23 @@ async function handleLine(line, options = {}) {
76640
76768
  }
76641
76769
  const consumed = await handleSlash(input3);
76642
76770
  if (consumed) return;
76643
- let triageResult = options.triageResult ?? null;
76644
- if (!options.skipTriage) {
76645
- triageResult = await triage(input3, {
76646
- locale: process.env.LANG,
76647
- recentCommands: []
76648
- });
76649
- if (
76650
- /*false && for debugging*/
76651
- triageResult.next?.route
76652
- ) {
76653
- const commandParts = [
76654
- triageResult.next.route,
76655
- ...triageResult.next.args ?? []
76656
- ];
76657
- const routedLine = commandParts.join(" ").trim();
76658
- console.log(chalk40__default.default.white("Routed:"));
76659
- console.log(chalk40__default.default.white(routedLine));
76660
- await handleLine(routedLine, {
76661
- skipChoiceResolution: true,
76662
- skipTriage: true
76663
- });
76664
- console.log(chalk40__default.default.white(""));
76665
- console.log(chalk40__default.default.white("Summary:"));
76666
- if (triageResult.type === "route-code") {
76667
- console.log(chalk40__default.default.white("OK: routed to /code plan-only"));
76668
- console.log(chalk40__default.default.white("Next steps:"));
76669
- console.log(chalk40__default.default.white("- Run /code --apply --yes after reviewing the plan"));
76670
- } else if (triageResult.type === "route-image") {
76671
- console.log(chalk40__default.default.white("OK: routed to /image"));
76672
- console.log(chalk40__default.default.white("Next steps:"));
76673
- console.log(chalk40__default.default.white("- Review generated images and iterate if needed"));
76674
- } else if (triageResult.type === "route-video") {
76675
- console.log(chalk40__default.default.white("OK: routed to /video"));
76676
- console.log(chalk40__default.default.white("Next steps:"));
76677
- console.log(chalk40__default.default.white("- Inspect the storyboard or render output"));
76678
- } else {
76679
- console.log(chalk40__default.default.white("OK: routed"));
76680
- console.log(chalk40__default.default.white("Next steps:"));
76681
- console.log(chalk40__default.default.white("- Follow the routed workflow"));
76771
+ if (!input3.startsWith("/")) {
76772
+ const mapped = await mapInputToTopLevelCommand(input3);
76773
+ if (process.env.MARIA_DEBUG === "1") {
76774
+ console.log(chalk40__default.default.white(`Command: {command: '${mapped.command}', args: '${mapped.args}', confidence: '${mapped.confidence}'}`));
76775
+ }
76776
+ try {
76777
+ const threshold = Number(process.env.MARIA_ROUTE_CONFIDENCE || "0.7");
76778
+ if (mapped && mapped.command) {
76779
+ const conf = typeof mapped.confidence === "number" ? mapped.confidence : 1;
76780
+ if (mapped.command === "chat") {
76781
+ } else if (conf >= threshold) {
76782
+ const routed = [mapped.command, ...mapped.args || [input3]].join(" ").trim();
76783
+ await handleLine(routed, { skipChoiceResolution: true, skipTriage: true });
76784
+ return;
76785
+ }
76682
76786
  }
76683
- return;
76787
+ } finally {
76684
76788
  }
76685
76789
  }
76686
76790
  const isAuthenticated = await authManager.isAuthenticated();
@@ -76693,73 +76797,7 @@ async function handleLine(line, options = {}) {
76693
76797
  const user = { role: "user", content: input3, timestamp: /* @__PURE__ */ new Date() };
76694
76798
  session.push(user);
76695
76799
  if (store?.addMessage) await store.addMessage(user);
76696
- if (triageResult?.type === "complex") {
76697
- await handleComplexChat(input3, triageResult);
76698
- return;
76699
- }
76700
- await streamAnswer(input3, { triage: triageResult });
76701
- }
76702
- async function handleComplexChat(request, triageResult) {
76703
- const animation = new ProcessAnimation();
76704
- animation.start();
76705
- try {
76706
- const authed = await authManager.isAuthenticated();
76707
- let content = "";
76708
- if (authed) {
76709
- try {
76710
- const resp = await callApiJson("/api/ai", {
76711
- method: "POST",
76712
- body: JSON.stringify({ prompt: request, taskType: "planning" }),
76713
- headers: { "Content-Type": "application/json" }
76714
- });
76715
- content = resp?.data?.response || resp?.data?.content || "";
76716
- } catch {
76717
- }
76718
- }
76719
- if (!content) {
76720
- animation.stop();
76721
- await streamAnswer(request, { triage: triageResult });
76722
- return;
76723
- }
76724
- animation.stop();
76725
- const cleaned = content && typeof content === "string" ? content : buildComplexPlanSteps(request).join("\n");
76726
- console.log(chalk40__default.default.white(cleaned));
76727
- const planMessage = {
76728
- role: "assistant",
76729
- content: cleaned,
76730
- timestamp: /* @__PURE__ */ new Date(),
76731
- metadata: { tag: "complex-chat", triage: triageResult }
76732
- };
76733
- session.push(planMessage);
76734
- if (store?.addMessage) await store.addMessage(planMessage);
76735
- console.log(chalk40__default.default.white(""));
76736
- console.log(chalk40__default.default.white("Summary:"));
76737
- console.log(chalk40__default.default.white("OK: plan prepared"));
76738
- console.log(chalk40__default.default.white("Next steps:"));
76739
- console.log(chalk40__default.default.white("- Ask to apply or adjust the plan"));
76740
- } finally {
76741
- try {
76742
- animation.stop();
76743
- } catch {
76744
- }
76745
- }
76746
- }
76747
- function buildComplexPlanSteps(request) {
76748
- const scoped = request.trim();
76749
- const steps = [
76750
- `Clarify scope, constraints, and success criteria for "${scoped}"`,
76751
- `Review existing modules in src/ and docs/ for related work`,
76752
- `Design the solution with safe defaults and feature flags if needed`,
76753
- `Implement changes and document decisions`,
76754
- `Validate with pnpm test and peer review artifacts`
76755
- ];
76756
- if (/(test|spec|verify|検証)/i.test(scoped)) {
76757
- steps.push("Extend or add Vitest coverage for new behaviour");
76758
- }
76759
- if (/(ui|frontend|component|画面)/i.test(scoped)) {
76760
- steps.push("Capture CLI or UI snapshots to confirm UX changes");
76761
- }
76762
- return steps;
76800
+ await streamAnswer(input3, {});
76763
76801
  }
76764
76802
  async function tryResolveChoice(rawLine) {
76765
76803
  const resolution = choiceMemory.resolve(rawLine);
@@ -76858,9 +76896,8 @@ var init_cli = __esm({
76858
76896
  init_version();
76859
76897
  init_animations();
76860
76898
  init_cli_auth();
76861
- init_api_client();
76862
76899
  init_choice_memory();
76863
- init_triage_orchestrator();
76900
+ init_LlmTopLevelRouter();
76864
76901
  init_handle_slash();
76865
76902
  init_session_state();
76866
76903
  init_process_handlers();