@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.
@@ -26067,8 +26067,8 @@ var require_package = __commonJS({
26067
26067
  "package.json"(exports, module) {
26068
26068
  module.exports = {
26069
26069
  name: "@bonginkan/maria",
26070
- version: "4.4.0",
26071
- 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.",
26070
+ version: "4.4.2",
26071
+ description: "\u{1F680} MARIA v4.4.2 - Enterprise AI Development Platform with identity system and character voice implementation. Features 74 production-ready commands with comprehensive fallback implementation, local LLM support, and zero external dependencies. Includes natural language coding, AI safety evaluation, intelligent evolution system, episodic memory with PII masking, and real-time monitoring dashboard. Built with TypeScript AST-powered code generation, OAuth2.0 + PKCE authentication, quantum-resistant cryptography, and enterprise-grade performance.",
26072
26072
  keywords: [
26073
26073
  "ai",
26074
26074
  "cli",
@@ -28131,7 +28131,7 @@ var init_AuthenticationManager = __esm({
28131
28131
  const response = await fetch(`${this.apiBase}/api/user/profile`, {
28132
28132
  headers: {
28133
28133
  "Authorization": `Bearer ${tokens2.accessToken}`,
28134
- "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.4.0"}`
28134
+ "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.4.2"}`
28135
28135
  }
28136
28136
  });
28137
28137
  if (response.status === 401) {
@@ -28785,7 +28785,7 @@ async function callApi(path66, init3 = {}) {
28785
28785
  "Authorization": `Bearer ${token}`,
28786
28786
  "X-Device-Id": getDeviceId(),
28787
28787
  "X-Session-Id": getSessionId() || "",
28788
- "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.4.0"}`,
28788
+ "User-Agent": `maria-cli/${process.env.CLI_VERSION || "4.4.2"}`,
28789
28789
  "Content-Type": init3.headers?.["Content-Type"] || "application/json"
28790
28790
  });
28791
28791
  const doFetch = async (token) => {
@@ -35748,10 +35748,10 @@ var init_ignore = __esm({
35748
35748
  ignored(p) {
35749
35749
  const fullpath = p.fullpath();
35750
35750
  const fullpaths = `${fullpath}/`;
35751
- const relative5 = p.relative() || ".";
35752
- const relatives = `${relative5}/`;
35751
+ const relative6 = p.relative() || ".";
35752
+ const relatives = `${relative6}/`;
35753
35753
  for (const m2 of this.relative) {
35754
- if (m2.match(relative5) || m2.match(relatives))
35754
+ if (m2.match(relative6) || m2.match(relatives))
35755
35755
  return true;
35756
35756
  }
35757
35757
  for (const m2 of this.absolute) {
@@ -35762,9 +35762,9 @@ var init_ignore = __esm({
35762
35762
  }
35763
35763
  childrenIgnored(p) {
35764
35764
  const fullpath = p.fullpath() + "/";
35765
- const relative5 = (p.relative() || ".") + "/";
35765
+ const relative6 = (p.relative() || ".") + "/";
35766
35766
  for (const m2 of this.relativeChildren) {
35767
- if (m2.match(relative5))
35767
+ if (m2.match(relative6))
35768
35768
  return true;
35769
35769
  }
35770
35770
  for (const m2 of this.absoluteChildren) {
@@ -39105,16 +39105,7 @@ var init_HelpCommand = __esm({
39105
39105
  async showCommandHelp(commandName) {
39106
39106
  const command = await this.readyService.getCommand(commandName);
39107
39107
  if (!command) {
39108
- const searchResults = await this.readyService.searchCommands(commandName, 3);
39109
- const suggestions = searchResults.map((r2) => `/${r2.command.name}`);
39110
- return this.error(
39111
- `READY command not found: /${commandName}`,
39112
- "COMMAND_NOT_FOUND",
39113
- {
39114
- suggestions,
39115
- tip: "Only contract-validated READY commands are shown"
39116
- }
39117
- );
39108
+ return await this.showGeneralHelp();
39118
39109
  }
39119
39110
  const lines = this.formatMinimalUsage(command);
39120
39111
  return this.success(lines);
@@ -48095,6 +48086,94 @@ var init_ImageArgumentInference = __esm({
48095
48086
  init_api_caller();
48096
48087
  }
48097
48088
  });
48089
+
48090
+ // src/services/media-orchestrator/VideoArgumentInference.ts
48091
+ function extractFirstJson4(text) {
48092
+ const matches = text.match(/[\[{][\s\S]*[\]}]/g) || [];
48093
+ for (const cand of matches) {
48094
+ try {
48095
+ JSON.parse(cand);
48096
+ return cand;
48097
+ } catch {
48098
+ }
48099
+ }
48100
+ return null;
48101
+ }
48102
+ function parseSizeAny2(x2) {
48103
+ if (!x2) return void 0;
48104
+ const s2 = String(x2).trim().toLowerCase().replace(/p$/, "");
48105
+ const m2 = /^(\d{2,4})x(\d{2,4})$/.exec(s2);
48106
+ if (m2) {
48107
+ const w = Number(m2[1]);
48108
+ const h2 = Number(m2[2]);
48109
+ if (Number.isFinite(w) && Number.isFinite(h2) && w >= 256 && h2 >= 256 && w <= 4096 && h2 <= 4096) return [w, h2];
48110
+ return void 0;
48111
+ }
48112
+ if (s2 === "720") return [1280, 720];
48113
+ if (s2 === "1080") return [1920, 1080];
48114
+ return void 0;
48115
+ }
48116
+ async function inferVideoArgsLLM(promptText) {
48117
+ const system = [
48118
+ "You extract video generation options from user natural language.",
48119
+ 'Return JSON only with keys: { "model"?: "sora-2"|"veo-3.1-generate-preview", "duration"?: number, "aspect"?: "16:9"|"9:16", "size"?: "WIDTHxHEIGHT"|"720"|"1080" }.',
48120
+ "Rules:",
48121
+ '- If user mentions OpenAI Sora, choose model "sora-2". If Google Veo, choose "veo-3.1-generate-preview".',
48122
+ "- Duration options differ: for Sora use one of 4, 8, 12; for Veo prefer 4, 6, 8 (1080p fixed 8).",
48123
+ "- If user says 10 seconds, map to closest allowed (e.g., 8 for Sora/Veo).",
48124
+ '- 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).',
48125
+ '- Size: if 720p or 1080p mentioned, return "720" or "1080". If explicit WxH, return as is if within 256..4096 per side.',
48126
+ "Do not add explanations; JSON only."
48127
+ ].join("\n");
48128
+ let explicitModel;
48129
+ let explicitProvider;
48130
+ try {
48131
+ const { extractExplicitModel: extractExplicitModel2, extractExplicitProvider: extractExplicitProvider2, providerFromModel: providerFromModel2 } = await Promise.resolve().then(() => (init_llm_flags(), llm_flags_exports));
48132
+ explicitModel = extractExplicitModel2(promptText);
48133
+ explicitProvider = extractExplicitProvider2(promptText) || providerFromModel2(explicitModel);
48134
+ } catch {
48135
+ }
48136
+ let attachments = [];
48137
+ try {
48138
+ const { collectFileAttachmentsFromText: collectFileAttachmentsFromText2 } = await Promise.resolve().then(() => (init_attachment_utils(), attachment_utils_exports));
48139
+ attachments = await collectFileAttachmentsFromText2(promptText, process.cwd(), { maxBytes: 12 * 1024 * 1024 });
48140
+ } catch {
48141
+ }
48142
+ const resp = await callAPI("/v1/ai-proxy", {
48143
+ method: "POST",
48144
+ body: {
48145
+ ...explicitProvider ? { provider: explicitProvider } : {},
48146
+ ...explicitModel ? { model: explicitModel } : {},
48147
+ prompt: `${system}
48148
+
48149
+ ---
48150
+
48151
+ ${promptText}`,
48152
+ taskType: "media",
48153
+ ...attachments.length ? { metadata: { attachments } } : {}
48154
+ }
48155
+ });
48156
+ const raw = (resp?.data?.content || resp?.output || "").trim();
48157
+ const jsonText = extractFirstJson4(raw) || raw;
48158
+ let parsed;
48159
+ try {
48160
+ parsed = JSON.parse(jsonText);
48161
+ } catch {
48162
+ return {};
48163
+ }
48164
+ const out = {};
48165
+ if (typeof parsed?.model === "string" && parsed.model.trim()) out.model = String(parsed.model).trim();
48166
+ if (Number.isFinite(Number(parsed?.duration))) out.duration = Math.max(1, Math.floor(Number(parsed.duration)));
48167
+ if (parsed?.aspect === "16:9" || parsed?.aspect === "9:16") out.aspect = parsed.aspect;
48168
+ const size = parseSizeAny2(parsed?.size);
48169
+ if (size) out.size = size;
48170
+ return out;
48171
+ }
48172
+ var init_VideoArgumentInference = __esm({
48173
+ "src/services/media-orchestrator/VideoArgumentInference.ts"() {
48174
+ init_api_caller();
48175
+ }
48176
+ });
48098
48177
  function parseSize(value) {
48099
48178
  const m2 = /^\s*(\d{2,4})x(\d{2,4})\s*$/i.exec(value || "");
48100
48179
  if (!m2) throw new Error(`invalid size: ${value}`);
@@ -48314,6 +48393,15 @@ function normalizeVideoArgs(raw, root) {
48314
48393
  break;
48315
48394
  }
48316
48395
  }
48396
+ try {
48397
+ if (String(process.env.MARIA_USE_LLM_INFER || "1") === "1") {
48398
+ global.__MARIA_VIDEO_LLM_INFER__ = async () => {
48399
+ const llm = await inferVideoArgsLLM(prompt);
48400
+ return llm;
48401
+ };
48402
+ }
48403
+ } catch {
48404
+ }
48317
48405
  if (!out.apply && !out.planOnly && !out.dryRun) {
48318
48406
  out.apply = true;
48319
48407
  }
@@ -48353,6 +48441,7 @@ var init_Normalizer = __esm({
48353
48441
  init_types4();
48354
48442
  init_NLInference();
48355
48443
  init_ImageArgumentInference();
48444
+ init_VideoArgumentInference();
48356
48445
  }
48357
48446
  });
48358
48447
  function ensureDirSync(p) {
@@ -48986,193 +49075,6 @@ ${(/* @__PURE__ */ new Date()).toISOString()}`;
48986
49075
  };
48987
49076
  }
48988
49077
  });
48989
- function assertSnapshot(data) {
48990
- const res = SnapshotZ.safeParse(data);
48991
- if (!res.success) {
48992
- const details = res.error.issues.map((i2) => `${i2.path.join(".") || "<root>"} ${i2.message}`).join(" | ");
48993
- throw new ValidationError2(`Invalid snapshot: ${details}`);
48994
- }
48995
- }
48996
- var SnapshotZ, ValidationError2;
48997
- var init_validators = __esm({
48998
- "src/memory/validators.ts"() {
48999
- SnapshotZ = zod.z.object({
49000
- snapshotVersion: zod.z.literal(1),
49001
- projectId: zod.z.string().optional(),
49002
- taskId: zod.z.string().min(1),
49003
- timestamp: zod.z.string().datetime(),
49004
- // ISO-8601 UTC expected
49005
- summary: zod.z.string().min(1),
49006
- decisions: zod.z.array(zod.z.string()).optional(),
49007
- artifacts: zod.z.array(zod.z.string()).optional(),
49008
- links: zod.z.array(
49009
- zod.z.object({
49010
- type: zod.z.enum(["doc", "fs", "url", "firestore"]),
49011
- ref: zod.z.string().min(1)
49012
- })
49013
- ).optional(),
49014
- hash: zod.z.string().optional(),
49015
- score: zod.z.object({
49016
- testsPassRate: zod.z.number().min(0).max(1).optional(),
49017
- coverage: zod.z.number().min(0).max(1).optional()
49018
- }).optional(),
49019
- tags: zod.z.array(zod.z.string()).optional(),
49020
- resumePrompt: zod.z.string().optional()
49021
- });
49022
- ValidationError2 = class extends Error {
49023
- constructor(message) {
49024
- super(message);
49025
- this.name = "ValidationError";
49026
- }
49027
- };
49028
- }
49029
- });
49030
- function storeFactory(ctx2) {
49031
- const mode = process.env.MARIA_STORE || "mock";
49032
- ctx2.logger?.info?.(`[resume] store=${mode}`);
49033
- if (mode === "firestore") {
49034
- try {
49035
- const db = ctx2.firestore || tryGetFirestore();
49036
- if (db) return new FirestoreSnapshotStore(db);
49037
- console.warn("[resume] firestore not available; falling back to mock store");
49038
- } catch (e2) {
49039
- console.warn("[resume] firestore error; falling back to mock store:", e2?.message || e2);
49040
- }
49041
- }
49042
- return new MockSnapshotStore(ctx2.cwd || process.cwd());
49043
- }
49044
- function tryGetFirestore() {
49045
- try {
49046
- const admin = __require("firebase-admin");
49047
- if (!admin.apps || admin.apps.length === 0) {
49048
- try {
49049
- admin.initializeApp();
49050
- } catch {
49051
- }
49052
- }
49053
- const { getFirestore } = __require("firebase-admin/firestore");
49054
- return getFirestore();
49055
- } catch {
49056
- return null;
49057
- }
49058
- }
49059
- async function trySaveSnapshot(projectId, taskId, data) {
49060
- try {
49061
- const db = tryGetFirestore();
49062
- if (!db) return false;
49063
- const tsId = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").split(".")[0] + "Z";
49064
- const ref = db.collection("projects").doc(projectId).collection("tasks").doc(taskId).collection("snapshots").doc(tsId);
49065
- await ref.set({
49066
- snapshotVersion: 1,
49067
- projectId,
49068
- taskId,
49069
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
49070
- summary: data.summary,
49071
- decisions: data.decisions || [],
49072
- artifacts: data.artifacts || [],
49073
- links: (data.refs || []).map((r2) => ({ type: "fs", ref: r2 })),
49074
- resumePrompt: data.resumePrompt || ""
49075
- });
49076
- return true;
49077
- } catch {
49078
- return false;
49079
- }
49080
- }
49081
- var MockSnapshotStore, FirestoreSnapshotStore;
49082
- var init_firestore = __esm({
49083
- "src/memory/firestore.ts"() {
49084
- init_validators();
49085
- MockSnapshotStore = class {
49086
- constructor(cwd2 = process.cwd()) {
49087
- this.cwd = cwd2;
49088
- }
49089
- async getLatest(_projectId, limit = 1) {
49090
- const s2 = this.readLocal();
49091
- return s2.slice(0, limit);
49092
- }
49093
- async getByTask(_projectId, taskId, limit = 5) {
49094
- const s2 = this.readLocal().filter((x2) => x2.taskId === taskId);
49095
- return s2.slice(0, limit);
49096
- }
49097
- async getByDate(_projectId, dateISO, limit = 5) {
49098
- const s2 = this.readLocal().filter((x2) => x2.timestamp?.startsWith(dateISO));
49099
- return s2.slice(0, limit);
49100
- }
49101
- readLocal() {
49102
- const sessionPath = path12__namespace.default.join(this.cwd, ".maria", "memory", "session.json");
49103
- const candidates = [];
49104
- try {
49105
- const raw = JSON.parse(fs22__namespace.default.readFileSync(sessionPath, "utf8"));
49106
- const ctx2 = raw?.context;
49107
- if (ctx2?.summary) {
49108
- const synthetic = {
49109
- snapshotVersion: 1,
49110
- projectId: "default",
49111
- taskId: raw.taskId || "resume.task",
49112
- timestamp: raw.resumeAt || (/* @__PURE__ */ new Date()).toISOString(),
49113
- summary: ctx2.summary,
49114
- decisions: ctx2.decisions || [],
49115
- artifacts: ctx2.artifacts || [],
49116
- links: (ctx2.refs || []).map((r2) => ({ type: "url", ref: r2 }))
49117
- };
49118
- assertSnapshot(synthetic);
49119
- candidates.push(synthetic);
49120
- }
49121
- } catch {
49122
- }
49123
- if (candidates.length === 0) {
49124
- const fallback2 = {
49125
- snapshotVersion: 1,
49126
- projectId: "default",
49127
- taskId: "example.task",
49128
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
49129
- summary: "\u524D\u56DE\u4F5C\u696D\u306E\u7D9A\u304D\u3002/code \u3092\u518D\u958B\u3067\u304D\u308B\u3088\u3046\u306B\u6E96\u5099\u6E08\u307F\u3002",
49130
- decisions: ["\u81EA\u52D5\u30C6\u30B9\u30C8\u306F\u6700\u4F4E\u9650", "\u7834\u58CA\u7684\u5909\u66F4\u306F\u3057\u306A\u3044"],
49131
- artifacts: ["README.md"],
49132
- links: [{ type: "doc", ref: "docs/RESUME_FUNCTION_DESIGN.md" }],
49133
- 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"
49134
- };
49135
- assertSnapshot(fallback2);
49136
- candidates.push(fallback2);
49137
- }
49138
- return candidates;
49139
- }
49140
- };
49141
- FirestoreSnapshotStore = class {
49142
- constructor(db) {
49143
- this.db = db;
49144
- }
49145
- async getLatest(projectId, limit = 1) {
49146
- const q = this.db.collectionGroup("snapshots").where("projectId", "==", projectId).orderBy("timestamp", "desc").limit(limit);
49147
- const ss = await q.get();
49148
- return this.validateDocs(ss.docs.map((d) => d.data()));
49149
- }
49150
- async getByTask(projectId, taskId, limit = 5) {
49151
- const q = this.db.collection("projects").doc(projectId).collection("tasks").doc(taskId).collection("snapshots").orderBy("timestamp", "desc").limit(limit);
49152
- const ss = await q.get();
49153
- return this.validateDocs(ss.docs.map((d) => d.data()));
49154
- }
49155
- async getByDate(projectId, dateISO, limit = 5) {
49156
- const start = new Date(dateISO).toISOString();
49157
- const end = new Date(new Date(dateISO).getTime() + 24 * 60 * 60 * 1e3).toISOString();
49158
- const q = this.db.collectionGroup("snapshots").where("projectId", "==", projectId).where("timestamp", ">=", start).where("timestamp", "<", end).orderBy("timestamp", "desc").limit(limit);
49159
- const ss = await q.get();
49160
- return this.validateDocs(ss.docs.map((d) => d.data()));
49161
- }
49162
- validateDocs(rows) {
49163
- const out = [];
49164
- for (const r2 of rows) {
49165
- try {
49166
- assertSnapshot(r2);
49167
- out.push(r2);
49168
- } catch {
49169
- }
49170
- }
49171
- return out;
49172
- }
49173
- };
49174
- }
49175
- });
49176
49078
 
49177
49079
  // src/slash-commands/categories/media/image.command.ts
49178
49080
  var image_command_exports = {};
@@ -49187,7 +49089,7 @@ var init_image_command = __esm({
49187
49089
  init_Normalizer();
49188
49090
  init_ImagePipeline();
49189
49091
  init_session();
49190
- init_firestore();
49092
+ init_api_caller();
49191
49093
  init_cli_auth();
49192
49094
  init_api_client();
49193
49095
  init_cli_auth();
@@ -49295,6 +49197,22 @@ var init_image_command = __esm({
49295
49197
  await api.consumeQuota({ requests: 1, image: Math.max(1, savedPaths.length) });
49296
49198
  } catch {
49297
49199
  }
49200
+ try {
49201
+ new SessionMemory(context2.environment.cwd).save({
49202
+ taskId: "media.image.remote",
49203
+ resumeAt: (/* @__PURE__ */ new Date()).toISOString(),
49204
+ context: { summary: `Generated (remote) ${cli.size[0]}x${cli.size[1]} ${cli.format}`, decisions: [], artifacts: savedPaths, refs: savedPaths }
49205
+ });
49206
+ await callAPI("/api/v1/snapshots", {
49207
+ method: "POST",
49208
+ 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" }
49209
+ });
49210
+ } catch (err) {
49211
+ try {
49212
+ console.warn("[snapshots] save failed:", err?.message || String(err));
49213
+ } catch {
49214
+ }
49215
+ }
49298
49216
  return this.success(output4, void 0, void 0);
49299
49217
  }
49300
49218
  if (Array.isArray(filesList) && filesList.length > 0) {
@@ -49338,6 +49256,22 @@ var init_image_command = __esm({
49338
49256
  await api.consumeQuota({ requests: 1, image: Math.max(1, savedPaths.length) });
49339
49257
  } catch {
49340
49258
  }
49259
+ try {
49260
+ new SessionMemory(context2.environment.cwd).save({
49261
+ taskId: "media.image.remote",
49262
+ resumeAt: (/* @__PURE__ */ new Date()).toISOString(),
49263
+ context: { summary: `Generated (remote) ${cli.size[0]}x${cli.size[1]} ${cli.format}`, decisions: [], artifacts: savedPaths, refs: savedPaths }
49264
+ });
49265
+ await callAPI("/api/v1/snapshots", {
49266
+ method: "POST",
49267
+ 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" }
49268
+ });
49269
+ } catch (err) {
49270
+ try {
49271
+ console.warn("[snapshots] save failed:", err?.message || String(err));
49272
+ } catch {
49273
+ }
49274
+ }
49341
49275
  return this.success(output4, void 0, void 0);
49342
49276
  }
49343
49277
  if (urls.length > 0) {
@@ -49359,6 +49293,22 @@ var init_image_command = __esm({
49359
49293
  await api.consumeQuota({ requests: 1, image: consumed });
49360
49294
  } catch {
49361
49295
  }
49296
+ try {
49297
+ new SessionMemory(context2.environment.cwd).save({
49298
+ taskId: "media.image.remote",
49299
+ resumeAt: (/* @__PURE__ */ new Date()).toISOString(),
49300
+ context: { summary: `Generated (remote) ${cli.size[0]}x${cli.size[1]} ${cli.format}`, decisions: [], artifacts: urls, refs: urls }
49301
+ });
49302
+ await callAPI("/api/v1/snapshots", {
49303
+ method: "POST",
49304
+ 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" }
49305
+ });
49306
+ } catch (err) {
49307
+ try {
49308
+ console.warn("[snapshots] save failed:", err?.message || String(err));
49309
+ } catch {
49310
+ }
49311
+ }
49362
49312
  return this.success(output4, void 0, void 0);
49363
49313
  }
49364
49314
  const { formatRemoteAcceptedImage: formatRemoteAcceptedImage2 } = await Promise.resolve().then(() => (init_cli_style(), cli_style_exports));
@@ -49376,13 +49326,7 @@ var init_image_command = __esm({
49376
49326
  resumeAt: (/* @__PURE__ */ new Date()).toISOString(),
49377
49327
  context: { summary: `Generated (remote) ${cli.size[0]}x${cli.size[1]} ${cli.format}`, decisions: [], artifacts: urls, refs: urls }
49378
49328
  });
49379
- await trySaveSnapshot("default", "media.image.remote", {
49380
- summary: `Generated (remote) ${cli.size[0]}x${cli.size[1]} ${cli.format}`,
49381
- decisions: [],
49382
- artifacts: urls,
49383
- refs: urls,
49384
- resumePrompt: "Continue media work based on last remote output"
49385
- });
49329
+ 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" } });
49386
49330
  } catch {
49387
49331
  }
49388
49332
  try {
@@ -49426,13 +49370,7 @@ var init_image_command = __esm({
49426
49370
  refs: [res.saved.manifestPath]
49427
49371
  }
49428
49372
  });
49429
- await trySaveSnapshot("default", "media.image", {
49430
- summary: `Generated ${ok} image(s) ${cli.size[0]}x${cli.size[1]} ${cli.format}`,
49431
- decisions: [],
49432
- artifacts: res.saved.files,
49433
- refs: [res.saved.manifestPath],
49434
- resumePrompt: "Continue media work based on last output"
49435
- });
49373
+ 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" } });
49436
49374
  } catch {
49437
49375
  }
49438
49376
  try {
@@ -49700,7 +49638,7 @@ var init_video_command = __esm({
49700
49638
  init_Normalizer();
49701
49639
  init_VideoPipeline();
49702
49640
  init_session();
49703
- init_firestore();
49641
+ init_api_caller();
49704
49642
  init_cli_auth();
49705
49643
  init_api_client();
49706
49644
  init_cli_auth();
@@ -49719,7 +49657,39 @@ var init_video_command = __esm({
49719
49657
  try {
49720
49658
  const root = context2.environment.cwd;
49721
49659
  const cli = normalizeVideoArgs(args2.raw, root);
49722
- cli.duration = 8;
49660
+ try {
49661
+ const hook = global.__MARIA_VIDEO_LLM_INFER__;
49662
+ if (hook) {
49663
+ const llm = await hook();
49664
+ if (llm) {
49665
+ if (llm.model && typeof llm.model === "string") cli.model = llm.model;
49666
+ if (Number.isFinite(Number(llm.duration))) {
49667
+ const d = Math.floor(Number(llm.duration));
49668
+ cli.duration = Math.max(1, Math.min(60, d));
49669
+ }
49670
+ if (llm.aspect === "16:9" || llm.aspect === "9:16") {
49671
+ cli.aspect = llm.aspect;
49672
+ const [w, h2] = cli.size;
49673
+ if (llm.size && Array.isArray(llm.size) && llm.size.length === 2) {
49674
+ cli.size = llm.size;
49675
+ } else if (w === 1280 && h2 === 720 || w === 720 && h2 === 1280 || w === 1920 && h2 === 1080 || w === 1080 && h2 === 1920) {
49676
+ if (llm.aspect === "9:16") {
49677
+ if (h2 === 720) cli.size = [720, 1280];
49678
+ else if (h2 === 1080) cli.size = [1080, 1920];
49679
+ } else {
49680
+ if (w === 720) cli.size = [1280, 720];
49681
+ else if (w === 1080) cli.size = [1920, 1080];
49682
+ if (w === 1080 && h2 === 1920) cli.size = [1920, 1080];
49683
+ }
49684
+ }
49685
+ } else if (llm.size && Array.isArray(llm.size) && llm.size.length === 2) {
49686
+ cli.size = llm.size;
49687
+ cli.aspect = cli.size[0] >= cli.size[1] ? "16:9" : "9:16";
49688
+ }
49689
+ }
49690
+ }
49691
+ } catch {
49692
+ }
49723
49693
  if (cli.planOnly || cli.dryRun || !cli.apply) {
49724
49694
  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}`;
49725
49695
  const next = `Next: /video "${cli.prompt}" --duration ${cli.duration} --fps ${cli.fps} --res ${cli.size[0]}x${cli.size[1]} --apply`;
@@ -49849,6 +49819,15 @@ var init_video_command = __esm({
49849
49819
  await api.consumeQuota({ requests: 1, video: savedPaths.length > 0 ? 1 : 0 });
49850
49820
  } catch {
49851
49821
  }
49822
+ try {
49823
+ 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 } });
49824
+ 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" } });
49825
+ } catch (err) {
49826
+ try {
49827
+ console.warn("[snapshots] save failed:", err?.message || String(err));
49828
+ } catch {
49829
+ }
49830
+ }
49852
49831
  return this.success(output4);
49853
49832
  }
49854
49833
  const { formatRemoteAcceptedVideo: formatRemoteAcceptedVideo2 } = await Promise.resolve().then(() => (init_cli_style(), cli_style_exports));
@@ -49872,13 +49851,7 @@ var init_video_command = __esm({
49872
49851
  refs: []
49873
49852
  }
49874
49853
  });
49875
- await trySaveSnapshot("default", "media.video.remote", {
49876
- summary: `Generated (remote) video ${cli.duration}s @${cli.fps}fps ${cli.size[0]}x${cli.size[1]}`,
49877
- decisions: [],
49878
- artifacts: [],
49879
- refs: [],
49880
- resumePrompt: "Continue media work based on last remote output"
49881
- });
49854
+ 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" } });
49882
49855
  } catch {
49883
49856
  }
49884
49857
  try {
@@ -49920,13 +49893,7 @@ var init_video_command = __esm({
49920
49893
  refs: [res.saved.manifestPath]
49921
49894
  }
49922
49895
  });
49923
- await trySaveSnapshot("default", "media.video", {
49924
- summary: `Generated video ${cli.duration}s @${cli.fps}fps ${cli.size[0]}x${cli.size[1]}${res.warnFallback ? " (frames fallback)" : ""}`,
49925
- decisions: [],
49926
- artifacts: res.saved.files,
49927
- refs: [res.saved.manifestPath],
49928
- resumePrompt: "Continue media work based on last output"
49929
- });
49896
+ 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" } });
49930
49897
  } catch {
49931
49898
  }
49932
49899
  try {
@@ -51538,40 +51505,40 @@ var init_about_command = __esm({
51538
51505
  async execute(args2, context2) {
51539
51506
  const output3 = [];
51540
51507
  output3.push("");
51541
- output3.push(chalk14__default.default.cyan.bold("\u{1F916} About MARIA v4.4.0"));
51508
+ output3.push(chalk14__default.default.cyan.bold("About MARIA v4.4.2"));
51542
51509
  output3.push(chalk14__default.default.gray("\u2550".repeat(40)));
51543
51510
  output3.push("");
51544
51511
  output3.push(chalk14__default.default.white.bold("MARIA - Minimal API, Maximum Power"));
51545
51512
  output3.push("");
51546
- output3.push(chalk14__default.default.white("\u{1F3AF} Revolutionary AI Development Platform:"));
51513
+ output3.push(chalk14__default.default.white("Revolutionary AI Development Platform:"));
51547
51514
  output3.push(" \u2022 Natural Language Code Operations");
51548
51515
  output3.push(" \u2022 Graph RAG Knowledge System");
51549
51516
  output3.push(" \u2022 Dual Memory Architecture");
51550
51517
  output3.push(" \u2022 Enterprise-Grade Security");
51551
51518
  output3.push(" \u2022 Multimodal AI Generation");
51552
51519
  output3.push("");
51553
- output3.push(chalk14__default.default.white("\u{1F31F} Key Features:"));
51520
+ output3.push(chalk14__default.default.white("Key Features:"));
51554
51521
  output3.push(" \u2022 /code - Natural language coding");
51555
51522
  output3.push(" \u2022 68+ Slash Commands");
51556
51523
  output3.push(" \u2022 8 AI Provider Support");
51557
51524
  output3.push(" \u2022 Business Operations Suite");
51558
51525
  output3.push(" \u2022 Real-time Streaming");
51559
51526
  output3.push("");
51560
- output3.push(chalk14__default.default.white("\u{1F468}\u200D\u{1F4BB} Created by:"));
51527
+ output3.push(chalk14__default.default.white("Created by:"));
51561
51528
  output3.push(" \u2022 Bonginkan Team");
51562
51529
  output3.push(" \u2022 Enterprise AI Solutions");
51563
51530
  output3.push("");
51564
- output3.push(chalk14__default.default.white("\u{1F517} Links:"));
51531
+ output3.push(chalk14__default.default.white("Links:"));
51565
51532
  output3.push(chalk14__default.default.blue(" Website: https://maria-code.ai"));
51566
51533
  output3.push(chalk14__default.default.blue(" Company: https://bonginkan.ai"));
51567
51534
  output3.push(chalk14__default.default.blue(" Discord: https://discord.gg/SMSmSGcEQy"));
51568
51535
  output3.push(chalk14__default.default.blue(" GitHub: https://github.com/bonginkan/maria"));
51569
51536
  output3.push(chalk14__default.default.blue(" NPM: https://www.npmjs.com/package/@bonginkan/maria"));
51570
51537
  output3.push("");
51571
- output3.push(chalk14__default.default.white("\u{1F4C4} License: MIT"));
51572
- output3.push(chalk14__default.default.white("\u{1F3D7}\uFE0F Built with: TypeScript, Node.js, React"));
51538
+ output3.push(chalk14__default.default.white("License: MIT"));
51539
+ output3.push(chalk14__default.default.white("Built with: TypeScript, Node.js, React"));
51573
51540
  output3.push("");
51574
- output3.push(chalk14__default.default.green("Thank you for using MARIA! \u{1F680}"));
51541
+ output3.push(chalk14__default.default.green("Thank you for using MARIA!"));
51575
51542
  output3.push("");
51576
51543
  return {
51577
51544
  success: true,
@@ -54847,7 +54814,7 @@ var init_code_utils = __esm({
54847
54814
  });
54848
54815
 
54849
54816
  // src/services/creative/NovelArgumentInference.ts
54850
- function extractFirstJson4(text) {
54817
+ function extractFirstJson5(text) {
54851
54818
  if (!text) return null;
54852
54819
  const start = text.indexOf("{");
54853
54820
  const end = text.lastIndexOf("}");
@@ -54898,7 +54865,7 @@ ${rawText}`,
54898
54865
  }
54899
54866
  });
54900
54867
  const raw = (resp?.data?.content || resp?.output || "").trim();
54901
- const jsonText = extractFirstJson4(raw) || raw;
54868
+ const jsonText = extractFirstJson5(raw) || raw;
54902
54869
  let parsed = {};
54903
54870
  try {
54904
54871
  parsed = JSON.parse(jsonText);
@@ -55063,10 +55030,11 @@ var NovelCommand, novel_command_default;
55063
55030
  var init_novel_command = __esm({
55064
55031
  "src/slash-commands/categories/creative/novel.command.ts"() {
55065
55032
  init_base_command();
55066
- init_code_utils();
55067
55033
  init_api_caller();
55034
+ init_code_utils();
55068
55035
  init_NovelArgumentInference();
55069
55036
  init_animations();
55037
+ init_session();
55070
55038
  NovelCommand = class extends BaseCommand {
55071
55039
  name = "novel";
55072
55040
  category = "creative";
@@ -55162,6 +55130,12 @@ var init_novel_command = __esm({
55162
55130
  await writeText(planPath, plan);
55163
55131
  if (planOnly) {
55164
55132
  const msg2 = [`Saved plan to ${planPath}`, "", "Files:", `- ${planPath}`].join("\n");
55133
+ try {
55134
+ const summary = `Novel plan saved: ${path12__namespace.relative(root, planPath)}`;
55135
+ new SessionMemory(root).save({ taskId: "llm.novel", resumeAt: (/* @__PURE__ */ new Date()).toISOString(), context: { summary, decisions: [], artifacts: [planPath], refs: [planPath] } });
55136
+ await callAPI("/api/v1/snapshots", { method: "POST", body: { projectId: "default", taskId: "llm.novel", summary, decisions: [], artifacts: [path12__namespace.relative(root, planPath)], refs: [path12__namespace.relative(root, planPath)], resumePrompt: ideaText } });
55137
+ } catch {
55138
+ }
55165
55139
  return this.success(msg2, { dir: novelDir, plan: planPath });
55166
55140
  }
55167
55141
  const chapterObjs = await (async () => {
@@ -55196,6 +55170,13 @@ ${ch.content}` : ch.content;
55196
55170
  "Files:",
55197
55171
  ...saved.map((p) => `- ${p}`)
55198
55172
  ].join("\n");
55173
+ try {
55174
+ const rels = saved.map((p) => path12__namespace.relative(root, p));
55175
+ const summary = `Novel generated: ${title}`;
55176
+ new SessionMemory(root).save({ taskId: "llm.novel", resumeAt: (/* @__PURE__ */ new Date()).toISOString(), context: { summary, decisions: [], artifacts: rels, refs: rels } });
55177
+ await callAPI("/api/v1/snapshots", { method: "POST", body: { projectId: "default", taskId: "llm.novel", summary, decisions: [], artifacts: rels, refs: rels, resumePrompt: ideaText } });
55178
+ } catch {
55179
+ }
55199
55180
  return this.success(msg, { dir: novelDir, files: saved });
55200
55181
  }
55201
55182
  };
@@ -55286,7 +55267,7 @@ var init_rate_limit_handler = __esm({
55286
55267
  });
55287
55268
 
55288
55269
  // src/services/code-orchestrator/ArgumentInference.ts
55289
- function extractFirstJson5(text) {
55270
+ function extractFirstJson6(text) {
55290
55271
  const fence = /```json\r?\n([\s\S]*?)```/i.exec(text);
55291
55272
  if (fence) return fence[1];
55292
55273
  const start = text.indexOf("{");
@@ -55338,7 +55319,7 @@ ${rawText}`,
55338
55319
  }
55339
55320
  });
55340
55321
  const raw = (resp?.data?.content || resp?.output || "").trim();
55341
- const jsonText = extractFirstJson5(raw) || raw;
55322
+ const jsonText = extractFirstJson6(raw) || raw;
55342
55323
  let parsed = {};
55343
55324
  try {
55344
55325
  parsed = JSON.parse(jsonText);
@@ -57963,11 +57944,12 @@ var LANGUAGE_EXTENSIONS, CodeCommand, codeCommand, metadata3;
57963
57944
  var init_code_command = __esm({
57964
57945
  "src/slash-commands/categories/code/code.command.ts"() {
57965
57946
  init_base_command();
57966
- init_api_caller();
57967
57947
  init_rate_limit_handler();
57968
57948
  init_animations();
57969
57949
  init_code_utils();
57970
57950
  init_ArgumentInference();
57951
+ init_session();
57952
+ init_api_caller();
57971
57953
  LANGUAGE_EXTENSIONS = {
57972
57954
  javascript: ".js",
57973
57955
  typescript: ".ts",
@@ -58131,6 +58113,12 @@ var init_code_command = __esm({
58131
58113
  const outPath = path66.join(plansDir, fileName);
58132
58114
  await fs54.writeFile(outPath, md.join("\n") + "\n", "utf8");
58133
58115
  const rel = path66.relative(root, outPath);
58116
+ try {
58117
+ const summary = `Code plan saved: ${rel}`;
58118
+ new SessionMemory(root).save({ taskId: "llm.code", resumeAt: (/* @__PURE__ */ new Date()).toISOString(), context: { summary, decisions: [], artifacts: [rel], refs: [rel] } });
58119
+ await callAPI("/api/v1/snapshots", { method: "POST", body: { projectId: "default", taskId: "llm.code", summary, decisions: [], artifacts: [rel], refs: [rel], resumePrompt: request } });
58120
+ } catch {
58121
+ }
58134
58122
  return this.success(`Code plan saved: ${rel}`);
58135
58123
  }
58136
58124
  const detail = res?.detailLines;
@@ -58138,6 +58126,14 @@ var init_code_command = __esm({
58138
58126
  return this.success(detail.join("\n"));
58139
58127
  }
58140
58128
  const out = Array.isArray(res?.summaryLines) ? res.summaryLines.join("\n") : "";
58129
+ try {
58130
+ const artifacts = [];
58131
+ const refs = [];
58132
+ const summary = out || "Code generation completed";
58133
+ new SessionMemory(root).save({ taskId: "llm.code", resumeAt: (/* @__PURE__ */ new Date()).toISOString(), context: { summary, decisions: [], artifacts, refs } });
58134
+ await callAPI("/api/v1/snapshots", { method: "POST", body: { projectId: "default", taskId: "llm.code", summary, decisions: [], artifacts, refs, resumePrompt: request } });
58135
+ } catch {
58136
+ }
58141
58137
  return this.success(out);
58142
58138
  } finally {
58143
58139
  if (startedLocalSpinner && spinner) {
@@ -58311,7 +58307,7 @@ ${user}`
58311
58307
  } catch {
58312
58308
  }
58313
58309
  const content = (resp?.data?.content || resp?.content || "").trim();
58314
- const extractFirstJson7 = (text) => {
58310
+ const extractFirstJson8 = (text) => {
58315
58311
  const fence = /```\s*json\s*\r?\n([\s\S]*?)```/i.exec(text);
58316
58312
  if (fence) return fence[1];
58317
58313
  const generic = /```\s*\r?\n([\s\S]*?)```/i.exec(text);
@@ -58334,7 +58330,7 @@ ${user}`
58334
58330
  }
58335
58331
  return null;
58336
58332
  };
58337
- const jsonText = extractFirstJson7(content) || content;
58333
+ const jsonText = extractFirstJson8(content) || content;
58338
58334
  let parsed = {};
58339
58335
  try {
58340
58336
  parsed = JSON.parse(jsonText);
@@ -58817,6 +58813,218 @@ var init_resume_plan = __esm({
58817
58813
  "src/memory/resume-plan.ts"() {
58818
58814
  }
58819
58815
  });
58816
+ function assertSnapshot(data) {
58817
+ const res = SnapshotZ.safeParse(data);
58818
+ if (!res.success) {
58819
+ const details = res.error.issues.map((i2) => `${i2.path.join(".") || "<root>"} ${i2.message}`).join(" | ");
58820
+ throw new ValidationError2(`Invalid snapshot: ${details}`);
58821
+ }
58822
+ }
58823
+ var SnapshotZ, ValidationError2;
58824
+ var init_validators = __esm({
58825
+ "src/memory/validators.ts"() {
58826
+ SnapshotZ = zod.z.object({
58827
+ snapshotVersion: zod.z.literal(1),
58828
+ projectId: zod.z.string().optional(),
58829
+ taskId: zod.z.string().min(1),
58830
+ timestamp: zod.z.string().datetime(),
58831
+ // ISO-8601 UTC expected
58832
+ summary: zod.z.string().min(1),
58833
+ decisions: zod.z.array(zod.z.string()).optional(),
58834
+ artifacts: zod.z.array(zod.z.string()).optional(),
58835
+ links: zod.z.array(
58836
+ zod.z.object({
58837
+ type: zod.z.enum(["doc", "fs", "url", "firestore"]),
58838
+ ref: zod.z.string().min(1)
58839
+ })
58840
+ ).optional(),
58841
+ hash: zod.z.string().optional(),
58842
+ score: zod.z.object({
58843
+ testsPassRate: zod.z.number().min(0).max(1).optional(),
58844
+ coverage: zod.z.number().min(0).max(1).optional()
58845
+ }).optional(),
58846
+ tags: zod.z.array(zod.z.string()).optional(),
58847
+ resumePrompt: zod.z.string().optional()
58848
+ });
58849
+ ValidationError2 = class extends Error {
58850
+ constructor(message) {
58851
+ super(message);
58852
+ this.name = "ValidationError";
58853
+ }
58854
+ };
58855
+ }
58856
+ });
58857
+ function storeFactory(ctx2) {
58858
+ const mode = process.env.MARIA_STORE || "firestore";
58859
+ if (process.env.MARIA_DEBUG === "1") ctx2.logger?.info?.(`[resume] store=${mode}`);
58860
+ if (mode === "firestore") {
58861
+ try {
58862
+ const uid = ctx2.uid;
58863
+ const projectId = ctx2.projectId || "default";
58864
+ if (uid) return new HttpSnapshotStore(projectId);
58865
+ const db = ctx2.firestore || tryGetFirestore();
58866
+ if (db) return new FirestoreSnapshotStore(db);
58867
+ console.warn("[resume] http/firestore not available; falling back to mock store");
58868
+ } catch (e2) {
58869
+ console.warn("[resume] firestore error; falling back to mock store:", e2?.message || e2);
58870
+ }
58871
+ }
58872
+ return new MockSnapshotStore(ctx2.cwd || process.cwd());
58873
+ }
58874
+ function tryGetFirestore() {
58875
+ try {
58876
+ const admin = __require("firebase-admin");
58877
+ if (!admin.apps || admin.apps.length === 0) {
58878
+ try {
58879
+ admin.initializeApp();
58880
+ } catch {
58881
+ }
58882
+ }
58883
+ const { getFirestore } = __require("firebase-admin/firestore");
58884
+ return getFirestore();
58885
+ } catch {
58886
+ return null;
58887
+ }
58888
+ }
58889
+ var MockSnapshotStore, FirestoreSnapshotStore, HttpSnapshotStore;
58890
+ var init_firestore = __esm({
58891
+ "src/memory/firestore.ts"() {
58892
+ init_validators();
58893
+ MockSnapshotStore = class {
58894
+ constructor(cwd2 = process.cwd()) {
58895
+ this.cwd = cwd2;
58896
+ }
58897
+ async getLatest(_projectId, limit = 1) {
58898
+ const s2 = this.readLocal();
58899
+ return s2.slice(0, limit);
58900
+ }
58901
+ async getByTask(_projectId, taskId, limit = 5) {
58902
+ const s2 = this.readLocal().filter((x2) => x2.taskId === taskId);
58903
+ return s2.slice(0, limit);
58904
+ }
58905
+ async getByDate(_projectId, dateISO, limit = 5) {
58906
+ const s2 = this.readLocal().filter((x2) => x2.timestamp?.startsWith(dateISO));
58907
+ return s2.slice(0, limit);
58908
+ }
58909
+ readLocal() {
58910
+ const sessionPath = path12__namespace.default.join(this.cwd, ".maria", "memory", "session.json");
58911
+ const candidates = [];
58912
+ try {
58913
+ const raw = JSON.parse(fs22__namespace.default.readFileSync(sessionPath, "utf8"));
58914
+ const ctx2 = raw?.context;
58915
+ if (ctx2?.summary) {
58916
+ const synthetic = {
58917
+ snapshotVersion: 1,
58918
+ projectId: "default",
58919
+ taskId: raw.taskId || "resume.task",
58920
+ timestamp: raw.resumeAt || (/* @__PURE__ */ new Date()).toISOString(),
58921
+ summary: ctx2.summary,
58922
+ decisions: ctx2.decisions || [],
58923
+ artifacts: ctx2.artifacts || [],
58924
+ links: (ctx2.refs || []).map((r2) => ({ type: "url", ref: r2 }))
58925
+ };
58926
+ assertSnapshot(synthetic);
58927
+ const snap = synthetic;
58928
+ candidates.push(snap);
58929
+ }
58930
+ } catch {
58931
+ }
58932
+ if (candidates.length === 0) {
58933
+ const fallback2 = {
58934
+ snapshotVersion: 1,
58935
+ projectId: "default",
58936
+ taskId: "example.task",
58937
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
58938
+ summary: "\u524D\u56DE\u4F5C\u696D\u306E\u7D9A\u304D\u3002/code \u3092\u518D\u958B\u3067\u304D\u308B\u3088\u3046\u306B\u6E96\u5099\u6E08\u307F\u3002",
58939
+ decisions: ["\u81EA\u52D5\u30C6\u30B9\u30C8\u306F\u6700\u4F4E\u9650", "\u7834\u58CA\u7684\u5909\u66F4\u306F\u3057\u306A\u3044"],
58940
+ artifacts: ["README.md"],
58941
+ links: [{ type: "doc", ref: "docs/RESUME_FUNCTION_DESIGN.md" }],
58942
+ 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"
58943
+ };
58944
+ assertSnapshot(fallback2);
58945
+ const snap = fallback2;
58946
+ candidates.push(snap);
58947
+ }
58948
+ return candidates;
58949
+ }
58950
+ };
58951
+ FirestoreSnapshotStore = class {
58952
+ constructor(db) {
58953
+ this.db = db;
58954
+ }
58955
+ async getLatest(projectId, limit = 1) {
58956
+ const q = this.db.collectionGroup("snapshots").where("projectId", "==", projectId).orderBy("timestamp", "desc").limit(limit);
58957
+ const ss = await q.get();
58958
+ return this.validateDocs(ss.docs.map((d) => d.data()));
58959
+ }
58960
+ async getByTask(projectId, taskId, limit = 5) {
58961
+ const q = this.db.collection("projects").doc(projectId).collection("tasks").doc(taskId).collection("snapshots").orderBy("timestamp", "desc").limit(limit);
58962
+ const ss = await q.get();
58963
+ return this.validateDocs(ss.docs.map((d) => d.data()));
58964
+ }
58965
+ async getByDate(projectId, dateISO, limit = 5) {
58966
+ const start = new Date(dateISO).toISOString();
58967
+ const end = new Date(new Date(dateISO).getTime() + 24 * 60 * 60 * 1e3).toISOString();
58968
+ const q = this.db.collectionGroup("snapshots").where("projectId", "==", projectId).where("timestamp", ">=", start).where("timestamp", "<", end).orderBy("timestamp", "desc").limit(limit);
58969
+ const ss = await q.get();
58970
+ return this.validateDocs(ss.docs.map((d) => d.data()));
58971
+ }
58972
+ validateDocs(rows) {
58973
+ const out = [];
58974
+ for (const r2 of rows) {
58975
+ try {
58976
+ assertSnapshot(r2);
58977
+ out.push(r2);
58978
+ } catch {
58979
+ }
58980
+ }
58981
+ return out;
58982
+ }
58983
+ };
58984
+ HttpSnapshotStore = class {
58985
+ constructor(projectId) {
58986
+ this.projectId = projectId;
58987
+ }
58988
+ async fetchJson(pathname) {
58989
+ const { callAPI: callAPI2 } = await Promise.resolve().then(() => (init_api_caller(), api_caller_exports));
58990
+ return await callAPI2(pathname, { method: "GET" });
58991
+ }
58992
+ async getLatest(projectId, limit = 5) {
58993
+ const pid = projectId || this.projectId || "default";
58994
+ const resp = await this.fetchJson(`/api/v1/get-snapshots?projectId=${encodeURIComponent(pid)}&limit=${limit}`);
58995
+ const arr = Array.isArray(resp?.data?.snapshots) ? resp.data.snapshots : [];
58996
+ return this.validate(arr);
58997
+ }
58998
+ async getByTask(projectId, taskId, limit = 5) {
58999
+ const pid = projectId || this.projectId || "default";
59000
+ const resp = await this.fetchJson(`/api/v1/get-snapshots?projectId=${encodeURIComponent(pid)}&taskId=${encodeURIComponent(taskId)}&limit=${limit}`);
59001
+ const arr = Array.isArray(resp?.data?.snapshots) ? resp.data.snapshots : [];
59002
+ return this.validate(arr);
59003
+ }
59004
+ async getByDate(projectId, dateISO, limit = 5) {
59005
+ const pid = projectId || this.projectId || "default";
59006
+ const resp = await this.fetchJson(`/api/v1/get-snapshots?projectId=${encodeURIComponent(pid)}&date=${encodeURIComponent(dateISO)}&limit=${limit}`);
59007
+ const arr = Array.isArray(resp?.data?.snapshots) ? resp.data.snapshots : [];
59008
+ return this.validate(arr);
59009
+ }
59010
+ validate(rows) {
59011
+ const out = [];
59012
+ for (const r2 of rows) {
59013
+ try {
59014
+ assertSnapshot(r2);
59015
+ out.push(r2);
59016
+ } catch {
59017
+ }
59018
+ }
59019
+ if (out.length === 0) {
59020
+ const mock = new MockSnapshotStore(process.cwd());
59021
+ return (async () => await mock.getLatest(this.projectId, 1))();
59022
+ }
59023
+ return out;
59024
+ }
59025
+ };
59026
+ }
59027
+ });
58820
59028
 
58821
59029
  // src/memory/rehydrator.ts
58822
59030
  function rehydrateSnapshot(s2, opts = {}) {
@@ -58953,27 +59161,59 @@ function truncate2(s2, n) {
58953
59161
  }
58954
59162
  function promptLine(timeoutMs = 15e3) {
58955
59163
  return new Promise((resolve19) => {
58956
- const rl = readline__namespace.default.createInterface({ input: process.stdin, output: process.stdout });
58957
- const done = (ok, line) => {
59164
+ let finished = false;
59165
+ const input3 = process.stdin;
59166
+ const wasRaw = !!input3.isRaw;
59167
+ const finish = (ok, line) => {
59168
+ if (finished) return;
59169
+ finished = true;
58958
59170
  try {
58959
- rl.close();
59171
+ input3.removeListener("keypress", onKey);
59172
+ } catch {
59173
+ }
59174
+ try {
59175
+ if (input3.isTTY) input3.setRawMode(wasRaw);
58960
59176
  } catch {
58961
59177
  }
58962
59178
  resolve19({ ok, line });
58963
59179
  };
58964
- const t2 = setTimeout(() => done(true, "1"), timeoutMs);
58965
- rl.question("\u756A\u53F7\u3092\u5165\u529B > ", (l) => {
58966
- clearTimeout(t2);
58967
- done(true, l);
58968
- });
58969
- rl.once("SIGINT", () => {
58970
- clearTimeout(t2);
58971
- done(false);
58972
- });
58973
- rl.once("close", () => {
58974
- clearTimeout(t2);
58975
- done(false);
58976
- });
59180
+ const t2 = setTimeout(() => finish(true, "1"), timeoutMs);
59181
+ try {
59182
+ process.stdout.write("Enter number > ");
59183
+ } catch {
59184
+ }
59185
+ try {
59186
+ if (input3.isTTY) input3.setRawMode(true);
59187
+ } catch {
59188
+ }
59189
+ readline__namespace.emitKeypressEvents(input3);
59190
+ let buffer = "";
59191
+ const onKey = (_str, key) => {
59192
+ if (key?.ctrl && key.name === "c") {
59193
+ clearTimeout(t2);
59194
+ finish(false);
59195
+ return;
59196
+ }
59197
+ if (key?.name === "escape") {
59198
+ clearTimeout(t2);
59199
+ finish(false);
59200
+ return;
59201
+ }
59202
+ if (key?.name === "return" || key?.name === "enter") {
59203
+ clearTimeout(t2);
59204
+ const value = buffer.trim() || "1";
59205
+ finish(true, value);
59206
+ return;
59207
+ }
59208
+ if (key?.name === "backspace") {
59209
+ buffer = buffer.slice(0, -1);
59210
+ return;
59211
+ }
59212
+ if (/^[0-9]$/.test(_str)) {
59213
+ buffer += _str;
59214
+ }
59215
+ };
59216
+ input3.on("keypress", onKey);
58977
59217
  });
58978
59218
  }
58979
59219
  async function readLastDebugStatusSafe(cwd2) {
@@ -59026,7 +59266,8 @@ var init_resume_command = __esm({
59026
59266
  const dbg = await readLastDebugStatusSafe(context2.environment.cwd);
59027
59267
  const opts = this.parseOptions(args2.raw);
59028
59268
  const projectId = "default";
59029
- const store2 = storeFactory({ cwd: context2.environment.cwd, logger: console });
59269
+ const uid = context2.user?.id || void 0;
59270
+ const store2 = storeFactory({ cwd: context2.environment.cwd, logger: console, uid, projectId });
59030
59271
  let candidates = [];
59031
59272
  if (opts.taskId) candidates = await store2.getByTask(projectId, opts.taskId, opts.limit || 5);
59032
59273
  else if (opts.date) candidates = await store2.getByDate(projectId, opts.date, opts.limit || 5);
@@ -59080,9 +59321,9 @@ var init_resume_command = __esm({
59080
59321
  context: plan.context
59081
59322
  });
59082
59323
  const lines = [];
59083
- if (dbg && (opts.debugLatest || !opts.debugList && !opts.noDebug)) {
59324
+ if (process.env.MARIA_DEBUG === "1" && dbg && (opts.debugLatest || !opts.debugList && !opts.noDebug)) {
59084
59325
  lines.push("");
59085
- lines.push("\u{1F9ED} Last debug-fix status");
59326
+ lines.push("Last debug-fix status");
59086
59327
  lines.push("".padEnd(30, "\u2550"));
59087
59328
  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}`);
59088
59329
  if (dbg.verify && !dbg.verify.ok && dbg.verify.stage) {
@@ -59090,12 +59331,12 @@ var init_resume_command = __esm({
59090
59331
  }
59091
59332
  lines.push("");
59092
59333
  }
59093
- if (opts.debugList) {
59334
+ if (process.env.MARIA_DEBUG === "1" && opts.debugList) {
59094
59335
  const count = Number.isFinite(opts.debugLimit) ? Math.max(1, Math.min(50, Number(opts.debugLimit))) : 5;
59095
59336
  const list = await readDebugJournalListSafe(context2.environment.cwd, count);
59096
59337
  if (list.length) {
59097
59338
  lines.push("");
59098
- lines.push(`\u{1F9ED} Debug history (latest ${list.length})`);
59339
+ lines.push(`Debug history (latest ${list.length})`);
59099
59340
  lines.push("".padEnd(34, "\u2550"));
59100
59341
  for (const it of list) {
59101
59342
  const t2 = it.createdAt ? new Date(it.createdAt).toISOString().replace("T", " ").replace("Z", "Z") : "";
@@ -59106,7 +59347,7 @@ var init_resume_command = __esm({
59106
59347
  }
59107
59348
  }
59108
59349
  lines.push(`
59109
- \u{1F4CC} Resuming: ${s2.taskId}`);
59350
+ Resuming: ${s2.taskId}`);
59110
59351
  lines.push(`Summary: ${truncate2(plan.context.summary, 400)}`);
59111
59352
  if (plan.context.decisions?.length) lines.push(`Decisions: ${plan.context.decisions.join(" / ")}`);
59112
59353
  if (plan.context.artifacts?.length) lines.push(`Artifacts: ${plan.context.artifacts.slice(0, 10).join(", ")}`);
@@ -59159,7 +59400,6 @@ var init_resume_command = __esm({
59159
59400
  lines.push("\u26A0 /code execution threw \u2014 showing suggestion instead");
59160
59401
  lines.push("");
59161
59402
  }
59162
- lines.push(`\u{1F449} Next: /code "${plan.nextPrompt}" ${plan.codeFlags.join(" ")}`.trim());
59163
59403
  return this.success(lines.join("\n"), { elapsedMs: Date.now() - start });
59164
59404
  } catch (e2) {
59165
59405
  return this.error("Failed to resume", "RESUME_ERROR", e2?.message || String(e2));
@@ -59198,13 +59438,15 @@ var init_resume_command = __esm({
59198
59438
  const t2 = new Date(c.timestamp).toISOString().replace("T", " ").replace("Z", "Z");
59199
59439
  return `${idx + 1}) [${t2}] ${c.taskId} \u2014 ${head2(c.summary)}`;
59200
59440
  };
59201
- console.log("\n\u5019\u88DC\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044 (15s \u3067 1 \u3092\u63A1\u7528):");
59441
+ console.log("\nSelect a candidate (defaults to 1 after 15s):");
59202
59442
  for (let i2 = 0; i2 < cands.length; i2++) {
59203
59443
  console.log(" " + fmt(cands[i2], i2));
59204
59444
  }
59205
59445
  const ans = await promptLine(15e3);
59206
59446
  if (!ans.ok) return null;
59207
- const n = parseInt((ans.line || "1").trim(), 10);
59447
+ const raw = (ans.line || "1").trim();
59448
+ const m2 = raw.match(/\d+/);
59449
+ const n = m2 ? parseInt(m2[0], 10) : 1;
59208
59450
  if (!Number.isFinite(n) || n < 1 || n > cands.length) return cands[0];
59209
59451
  return cands[n - 1];
59210
59452
  }
@@ -68837,6 +69079,7 @@ var init_ResearchCommand = __esm({
68837
69079
  init_logger();
68838
69080
  init_api_client();
68839
69081
  init_animations();
69082
+ init_session();
68840
69083
  ResearchCommand = class extends BaseCommand {
68841
69084
  name = "research";
68842
69085
  category = "analysis";
@@ -68920,6 +69163,13 @@ var init_ResearchCommand = __esm({
68920
69163
  });
68921
69164
  }
68922
69165
  const message = lines.filter(Boolean).join("\n");
69166
+ try {
69167
+ const root = context2.environment?.cwd || process.cwd();
69168
+ const summary = "Research completed";
69169
+ new SessionMemory(root).save({ taskId: "llm.research", resumeAt: (/* @__PURE__ */ new Date()).toISOString(), context: { summary, decisions: [], artifacts: [], refs: [] } });
69170
+ 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" } });
69171
+ } catch {
69172
+ }
68923
69173
  const result = this.success(message);
68924
69174
  result.metadata = { executionTime: Date.now() - startedAt };
68925
69175
  this.logExecution(_args, context2, result);
@@ -73100,7 +73350,7 @@ ${user}`,
73100
73350
  };
73101
73351
  }
73102
73352
  });
73103
- function extractFirstJson6(text) {
73353
+ function extractFirstJson7(text) {
73104
73354
  const fence = /```json\r?\n([\s\S]*?)```/i.exec(text);
73105
73355
  if (fence) return fence[1];
73106
73356
  const start = text.indexOf("{");
@@ -73162,7 +73412,7 @@ ${user}`,
73162
73412
  }
73163
73413
  });
73164
73414
  const raw = (response?.data?.content || response?.output || "").trim();
73165
- const jsonText = extractFirstJson6(raw) || raw;
73415
+ const jsonText = extractFirstJson7(raw) || raw;
73166
73416
  let parsed = {};
73167
73417
  try {
73168
73418
  parsed = JSON.parse(jsonText);
@@ -73204,9 +73454,10 @@ var init_evaluate_command = __esm({
73204
73454
  init_base_command();
73205
73455
  init_logger();
73206
73456
  init_EvaluationOrchestrator();
73207
- init_api_caller();
73208
73457
  init_animations();
73209
73458
  init_ArgumentInference2();
73459
+ init_session();
73460
+ init_api_caller();
73210
73461
  EvaluateCommand = class extends BaseCommand {
73211
73462
  name = "evaluate";
73212
73463
  category = "evaluation";
@@ -73474,6 +73725,13 @@ ${options["code"] || inferred.code}` : void 0
73474
73725
  const finalText = uploadNote ? `${uploadNote}
73475
73726
 
73476
73727
  ${content}` : content;
73728
+ try {
73729
+ const summary = `Evaluation assess completed: total=${Math.round(result.totalScore * 100)}/100`;
73730
+ const rel = path12__namespace.default.relative(root, criteriaPath);
73731
+ new SessionMemory(root).save({ taskId: "llm.evaluate", resumeAt: (/* @__PURE__ */ new Date()).toISOString(), context: { summary, decisions: [], artifacts: [rel], refs: [rel] } });
73732
+ await callAPI("/api/v1/snapshots", { method: "POST", body: { projectId: "default", taskId: "llm.evaluate", summary, decisions: [], artifacts: [rel], refs: [rel], resumePrompt: rawCmd } });
73733
+ } catch {
73734
+ }
73477
73735
  return this.success(finalText, {
73478
73736
  type: "evaluation-assess",
73479
73737
  total: result.totalScore,