@modusensus/dsh-mneme 0.7.15 → 0.7.17

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/lib/dream.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { validateDecisions, applyDecisions } from "./dream/decisions.js";
2
2
  import { clusterMemories, findPotentialConflicts } from "./dream/clustering.js";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
- export { validateDecisions, applyDecisions };
4
+ export { validateDecisions, applyDecisions, withEffortFallback };
5
5
 
6
6
 
7
7
  // Extract the first JSON array from LLM output, tolerating markdown fences,
@@ -282,6 +282,15 @@ async function runAuditedLlm(ctx, service, config, spec, body) {
282
282
  // record it as error here so the audit shows the truth.
283
283
  status = "error";
284
284
  errorMessage = errorMessage ?? "llm stream aborted or errored";
285
+ } else if (typeof spec.auditError === "function") {
286
+ // A stream that returned text but yields nothing usable is still a
287
+ // failed call — record it as error, not the default success, so the
288
+ // audit no longer contradicts a failed run (dream "no json array").
289
+ const message = spec.auditError(result);
290
+ if (message) {
291
+ status = "error";
292
+ errorMessage = message;
293
+ }
285
294
  }
286
295
  return result;
287
296
  } catch (error) {
@@ -311,20 +320,50 @@ async function runAuditedLlm(ctx, service, config, spec, body) {
311
320
  }
312
321
 
313
322
  /**
314
- * Resolve the LLM route: agent default model (deployment) first, plugin config
315
- * (dreamProvider/dreamModel) as fallback. Falls through to undefined when no
316
- * route exists runDream then fails safe. Fallback is logged so a silent
317
- * route switch is observable.
323
+ * Reasoning-effort rejection fallback (v0.8.1): a configured dreamReasoningEffort
324
+ * / sleepReasoningEffort may be rejected by the provider (volcano-engine returns
325
+ * UNSUPPORTED_REASONING_EFFORT for values it does not accept "off" is known
326
+ * rejected there). When that happens, retry once WITHOUT the reasoning field
327
+ * instead of hard-failing the run, so effort config is safe to experiment with:
328
+ * accepted → reasoning capped; rejected → provider default (old behavior),
329
+ * logged so the rejection is observable.
330
+ */
331
+ async function withEffortFallback(ctx, effort, attempt, fallback) {
332
+ if (!effort || effort === "none") return attempt();
333
+ try {
334
+ return await attempt();
335
+ } catch (error) {
336
+ const message = String(error?.message ?? error);
337
+ // matches both "reasoning effort" (natural language) and the bare
338
+ // "UNSUPPORTED_REASONING_EFFORT" error code (underscore).
339
+ if (!/reasoning[\s_]*effort/i.test(message)) throw error;
340
+ ctx.logger?.warn?.(`dsh-mneme dream: reasoningEffort "${effort}" rejected (${message}); retrying without it`);
341
+ return fallback();
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Resolve the LLM route (Issue #25): an explicit plugin config
347
+ * (dreamProvider/dreamModel) is the user's declared override and wins; the
348
+ * agent default model (deployment) is only a fallback when no config route is
349
+ * set. In a standard DSH install agentDefaultModel always resolves, so without
350
+ * this ordering the config route would be dead code and dreamProvider/dreamModel
351
+ * could never take effect (v0.7.11 regressed this; README §config documents
352
+ * config-first). Falls through to undefined when no route exists — runDream
353
+ * then fails safe. A config→default switch is logged so it is observable.
318
354
  */
319
355
  function resolveRoute(ctx, config, logger) {
356
+ if (config.dreamProvider && config.dreamModel) return { provider: config.dreamProvider, model: config.dreamModel };
320
357
  try {
321
358
  const sel = ctx.agentDefaultModel?.currentSelection?.();
322
- if (sel?.provider && sel?.model) return { provider: sel.provider, model: sel.model };
323
- logger?.warn?.("dsh-mneme dream: agentDefaultModel unavailable, falling back to config route");
359
+ if (sel?.provider && sel?.model) {
360
+ logger?.info?.("dsh-mneme dream: no dreamProvider/dreamModel config, falling back to agent default");
361
+ return { provider: sel.provider, model: sel.model };
362
+ }
363
+ logger?.warn?.("dsh-mneme dream: agentDefaultModel unavailable, no config route either");
324
364
  } catch (error) {
325
- logger?.warn?.(`dsh-mneme dream: agentDefaultModel lookup failed, falling back to config route: ${String(error)}`);
365
+ logger?.warn?.(`dsh-mneme dream: agentDefaultModel lookup failed: ${String(error)}`);
326
366
  }
327
- if (config.dreamProvider && config.dreamModel) return { provider: config.dreamProvider, model: config.dreamModel };
328
367
  return undefined;
329
368
  }
330
369
 
@@ -585,28 +624,37 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
585
624
  ? CONSOLIDATION_PROMPT + `\n\n当前为「冲突冻结」模式:检测到内容矛盾的条目时,仍请输出 conflict,并以 winner/loser 作为候选、reason 说明理由;冲突不会被自动裁决,而会冻结待人工确认。`
586
625
  : CONSOLIDATION_PROMPT;
587
626
  let decisionText;
627
+ // 加固(v0.8.1):配置的 reasoningEffort 被 provider 拒收时回退重试一次
628
+ // (不带该字段),避免 thinking 模型配置 low/medium 直接整单失败。解析放
629
+ // 在 auditError 检查器里、闭包交回主流程,避免二次解析;解析失败同时如实
630
+ // 记 audit error 并在日志带原始输出前 300 字节,便于定位"推理吞预算返回空体"。
631
+ const effort = config.dreamReasoningEffort && config.dreamReasoningEffort !== "none" ? config.dreamReasoningEffort : null;
632
+ let decisions = null;
633
+ const runConsolidation = (withEffort) => runAuditedLlm(ctx, service, config, {
634
+ triggerSource: "autoDream",
635
+ operationType: "dream_consolidate",
636
+ modelId: `${route.provider}:${route.model}`,
637
+ relatedMemoryIds: [...snapshot.keys()],
638
+ auditError: (text) => {
639
+ decisions = extractJsonArray(text);
640
+ return Array.isArray(decisions) ? null : "no json array in llm output";
641
+ }
642
+ }, (reportUsage) => streamText(ctx, {
643
+ provider: route.provider,
644
+ model: route.model,
645
+ purpose: "compaction",
646
+ maxTokens: config.dreamMaxTokens ?? 4096,
647
+ ...(withEffort && effort ? { reasoningEffort: effort } : {}),
648
+ messages: [
649
+ { role: "system", content: [{ type: "text", text: consolidationPrompt }] },
650
+ { role: "user", content: [{ type: "text", text: listText }] }
651
+ ]
652
+ }, reportUsage));
588
653
  try {
589
654
  // Bug8: the consolidation call is audited (tokens/time/status). A throw
590
655
  // re-propagates to the catch below; an aborted stream returns undefined
591
656
  // and is treated as a failed run after the check below.
592
- decisionText = await runAuditedLlm(ctx, service, config, {
593
- triggerSource: "autoDream",
594
- operationType: "dream_consolidate",
595
- modelId: `${route.provider}:${route.model}`,
596
- relatedMemoryIds: [...snapshot.keys()]
597
- }, (reportUsage) => streamText(ctx, {
598
- provider: route.provider,
599
- model: route.model,
600
- purpose: "compaction",
601
- maxTokens: config.dreamMaxTokens ?? 4096,
602
- ...(config.dreamReasoningEffort && config.dreamReasoningEffort !== "none"
603
- ? { reasoningEffort: config.dreamReasoningEffort }
604
- : {}),
605
- messages: [
606
- { role: "system", content: [{ type: "text", text: consolidationPrompt }] },
607
- { role: "user", content: [{ type: "text", text: listText }] }
608
- ]
609
- }, reportUsage));
657
+ decisionText = await withEffortFallback(ctx, effort, () => runConsolidation(true), () => runConsolidation(false));
610
658
  } catch (error) {
611
659
  logger?.warn?.(`dsh-mneme dream: consolidation llm call failed: ${String(error)}`);
612
660
  return finish({ ok: false, error: "llm failed", summary: false });
@@ -615,10 +663,9 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
615
663
  logger?.warn?.("dsh-mneme dream: consolidation llm stream aborted or errored");
616
664
  return finish({ ok: false, error: "llm failed", summary: false });
617
665
  }
618
-
619
- const decisions = extractJsonArray(decisionText);
620
666
  if (!Array.isArray(decisions)) {
621
- logger?.warn?.(`dsh-mneme dream: no json array in llm output (raw length ${decisionText?.length ?? 0})`);
667
+ const head = (decisionText ?? "").slice(0, 300).replace(/\s+/g, " ").trim();
668
+ logger?.warn?.(`dsh-mneme dream: no json array in llm output (raw length ${decisionText?.length ?? 0}; head: ${head})`);
622
669
  return finish({ ok: false, error: "no json array in llm output", summary: false });
623
670
  }
624
671
  const { ok, errors } = validateDecisions(decisions, snapshot, {
@@ -735,26 +782,25 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
735
782
  // Summary generation (second LLM call). A throwing stream is reported as
736
783
  // a failed run; summary:false marks a run that produced no summary.
737
784
  let summaryText;
785
+ const runSummary = (withEffort) => runAuditedLlm(ctx, service, config, {
786
+ triggerSource: "autoDream",
787
+ operationType: "dream_summarize",
788
+ modelId: `${route.provider}:${route.model}`,
789
+ relatedMemoryIds: []
790
+ }, (reportUsage) => streamText(ctx, {
791
+ provider: route.provider,
792
+ model: route.model,
793
+ purpose: "compaction",
794
+ maxTokens: config.dreamMaxTokens ?? 2048,
795
+ ...(withEffort && effort ? { reasoningEffort: effort } : {}),
796
+ messages: [
797
+ { role: "system", content: [{ type: "text", text: SUMMARY_PROMPT }] },
798
+ { role: "user", content: [{ type: "text", text: service.all().filter((m) => !m.archived && m.type !== "summary").map((m) => `- ${m.title}: ${m.content}`).join("\n") }] }
799
+ ]
800
+ }, reportUsage));
738
801
  try {
739
802
  // Bug8: the summary call is audited too (operation dream_summarize).
740
- summaryText = await runAuditedLlm(ctx, service, config, {
741
- triggerSource: "autoDream",
742
- operationType: "dream_summarize",
743
- modelId: `${route.provider}:${route.model}`,
744
- relatedMemoryIds: []
745
- }, (reportUsage) => streamText(ctx, {
746
- provider: route.provider,
747
- model: route.model,
748
- purpose: "compaction",
749
- maxTokens: config.dreamMaxTokens ?? 2048,
750
- ...(config.dreamReasoningEffort && config.dreamReasoningEffort !== "none"
751
- ? { reasoningEffort: config.dreamReasoningEffort }
752
- : {}),
753
- messages: [
754
- { role: "system", content: [{ type: "text", text: SUMMARY_PROMPT }] },
755
- { role: "user", content: [{ type: "text", text: service.all().filter((m) => !m.archived && m.type !== "summary").map((m) => `- ${m.title}: ${m.content}`).join("\n") }] }
756
- ]
757
- }, reportUsage));
803
+ summaryText = await withEffortFallback(ctx, effort, () => runSummary(true), () => runSummary(false));
758
804
  } catch (error) {
759
805
  logger?.warn?.(`dsh-mneme dream: summary llm call failed: ${String(error)}`);
760
806
  return finish({ ok: false, error: "llm failed", applied, decisions: auditDecisions, outcome, frozen: frozenCount, summary: false });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@modusensus/dsh-mneme",
3
3
  "description": "Cross-session memory plugin for DeepSeek Harness with autoDream consolidation: SQLite store, Markdown mirrors, 7 model tools, automatic injection, session summarization, user profile/rules, custom slash commands, vector (semantic) search, and a Web GUI panel",
4
- "version": "0.7.15",
4
+ "version": "0.7.17",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -17,7 +17,7 @@
17
17
  import { randomUUID, createHash } from "node:crypto";
18
18
  import { validateDecisions, applyDecisions } from "./decisions.js";
19
19
  import { findPotentialConflicts } from "./clustering.js";
20
- import { buildReceipt } from "../dream.js";
20
+ import { buildReceipt, withEffortFallback } from "../dream.js";
21
21
 
22
22
  const SUMMARY_MAX = 120;
23
23
  // Conflict similarity threshold per strictness level (v0.4.0):
@@ -72,16 +72,18 @@ async function streamText(ctx, options) {
72
72
  return text;
73
73
  }
74
74
 
75
- /** LLM route: agent default model first, then sleepProvider/Model, then the
76
- * dream route as a shared fallback. Sleep can pin a cheaper model for its
77
- * bulk passes without disturbing the dream route. */
75
+ /** LLM route (Issue #25): explicit sleepProvider/Model wins, then the dream
76
+ * route as a shared explicit fallback, then the agent default model. Sleep
77
+ * can pin a cheaper model for its bulk passes without disturbing the dream
78
+ * route. Explicit config first — otherwise the config routes are dead code
79
+ * whenever agentDefaultModel resolves (see resolveRoute in dream.js). */
78
80
  function resolveSleepRoute(ctx, config, logger) {
81
+ if (config.sleepProvider && config.sleepModel) return { provider: config.sleepProvider, model: config.sleepModel };
82
+ if (config.dreamProvider && config.dreamModel) return { provider: config.dreamProvider, model: config.dreamModel };
79
83
  try {
80
84
  const sel = ctx?.agentDefaultModel?.currentSelection?.();
81
85
  if (sel?.provider && sel?.model) return { provider: sel.provider, model: sel.model };
82
- } catch { /* fall through to config route */ }
83
- if (config.sleepProvider && config.sleepModel) return { provider: config.sleepProvider, model: config.sleepModel };
84
- if (config.dreamProvider && config.dreamModel) return { provider: config.dreamProvider, model: config.dreamModel };
86
+ } catch { /* fall through to warn */ }
85
87
  logger?.warn?.("dsh-mneme sleep: no llm route available");
86
88
  return undefined;
87
89
  }
@@ -182,19 +184,19 @@ async function phaseConflicts(ctx, service, config, logger, runId, semantic = nu
182
184
  const listText = selected.map((p) =>
183
185
  `候选冲突:\nid=${p.a.id} | type=${p.a.type} | title=${p.a.title}\n${p.a.content}\n---\nid=${p.b.id} | type=${p.b.type} | title=${p.b.title}\n${p.b.content}\n(相似度 ${p.similarity.toFixed(2)})`
184
186
  ).join("\n\n");
185
- const text = await streamText(ctx, {
187
+ const sleepEffort = config.sleepReasoningEffort && config.sleepReasoningEffort !== "none" ? config.sleepReasoningEffort : null;
188
+ const runConflict = (withEffort) => streamText(ctx, {
186
189
  provider: route.provider,
187
190
  model: route.model,
188
191
  purpose: "sleep-conflict",
189
192
  maxTokens: 2048,
190
- ...(config.sleepReasoningEffort && config.sleepReasoningEffort !== "none"
191
- ? { reasoningEffort: config.sleepReasoningEffort }
192
- : {}),
193
+ ...(withEffort && sleepEffort ? { reasoningEffort: sleepEffort } : {}),
193
194
  messages: [
194
195
  { role: "system", content: [{ type: "text", text: CONFLICT_PROMPT }] },
195
196
  { role: "user", content: [{ type: "text", text: listText }] }
196
197
  ]
197
198
  });
199
+ const text = await withEffortFallback(ctx, sleepEffort, () => runConflict(true), () => runConflict(false));
198
200
  if (text === undefined) return { status: "failed", error: "llm failed" };
199
201
  const decisions = parseJsonArray(text);
200
202
  if (!decisions) return { status: "failed", error: "invalid decisions json" };
@@ -282,19 +284,19 @@ async function phasePatterns(ctx, service, config, logger, runId, signal = null)
282
284
  .map((m) => `id=${m.id} | type=${m.type} | importance=${m.importance} | updated=${m.updated_at} | title=${m.title} | content=${m.content}`)
283
285
  .join("\n");
284
286
  const maxPatterns = config.sleepMaxPatternPerRun ?? 3;
285
- const text = await streamText(ctx, {
287
+ const sleepEffort = config.sleepReasoningEffort && config.sleepReasoningEffort !== "none" ? config.sleepReasoningEffort : null;
288
+ const runPattern = (withEffort) => streamText(ctx, {
286
289
  provider: route.provider,
287
290
  model: route.model,
288
291
  purpose: "sleep-pattern",
289
292
  maxTokens: 2048,
290
- ...(config.sleepReasoningEffort && config.sleepReasoningEffort !== "none"
291
- ? { reasoningEffort: config.sleepReasoningEffort }
292
- : {}),
293
+ ...(withEffort && sleepEffort ? { reasoningEffort: sleepEffort } : {}),
293
294
  messages: [
294
295
  { role: "system", content: [{ type: "text", text: PATTERN_PROMPT.replace("N", String(maxPatterns)) }] },
295
296
  { role: "user", content: [{ type: "text", text: listText }] }
296
297
  ]
297
298
  });
299
+ const text = await withEffortFallback(ctx, sleepEffort, () => runPattern(true), () => runPattern(false));
298
300
  if (text === undefined) return { status: "failed", error: "llm failed" };
299
301
  const decisions = parseJsonArray(text);
300
302
  if (!decisions || decisions.length === 0) return { status: "skipped", reason: "no patterns found" };
package/src/dream.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { validateDecisions, applyDecisions } from "./dream/decisions.js";
2
2
  import { clusterMemories, findPotentialConflicts } from "./dream/clustering.js";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
- export { validateDecisions, applyDecisions };
4
+ export { validateDecisions, applyDecisions, withEffortFallback };
5
5
 
6
6
 
7
7
  // Extract the first JSON array from LLM output, tolerating markdown fences,
@@ -282,6 +282,15 @@ async function runAuditedLlm(ctx, service, config, spec, body) {
282
282
  // record it as error here so the audit shows the truth.
283
283
  status = "error";
284
284
  errorMessage = errorMessage ?? "llm stream aborted or errored";
285
+ } else if (typeof spec.auditError === "function") {
286
+ // A stream that returned text but yields nothing usable is still a
287
+ // failed call — record it as error, not the default success, so the
288
+ // audit no longer contradicts a failed run (dream "no json array").
289
+ const message = spec.auditError(result);
290
+ if (message) {
291
+ status = "error";
292
+ errorMessage = message;
293
+ }
285
294
  }
286
295
  return result;
287
296
  } catch (error) {
@@ -311,20 +320,50 @@ async function runAuditedLlm(ctx, service, config, spec, body) {
311
320
  }
312
321
 
313
322
  /**
314
- * Resolve the LLM route: agent default model (deployment) first, plugin config
315
- * (dreamProvider/dreamModel) as fallback. Falls through to undefined when no
316
- * route exists runDream then fails safe. Fallback is logged so a silent
317
- * route switch is observable.
323
+ * Reasoning-effort rejection fallback (v0.8.1): a configured dreamReasoningEffort
324
+ * / sleepReasoningEffort may be rejected by the provider (volcano-engine returns
325
+ * UNSUPPORTED_REASONING_EFFORT for values it does not accept "off" is known
326
+ * rejected there). When that happens, retry once WITHOUT the reasoning field
327
+ * instead of hard-failing the run, so effort config is safe to experiment with:
328
+ * accepted → reasoning capped; rejected → provider default (old behavior),
329
+ * logged so the rejection is observable.
330
+ */
331
+ async function withEffortFallback(ctx, effort, attempt, fallback) {
332
+ if (!effort || effort === "none") return attempt();
333
+ try {
334
+ return await attempt();
335
+ } catch (error) {
336
+ const message = String(error?.message ?? error);
337
+ // matches both "reasoning effort" (natural language) and the bare
338
+ // "UNSUPPORTED_REASONING_EFFORT" error code (underscore).
339
+ if (!/reasoning[\s_]*effort/i.test(message)) throw error;
340
+ ctx.logger?.warn?.(`dsh-mneme dream: reasoningEffort "${effort}" rejected (${message}); retrying without it`);
341
+ return fallback();
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Resolve the LLM route (Issue #25): an explicit plugin config
347
+ * (dreamProvider/dreamModel) is the user's declared override and wins; the
348
+ * agent default model (deployment) is only a fallback when no config route is
349
+ * set. In a standard DSH install agentDefaultModel always resolves, so without
350
+ * this ordering the config route would be dead code and dreamProvider/dreamModel
351
+ * could never take effect (v0.7.11 regressed this; README §config documents
352
+ * config-first). Falls through to undefined when no route exists — runDream
353
+ * then fails safe. A config→default switch is logged so it is observable.
318
354
  */
319
355
  function resolveRoute(ctx, config, logger) {
356
+ if (config.dreamProvider && config.dreamModel) return { provider: config.dreamProvider, model: config.dreamModel };
320
357
  try {
321
358
  const sel = ctx.agentDefaultModel?.currentSelection?.();
322
- if (sel?.provider && sel?.model) return { provider: sel.provider, model: sel.model };
323
- logger?.warn?.("dsh-mneme dream: agentDefaultModel unavailable, falling back to config route");
359
+ if (sel?.provider && sel?.model) {
360
+ logger?.info?.("dsh-mneme dream: no dreamProvider/dreamModel config, falling back to agent default");
361
+ return { provider: sel.provider, model: sel.model };
362
+ }
363
+ logger?.warn?.("dsh-mneme dream: agentDefaultModel unavailable, no config route either");
324
364
  } catch (error) {
325
- logger?.warn?.(`dsh-mneme dream: agentDefaultModel lookup failed, falling back to config route: ${String(error)}`);
365
+ logger?.warn?.(`dsh-mneme dream: agentDefaultModel lookup failed: ${String(error)}`);
326
366
  }
327
- if (config.dreamProvider && config.dreamModel) return { provider: config.dreamProvider, model: config.dreamModel };
328
367
  return undefined;
329
368
  }
330
369
 
@@ -585,28 +624,37 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
585
624
  ? CONSOLIDATION_PROMPT + `\n\n当前为「冲突冻结」模式:检测到内容矛盾的条目时,仍请输出 conflict,并以 winner/loser 作为候选、reason 说明理由;冲突不会被自动裁决,而会冻结待人工确认。`
586
625
  : CONSOLIDATION_PROMPT;
587
626
  let decisionText;
627
+ // 加固(v0.8.1):配置的 reasoningEffort 被 provider 拒收时回退重试一次
628
+ // (不带该字段),避免 thinking 模型配置 low/medium 直接整单失败。解析放
629
+ // 在 auditError 检查器里、闭包交回主流程,避免二次解析;解析失败同时如实
630
+ // 记 audit error 并在日志带原始输出前 300 字节,便于定位"推理吞预算返回空体"。
631
+ const effort = config.dreamReasoningEffort && config.dreamReasoningEffort !== "none" ? config.dreamReasoningEffort : null;
632
+ let decisions = null;
633
+ const runConsolidation = (withEffort) => runAuditedLlm(ctx, service, config, {
634
+ triggerSource: "autoDream",
635
+ operationType: "dream_consolidate",
636
+ modelId: `${route.provider}:${route.model}`,
637
+ relatedMemoryIds: [...snapshot.keys()],
638
+ auditError: (text) => {
639
+ decisions = extractJsonArray(text);
640
+ return Array.isArray(decisions) ? null : "no json array in llm output";
641
+ }
642
+ }, (reportUsage) => streamText(ctx, {
643
+ provider: route.provider,
644
+ model: route.model,
645
+ purpose: "compaction",
646
+ maxTokens: config.dreamMaxTokens ?? 4096,
647
+ ...(withEffort && effort ? { reasoningEffort: effort } : {}),
648
+ messages: [
649
+ { role: "system", content: [{ type: "text", text: consolidationPrompt }] },
650
+ { role: "user", content: [{ type: "text", text: listText }] }
651
+ ]
652
+ }, reportUsage));
588
653
  try {
589
654
  // Bug8: the consolidation call is audited (tokens/time/status). A throw
590
655
  // re-propagates to the catch below; an aborted stream returns undefined
591
656
  // and is treated as a failed run after the check below.
592
- decisionText = await runAuditedLlm(ctx, service, config, {
593
- triggerSource: "autoDream",
594
- operationType: "dream_consolidate",
595
- modelId: `${route.provider}:${route.model}`,
596
- relatedMemoryIds: [...snapshot.keys()]
597
- }, (reportUsage) => streamText(ctx, {
598
- provider: route.provider,
599
- model: route.model,
600
- purpose: "compaction",
601
- maxTokens: config.dreamMaxTokens ?? 4096,
602
- ...(config.dreamReasoningEffort && config.dreamReasoningEffort !== "none"
603
- ? { reasoningEffort: config.dreamReasoningEffort }
604
- : {}),
605
- messages: [
606
- { role: "system", content: [{ type: "text", text: consolidationPrompt }] },
607
- { role: "user", content: [{ type: "text", text: listText }] }
608
- ]
609
- }, reportUsage));
657
+ decisionText = await withEffortFallback(ctx, effort, () => runConsolidation(true), () => runConsolidation(false));
610
658
  } catch (error) {
611
659
  logger?.warn?.(`dsh-mneme dream: consolidation llm call failed: ${String(error)}`);
612
660
  return finish({ ok: false, error: "llm failed", summary: false });
@@ -615,10 +663,9 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
615
663
  logger?.warn?.("dsh-mneme dream: consolidation llm stream aborted or errored");
616
664
  return finish({ ok: false, error: "llm failed", summary: false });
617
665
  }
618
-
619
- const decisions = extractJsonArray(decisionText);
620
666
  if (!Array.isArray(decisions)) {
621
- logger?.warn?.(`dsh-mneme dream: no json array in llm output (raw length ${decisionText?.length ?? 0})`);
667
+ const head = (decisionText ?? "").slice(0, 300).replace(/\s+/g, " ").trim();
668
+ logger?.warn?.(`dsh-mneme dream: no json array in llm output (raw length ${decisionText?.length ?? 0}; head: ${head})`);
622
669
  return finish({ ok: false, error: "no json array in llm output", summary: false });
623
670
  }
624
671
  const { ok, errors } = validateDecisions(decisions, snapshot, {
@@ -735,26 +782,25 @@ export function createDreamScheduler({ onRun, thresholdCount = 10, thresholdChar
735
782
  // Summary generation (second LLM call). A throwing stream is reported as
736
783
  // a failed run; summary:false marks a run that produced no summary.
737
784
  let summaryText;
785
+ const runSummary = (withEffort) => runAuditedLlm(ctx, service, config, {
786
+ triggerSource: "autoDream",
787
+ operationType: "dream_summarize",
788
+ modelId: `${route.provider}:${route.model}`,
789
+ relatedMemoryIds: []
790
+ }, (reportUsage) => streamText(ctx, {
791
+ provider: route.provider,
792
+ model: route.model,
793
+ purpose: "compaction",
794
+ maxTokens: config.dreamMaxTokens ?? 2048,
795
+ ...(withEffort && effort ? { reasoningEffort: effort } : {}),
796
+ messages: [
797
+ { role: "system", content: [{ type: "text", text: SUMMARY_PROMPT }] },
798
+ { role: "user", content: [{ type: "text", text: service.all().filter((m) => !m.archived && m.type !== "summary").map((m) => `- ${m.title}: ${m.content}`).join("\n") }] }
799
+ ]
800
+ }, reportUsage));
738
801
  try {
739
802
  // Bug8: the summary call is audited too (operation dream_summarize).
740
- summaryText = await runAuditedLlm(ctx, service, config, {
741
- triggerSource: "autoDream",
742
- operationType: "dream_summarize",
743
- modelId: `${route.provider}:${route.model}`,
744
- relatedMemoryIds: []
745
- }, (reportUsage) => streamText(ctx, {
746
- provider: route.provider,
747
- model: route.model,
748
- purpose: "compaction",
749
- maxTokens: config.dreamMaxTokens ?? 2048,
750
- ...(config.dreamReasoningEffort && config.dreamReasoningEffort !== "none"
751
- ? { reasoningEffort: config.dreamReasoningEffort }
752
- : {}),
753
- messages: [
754
- { role: "system", content: [{ type: "text", text: SUMMARY_PROMPT }] },
755
- { role: "user", content: [{ type: "text", text: service.all().filter((m) => !m.archived && m.type !== "summary").map((m) => `- ${m.title}: ${m.content}`).join("\n") }] }
756
- ]
757
- }, reportUsage));
803
+ summaryText = await withEffortFallback(ctx, effort, () => runSummary(true), () => runSummary(false));
758
804
  } catch (error) {
759
805
  logger?.warn?.(`dsh-mneme dream: summary llm call failed: ${String(error)}`);
760
806
  return finish({ ok: false, error: "llm failed", applied, decisions: auditDecisions, outcome, frozen: frozenCount, summary: false });