@bonginkan/maria 4.4.0 → 4.4.2

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
@@ -20,12 +20,12 @@ var fs7 = require('fs-extra');
20
20
  var util = require('util');
21
21
  var promises = require('timers/promises');
22
22
  var dns = require('dns/promises');
23
- var zod = require('zod');
24
23
  var process6 = require('process');
25
24
  var readline = require('readline');
26
25
  var buffer = require('buffer');
27
26
  var net = require('net');
28
27
  var zlib = require('zlib');
28
+ var zod = require('zod');
29
29
  var yaml = require('js-yaml');
30
30
  var neo4j = require('neo4j-driver');
31
31
  var typescriptEstree = require('@typescript-eslint/typescript-estree');
@@ -1736,7 +1736,7 @@ var init_AuthenticationManager = __esm({
1736
1736
  const response = await fetch(`${this.apiBase}/api/user/profile`, {
1737
1737
  headers: {
1738
1738
  "Authorization": `Bearer ${tokens2.accessToken}`,
1739
- "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.4.0"}`
1739
+ "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.4.2"}`
1740
1740
  }
1741
1741
  });
1742
1742
  if (response.status === 401) {
@@ -2461,7 +2461,7 @@ async function callApi(path66, init3 = {}) {
2461
2461
  "Authorization": `Bearer ${token}`,
2462
2462
  "X-Device-Id": getDeviceId(),
2463
2463
  "X-Session-Id": getSessionId() || "",
2464
- "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.4.0"}`,
2464
+ "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.4.2"}`,
2465
2465
  "Content-Type": init3.headers?.["Content-Type"] || "application/json"
2466
2466
  });
2467
2467
  const doFetch = async (token) => {
@@ -10043,10 +10043,10 @@ var init_ignore = __esm({
10043
10043
  ignored(p) {
10044
10044
  const fullpath = p.fullpath();
10045
10045
  const fullpaths = `${fullpath}/`;
10046
- const relative5 = p.relative() || ".";
10047
- const relatives = `${relative5}/`;
10046
+ const relative6 = p.relative() || ".";
10047
+ const relatives = `${relative6}/`;
10048
10048
  for (const m2 of this.relative) {
10049
- if (m2.match(relative5) || m2.match(relatives))
10049
+ if (m2.match(relative6) || m2.match(relatives))
10050
10050
  return true;
10051
10051
  }
10052
10052
  for (const m2 of this.absolute) {
@@ -10057,9 +10057,9 @@ var init_ignore = __esm({
10057
10057
  }
10058
10058
  childrenIgnored(p) {
10059
10059
  const fullpath = p.fullpath() + "/";
10060
- const relative5 = (p.relative() || ".") + "/";
10060
+ const relative6 = (p.relative() || ".") + "/";
10061
10061
  for (const m2 of this.relativeChildren) {
10062
- if (m2.match(relative5))
10062
+ if (m2.match(relative6))
10063
10063
  return true;
10064
10064
  }
10065
10065
  for (const m2 of this.absoluteChildren) {
@@ -13421,16 +13421,7 @@ var init_HelpCommand = __esm({
13421
13421
  async showCommandHelp(commandName) {
13422
13422
  const command = await this.readyService.getCommand(commandName);
13423
13423
  if (!command) {
13424
- const searchResults = await this.readyService.searchCommands(commandName, 3);
13425
- const suggestions = searchResults.map((r2) => `/${r2.command.name}`);
13426
- return this.error(
13427
- `READY command not found: /${commandName}`,
13428
- "COMMAND_NOT_FOUND",
13429
- {
13430
- suggestions,
13431
- tip: "Only contract-validated READY commands are shown"
13432
- }
13433
- );
13424
+ return await this.showGeneralHelp();
13434
13425
  }
13435
13426
  const lines = this.formatMinimalUsage(command);
13436
13427
  return this.success(lines);
@@ -16622,8 +16613,8 @@ var require_package = __commonJS({
16622
16613
  "package.json"(exports, module) {
16623
16614
  module.exports = {
16624
16615
  name: "@bonginkan/maria",
16625
- version: "4.4.0",
16626
- description: "\u{1F680} MARIA v4.4.0 - 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.",
16616
+ version: "4.4.2",
16617
+ description: "\u{1F680} MARIA v4.4.2 - Enterprise AI Development Platform with identity system and character voice implementation. Features 74 production-ready commands with comprehensive fallback implementation, local LLM support, and zero external dependencies. Includes natural language coding, AI safety evaluation, intelligent evolution system, episodic memory with PII masking, and real-time monitoring dashboard. Built with TypeScript AST-powered code generation, OAuth2.0 + PKCE authentication, quantum-resistant cryptography, and enterprise-grade performance.",
16627
16618
  keywords: [
16628
16619
  "ai",
16629
16620
  "cli",
@@ -22937,6 +22928,94 @@ var init_ImageArgumentInference = __esm({
22937
22928
  init_api_caller();
22938
22929
  }
22939
22930
  });
22931
+
22932
+ // src/services/media-orchestrator/VideoArgumentInference.ts
22933
+ function extractFirstJson4(text) {
22934
+ const matches = text.match(/[\[{][\s\S]*[\]}]/g) || [];
22935
+ for (const cand of matches) {
22936
+ try {
22937
+ JSON.parse(cand);
22938
+ return cand;
22939
+ } catch {
22940
+ }
22941
+ }
22942
+ return null;
22943
+ }
22944
+ function parseSizeAny2(x2) {
22945
+ if (!x2) return void 0;
22946
+ const s2 = String(x2).trim().toLowerCase().replace(/p$/, "");
22947
+ const m2 = /^(\d{2,4})x(\d{2,4})$/.exec(s2);
22948
+ if (m2) {
22949
+ const w = Number(m2[1]);
22950
+ const h2 = Number(m2[2]);
22951
+ if (Number.isFinite(w) && Number.isFinite(h2) && w >= 256 && h2 >= 256 && w <= 4096 && h2 <= 4096) return [w, h2];
22952
+ return void 0;
22953
+ }
22954
+ if (s2 === "720") return [1280, 720];
22955
+ if (s2 === "1080") return [1920, 1080];
22956
+ return void 0;
22957
+ }
22958
+ async function inferVideoArgsLLM(promptText) {
22959
+ const system = [
22960
+ "You extract video generation options from user natural language.",
22961
+ 'Return JSON only with keys: { "model"?: "sora-2"|"veo-3.1-generate-preview", "duration"?: number, "aspect"?: "16:9"|"9:16", "size"?: "WIDTHxHEIGHT"|"720"|"1080" }.',
22962
+ "Rules:",
22963
+ '- If user mentions OpenAI Sora, choose model "sora-2". If Google Veo, choose "veo-3.1-generate-preview".',
22964
+ "- Duration options differ: for Sora use one of 4, 8, 12; for Veo prefer 4, 6, 8 (1080p fixed 8).",
22965
+ "- If user says 10 seconds, map to closest allowed (e.g., 8 for Sora/Veo).",
22966
+ '- 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).',
22967
+ '- Size: if 720p or 1080p mentioned, return "720" or "1080". If explicit WxH, return as is if within 256..4096 per side.',
22968
+ "Do not add explanations; JSON only."
22969
+ ].join("\n");
22970
+ let explicitModel;
22971
+ let explicitProvider;
22972
+ try {
22973
+ const { extractExplicitModel: extractExplicitModel2, extractExplicitProvider: extractExplicitProvider2, providerFromModel: providerFromModel2 } = await Promise.resolve().then(() => (init_llm_flags(), llm_flags_exports));
22974
+ explicitModel = extractExplicitModel2(promptText);
22975
+ explicitProvider = extractExplicitProvider2(promptText) || providerFromModel2(explicitModel);
22976
+ } catch {
22977
+ }
22978
+ let attachments = [];
22979
+ try {
22980
+ const { collectFileAttachmentsFromText: collectFileAttachmentsFromText2 } = await Promise.resolve().then(() => (init_attachment_utils(), attachment_utils_exports));
22981
+ attachments = await collectFileAttachmentsFromText2(promptText, process.cwd(), { maxBytes: 12 * 1024 * 1024 });
22982
+ } catch {
22983
+ }
22984
+ const resp = await callAPI("/v1/ai-proxy", {
22985
+ method: "POST",
22986
+ body: {
22987
+ ...explicitProvider ? { provider: explicitProvider } : {},
22988
+ ...explicitModel ? { model: explicitModel } : {},
22989
+ prompt: `${system}
22990
+
22991
+ ---
22992
+
22993
+ ${promptText}`,
22994
+ taskType: "media",
22995
+ ...attachments.length ? { metadata: { attachments } } : {}
22996
+ }
22997
+ });
22998
+ const raw = (resp?.data?.content || resp?.output || "").trim();
22999
+ const jsonText = extractFirstJson4(raw) || raw;
23000
+ let parsed;
23001
+ try {
23002
+ parsed = JSON.parse(jsonText);
23003
+ } catch {
23004
+ return {};
23005
+ }
23006
+ const out = {};
23007
+ if (typeof parsed?.model === "string" && parsed.model.trim()) out.model = String(parsed.model).trim();
23008
+ if (Number.isFinite(Number(parsed?.duration))) out.duration = Math.max(1, Math.floor(Number(parsed.duration)));
23009
+ if (parsed?.aspect === "16:9" || parsed?.aspect === "9:16") out.aspect = parsed.aspect;
23010
+ const size = parseSizeAny2(parsed?.size);
23011
+ if (size) out.size = size;
23012
+ return out;
23013
+ }
23014
+ var init_VideoArgumentInference = __esm({
23015
+ "src/services/media-orchestrator/VideoArgumentInference.ts"() {
23016
+ init_api_caller();
23017
+ }
23018
+ });
22940
23019
  function parseSize(value) {
22941
23020
  const m2 = /^\s*(\d{2,4})x(\d{2,4})\s*$/i.exec(value || "");
22942
23021
  if (!m2) throw new Error(`invalid size: ${value}`);
@@ -23156,6 +23235,15 @@ function normalizeVideoArgs(raw, root) {
23156
23235
  break;
23157
23236
  }
23158
23237
  }
23238
+ try {
23239
+ if (String(process.env.MARIA_USE_LLM_INFER || "1") === "1") {
23240
+ global.__MARIA_VIDEO_LLM_INFER__ = async () => {
23241
+ const llm = await inferVideoArgsLLM(prompt);
23242
+ return llm;
23243
+ };
23244
+ }
23245
+ } catch {
23246
+ }
23159
23247
  if (!out.apply && !out.planOnly && !out.dryRun) {
23160
23248
  out.apply = true;
23161
23249
  }
@@ -23195,6 +23283,7 @@ var init_Normalizer = __esm({
23195
23283
  init_types4();
23196
23284
  init_NLInference();
23197
23285
  init_ImageArgumentInference();
23286
+ init_VideoArgumentInference();
23198
23287
  }
23199
23288
  });
23200
23289
  function ensureDirSync(p) {
@@ -23828,193 +23917,6 @@ ${(/* @__PURE__ */ new Date()).toISOString()}`;
23828
23917
  };
23829
23918
  }
23830
23919
  });
23831
- function assertSnapshot(data) {
23832
- const res = SnapshotZ.safeParse(data);
23833
- if (!res.success) {
23834
- const details = res.error.issues.map((i2) => `${i2.path.join(".") || "<root>"} ${i2.message}`).join(" | ");
23835
- throw new ValidationError2(`Invalid snapshot: ${details}`);
23836
- }
23837
- }
23838
- var SnapshotZ, ValidationError2;
23839
- var init_validators = __esm({
23840
- "src/memory/validators.ts"() {
23841
- SnapshotZ = zod.z.object({
23842
- snapshotVersion: zod.z.literal(1),
23843
- projectId: zod.z.string().optional(),
23844
- taskId: zod.z.string().min(1),
23845
- timestamp: zod.z.string().datetime(),
23846
- // ISO-8601 UTC expected
23847
- summary: zod.z.string().min(1),
23848
- decisions: zod.z.array(zod.z.string()).optional(),
23849
- artifacts: zod.z.array(zod.z.string()).optional(),
23850
- links: zod.z.array(
23851
- zod.z.object({
23852
- type: zod.z.enum(["doc", "fs", "url", "firestore"]),
23853
- ref: zod.z.string().min(1)
23854
- })
23855
- ).optional(),
23856
- hash: zod.z.string().optional(),
23857
- score: zod.z.object({
23858
- testsPassRate: zod.z.number().min(0).max(1).optional(),
23859
- coverage: zod.z.number().min(0).max(1).optional()
23860
- }).optional(),
23861
- tags: zod.z.array(zod.z.string()).optional(),
23862
- resumePrompt: zod.z.string().optional()
23863
- });
23864
- ValidationError2 = class extends Error {
23865
- constructor(message) {
23866
- super(message);
23867
- this.name = "ValidationError";
23868
- }
23869
- };
23870
- }
23871
- });
23872
- function storeFactory(ctx2) {
23873
- const mode = process.env.MARIA_STORE || "mock";
23874
- ctx2.logger?.info?.(`[resume] store=${mode}`);
23875
- if (mode === "firestore") {
23876
- try {
23877
- const db = ctx2.firestore || tryGetFirestore();
23878
- if (db) return new FirestoreSnapshotStore(db);
23879
- console.warn("[resume] firestore not available; falling back to mock store");
23880
- } catch (e2) {
23881
- console.warn("[resume] firestore error; falling back to mock store:", e2?.message || e2);
23882
- }
23883
- }
23884
- return new MockSnapshotStore(ctx2.cwd || process.cwd());
23885
- }
23886
- function tryGetFirestore() {
23887
- try {
23888
- const admin = __require("firebase-admin");
23889
- if (!admin.apps || admin.apps.length === 0) {
23890
- try {
23891
- admin.initializeApp();
23892
- } catch {
23893
- }
23894
- }
23895
- const { getFirestore } = __require("firebase-admin/firestore");
23896
- return getFirestore();
23897
- } catch {
23898
- return null;
23899
- }
23900
- }
23901
- async function trySaveSnapshot(projectId, taskId, data) {
23902
- try {
23903
- const db = tryGetFirestore();
23904
- if (!db) return false;
23905
- const tsId = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").split(".")[0] + "Z";
23906
- const ref = db.collection("projects").doc(projectId).collection("tasks").doc(taskId).collection("snapshots").doc(tsId);
23907
- await ref.set({
23908
- snapshotVersion: 1,
23909
- projectId,
23910
- taskId,
23911
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
23912
- summary: data.summary,
23913
- decisions: data.decisions || [],
23914
- artifacts: data.artifacts || [],
23915
- links: (data.refs || []).map((r2) => ({ type: "fs", ref: r2 })),
23916
- resumePrompt: data.resumePrompt || ""
23917
- });
23918
- return true;
23919
- } catch {
23920
- return false;
23921
- }
23922
- }
23923
- var MockSnapshotStore, FirestoreSnapshotStore;
23924
- var init_firestore = __esm({
23925
- "src/memory/firestore.ts"() {
23926
- init_validators();
23927
- MockSnapshotStore = class {
23928
- constructor(cwd2 = process.cwd()) {
23929
- this.cwd = cwd2;
23930
- }
23931
- async getLatest(_projectId, limit = 1) {
23932
- const s2 = this.readLocal();
23933
- return s2.slice(0, limit);
23934
- }
23935
- async getByTask(_projectId, taskId, limit = 5) {
23936
- const s2 = this.readLocal().filter((x2) => x2.taskId === taskId);
23937
- return s2.slice(0, limit);
23938
- }
23939
- async getByDate(_projectId, dateISO, limit = 5) {
23940
- const s2 = this.readLocal().filter((x2) => x2.timestamp?.startsWith(dateISO));
23941
- return s2.slice(0, limit);
23942
- }
23943
- readLocal() {
23944
- const sessionPath = path11__namespace.default.join(this.cwd, ".maria", "memory", "session.json");
23945
- const candidates = [];
23946
- try {
23947
- const raw = JSON.parse(fs20__namespace.default.readFileSync(sessionPath, "utf8"));
23948
- const ctx2 = raw?.context;
23949
- if (ctx2?.summary) {
23950
- const synthetic = {
23951
- snapshotVersion: 1,
23952
- projectId: "default",
23953
- taskId: raw.taskId || "resume.task",
23954
- timestamp: raw.resumeAt || (/* @__PURE__ */ new Date()).toISOString(),
23955
- summary: ctx2.summary,
23956
- decisions: ctx2.decisions || [],
23957
- artifacts: ctx2.artifacts || [],
23958
- links: (ctx2.refs || []).map((r2) => ({ type: "url", ref: r2 }))
23959
- };
23960
- assertSnapshot(synthetic);
23961
- candidates.push(synthetic);
23962
- }
23963
- } catch {
23964
- }
23965
- if (candidates.length === 0) {
23966
- const fallback2 = {
23967
- snapshotVersion: 1,
23968
- projectId: "default",
23969
- taskId: "example.task",
23970
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
23971
- summary: "\u524D\u56DE\u4F5C\u696D\u306E\u7D9A\u304D\u3002/code \u3092\u518D\u958B\u3067\u304D\u308B\u3088\u3046\u306B\u6E96\u5099\u6E08\u307F\u3002",
23972
- decisions: ["\u81EA\u52D5\u30C6\u30B9\u30C8\u306F\u6700\u4F4E\u9650", "\u7834\u58CA\u7684\u5909\u66F4\u306F\u3057\u306A\u3044"],
23973
- artifacts: ["README.md"],
23974
- links: [{ type: "doc", ref: "docs/RESUME_FUNCTION_DESIGN.md" }],
23975
- resumePrompt: "\u6628\u65E5\u306E\u7D9A\u304D\u304B\u3089\u518D\u958B\u3057\u3066\u3001\u5DEE\u5206\u306E\u307F\u9069\u7528\u3057\u3066\u4E0B\u3055\u3044\u3002"
23976
- };
23977
- assertSnapshot(fallback2);
23978
- candidates.push(fallback2);
23979
- }
23980
- return candidates;
23981
- }
23982
- };
23983
- FirestoreSnapshotStore = class {
23984
- constructor(db) {
23985
- this.db = db;
23986
- }
23987
- async getLatest(projectId, limit = 1) {
23988
- const q = this.db.collectionGroup("snapshots").where("projectId", "==", projectId).orderBy("timestamp", "desc").limit(limit);
23989
- const ss = await q.get();
23990
- return this.validateDocs(ss.docs.map((d) => d.data()));
23991
- }
23992
- async getByTask(projectId, taskId, limit = 5) {
23993
- const q = this.db.collection("projects").doc(projectId).collection("tasks").doc(taskId).collection("snapshots").orderBy("timestamp", "desc").limit(limit);
23994
- const ss = await q.get();
23995
- return this.validateDocs(ss.docs.map((d) => d.data()));
23996
- }
23997
- async getByDate(projectId, dateISO, limit = 5) {
23998
- const start = new Date(dateISO).toISOString();
23999
- const end = new Date(new Date(dateISO).getTime() + 24 * 60 * 60 * 1e3).toISOString();
24000
- const q = this.db.collectionGroup("snapshots").where("projectId", "==", projectId).where("timestamp", ">=", start).where("timestamp", "<", end).orderBy("timestamp", "desc").limit(limit);
24001
- const ss = await q.get();
24002
- return this.validateDocs(ss.docs.map((d) => d.data()));
24003
- }
24004
- validateDocs(rows) {
24005
- const out = [];
24006
- for (const r2 of rows) {
24007
- try {
24008
- assertSnapshot(r2);
24009
- out.push(r2);
24010
- } catch {
24011
- }
24012
- }
24013
- return out;
24014
- }
24015
- };
24016
- }
24017
- });
24018
23920
 
24019
23921
  // src/slash-commands/categories/media/image.command.ts
24020
23922
  var image_command_exports = {};
@@ -24029,7 +23931,7 @@ var init_image_command = __esm({
24029
23931
  init_Normalizer();
24030
23932
  init_ImagePipeline();
24031
23933
  init_session();
24032
- init_firestore();
23934
+ init_api_caller();
24033
23935
  init_cli_auth();
24034
23936
  init_api_client();
24035
23937
  init_cli_auth();
@@ -24137,6 +24039,22 @@ var init_image_command = __esm({
24137
24039
  await api.consumeQuota({ requests: 1, image: Math.max(1, savedPaths.length) });
24138
24040
  } catch {
24139
24041
  }
24042
+ try {
24043
+ new SessionMemory(context2.environment.cwd).save({
24044
+ taskId: "media.image.remote",
24045
+ resumeAt: (/* @__PURE__ */ new Date()).toISOString(),
24046
+ context: { summary: `Generated (remote) ${cli.size[0]}x${cli.size[1]} ${cli.format}`, decisions: [], artifacts: savedPaths, refs: savedPaths }
24047
+ });
24048
+ await callAPI("/api/v1/snapshots", {
24049
+ method: "POST",
24050
+ body: { projectId: "default", taskId: "media.image.remote", summary: `Generated (remote) ${cli.size[0]}x${cli.size[1]} ${cli.format}`, decisions: [], artifacts: savedPaths, refs: savedPaths, resumePrompt: "Continue media work based on last remote output" }
24051
+ });
24052
+ } catch (err) {
24053
+ try {
24054
+ console.warn("[snapshots] save failed:", err?.message || String(err));
24055
+ } catch {
24056
+ }
24057
+ }
24140
24058
  return this.success(output4, void 0, void 0);
24141
24059
  }
24142
24060
  if (Array.isArray(filesList) && filesList.length > 0) {
@@ -24180,6 +24098,22 @@ var init_image_command = __esm({
24180
24098
  await api.consumeQuota({ requests: 1, image: Math.max(1, savedPaths.length) });
24181
24099
  } catch {
24182
24100
  }
24101
+ try {
24102
+ new SessionMemory(context2.environment.cwd).save({
24103
+ taskId: "media.image.remote",
24104
+ resumeAt: (/* @__PURE__ */ new Date()).toISOString(),
24105
+ context: { summary: `Generated (remote) ${cli.size[0]}x${cli.size[1]} ${cli.format}`, decisions: [], artifacts: savedPaths, refs: savedPaths }
24106
+ });
24107
+ await callAPI("/api/v1/snapshots", {
24108
+ method: "POST",
24109
+ body: { projectId: "default", taskId: "media.image.remote", summary: `Generated (remote) ${cli.size[0]}x${cli.size[1]} ${cli.format}`, decisions: [], artifacts: savedPaths, refs: savedPaths, resumePrompt: "Continue media work based on last remote output" }
24110
+ });
24111
+ } catch (err) {
24112
+ try {
24113
+ console.warn("[snapshots] save failed:", err?.message || String(err));
24114
+ } catch {
24115
+ }
24116
+ }
24183
24117
  return this.success(output4, void 0, void 0);
24184
24118
  }
24185
24119
  if (urls.length > 0) {
@@ -24201,6 +24135,22 @@ var init_image_command = __esm({
24201
24135
  await api.consumeQuota({ requests: 1, image: consumed });
24202
24136
  } catch {
24203
24137
  }
24138
+ try {
24139
+ new SessionMemory(context2.environment.cwd).save({
24140
+ taskId: "media.image.remote",
24141
+ resumeAt: (/* @__PURE__ */ new Date()).toISOString(),
24142
+ context: { summary: `Generated (remote) ${cli.size[0]}x${cli.size[1]} ${cli.format}`, decisions: [], artifacts: urls, refs: urls }
24143
+ });
24144
+ await callAPI("/api/v1/snapshots", {
24145
+ method: "POST",
24146
+ body: { projectId: "default", taskId: "media.image.remote", summary: `Generated (remote) ${cli.size[0]}x${cli.size[1]} ${cli.format}`, decisions: [], artifacts: urls, refs: urls, resumePrompt: "Continue media work based on last remote output" }
24147
+ });
24148
+ } catch (err) {
24149
+ try {
24150
+ console.warn("[snapshots] save failed:", err?.message || String(err));
24151
+ } catch {
24152
+ }
24153
+ }
24204
24154
  return this.success(output4, void 0, void 0);
24205
24155
  }
24206
24156
  const { formatRemoteAcceptedImage: formatRemoteAcceptedImage2 } = await Promise.resolve().then(() => (init_cli_style(), cli_style_exports));
@@ -24218,13 +24168,7 @@ var init_image_command = __esm({
24218
24168
  resumeAt: (/* @__PURE__ */ new Date()).toISOString(),
24219
24169
  context: { summary: `Generated (remote) ${cli.size[0]}x${cli.size[1]} ${cli.format}`, decisions: [], artifacts: urls, refs: urls }
24220
24170
  });
24221
- await trySaveSnapshot("default", "media.image.remote", {
24222
- summary: `Generated (remote) ${cli.size[0]}x${cli.size[1]} ${cli.format}`,
24223
- decisions: [],
24224
- artifacts: urls,
24225
- refs: urls,
24226
- resumePrompt: "Continue media work based on last remote output"
24227
- });
24171
+ await callAPI("/api/v1/snapshots", { method: "POST", body: { projectId: "default", taskId: "media.image.remote", summary: `Generated (remote) ${cli.size[0]}x${cli.size[1]} ${cli.format}`, decisions: [], artifacts: urls, refs: urls, resumePrompt: "Continue media work based on last remote output" } });
24228
24172
  } catch {
24229
24173
  }
24230
24174
  try {
@@ -24268,13 +24212,7 @@ var init_image_command = __esm({
24268
24212
  refs: [res.saved.manifestPath]
24269
24213
  }
24270
24214
  });
24271
- await trySaveSnapshot("default", "media.image", {
24272
- summary: `Generated ${ok} image(s) ${cli.size[0]}x${cli.size[1]} ${cli.format}`,
24273
- decisions: [],
24274
- artifacts: res.saved.files,
24275
- refs: [res.saved.manifestPath],
24276
- resumePrompt: "Continue media work based on last output"
24277
- });
24215
+ await callAPI("/api/v1/snapshots", { method: "POST", body: { projectId: "default", taskId: "media.image", summary: `Generated ${ok} image(s) ${cli.size[0]}x${cli.size[1]} ${cli.format}`, decisions: [], artifacts: res.saved.files, refs: [res.saved.manifestPath], resumePrompt: "Continue media work based on last output" } });
24278
24216
  } catch {
24279
24217
  }
24280
24218
  try {
@@ -24542,7 +24480,7 @@ var init_video_command = __esm({
24542
24480
  init_Normalizer();
24543
24481
  init_VideoPipeline();
24544
24482
  init_session();
24545
- init_firestore();
24483
+ init_api_caller();
24546
24484
  init_cli_auth();
24547
24485
  init_api_client();
24548
24486
  init_cli_auth();
@@ -24561,7 +24499,39 @@ var init_video_command = __esm({
24561
24499
  try {
24562
24500
  const root = context2.environment.cwd;
24563
24501
  const cli = normalizeVideoArgs(args2.raw, root);
24564
- cli.duration = 8;
24502
+ try {
24503
+ const hook = global.__MARIA_VIDEO_LLM_INFER__;
24504
+ if (hook) {
24505
+ const llm = await hook();
24506
+ if (llm) {
24507
+ if (llm.model && typeof llm.model === "string") cli.model = llm.model;
24508
+ if (Number.isFinite(Number(llm.duration))) {
24509
+ const d = Math.floor(Number(llm.duration));
24510
+ cli.duration = Math.max(1, Math.min(60, d));
24511
+ }
24512
+ if (llm.aspect === "16:9" || llm.aspect === "9:16") {
24513
+ cli.aspect = llm.aspect;
24514
+ const [w, h2] = cli.size;
24515
+ if (llm.size && Array.isArray(llm.size) && llm.size.length === 2) {
24516
+ cli.size = llm.size;
24517
+ } else if (w === 1280 && h2 === 720 || w === 720 && h2 === 1280 || w === 1920 && h2 === 1080 || w === 1080 && h2 === 1920) {
24518
+ if (llm.aspect === "9:16") {
24519
+ if (h2 === 720) cli.size = [720, 1280];
24520
+ else if (h2 === 1080) cli.size = [1080, 1920];
24521
+ } else {
24522
+ if (w === 720) cli.size = [1280, 720];
24523
+ else if (w === 1080) cli.size = [1920, 1080];
24524
+ if (w === 1080 && h2 === 1920) cli.size = [1920, 1080];
24525
+ }
24526
+ }
24527
+ } else if (llm.size && Array.isArray(llm.size) && llm.size.length === 2) {
24528
+ cli.size = llm.size;
24529
+ cli.aspect = cli.size[0] >= cli.size[1] ? "16:9" : "9:16";
24530
+ }
24531
+ }
24532
+ }
24533
+ } catch {
24534
+ }
24565
24535
  if (cli.planOnly || cli.dryRun || !cli.apply) {
24566
24536
  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}`;
24567
24537
  const next = `Next: /video "${cli.prompt}" --duration ${cli.duration} --fps ${cli.fps} --res ${cli.size[0]}x${cli.size[1]} --apply`;
@@ -24691,6 +24661,15 @@ var init_video_command = __esm({
24691
24661
  await api.consumeQuota({ requests: 1, video: savedPaths.length > 0 ? 1 : 0 });
24692
24662
  } catch {
24693
24663
  }
24664
+ try {
24665
+ new SessionMemory(root).save({ taskId: "media.video.remote", resumeAt: (/* @__PURE__ */ new Date()).toISOString(), context: { summary: `Generated (remote) video ${cli.duration}s @${cli.fps}fps ${cli.size[0]}x${cli.size[1]}`, decisions: [], artifacts: savedPaths, refs: savedPaths } });
24666
+ await callAPI("/api/v1/snapshots", { method: "POST", body: { projectId: "default", taskId: "media.video.remote", summary: `Generated (remote) video ${cli.duration}s @${cli.fps}fps ${cli.size[0]}x${cli.size[1]}`, decisions: [], artifacts: savedPaths, refs: savedPaths, resumePrompt: "Continue media work based on last remote output" } });
24667
+ } catch (err) {
24668
+ try {
24669
+ console.warn("[snapshots] save failed:", err?.message || String(err));
24670
+ } catch {
24671
+ }
24672
+ }
24694
24673
  return this.success(output4);
24695
24674
  }
24696
24675
  const { formatRemoteAcceptedVideo: formatRemoteAcceptedVideo2 } = await Promise.resolve().then(() => (init_cli_style(), cli_style_exports));
@@ -24714,13 +24693,7 @@ var init_video_command = __esm({
24714
24693
  refs: []
24715
24694
  }
24716
24695
  });
24717
- await trySaveSnapshot("default", "media.video.remote", {
24718
- summary: `Generated (remote) video ${cli.duration}s @${cli.fps}fps ${cli.size[0]}x${cli.size[1]}`,
24719
- decisions: [],
24720
- artifacts: [],
24721
- refs: [],
24722
- resumePrompt: "Continue media work based on last remote output"
24723
- });
24696
+ await callAPI("/api/v1/snapshots", { method: "POST", body: { projectId: "default", taskId: "media.video.remote", summary: `Generated (remote) video ${cli.duration}s @${cli.fps}fps ${cli.size[0]}x${cli.size[1]}`, decisions: [], artifacts: [], refs: [], resumePrompt: "Continue media work based on last remote output" } });
24724
24697
  } catch {
24725
24698
  }
24726
24699
  try {
@@ -24762,13 +24735,7 @@ var init_video_command = __esm({
24762
24735
  refs: [res.saved.manifestPath]
24763
24736
  }
24764
24737
  });
24765
- await trySaveSnapshot("default", "media.video", {
24766
- summary: `Generated video ${cli.duration}s @${cli.fps}fps ${cli.size[0]}x${cli.size[1]}${res.warnFallback ? " (frames fallback)" : ""}`,
24767
- decisions: [],
24768
- artifacts: res.saved.files,
24769
- refs: [res.saved.manifestPath],
24770
- resumePrompt: "Continue media work based on last output"
24771
- });
24738
+ await callAPI("/api/v1/snapshots", { method: "POST", body: { projectId: "default", taskId: "media.video", summary: `Generated video ${cli.duration}s @${cli.fps}fps ${cli.size[0]}x${cli.size[1]}${res.warnFallback ? " (frames fallback)" : ""}`, decisions: [], artifacts: res.saved.files, refs: [res.saved.manifestPath], resumePrompt: "Continue media work based on last output" } });
24772
24739
  } catch {
24773
24740
  }
24774
24741
  try {
@@ -26666,40 +26633,40 @@ var init_about_command = __esm({
26666
26633
  async execute(args2, context2) {
26667
26634
  const output3 = [];
26668
26635
  output3.push("");
26669
- output3.push(chalk40__default.default.cyan.bold("\u{1F916} About MARIA v4.4.0"));
26636
+ output3.push(chalk40__default.default.cyan.bold("About MARIA v4.4.2"));
26670
26637
  output3.push(chalk40__default.default.gray("\u2550".repeat(40)));
26671
26638
  output3.push("");
26672
26639
  output3.push(chalk40__default.default.white.bold("MARIA - Minimal API, Maximum Power"));
26673
26640
  output3.push("");
26674
- output3.push(chalk40__default.default.white("\u{1F3AF} Revolutionary AI Development Platform:"));
26641
+ output3.push(chalk40__default.default.white("Revolutionary AI Development Platform:"));
26675
26642
  output3.push(" \u2022 Natural Language Code Operations");
26676
26643
  output3.push(" \u2022 Graph RAG Knowledge System");
26677
26644
  output3.push(" \u2022 Dual Memory Architecture");
26678
26645
  output3.push(" \u2022 Enterprise-Grade Security");
26679
26646
  output3.push(" \u2022 Multimodal AI Generation");
26680
26647
  output3.push("");
26681
- output3.push(chalk40__default.default.white("\u{1F31F} Key Features:"));
26648
+ output3.push(chalk40__default.default.white("Key Features:"));
26682
26649
  output3.push(" \u2022 /code - Natural language coding");
26683
26650
  output3.push(" \u2022 68+ Slash Commands");
26684
26651
  output3.push(" \u2022 8 AI Provider Support");
26685
26652
  output3.push(" \u2022 Business Operations Suite");
26686
26653
  output3.push(" \u2022 Real-time Streaming");
26687
26654
  output3.push("");
26688
- output3.push(chalk40__default.default.white("\u{1F468}\u200D\u{1F4BB} Created by:"));
26655
+ output3.push(chalk40__default.default.white("Created by:"));
26689
26656
  output3.push(" \u2022 Bonginkan Team");
26690
26657
  output3.push(" \u2022 Enterprise AI Solutions");
26691
26658
  output3.push("");
26692
- output3.push(chalk40__default.default.white("\u{1F517} Links:"));
26659
+ output3.push(chalk40__default.default.white("Links:"));
26693
26660
  output3.push(chalk40__default.default.blue(" Website: https://maria-code.ai"));
26694
26661
  output3.push(chalk40__default.default.blue(" Company: https://bonginkan.ai"));
26695
26662
  output3.push(chalk40__default.default.blue(" Discord: https://discord.gg/SMSmSGcEQy"));
26696
26663
  output3.push(chalk40__default.default.blue(" GitHub: https://github.com/bonginkan/maria"));
26697
26664
  output3.push(chalk40__default.default.blue(" NPM: https://www.npmjs.com/package/@bonginkan/maria"));
26698
26665
  output3.push("");
26699
- output3.push(chalk40__default.default.white("\u{1F4C4} License: MIT"));
26700
- output3.push(chalk40__default.default.white("\u{1F3D7}\uFE0F Built with: TypeScript, Node.js, React"));
26666
+ output3.push(chalk40__default.default.white("License: MIT"));
26667
+ output3.push(chalk40__default.default.white("Built with: TypeScript, Node.js, React"));
26701
26668
  output3.push("");
26702
- output3.push(chalk40__default.default.green("Thank you for using MARIA! \u{1F680}"));
26669
+ output3.push(chalk40__default.default.green("Thank you for using MARIA!"));
26703
26670
  output3.push("");
26704
26671
  return {
26705
26672
  success: true,
@@ -38738,7 +38705,7 @@ var init_code_utils = __esm({
38738
38705
  });
38739
38706
 
38740
38707
  // src/services/creative/NovelArgumentInference.ts
38741
- function extractFirstJson4(text) {
38708
+ function extractFirstJson5(text) {
38742
38709
  if (!text) return null;
38743
38710
  const start = text.indexOf("{");
38744
38711
  const end = text.lastIndexOf("}");
@@ -38789,7 +38756,7 @@ ${rawText}`,
38789
38756
  }
38790
38757
  });
38791
38758
  const raw = (resp?.data?.content || resp?.output || "").trim();
38792
- const jsonText = extractFirstJson4(raw) || raw;
38759
+ const jsonText = extractFirstJson5(raw) || raw;
38793
38760
  let parsed = {};
38794
38761
  try {
38795
38762
  parsed = JSON.parse(jsonText);
@@ -38954,10 +38921,11 @@ var NovelCommand, novel_command_default;
38954
38921
  var init_novel_command = __esm({
38955
38922
  "src/slash-commands/categories/creative/novel.command.ts"() {
38956
38923
  init_base_command();
38957
- init_code_utils();
38958
38924
  init_api_caller();
38925
+ init_code_utils();
38959
38926
  init_NovelArgumentInference();
38960
38927
  init_animations();
38928
+ init_session();
38961
38929
  NovelCommand = class extends BaseCommand {
38962
38930
  name = "novel";
38963
38931
  category = "creative";
@@ -39053,6 +39021,12 @@ var init_novel_command = __esm({
39053
39021
  await writeText(planPath, plan);
39054
39022
  if (planOnly) {
39055
39023
  const msg2 = [`Saved plan to ${planPath}`, "", "Files:", `- ${planPath}`].join("\n");
39024
+ try {
39025
+ const summary = `Novel plan saved: ${path11__namespace.relative(root, planPath)}`;
39026
+ new SessionMemory(root).save({ taskId: "llm.novel", resumeAt: (/* @__PURE__ */ new Date()).toISOString(), context: { summary, decisions: [], artifacts: [planPath], refs: [planPath] } });
39027
+ await callAPI("/api/v1/snapshots", { method: "POST", body: { projectId: "default", taskId: "llm.novel", summary, decisions: [], artifacts: [path11__namespace.relative(root, planPath)], refs: [path11__namespace.relative(root, planPath)], resumePrompt: ideaText } });
39028
+ } catch {
39029
+ }
39056
39030
  return this.success(msg2, { dir: novelDir, plan: planPath });
39057
39031
  }
39058
39032
  const chapterObjs = await (async () => {
@@ -39087,6 +39061,13 @@ ${ch.content}` : ch.content;
39087
39061
  "Files:",
39088
39062
  ...saved.map((p) => `- ${p}`)
39089
39063
  ].join("\n");
39064
+ try {
39065
+ const rels = saved.map((p) => path11__namespace.relative(root, p));
39066
+ const summary = `Novel generated: ${title}`;
39067
+ new SessionMemory(root).save({ taskId: "llm.novel", resumeAt: (/* @__PURE__ */ new Date()).toISOString(), context: { summary, decisions: [], artifacts: rels, refs: rels } });
39068
+ await callAPI("/api/v1/snapshots", { method: "POST", body: { projectId: "default", taskId: "llm.novel", summary, decisions: [], artifacts: rels, refs: rels, resumePrompt: ideaText } });
39069
+ } catch {
39070
+ }
39090
39071
  return this.success(msg, { dir: novelDir, files: saved });
39091
39072
  }
39092
39073
  };
@@ -39177,7 +39158,7 @@ var init_rate_limit_handler = __esm({
39177
39158
  });
39178
39159
 
39179
39160
  // src/services/code-orchestrator/ArgumentInference.ts
39180
- function extractFirstJson5(text) {
39161
+ function extractFirstJson6(text) {
39181
39162
  const fence = /```json\r?\n([\s\S]*?)```/i.exec(text);
39182
39163
  if (fence) return fence[1];
39183
39164
  const start = text.indexOf("{");
@@ -39229,7 +39210,7 @@ ${rawText}`,
39229
39210
  }
39230
39211
  });
39231
39212
  const raw = (resp?.data?.content || resp?.output || "").trim();
39232
- const jsonText = extractFirstJson5(raw) || raw;
39213
+ const jsonText = extractFirstJson6(raw) || raw;
39233
39214
  let parsed = {};
39234
39215
  try {
39235
39216
  parsed = JSON.parse(jsonText);
@@ -41854,11 +41835,12 @@ var LANGUAGE_EXTENSIONS, CodeCommand, codeCommand, metadata3;
41854
41835
  var init_code_command = __esm({
41855
41836
  "src/slash-commands/categories/code/code.command.ts"() {
41856
41837
  init_base_command();
41857
- init_api_caller();
41858
41838
  init_rate_limit_handler();
41859
41839
  init_animations();
41860
41840
  init_code_utils();
41861
41841
  init_ArgumentInference();
41842
+ init_session();
41843
+ init_api_caller();
41862
41844
  LANGUAGE_EXTENSIONS = {
41863
41845
  javascript: ".js",
41864
41846
  typescript: ".ts",
@@ -42022,6 +42004,12 @@ var init_code_command = __esm({
42022
42004
  const outPath = path66.join(plansDir, fileName);
42023
42005
  await fs54.writeFile(outPath, md.join("\n") + "\n", "utf8");
42024
42006
  const rel = path66.relative(root, outPath);
42007
+ try {
42008
+ const summary = `Code plan saved: ${rel}`;
42009
+ new SessionMemory(root).save({ taskId: "llm.code", resumeAt: (/* @__PURE__ */ new Date()).toISOString(), context: { summary, decisions: [], artifacts: [rel], refs: [rel] } });
42010
+ await callAPI("/api/v1/snapshots", { method: "POST", body: { projectId: "default", taskId: "llm.code", summary, decisions: [], artifacts: [rel], refs: [rel], resumePrompt: request } });
42011
+ } catch {
42012
+ }
42025
42013
  return this.success(`Code plan saved: ${rel}`);
42026
42014
  }
42027
42015
  const detail = res?.detailLines;
@@ -42029,6 +42017,14 @@ var init_code_command = __esm({
42029
42017
  return this.success(detail.join("\n"));
42030
42018
  }
42031
42019
  const out = Array.isArray(res?.summaryLines) ? res.summaryLines.join("\n") : "";
42020
+ try {
42021
+ const artifacts = [];
42022
+ const refs = [];
42023
+ const summary = out || "Code generation completed";
42024
+ new SessionMemory(root).save({ taskId: "llm.code", resumeAt: (/* @__PURE__ */ new Date()).toISOString(), context: { summary, decisions: [], artifacts, refs } });
42025
+ await callAPI("/api/v1/snapshots", { method: "POST", body: { projectId: "default", taskId: "llm.code", summary, decisions: [], artifacts, refs, resumePrompt: request } });
42026
+ } catch {
42027
+ }
42032
42028
  return this.success(out);
42033
42029
  } finally {
42034
42030
  if (startedLocalSpinner && spinner) {
@@ -42202,7 +42198,7 @@ ${user}`
42202
42198
  } catch {
42203
42199
  }
42204
42200
  const content = (resp?.data?.content || resp?.content || "").trim();
42205
- const extractFirstJson7 = (text) => {
42201
+ const extractFirstJson8 = (text) => {
42206
42202
  const fence = /```\s*json\s*\r?\n([\s\S]*?)```/i.exec(text);
42207
42203
  if (fence) return fence[1];
42208
42204
  const generic = /```\s*\r?\n([\s\S]*?)```/i.exec(text);
@@ -42225,7 +42221,7 @@ ${user}`
42225
42221
  }
42226
42222
  return null;
42227
42223
  };
42228
- const jsonText = extractFirstJson7(content) || content;
42224
+ const jsonText = extractFirstJson8(content) || content;
42229
42225
  let parsed = {};
42230
42226
  try {
42231
42227
  parsed = JSON.parse(jsonText);
@@ -42708,6 +42704,218 @@ var init_resume_plan = __esm({
42708
42704
  "src/memory/resume-plan.ts"() {
42709
42705
  }
42710
42706
  });
42707
+ function assertSnapshot(data) {
42708
+ const res = SnapshotZ.safeParse(data);
42709
+ if (!res.success) {
42710
+ const details = res.error.issues.map((i2) => `${i2.path.join(".") || "<root>"} ${i2.message}`).join(" | ");
42711
+ throw new ValidationError2(`Invalid snapshot: ${details}`);
42712
+ }
42713
+ }
42714
+ var SnapshotZ, ValidationError2;
42715
+ var init_validators = __esm({
42716
+ "src/memory/validators.ts"() {
42717
+ SnapshotZ = zod.z.object({
42718
+ snapshotVersion: zod.z.literal(1),
42719
+ projectId: zod.z.string().optional(),
42720
+ taskId: zod.z.string().min(1),
42721
+ timestamp: zod.z.string().datetime(),
42722
+ // ISO-8601 UTC expected
42723
+ summary: zod.z.string().min(1),
42724
+ decisions: zod.z.array(zod.z.string()).optional(),
42725
+ artifacts: zod.z.array(zod.z.string()).optional(),
42726
+ links: zod.z.array(
42727
+ zod.z.object({
42728
+ type: zod.z.enum(["doc", "fs", "url", "firestore"]),
42729
+ ref: zod.z.string().min(1)
42730
+ })
42731
+ ).optional(),
42732
+ hash: zod.z.string().optional(),
42733
+ score: zod.z.object({
42734
+ testsPassRate: zod.z.number().min(0).max(1).optional(),
42735
+ coverage: zod.z.number().min(0).max(1).optional()
42736
+ }).optional(),
42737
+ tags: zod.z.array(zod.z.string()).optional(),
42738
+ resumePrompt: zod.z.string().optional()
42739
+ });
42740
+ ValidationError2 = class extends Error {
42741
+ constructor(message) {
42742
+ super(message);
42743
+ this.name = "ValidationError";
42744
+ }
42745
+ };
42746
+ }
42747
+ });
42748
+ function storeFactory(ctx2) {
42749
+ const mode = process.env.MARIA_STORE || "firestore";
42750
+ if (process.env.MARIA_DEBUG === "1") ctx2.logger?.info?.(`[resume] store=${mode}`);
42751
+ if (mode === "firestore") {
42752
+ try {
42753
+ const uid = ctx2.uid;
42754
+ const projectId = ctx2.projectId || "default";
42755
+ if (uid) return new HttpSnapshotStore(projectId);
42756
+ const db = ctx2.firestore || tryGetFirestore();
42757
+ if (db) return new FirestoreSnapshotStore(db);
42758
+ console.warn("[resume] http/firestore not available; falling back to mock store");
42759
+ } catch (e2) {
42760
+ console.warn("[resume] firestore error; falling back to mock store:", e2?.message || e2);
42761
+ }
42762
+ }
42763
+ return new MockSnapshotStore(ctx2.cwd || process.cwd());
42764
+ }
42765
+ function tryGetFirestore() {
42766
+ try {
42767
+ const admin = __require("firebase-admin");
42768
+ if (!admin.apps || admin.apps.length === 0) {
42769
+ try {
42770
+ admin.initializeApp();
42771
+ } catch {
42772
+ }
42773
+ }
42774
+ const { getFirestore } = __require("firebase-admin/firestore");
42775
+ return getFirestore();
42776
+ } catch {
42777
+ return null;
42778
+ }
42779
+ }
42780
+ var MockSnapshotStore, FirestoreSnapshotStore, HttpSnapshotStore;
42781
+ var init_firestore = __esm({
42782
+ "src/memory/firestore.ts"() {
42783
+ init_validators();
42784
+ MockSnapshotStore = class {
42785
+ constructor(cwd2 = process.cwd()) {
42786
+ this.cwd = cwd2;
42787
+ }
42788
+ async getLatest(_projectId, limit = 1) {
42789
+ const s2 = this.readLocal();
42790
+ return s2.slice(0, limit);
42791
+ }
42792
+ async getByTask(_projectId, taskId, limit = 5) {
42793
+ const s2 = this.readLocal().filter((x2) => x2.taskId === taskId);
42794
+ return s2.slice(0, limit);
42795
+ }
42796
+ async getByDate(_projectId, dateISO, limit = 5) {
42797
+ const s2 = this.readLocal().filter((x2) => x2.timestamp?.startsWith(dateISO));
42798
+ return s2.slice(0, limit);
42799
+ }
42800
+ readLocal() {
42801
+ const sessionPath = path11__namespace.default.join(this.cwd, ".maria", "memory", "session.json");
42802
+ const candidates = [];
42803
+ try {
42804
+ const raw = JSON.parse(fs20__namespace.default.readFileSync(sessionPath, "utf8"));
42805
+ const ctx2 = raw?.context;
42806
+ if (ctx2?.summary) {
42807
+ const synthetic = {
42808
+ snapshotVersion: 1,
42809
+ projectId: "default",
42810
+ taskId: raw.taskId || "resume.task",
42811
+ timestamp: raw.resumeAt || (/* @__PURE__ */ new Date()).toISOString(),
42812
+ summary: ctx2.summary,
42813
+ decisions: ctx2.decisions || [],
42814
+ artifacts: ctx2.artifacts || [],
42815
+ links: (ctx2.refs || []).map((r2) => ({ type: "url", ref: r2 }))
42816
+ };
42817
+ assertSnapshot(synthetic);
42818
+ const snap = synthetic;
42819
+ candidates.push(snap);
42820
+ }
42821
+ } catch {
42822
+ }
42823
+ if (candidates.length === 0) {
42824
+ const fallback2 = {
42825
+ snapshotVersion: 1,
42826
+ projectId: "default",
42827
+ taskId: "example.task",
42828
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
42829
+ summary: "\u524D\u56DE\u4F5C\u696D\u306E\u7D9A\u304D\u3002/code \u3092\u518D\u958B\u3067\u304D\u308B\u3088\u3046\u306B\u6E96\u5099\u6E08\u307F\u3002",
42830
+ decisions: ["\u81EA\u52D5\u30C6\u30B9\u30C8\u306F\u6700\u4F4E\u9650", "\u7834\u58CA\u7684\u5909\u66F4\u306F\u3057\u306A\u3044"],
42831
+ artifacts: ["README.md"],
42832
+ links: [{ type: "doc", ref: "docs/RESUME_FUNCTION_DESIGN.md" }],
42833
+ resumePrompt: "\u6628\u65E5\u306E\u7D9A\u304D\u304B\u3089\u518D\u958B\u3057\u3066\u3001\u5DEE\u5206\u306E\u307F\u9069\u7528\u3057\u3066\u4E0B\u3055\u3044\u3002"
42834
+ };
42835
+ assertSnapshot(fallback2);
42836
+ const snap = fallback2;
42837
+ candidates.push(snap);
42838
+ }
42839
+ return candidates;
42840
+ }
42841
+ };
42842
+ FirestoreSnapshotStore = class {
42843
+ constructor(db) {
42844
+ this.db = db;
42845
+ }
42846
+ async getLatest(projectId, limit = 1) {
42847
+ const q = this.db.collectionGroup("snapshots").where("projectId", "==", projectId).orderBy("timestamp", "desc").limit(limit);
42848
+ const ss = await q.get();
42849
+ return this.validateDocs(ss.docs.map((d) => d.data()));
42850
+ }
42851
+ async getByTask(projectId, taskId, limit = 5) {
42852
+ const q = this.db.collection("projects").doc(projectId).collection("tasks").doc(taskId).collection("snapshots").orderBy("timestamp", "desc").limit(limit);
42853
+ const ss = await q.get();
42854
+ return this.validateDocs(ss.docs.map((d) => d.data()));
42855
+ }
42856
+ async getByDate(projectId, dateISO, limit = 5) {
42857
+ const start = new Date(dateISO).toISOString();
42858
+ const end = new Date(new Date(dateISO).getTime() + 24 * 60 * 60 * 1e3).toISOString();
42859
+ const q = this.db.collectionGroup("snapshots").where("projectId", "==", projectId).where("timestamp", ">=", start).where("timestamp", "<", end).orderBy("timestamp", "desc").limit(limit);
42860
+ const ss = await q.get();
42861
+ return this.validateDocs(ss.docs.map((d) => d.data()));
42862
+ }
42863
+ validateDocs(rows) {
42864
+ const out = [];
42865
+ for (const r2 of rows) {
42866
+ try {
42867
+ assertSnapshot(r2);
42868
+ out.push(r2);
42869
+ } catch {
42870
+ }
42871
+ }
42872
+ return out;
42873
+ }
42874
+ };
42875
+ HttpSnapshotStore = class {
42876
+ constructor(projectId) {
42877
+ this.projectId = projectId;
42878
+ }
42879
+ async fetchJson(pathname) {
42880
+ const { callAPI: callAPI2 } = await Promise.resolve().then(() => (init_api_caller(), api_caller_exports));
42881
+ return await callAPI2(pathname, { method: "GET" });
42882
+ }
42883
+ async getLatest(projectId, limit = 5) {
42884
+ const pid = projectId || this.projectId || "default";
42885
+ const resp = await this.fetchJson(`/api/v1/get-snapshots?projectId=${encodeURIComponent(pid)}&limit=${limit}`);
42886
+ const arr = Array.isArray(resp?.data?.snapshots) ? resp.data.snapshots : [];
42887
+ return this.validate(arr);
42888
+ }
42889
+ async getByTask(projectId, taskId, limit = 5) {
42890
+ const pid = projectId || this.projectId || "default";
42891
+ const resp = await this.fetchJson(`/api/v1/get-snapshots?projectId=${encodeURIComponent(pid)}&taskId=${encodeURIComponent(taskId)}&limit=${limit}`);
42892
+ const arr = Array.isArray(resp?.data?.snapshots) ? resp.data.snapshots : [];
42893
+ return this.validate(arr);
42894
+ }
42895
+ async getByDate(projectId, dateISO, limit = 5) {
42896
+ const pid = projectId || this.projectId || "default";
42897
+ const resp = await this.fetchJson(`/api/v1/get-snapshots?projectId=${encodeURIComponent(pid)}&date=${encodeURIComponent(dateISO)}&limit=${limit}`);
42898
+ const arr = Array.isArray(resp?.data?.snapshots) ? resp.data.snapshots : [];
42899
+ return this.validate(arr);
42900
+ }
42901
+ validate(rows) {
42902
+ const out = [];
42903
+ for (const r2 of rows) {
42904
+ try {
42905
+ assertSnapshot(r2);
42906
+ out.push(r2);
42907
+ } catch {
42908
+ }
42909
+ }
42910
+ if (out.length === 0) {
42911
+ const mock = new MockSnapshotStore(process.cwd());
42912
+ return (async () => await mock.getLatest(this.projectId, 1))();
42913
+ }
42914
+ return out;
42915
+ }
42916
+ };
42917
+ }
42918
+ });
42711
42919
 
42712
42920
  // src/memory/rehydrator.ts
42713
42921
  function rehydrateSnapshot(s2, opts = {}) {
@@ -42844,27 +43052,59 @@ function truncate2(s2, n) {
42844
43052
  }
42845
43053
  function promptLine(timeoutMs = 15e3) {
42846
43054
  return new Promise((resolve19) => {
42847
- const rl = readline__namespace.default.createInterface({ input: process.stdin, output: process.stdout });
42848
- const done = (ok, line) => {
43055
+ let finished = false;
43056
+ const input3 = process.stdin;
43057
+ const wasRaw = !!input3.isRaw;
43058
+ const finish = (ok, line) => {
43059
+ if (finished) return;
43060
+ finished = true;
42849
43061
  try {
42850
- rl.close();
43062
+ input3.removeListener("keypress", onKey);
43063
+ } catch {
43064
+ }
43065
+ try {
43066
+ if (input3.isTTY) input3.setRawMode(wasRaw);
42851
43067
  } catch {
42852
43068
  }
42853
43069
  resolve19({ ok, line });
42854
43070
  };
42855
- const t2 = setTimeout(() => done(true, "1"), timeoutMs);
42856
- rl.question("\u756A\u53F7\u3092\u5165\u529B > ", (l) => {
42857
- clearTimeout(t2);
42858
- done(true, l);
42859
- });
42860
- rl.once("SIGINT", () => {
42861
- clearTimeout(t2);
42862
- done(false);
42863
- });
42864
- rl.once("close", () => {
42865
- clearTimeout(t2);
42866
- done(false);
42867
- });
43071
+ const t2 = setTimeout(() => finish(true, "1"), timeoutMs);
43072
+ try {
43073
+ process.stdout.write("Enter number > ");
43074
+ } catch {
43075
+ }
43076
+ try {
43077
+ if (input3.isTTY) input3.setRawMode(true);
43078
+ } catch {
43079
+ }
43080
+ readline__namespace.emitKeypressEvents(input3);
43081
+ let buffer = "";
43082
+ const onKey = (_str, key) => {
43083
+ if (key?.ctrl && key.name === "c") {
43084
+ clearTimeout(t2);
43085
+ finish(false);
43086
+ return;
43087
+ }
43088
+ if (key?.name === "escape") {
43089
+ clearTimeout(t2);
43090
+ finish(false);
43091
+ return;
43092
+ }
43093
+ if (key?.name === "return" || key?.name === "enter") {
43094
+ clearTimeout(t2);
43095
+ const value = buffer.trim() || "1";
43096
+ finish(true, value);
43097
+ return;
43098
+ }
43099
+ if (key?.name === "backspace") {
43100
+ buffer = buffer.slice(0, -1);
43101
+ return;
43102
+ }
43103
+ if (/^[0-9]$/.test(_str)) {
43104
+ buffer += _str;
43105
+ }
43106
+ };
43107
+ input3.on("keypress", onKey);
42868
43108
  });
42869
43109
  }
42870
43110
  async function readLastDebugStatusSafe(cwd2) {
@@ -42917,7 +43157,8 @@ var init_resume_command = __esm({
42917
43157
  const dbg = await readLastDebugStatusSafe(context2.environment.cwd);
42918
43158
  const opts = this.parseOptions(args2.raw);
42919
43159
  const projectId = "default";
42920
- const store2 = storeFactory({ cwd: context2.environment.cwd, logger: console });
43160
+ const uid = context2.user?.id || void 0;
43161
+ const store2 = storeFactory({ cwd: context2.environment.cwd, logger: console, uid, projectId });
42921
43162
  let candidates = [];
42922
43163
  if (opts.taskId) candidates = await store2.getByTask(projectId, opts.taskId, opts.limit || 5);
42923
43164
  else if (opts.date) candidates = await store2.getByDate(projectId, opts.date, opts.limit || 5);
@@ -42971,9 +43212,9 @@ var init_resume_command = __esm({
42971
43212
  context: plan.context
42972
43213
  });
42973
43214
  const lines = [];
42974
- if (dbg && (opts.debugLatest || !opts.debugList && !opts.noDebug)) {
43215
+ if (process.env.MARIA_DEBUG === "1" && dbg && (opts.debugLatest || !opts.debugList && !opts.noDebug)) {
42975
43216
  lines.push("");
42976
- lines.push("\u{1F9ED} Last debug-fix status");
43217
+ lines.push("Last debug-fix status");
42977
43218
  lines.push("".padEnd(30, "\u2550"));
42978
43219
  lines.push(`hash: ${dbg.promptHash.slice(0, 12)} \xB7 plan=${dbg.planUsed || "none"} \xB7 category=${dbg.errorCategory || (dbg.verify?.ok ? "ok" : "unknown")} \xB7 exit=${typeof dbg.exitCode === "number" ? dbg.exitCode : dbg.verify?.ok ? 0 : 1}`);
42979
43220
  if (dbg.verify && !dbg.verify.ok && dbg.verify.stage) {
@@ -42981,12 +43222,12 @@ var init_resume_command = __esm({
42981
43222
  }
42982
43223
  lines.push("");
42983
43224
  }
42984
- if (opts.debugList) {
43225
+ if (process.env.MARIA_DEBUG === "1" && opts.debugList) {
42985
43226
  const count = Number.isFinite(opts.debugLimit) ? Math.max(1, Math.min(50, Number(opts.debugLimit))) : 5;
42986
43227
  const list = await readDebugJournalListSafe(context2.environment.cwd, count);
42987
43228
  if (list.length) {
42988
43229
  lines.push("");
42989
- lines.push(`\u{1F9ED} Debug history (latest ${list.length})`);
43230
+ lines.push(`Debug history (latest ${list.length})`);
42990
43231
  lines.push("".padEnd(34, "\u2550"));
42991
43232
  for (const it of list) {
42992
43233
  const t2 = it.createdAt ? new Date(it.createdAt).toISOString().replace("T", " ").replace("Z", "Z") : "";
@@ -42997,7 +43238,7 @@ var init_resume_command = __esm({
42997
43238
  }
42998
43239
  }
42999
43240
  lines.push(`
43000
- \u{1F4CC} Resuming: ${s2.taskId}`);
43241
+ Resuming: ${s2.taskId}`);
43001
43242
  lines.push(`Summary: ${truncate2(plan.context.summary, 400)}`);
43002
43243
  if (plan.context.decisions?.length) lines.push(`Decisions: ${plan.context.decisions.join(" / ")}`);
43003
43244
  if (plan.context.artifacts?.length) lines.push(`Artifacts: ${plan.context.artifacts.slice(0, 10).join(", ")}`);
@@ -43050,7 +43291,6 @@ var init_resume_command = __esm({
43050
43291
  lines.push("\u26A0 /code execution threw \u2014 showing suggestion instead");
43051
43292
  lines.push("");
43052
43293
  }
43053
- lines.push(`\u{1F449} Next: /code "${plan.nextPrompt}" ${plan.codeFlags.join(" ")}`.trim());
43054
43294
  return this.success(lines.join("\n"), { elapsedMs: Date.now() - start });
43055
43295
  } catch (e2) {
43056
43296
  return this.error("Failed to resume", "RESUME_ERROR", e2?.message || String(e2));
@@ -43089,13 +43329,15 @@ var init_resume_command = __esm({
43089
43329
  const t2 = new Date(c.timestamp).toISOString().replace("T", " ").replace("Z", "Z");
43090
43330
  return `${idx + 1}) [${t2}] ${c.taskId} \u2014 ${head2(c.summary)}`;
43091
43331
  };
43092
- console.log("\n\u5019\u88DC\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044 (15s \u3067 1 \u3092\u63A1\u7528):");
43332
+ console.log("\nSelect a candidate (defaults to 1 after 15s):");
43093
43333
  for (let i2 = 0; i2 < cands.length; i2++) {
43094
43334
  console.log(" " + fmt(cands[i2], i2));
43095
43335
  }
43096
43336
  const ans = await promptLine(15e3);
43097
43337
  if (!ans.ok) return null;
43098
- const n = parseInt((ans.line || "1").trim(), 10);
43338
+ const raw = (ans.line || "1").trim();
43339
+ const m2 = raw.match(/\d+/);
43340
+ const n = m2 ? parseInt(m2[0], 10) : 1;
43099
43341
  if (!Number.isFinite(n) || n < 1 || n > cands.length) return cands[0];
43100
43342
  return cands[n - 1];
43101
43343
  }
@@ -55622,6 +55864,7 @@ var init_ResearchCommand = __esm({
55622
55864
  init_logger();
55623
55865
  init_api_client();
55624
55866
  init_animations();
55867
+ init_session();
55625
55868
  ResearchCommand = class extends BaseCommand {
55626
55869
  name = "research";
55627
55870
  category = "analysis";
@@ -55705,6 +55948,13 @@ var init_ResearchCommand = __esm({
55705
55948
  });
55706
55949
  }
55707
55950
  const message = lines.filter(Boolean).join("\n");
55951
+ try {
55952
+ const root = context2.environment?.cwd || process.cwd();
55953
+ const summary = "Research completed";
55954
+ new SessionMemory(root).save({ taskId: "llm.research", resumeAt: (/* @__PURE__ */ new Date()).toISOString(), context: { summary, decisions: [], artifacts: [], refs: [] } });
55955
+ await callApiJson("/api/v1/snapshots", { method: "POST", body: JSON.stringify({ projectId: "default", taskId: "llm.research", summary, decisions: [], artifacts: [], refs: [], resumePrompt: (_args.raw || []).join(" ") }), headers: { "Content-Type": "application/json" } });
55956
+ } catch {
55957
+ }
55708
55958
  const result = this.success(message);
55709
55959
  result.metadata = { executionTime: Date.now() - startedAt };
55710
55960
  this.logExecution(_args, context2, result);
@@ -59885,7 +60135,7 @@ ${user}`,
59885
60135
  };
59886
60136
  }
59887
60137
  });
59888
- function extractFirstJson6(text) {
60138
+ function extractFirstJson7(text) {
59889
60139
  const fence = /```json\r?\n([\s\S]*?)```/i.exec(text);
59890
60140
  if (fence) return fence[1];
59891
60141
  const start = text.indexOf("{");
@@ -59947,7 +60197,7 @@ ${user}`,
59947
60197
  }
59948
60198
  });
59949
60199
  const raw = (response?.data?.content || response?.output || "").trim();
59950
- const jsonText = extractFirstJson6(raw) || raw;
60200
+ const jsonText = extractFirstJson7(raw) || raw;
59951
60201
  let parsed = {};
59952
60202
  try {
59953
60203
  parsed = JSON.parse(jsonText);
@@ -59989,9 +60239,10 @@ var init_evaluate_command = __esm({
59989
60239
  init_base_command();
59990
60240
  init_logger();
59991
60241
  init_EvaluationOrchestrator();
59992
- init_api_caller();
59993
60242
  init_animations();
59994
60243
  init_ArgumentInference2();
60244
+ init_session();
60245
+ init_api_caller();
59995
60246
  EvaluateCommand = class extends BaseCommand {
59996
60247
  name = "evaluate";
59997
60248
  category = "evaluation";
@@ -60259,6 +60510,13 @@ ${options["code"] || inferred.code}` : void 0
60259
60510
  const finalText = uploadNote ? `${uploadNote}
60260
60511
 
60261
60512
  ${content}` : content;
60513
+ try {
60514
+ const summary = `Evaluation assess completed: total=${Math.round(result.totalScore * 100)}/100`;
60515
+ const rel = path11__namespace.default.relative(root, criteriaPath);
60516
+ new SessionMemory(root).save({ taskId: "llm.evaluate", resumeAt: (/* @__PURE__ */ new Date()).toISOString(), context: { summary, decisions: [], artifacts: [rel], refs: [rel] } });
60517
+ await callAPI("/api/v1/snapshots", { method: "POST", body: { projectId: "default", taskId: "llm.evaluate", summary, decisions: [], artifacts: [rel], refs: [rel], resumePrompt: rawCmd } });
60518
+ } catch {
60519
+ }
60262
60520
  return this.success(finalText, {
60263
60521
  type: "evaluation-assess",
60264
60522
  total: result.totalScore,