somora 2026.930.1
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/LICENSE +21 -0
- package/README.md +364 -0
- package/bin/node-version.d.mts +3 -0
- package/bin/node-version.mjs +45 -0
- package/bin/somora.mjs +77 -0
- package/config.example.yaml +896 -0
- package/docs/agents.md +677 -0
- package/docs/api.md +3194 -0
- package/docs/browser.md +317 -0
- package/docs/builder.md +331 -0
- package/docs/cache-strategy.md +373 -0
- package/docs/compaction.md +253 -0
- package/docs/display.md +154 -0
- package/docs/dream-phases.md +891 -0
- package/docs/files.md +387 -0
- package/docs/imagegen.md +366 -0
- package/docs/images/somora-hero.png +0 -0
- package/docs/images/somora-mobile-2026-05-23.png +0 -0
- package/docs/images/somora-tui-2026-05-23.png +0 -0
- package/docs/images/somora-web-2026-05-23.png +0 -0
- package/docs/index.md +178 -0
- package/docs/lsp.md +93 -0
- package/docs/mcp.md +332 -0
- package/docs/memory.md +407 -0
- package/docs/mobile.md +310 -0
- package/docs/models.md +379 -0
- package/docs/projects.md +425 -0
- package/docs/realtime-voice.md +293 -0
- package/docs/resources.md +230 -0
- package/docs/sampling.md +128 -0
- package/docs/security.md +189 -0
- package/docs/sentinel.md +295 -0
- package/docs/setup.md +1217 -0
- package/docs/skills.md +501 -0
- package/docs/team.md +189 -0
- package/docs/thinking.md +463 -0
- package/docs/tmux.md +399 -0
- package/docs/tools.md +117 -0
- package/docs/videogen.md +191 -0
- package/docs/voice.md +288 -0
- package/docs/web.md +893 -0
- package/docs/wiki.md +583 -0
- package/npm-shrinkwrap.json +5670 -0
- package/package.json +116 -0
- package/src/attachments/store.ts +196 -0
- package/src/browser/change-stream.ts +31 -0
- package/src/browser/display.ts +108 -0
- package/src/browser/policy.ts +121 -0
- package/src/browser/screencast.ts +374 -0
- package/src/browser/service.ts +1337 -0
- package/src/browser/session.ts +15 -0
- package/src/browser/snapshot.ts +40 -0
- package/src/cli/auth.ts +117 -0
- package/src/cli/codex.ts +41 -0
- package/src/cli/lsp.ts +71 -0
- package/src/cli/resolvers/clawhub.ts +400 -0
- package/src/cli/setup.ts +835 -0
- package/src/cli/skill.ts +619 -0
- package/src/cli/somora.ts +548 -0
- package/src/cli/systemd-unit.ts +72 -0
- package/src/cli/team.ts +148 -0
- package/src/cli/tui/activity-stream.ts +121 -0
- package/src/cli/tui/api.ts +479 -0
- package/src/cli/tui/app.tsx +1169 -0
- package/src/cli/tui/autocomplete.tsx +55 -0
- package/src/cli/tui/commands.ts +913 -0
- package/src/cli/tui/dream-glyphs.ts +22 -0
- package/src/cli/tui/footer.tsx +15 -0
- package/src/cli/tui/format.ts +28 -0
- package/src/cli/tui/header.tsx +279 -0
- package/src/cli/tui/index.tsx +120 -0
- package/src/cli/tui/markdown.tsx +63 -0
- package/src/cli/tui/sampling.ts +162 -0
- package/src/cli/tui/separator.tsx +13 -0
- package/src/cli/tui/state.ts +42 -0
- package/src/cli/tui/stream.ts +330 -0
- package/src/cli/tui/thinking-text.ts +54 -0
- package/src/cli/tui/turn-views.tsx +499 -0
- package/src/cli/tui/types.ts +410 -0
- package/src/cli/tui/work-queue.ts +161 -0
- package/src/cli/update-args.ts +55 -0
- package/src/cli/wiki.ts +406 -0
- package/src/compaction/index.ts +28 -0
- package/src/compaction/midturn.ts +210 -0
- package/src/compaction/policy.ts +154 -0
- package/src/compaction/summarize.ts +691 -0
- package/src/compaction/template.ts +90 -0
- package/src/compaction/types.ts +148 -0
- package/src/config/loader.ts +276 -0
- package/src/config/reload.ts +43 -0
- package/src/config/types.ts +2292 -0
- package/src/dream/deep-actions.ts +324 -0
- package/src/dream/deep-dispatcher.ts +237 -0
- package/src/dream/deep-llm.ts +388 -0
- package/src/dream/deep-prompts.ts +106 -0
- package/src/dream/deep-runner.ts +757 -0
- package/src/dream/deep-skip-cache.ts +199 -0
- package/src/dream/deep-worker.ts +229 -0
- package/src/dream/json-salvage.ts +34 -0
- package/src/dream/judge.ts +188 -0
- package/src/dream/loop-state.ts +286 -0
- package/src/dream/lucid-actions.ts +303 -0
- package/src/dream/lucid-batches.ts +94 -0
- package/src/dream/lucid-prompt.ts +82 -0
- package/src/dream/lucid-runner.ts +744 -0
- package/src/dream/lucid-storage.ts +277 -0
- package/src/dream/lucid-structure.ts +102 -0
- package/src/dream/lucid-types.ts +137 -0
- package/src/dream/lucid-worker.ts +224 -0
- package/src/dream/rem-dedup.ts +502 -0
- package/src/dream/rem-extract.ts +782 -0
- package/src/dream/rem-reset-run.ts +67 -0
- package/src/dream/rem-runner.ts +696 -0
- package/src/dream/rem-worker.ts +527 -0
- package/src/dream/review-window.ts +71 -0
- package/src/dream/scheduler-state.ts +129 -0
- package/src/dream/storage.ts +497 -0
- package/src/dream/types.ts +133 -0
- package/src/dream/wiki-context.ts +133 -0
- package/src/engine/a2a.ts +33 -0
- package/src/engine/availability.ts +63 -0
- package/src/engine/claude-cli.ts +969 -0
- package/src/engine/codex-app-server-client.ts +294 -0
- package/src/engine/codex-bin.ts +49 -0
- package/src/engine/codex-cli.ts +1014 -0
- package/src/engine/codex-dynamic-tools.ts +239 -0
- package/src/engine/codex-home.ts +63 -0
- package/src/engine/codex-thread-config.ts +74 -0
- package/src/engine/context-budget.ts +257 -0
- package/src/engine/engine-meta-labels.ts +211 -0
- package/src/engine/grok-cli.ts +941 -0
- package/src/engine/inline-think.ts +59 -0
- package/src/engine/model-availability.ts +105 -0
- package/src/engine/openai-compatible.ts +2464 -0
- package/src/engine/reasoning-retry.ts +83 -0
- package/src/engine/registry.ts +13 -0
- package/src/engine/replay.ts +195 -0
- package/src/engine/sampling.ts +90 -0
- package/src/engine/thinking-params.ts +264 -0
- package/src/engine/types.ts +269 -0
- package/src/engine/user-tag.ts +24 -0
- package/src/imagegen/aspect.ts +128 -0
- package/src/imagegen/generate.ts +642 -0
- package/src/imagegen/references.ts +75 -0
- package/src/imagegen/types.ts +154 -0
- package/src/lsp/client.ts +183 -0
- package/src/lsp/fake-server.helper.mjs +42 -0
- package/src/lsp/format.ts +29 -0
- package/src/lsp/index.ts +21 -0
- package/src/lsp/manager.ts +238 -0
- package/src/lsp/registry.ts +151 -0
- package/src/mcp/config.ts +117 -0
- package/src/mcp/hub/audit.ts +55 -0
- package/src/mcp/hub/bridge.ts +115 -0
- package/src/mcp/hub/catalog.ts +69 -0
- package/src/mcp/hub/credentials.ts +406 -0
- package/src/mcp/hub/env-expand.ts +14 -0
- package/src/mcp/hub/manager.ts +770 -0
- package/src/mcp/hub/normalize.ts +213 -0
- package/src/mcp/server.ts +368 -0
- package/src/mcp/tool-schema.ts +20 -0
- package/src/media/capabilities.ts +392 -0
- package/src/media/records.ts +175 -0
- package/src/media/store.ts +217 -0
- package/src/media/types.ts +69 -0
- package/src/memory/chunking.ts +168 -0
- package/src/memory/embeddings.ts +262 -0
- package/src/memory/index.ts +15 -0
- package/src/memory/inject.ts +197 -0
- package/src/memory/manager.ts +996 -0
- package/src/memory/registry.ts +176 -0
- package/src/memory/rescan.ts +101 -0
- package/src/memory/retrieval.ts +586 -0
- package/src/memory/shared-index.ts +372 -0
- package/src/memory/slug.ts +39 -0
- package/src/memory/storage.ts +385 -0
- package/src/memory/watcher.ts +134 -0
- package/src/multimodal/blocks.ts +101 -0
- package/src/multimodal/dimensions.ts +214 -0
- package/src/multimodal/load.ts +86 -0
- package/src/multimodal/mime.ts +135 -0
- package/src/multimodal/pdf-render.ts +80 -0
- package/src/multimodal/user-content.ts +266 -0
- package/src/persona/files.ts +144 -0
- package/src/persona/loader.ts +598 -0
- package/src/persona/skill-gating-store.ts +59 -0
- package/src/persona/tool-gating-store.ts +113 -0
- package/src/projects/focus.ts +186 -0
- package/src/projects/prompt-block.ts +106 -0
- package/src/projects/scheme.ts +107 -0
- package/src/projects/store.ts +144 -0
- package/src/projects/types.ts +73 -0
- package/src/sentinel/dispatcher.ts +97 -0
- package/src/sentinel/schedule.ts +271 -0
- package/src/sentinel/scheduler.ts +840 -0
- package/src/sentinel/store.ts +259 -0
- package/src/sentinel/types.ts +221 -0
- package/src/server/activity-stream.ts +160 -0
- package/src/server/ask-calls.ts +137 -0
- package/src/server/ask-wait-graph.ts +171 -0
- package/src/server/async-tasks.ts +199 -0
- package/src/server/builder-busy.ts +86 -0
- package/src/server/builder-prompt.ts +204 -0
- package/src/server/builder-questions.ts +117 -0
- package/src/server/builder-session.ts +249 -0
- package/src/server/chat-aborts.ts +83 -0
- package/src/server/claude-config-dir.ts +71 -0
- package/src/server/claude-credential-sync.ts +454 -0
- package/src/server/env-file.ts +100 -0
- package/src/server/env.ts +115 -0
- package/src/server/heal-session.ts +151 -0
- package/src/server/history-page.ts +46 -0
- package/src/server/index.ts +7244 -0
- package/src/server/lockfile.ts +89 -0
- package/src/server/logger.ts +67 -0
- package/src/server/logs.ts +187 -0
- package/src/server/loopback-fetch.ts +130 -0
- package/src/server/openai-client.ts +89 -0
- package/src/server/prompt-assembly.ts +334 -0
- package/src/server/restart-reconcile.ts +139 -0
- package/src/server/run-turn-fallback.ts +275 -0
- package/src/server/run-turn-types.ts +91 -0
- package/src/server/run-turn.ts +1474 -0
- package/src/server/sanitize-assistant-text.ts +112 -0
- package/src/server/session-export.ts +220 -0
- package/src/server/session-queue.ts +376 -0
- package/src/server/session-workdir.ts +49 -0
- package/src/server/sse-h2-safe.ts +61 -0
- package/src/server/sse-liveness.ts +162 -0
- package/src/server/sse-serializer.ts +161 -0
- package/src/server/start-turn.ts +249 -0
- package/src/server/steer-inbox.ts +107 -0
- package/src/server/tls-keeper.ts +153 -0
- package/src/server/tool-format.ts +167 -0
- package/src/server/turn-framing.ts +52 -0
- package/src/server/turn-origin-kind.ts +74 -0
- package/src/server/turn-origin.ts +40 -0
- package/src/server/work-ledger.ts +975 -0
- package/src/server/workspace.ts +114 -0
- package/src/setup/config-edit.ts +201 -0
- package/src/setup/presets.ts +71 -0
- package/src/setup/prompt.ts +163 -0
- package/src/setup/tailscale.ts +44 -0
- package/src/skills/bin-checks.ts +227 -0
- package/src/skills/bootstrap.ts +347 -0
- package/src/skills/env-scope.ts +175 -0
- package/src/skills/gating.ts +71 -0
- package/src/skills/lint.ts +202 -0
- package/src/skills/load.ts +368 -0
- package/src/skills/path-helpers.ts +102 -0
- package/src/skills/registry.ts +178 -0
- package/src/ssh/exec.ts +142 -0
- package/src/ssh/index.ts +12 -0
- package/src/ssh/known-hosts.ts +109 -0
- package/src/ssh/pool.ts +307 -0
- package/src/storage/sessions.ts +602 -0
- package/src/team/render.ts +149 -0
- package/src/team/resolve.ts +122 -0
- package/src/team/store.ts +124 -0
- package/src/team/types.ts +111 -0
- package/src/team/write.ts +95 -0
- package/src/testing/isolated-home.mts +46 -0
- package/src/tmux/attention-watcher.ts +272 -0
- package/src/tmux/attention.ts +336 -0
- package/src/tmux/list.ts +91 -0
- package/src/tmux/origin-store.ts +102 -0
- package/src/tmux/tui-markers.ts +267 -0
- package/src/tools/agents/ask-cancel.ts +94 -0
- package/src/tools/agents/ask-result.ts +235 -0
- package/src/tools/agents/ask.ts +704 -0
- package/src/tools/agents/builder-dispatch.ts +217 -0
- package/src/tools/agents/images.ts +104 -0
- package/src/tools/agents/index.ts +42 -0
- package/src/tools/agents/long-task-timeouts.ts +39 -0
- package/src/tools/agents/session-list.ts +136 -0
- package/src/tools/agents/session-model.ts +106 -0
- package/src/tools/agents/spawn.ts +845 -0
- package/src/tools/agents/status.ts +589 -0
- package/src/tools/browser/index.ts +6 -0
- package/src/tools/browser/ops.ts +145 -0
- package/src/tools/browser/tools.ts +184 -0
- package/src/tools/builder/short-descriptions.ts +80 -0
- package/src/tools/builder/tools.ts +222 -0
- package/src/tools/docs/index.ts +1 -0
- package/src/tools/docs/tools.ts +228 -0
- package/src/tools/dream/index.ts +11 -0
- package/src/tools/dream/tools.ts +1002 -0
- package/src/tools/exec/allowlist.ts +233 -0
- package/src/tools/exec/background-detach.helper.mts +27 -0
- package/src/tools/exec/blacklist.ts +336 -0
- package/src/tools/exec/concurrency.ts +150 -0
- package/src/tools/exec/fit-output.ts +82 -0
- package/src/tools/exec/index.ts +7 -0
- package/src/tools/exec/internal-env.ts +89 -0
- package/src/tools/exec/job-store.ts +403 -0
- package/src/tools/exec/local.ts +649 -0
- package/src/tools/exec/remote.ts +399 -0
- package/src/tools/exec/tools.ts +934 -0
- package/src/tools/file/analyze.ts +378 -0
- package/src/tools/file/index.ts +2 -0
- package/src/tools/file/local.ts +707 -0
- package/src/tools/file/lsp-hook.ts +72 -0
- package/src/tools/file/persona-guard.ts +61 -0
- package/src/tools/file/policy.ts +292 -0
- package/src/tools/file/read-format.ts +129 -0
- package/src/tools/file/remote.ts +680 -0
- package/src/tools/file/replace.ts +507 -0
- package/src/tools/file/search-window.ts +224 -0
- package/src/tools/file/tools.ts +658 -0
- package/src/tools/file/write-scope.ts +182 -0
- package/src/tools/gating.ts +106 -0
- package/src/tools/image/budget.ts +82 -0
- package/src/tools/image/index.ts +7 -0
- package/src/tools/image/tools.ts +601 -0
- package/src/tools/index.ts +99 -0
- package/src/tools/memory/index.ts +12 -0
- package/src/tools/memory/tools.ts +399 -0
- package/src/tools/projects/index.ts +1 -0
- package/src/tools/projects/tools.ts +643 -0
- package/src/tools/registry.ts +427 -0
- package/src/tools/resources/index.ts +8 -0
- package/src/tools/resources/tools.ts +176 -0
- package/src/tools/resources/visibility.ts +60 -0
- package/src/tools/sentinel/index.ts +1 -0
- package/src/tools/sentinel/tools.ts +592 -0
- package/src/tools/skill/index.ts +4 -0
- package/src/tools/skill/tools.ts +285 -0
- package/src/tools/time/index.ts +5 -0
- package/src/tools/time/tools.ts +123 -0
- package/src/tools/tmux/index.ts +1 -0
- package/src/tools/tmux/local.ts +277 -0
- package/src/tools/tmux/remote.ts +168 -0
- package/src/tools/tmux/tools.ts +1064 -0
- package/src/tools/tool-output.ts +97 -0
- package/src/tools/types.ts +227 -0
- package/src/tools/video/index.ts +1 -0
- package/src/tools/video/tools.ts +425 -0
- package/src/tools/web/fetch.ts +337 -0
- package/src/tools/web/index.ts +4 -0
- package/src/tools/web/tools.ts +186 -0
- package/src/tools/wiki/index.ts +1 -0
- package/src/tools/wiki/tools.ts +445 -0
- package/src/tts/cache-gc.ts +128 -0
- package/src/tts/prepare-for-tts.ts +114 -0
- package/src/tts/service.ts +332 -0
- package/src/types/events.ts +695 -0
- package/src/types/turn-origin.ts +53 -0
- package/src/version.ts +21 -0
- package/src/videogen/dialects.ts +222 -0
- package/src/videogen/generate.ts +484 -0
- package/src/videogen/jobs.ts +178 -0
- package/src/videogen/runner.ts +125 -0
- package/src/videogen/wake.ts +119 -0
- package/src/voice/realtime/call.ts +948 -0
- package/src/voice/realtime/consult.ts +293 -0
- package/src/voice/realtime/fake-provider.ts +134 -0
- package/src/voice/realtime/manager.ts +384 -0
- package/src/voice/realtime/openai-provider.ts +471 -0
- package/src/voice/realtime/persona.ts +227 -0
- package/src/voice/realtime/session-match.ts +116 -0
- package/src/voice/realtime/types.ts +182 -0
- package/src/wiki/conflict.ts +113 -0
- package/src/wiki/explorer.ts +578 -0
- package/src/wiki/index-builder.ts +172 -0
- package/src/wiki/language.ts +134 -0
- package/src/wiki/log-builder.ts +150 -0
- package/src/wiki/map.ts +258 -0
- package/src/wiki/migration/analyze.ts +304 -0
- package/src/wiki/migration/execute.ts +689 -0
- package/src/wiki/migration/refine.ts +402 -0
- package/src/wiki/migration/store.ts +100 -0
- package/src/wiki/move-page.ts +57 -0
- package/src/wiki/structure-file.ts +192 -0
- package/src/wiki/taxonomy.ts +140 -0
- package/src/wiki/templates.ts +163 -0
- package/src/wiki/types.ts +133 -0
- package/templates/skills/README.md +24 -0
- package/templates/skills/_templates/api-wrapper/SKILL.md +26 -0
- package/templates/skills/_templates/cli-wrapper/BOOTSTRAP.md +32 -0
- package/templates/skills/_templates/cli-wrapper/SKILL.md +24 -0
- package/templates/skills/_templates/default/SKILL.md +25 -0
- package/templates/skills/builder-handover/SKILL.md +96 -0
- package/templates/skills/builder-handover/assets/ORDER.md +12 -0
- package/templates/skills/skill-author/SKILL.md +110 -0
- package/tsconfig.json +22 -0
- package/web/dist/assets/index-BaVv6pB2.js +631 -0
- package/web/dist/assets/index-BaVv6pB2.js.map +1 -0
- package/web/dist/assets/index-V3FV3Z25.css +32 -0
- package/web/dist/favicon.svg +8 -0
- package/web/dist/index.html +20 -0
- package/web/package.json +36 -0
- package/web/tsconfig.json +25 -0
- package/web-mobile/dist/apple-touch-icon.png +0 -0
- package/web-mobile/dist/assets/index-BqKt7IMx.css +1 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js +88 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js.map +1 -0
- package/web-mobile/dist/favicon.svg +8 -0
- package/web-mobile/dist/icon-192.png +0 -0
- package/web-mobile/dist/icon-512.png +0 -0
- package/web-mobile/dist/index.html +27 -0
- package/web-mobile/dist/manifest.webmanifest +32 -0
- package/web-mobile/dist/service-worker.js +90 -0
- package/web-mobile/package.json +28 -0
- package/web-mobile/tsconfig.json +25 -0
|
@@ -0,0 +1,696 @@
|
|
|
1
|
+
// Dream-Mode runner. The universal driver that orchestrates extraction +
|
|
2
|
+
// storage + status transitions. Used by both manual triggers (/reset) and
|
|
3
|
+
// the future auto-trigger idle worker. Differences between the two reduce
|
|
4
|
+
// to: the trigger field on the DreamMeta, and whether an AbortSignal is
|
|
5
|
+
// passed (auto = signal cancels on user activity; manual = no signal,
|
|
6
|
+
// runs to completion regardless).
|
|
7
|
+
|
|
8
|
+
import { readFile, unlink } from 'node:fs/promises';
|
|
9
|
+
import type { Config, ResolvedModel } from '../config/types.ts';
|
|
10
|
+
import type { MemoryManager } from '../memory/manager.ts';
|
|
11
|
+
import type { RemConfig } from '../persona/loader.ts';
|
|
12
|
+
import { logger } from '../server/logger.ts';
|
|
13
|
+
import { getHistory } from '../storage/sessions.ts';
|
|
14
|
+
import {
|
|
15
|
+
dreamFilePath,
|
|
16
|
+
dreamIdFor,
|
|
17
|
+
pruneFailedDreams,
|
|
18
|
+
readDreamById,
|
|
19
|
+
transitionDreamStatus,
|
|
20
|
+
writeDreamFile,
|
|
21
|
+
} from './storage.ts';
|
|
22
|
+
import { extractFromSession, resolveDreamModel } from './rem-extract.ts';
|
|
23
|
+
import type { DreamFile, DreamMeta, DreamTriggerKind } from './types.ts';
|
|
24
|
+
import { modelRef, modelUnavailable, unavailableReason } from '../engine/model-availability.ts';
|
|
25
|
+
import { effectiveJudgeModel, resolveJudgeModel } from './judge.ts';
|
|
26
|
+
import { applyRemDedup } from './rem-dedup.ts';
|
|
27
|
+
import { loadWikiContext } from './wiki-context.ts';
|
|
28
|
+
import { excludeReviewWindows } from './review-window.ts';
|
|
29
|
+
import { resolveObsidianSource } from '../memory/registry.ts';
|
|
30
|
+
import { join } from 'node:path';
|
|
31
|
+
|
|
32
|
+
export interface RunDreamArgs {
|
|
33
|
+
agent: string;
|
|
34
|
+
/** Source session whose JSONL delta to analyze. */
|
|
35
|
+
sourceSession: string;
|
|
36
|
+
trigger: DreamTriggerKind;
|
|
37
|
+
/**
|
|
38
|
+
* Lower bound (inclusive) of the JSONL range to extract. Use 0 for
|
|
39
|
+
* "from the start of the session". Auto-trigger passes the session's
|
|
40
|
+
* dreamReadThroughTs marker; manual /reset usually passes the same.
|
|
41
|
+
*/
|
|
42
|
+
rangeFromTs: number;
|
|
43
|
+
/** Upper bound (inclusive). Date.now() for "all events up to now". */
|
|
44
|
+
rangeThroughTs: number;
|
|
45
|
+
/** Resolved per-agent dream config (model, chunk sizes, timeouts). */
|
|
46
|
+
rem: RemConfig;
|
|
47
|
+
/** Loaded server config — used to resolve dream.model to a ResolvedModel. */
|
|
48
|
+
config: Config;
|
|
49
|
+
/** Per-agent memory manager (already initialized). */
|
|
50
|
+
mgr: MemoryManager;
|
|
51
|
+
/**
|
|
52
|
+
* Optional AbortSignal — auto-trigger sets one and aborts on user
|
|
53
|
+
* activity; manual trigger leaves undefined (run to completion).
|
|
54
|
+
*/
|
|
55
|
+
signal?: AbortSignal;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Build a single combined search query from all user messages in the
|
|
60
|
+
* range. Used to find which vault notes would have been referenced by
|
|
61
|
+
* the runtime auto-inject for this conversation. Approximation but
|
|
62
|
+
* cheaper than re-running search per user message.
|
|
63
|
+
*/
|
|
64
|
+
/** Bounds for the vault/wiki recall query. It used to be EVERY user
|
|
65
|
+
* message of the range joined together — 900 messages / 275k chars on
|
|
66
|
+
* one reset, which the FTS layer then turned into ~50k OR-terms and
|
|
67
|
+
* the server stood still for minutes (2026-09-03). The recall only
|
|
68
|
+
* needs the gist of what the conversation was about: the most recent
|
|
69
|
+
* messages, human ones only (A2A traffic and injected blocks are
|
|
70
|
+
* persisted as user_message too), capped in characters. */
|
|
71
|
+
export const RECALL_QUERY_MAX_MESSAGES = 20;
|
|
72
|
+
export const RECALL_QUERY_MAX_CHARS = 4000;
|
|
73
|
+
|
|
74
|
+
export function buildVaultRecallQuery(
|
|
75
|
+
events: ReadonlyArray<{ kind: string; text?: string; from_agent?: string }>,
|
|
76
|
+
limits: { maxMessages?: number; maxChars?: number } = {},
|
|
77
|
+
): string {
|
|
78
|
+
const maxMessages = limits.maxMessages ?? RECALL_QUERY_MAX_MESSAGES;
|
|
79
|
+
const maxChars = limits.maxChars ?? RECALL_QUERY_MAX_CHARS;
|
|
80
|
+
const texts = events
|
|
81
|
+
.filter((e) => e.kind === 'user_message' && !e.from_agent && typeof e.text === 'string' && e.text.trim().length > 0)
|
|
82
|
+
.map((e) => e.text as string)
|
|
83
|
+
.slice(-maxMessages);
|
|
84
|
+
// Newest first so the tail of the conversation survives the char cap.
|
|
85
|
+
const out: string[] = [];
|
|
86
|
+
let chars = 0;
|
|
87
|
+
for (let i = texts.length - 1; i >= 0; i--) {
|
|
88
|
+
const t = texts[i]!;
|
|
89
|
+
if (chars + t.length > maxChars) {
|
|
90
|
+
const room = maxChars - chars;
|
|
91
|
+
if (room > 40) out.unshift(t.slice(t.length - room));
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
out.unshift(t);
|
|
95
|
+
chars += t.length + 1;
|
|
96
|
+
}
|
|
97
|
+
return out.join(' ');
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Render the human-readable Markdown body for a completed dream.
|
|
102
|
+
* Optional sources block lets the caller surface which memory + vault
|
|
103
|
+
* notes were considered as input — useful to verify the extractor saw
|
|
104
|
+
* the right source material.
|
|
105
|
+
*/
|
|
106
|
+
function renderBody(
|
|
107
|
+
meta: DreamMeta,
|
|
108
|
+
sourceTitle: string,
|
|
109
|
+
sources?: {
|
|
110
|
+
memorySlugs: string[];
|
|
111
|
+
vaultSlugsWithScore: string[]; // pre-formatted "slug@0.74"
|
|
112
|
+
wikiSlugs?: string[]; // Phase 4
|
|
113
|
+
},
|
|
114
|
+
): string {
|
|
115
|
+
const triggerWord = meta.trigger === 'manual' ? 'manual' : 'auto';
|
|
116
|
+
const lines: string[] = [
|
|
117
|
+
`# Dream — ${sourceTitle} (${triggerWord})`,
|
|
118
|
+
'',
|
|
119
|
+
`Source session: \`${meta.source_session}\` `,
|
|
120
|
+
`Range: \`${new Date(meta.range_from_ts).toISOString()}\` → \`${new Date(meta.range_through_ts).toISOString()}\` `,
|
|
121
|
+
`Worker model: \`${meta.worker_model_ref}\`${meta.worker_fallback_ref ? ` (backup: \`${meta.worker_fallback_ref}\`)` : ''} `,
|
|
122
|
+
...(meta.worker_switch
|
|
123
|
+
? [
|
|
124
|
+
`Worker switched: \`${meta.worker_switch.from}\` → \`${meta.worker_switch.to}\` from chunk ${meta.worker_switch.at_chunk} on — ${meta.worker_switch.reason} `,
|
|
125
|
+
]
|
|
126
|
+
: []),
|
|
127
|
+
`Created: \`${meta.created_at}\` `,
|
|
128
|
+
`Status: **${meta.status}**`,
|
|
129
|
+
'',
|
|
130
|
+
];
|
|
131
|
+
if (meta.error) {
|
|
132
|
+
lines.push(`> ⚠️ ${meta.error}`, '');
|
|
133
|
+
}
|
|
134
|
+
if (sources) {
|
|
135
|
+
lines.push('## Sources analyzed', '');
|
|
136
|
+
lines.push(
|
|
137
|
+
`- Memory notes (full content): ${sources.memorySlugs.length === 0 ? '_none_' : sources.memorySlugs.map((s) => `\`${s}\``).join(', ')}`,
|
|
138
|
+
);
|
|
139
|
+
lines.push(
|
|
140
|
+
`- Vault notes (recall hits): ${sources.vaultSlugsWithScore.length === 0 ? '_none_' : sources.vaultSlugsWithScore.map((s) => `\`${s}\``).join(', ')}`,
|
|
141
|
+
);
|
|
142
|
+
if (sources.wikiSlugs && sources.wikiSlugs.length > 0) {
|
|
143
|
+
lines.push(
|
|
144
|
+
`- Wiki pages (stub-derived + recall): ${sources.wikiSlugs.map((s) => `\`wiki/${s}\``).join(', ')}`,
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
lines.push('');
|
|
148
|
+
}
|
|
149
|
+
if (meta.findings.length === 0) {
|
|
150
|
+
if ((meta.chunks_failed ?? 0) > 0 || meta.status === 'failed') {
|
|
151
|
+
lines.push(
|
|
152
|
+
'Extraction did NOT complete cleanly — no findings is a failure artifact, ' +
|
|
153
|
+
'not an empty result. The range will be retried.',
|
|
154
|
+
'',
|
|
155
|
+
);
|
|
156
|
+
} else {
|
|
157
|
+
lines.push('No memory-worthy findings extracted from this range.', '');
|
|
158
|
+
}
|
|
159
|
+
} else {
|
|
160
|
+
lines.push('## Findings', '');
|
|
161
|
+
for (const f of meta.findings) {
|
|
162
|
+
const statusBadge =
|
|
163
|
+
f.status === 'applied'
|
|
164
|
+
? '✓ applied'
|
|
165
|
+
: f.status === 'dismissed'
|
|
166
|
+
? '✗ dismissed'
|
|
167
|
+
: f.status === 'resolved_manually'
|
|
168
|
+
? '✔ resolved manually'
|
|
169
|
+
: '· pending';
|
|
170
|
+
const dupBadge = f.likely_duplicate ? ' ⚠️ likely-duplicate' : '';
|
|
171
|
+
lines.push(`### ${f.id}. \`${f.action}\` → \`${f.slug}\` (${statusBadge})${dupBadge}`);
|
|
172
|
+
lines.push('');
|
|
173
|
+
if (f.likely_duplicate && f.duplicate_of) {
|
|
174
|
+
lines.push(
|
|
175
|
+
f.novel_details
|
|
176
|
+
? `> ⚠️ Topic matches \`${f.duplicate_of}\` — but the finding carries concrete ` +
|
|
177
|
+
`details (numbers/dates) NOT found there. Likely a NEW fact on a known topic; ` +
|
|
178
|
+
`do not batch-dismiss.`
|
|
179
|
+
: `> ⚠️ Near-duplicate of \`${f.duplicate_of}\` — review with dismissal in mind.`,
|
|
180
|
+
);
|
|
181
|
+
if (f.matched_excerpt) {
|
|
182
|
+
lines.push(`> Matched text: "${f.matched_excerpt}"`);
|
|
183
|
+
}
|
|
184
|
+
lines.push('');
|
|
185
|
+
}
|
|
186
|
+
lines.push(f.reason);
|
|
187
|
+
lines.push('');
|
|
188
|
+
if (f.current_excerpt) {
|
|
189
|
+
lines.push('> Current memory:');
|
|
190
|
+
lines.push('');
|
|
191
|
+
lines.push('```');
|
|
192
|
+
lines.push(f.current_excerpt);
|
|
193
|
+
lines.push('```');
|
|
194
|
+
lines.push('');
|
|
195
|
+
}
|
|
196
|
+
if (f.proposed_content) {
|
|
197
|
+
lines.push('> Proposed content:');
|
|
198
|
+
lines.push('');
|
|
199
|
+
lines.push('```markdown');
|
|
200
|
+
lines.push(f.proposed_content);
|
|
201
|
+
lines.push('```');
|
|
202
|
+
lines.push('');
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return lines.join('\n');
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Main entry. Creates a `running` dream file, runs extraction, updates the
|
|
211
|
+
* file to `paused` / `failed` / `completed` based on outcome.
|
|
212
|
+
*
|
|
213
|
+
* Errors in extraction are caught and result in a `failed` dream — never
|
|
214
|
+
* thrown to the caller. The caller (server-side trigger) just fires this
|
|
215
|
+
* and forgets. Diagnostic output goes to the Pino log.
|
|
216
|
+
*/
|
|
217
|
+
export async function runDream(args: RunDreamArgs): Promise<{ id: string; finalStatus: DreamMeta['status'] }> {
|
|
218
|
+
const startedAt = new Date().toISOString();
|
|
219
|
+
const id = dreamIdFor(args.agent, args.sourceSession, args.trigger);
|
|
220
|
+
|
|
221
|
+
// Resolve worker model first — fail-loud per design (RemConfig requires
|
|
222
|
+
// an explicit model when enabled, no fallback).
|
|
223
|
+
let workerModel: ResolvedModel;
|
|
224
|
+
// The fallback chain in config order, primary and duplicates dropped.
|
|
225
|
+
const fallbackModels: ResolvedModel[] = [];
|
|
226
|
+
let startSwitch: { from: string; to: string; reason: string; at_chunk: number } | undefined;
|
|
227
|
+
// The coverage judge's model (rem.dedup.judge): the worker unless a
|
|
228
|
+
// ref is named; validated here so a typo fails the run at its start.
|
|
229
|
+
let judgeModel: ResolvedModel | undefined;
|
|
230
|
+
try {
|
|
231
|
+
workerModel = resolveDreamModel(args.config, args.rem.model);
|
|
232
|
+
if (args.config.rem.dedup.judge.enabled) {
|
|
233
|
+
judgeModel = resolveJudgeModel(args.config, args.config.rem.dedup.judge.model, workerModel);
|
|
234
|
+
}
|
|
235
|
+
// The backup is validated up front too: a typo in `rem.fallback`
|
|
236
|
+
// must surface now, not on the day the primary is down.
|
|
237
|
+
const refs = args.rem.fallback ? (Array.isArray(args.rem.fallback) ? args.rem.fallback : [args.rem.fallback]) : [];
|
|
238
|
+
for (const ref of refs) {
|
|
239
|
+
const m = resolveDreamModel(args.config, ref);
|
|
240
|
+
const same = (a: ResolvedModel, b: ResolvedModel) => a.providerName === b.providerName && a.modelId === b.modelId;
|
|
241
|
+
if (same(m, workerModel)) {
|
|
242
|
+
logger.warn({ msg: 'dream.worker_fallback_is_primary', agent: args.agent, ref });
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
if (fallbackModels.some((f) => same(f, m))) continue;
|
|
246
|
+
fallbackModels.push(m);
|
|
247
|
+
}
|
|
248
|
+
// A worker marked unavailable (model-availability.ts) is not knocked
|
|
249
|
+
// on again: the run starts on the first backup that is not marked,
|
|
250
|
+
// recorded as a switch at chunk 0 so the file and the judge follow.
|
|
251
|
+
const startMark = modelUnavailable(modelRef(workerModel));
|
|
252
|
+
if (startMark) {
|
|
253
|
+
const idx = fallbackModels.findIndex((m) => !modelUnavailable(modelRef(m)));
|
|
254
|
+
if (idx >= 0) {
|
|
255
|
+
const to = fallbackModels[idx]!;
|
|
256
|
+
startSwitch = { from: modelRef(workerModel), to: modelRef(to), reason: unavailableReason(startMark), at_chunk: 0 };
|
|
257
|
+
logger.info({ msg: 'dream.worker_start_on_fallback', agent: args.agent, ...startSwitch });
|
|
258
|
+
const rest = fallbackModels.slice(idx + 1);
|
|
259
|
+
fallbackModels.length = 0;
|
|
260
|
+
fallbackModels.push(...rest);
|
|
261
|
+
workerModel = to;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
} catch (err) {
|
|
265
|
+
logger.error({
|
|
266
|
+
msg: 'dream.worker_resolve_failed',
|
|
267
|
+
agent: args.agent,
|
|
268
|
+
err: (err as Error).message,
|
|
269
|
+
});
|
|
270
|
+
// Persist a failed dream so the user sees something rather than silent skip.
|
|
271
|
+
const meta: DreamMeta = {
|
|
272
|
+
id,
|
|
273
|
+
agent: args.agent,
|
|
274
|
+
source_session: args.sourceSession,
|
|
275
|
+
trigger: args.trigger,
|
|
276
|
+
status: 'failed',
|
|
277
|
+
range_from_ts: args.rangeFromTs,
|
|
278
|
+
range_through_ts: args.rangeThroughTs,
|
|
279
|
+
created_at: startedAt,
|
|
280
|
+
error: (err as Error).message,
|
|
281
|
+
chunks_done: 0,
|
|
282
|
+
chunks_total: 0,
|
|
283
|
+
worker_model_ref: args.rem.model,
|
|
284
|
+
findings: [],
|
|
285
|
+
};
|
|
286
|
+
// No `sources` block here — we never got past resolveDreamModel,
|
|
287
|
+
// there's nothing to attribute.
|
|
288
|
+
await writeDreamFile(args.agent, { meta, body: renderBody(meta, args.sourceSession) });
|
|
289
|
+
return { id, finalStatus: 'failed' };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// Pull source events.
|
|
293
|
+
const events = await getHistory(args.agent, args.sourceSession);
|
|
294
|
+
// Review-loop windows are found on the FULL history, not the range:
|
|
295
|
+
// a loop that started before rangeFromTs and ends inside it must
|
|
296
|
+
// still be recognised as a window.
|
|
297
|
+
const review = excludeReviewWindows(events);
|
|
298
|
+
if (review.dropped > 0) {
|
|
299
|
+
logger.info({
|
|
300
|
+
msg: 'dream.rem.review_windows_skipped',
|
|
301
|
+
agent: args.agent,
|
|
302
|
+
session: args.sourceSession,
|
|
303
|
+
windows: review.windows.map((w) => ({
|
|
304
|
+
fromTs: w.fromTs,
|
|
305
|
+
throughTs: Number.isFinite(w.throughTs) ? w.throughTs : null,
|
|
306
|
+
})),
|
|
307
|
+
dropped: review.dropped,
|
|
308
|
+
hint: 'facts clarified inside a dream_review loop are written to the wiki directly; REM must not re-extract them',
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
const eventsInRange = review.events.filter(
|
|
312
|
+
(e) => e.ts > args.rangeFromTs && e.ts <= args.rangeThroughTs,
|
|
313
|
+
);
|
|
314
|
+
|
|
315
|
+
// Memory snapshot.
|
|
316
|
+
const noteSummaries = await args.mgr.listNotes();
|
|
317
|
+
const existingMemory: Array<{ slug: string; markdown: string }> = [];
|
|
318
|
+
for (const n of noteSummaries) {
|
|
319
|
+
try {
|
|
320
|
+
const note = await args.mgr.getNote(n.slug);
|
|
321
|
+
if (note) existingMemory.push({ slug: n.slug, markdown: note.markdown });
|
|
322
|
+
} catch (err) {
|
|
323
|
+
logger.warn({ msg: 'dream.memory_read_failed', slug: n.slug, err: (err as Error).message });
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// Vault references — single combined query. We bump the limit (40) high
|
|
328
|
+
// enough that vault hits don't get crowded out by memory hits in the
|
|
329
|
+
// mixed search results: existing memory is already passed in full (see
|
|
330
|
+
// listNotes() above), so memory-source hits in this search are
|
|
331
|
+
// effectively duplicates and we drop them. Up to 15 vault notes pass
|
|
332
|
+
// through to the extractor.
|
|
333
|
+
const referencedVault: Array<{ slug: string; markdown: string; score: number }> = [];
|
|
334
|
+
const recallQuery = buildVaultRecallQuery(eventsInRange);
|
|
335
|
+
// Logged BEFORE the two synchronous searches so a slow recall is
|
|
336
|
+
// visible in the log instead of a silent gap before dream.start.
|
|
337
|
+
logger.info({
|
|
338
|
+
msg: 'dream.recall_query',
|
|
339
|
+
agent: args.agent,
|
|
340
|
+
sourceSession: args.sourceSession,
|
|
341
|
+
eventsInRange: eventsInRange.length,
|
|
342
|
+
queryChars: recallQuery.length,
|
|
343
|
+
});
|
|
344
|
+
if (recallQuery.trim().length > 0) {
|
|
345
|
+
try {
|
|
346
|
+
const hits = await args.mgr.search(recallQuery, { limit: 40, minScore: 0.4 });
|
|
347
|
+
const vaultHits = hits.filter((h) => h.source === 'vault').slice(0, 15);
|
|
348
|
+
const seenSlugs = new Set<string>();
|
|
349
|
+
for (const h of vaultHits) {
|
|
350
|
+
if (seenSlugs.has(h.slug)) continue;
|
|
351
|
+
seenSlugs.add(h.slug);
|
|
352
|
+
try {
|
|
353
|
+
const raw = await readFile(h.filePath, 'utf8');
|
|
354
|
+
referencedVault.push({ slug: h.slug, markdown: raw, score: h.score });
|
|
355
|
+
} catch (err) {
|
|
356
|
+
logger.debug({
|
|
357
|
+
msg: 'dream.vault_read_failed',
|
|
358
|
+
slug: h.slug,
|
|
359
|
+
err: (err as Error).message,
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
} catch (err) {
|
|
364
|
+
logger.warn({ msg: 'dream.vault_recall_failed', err: (err as Error).message });
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// Wiki context for dedup (v2.5): index.md (topology) + top-N
|
|
369
|
+
// embedding-matched wiki pages with full bodies. REM uses this to
|
|
370
|
+
// decide "is this fact already in the long-term wiki?" — Wiki is
|
|
371
|
+
// canonical, Memory is volatile inbox.
|
|
372
|
+
let wikiIndex = '';
|
|
373
|
+
const referencedWiki: Array<{ slug: string; markdown: string }> = [];
|
|
374
|
+
if (args.config.wiki.enabled) {
|
|
375
|
+
try {
|
|
376
|
+
const obs = resolveObsidianSource(args.config.obsidian);
|
|
377
|
+
const wikiAbs = obs?.vaultPath
|
|
378
|
+
? join(obs.vaultPath, args.config.wiki.vaultSubfolder)
|
|
379
|
+
: null;
|
|
380
|
+
const ctx = await loadWikiContext({
|
|
381
|
+
mgr: args.mgr,
|
|
382
|
+
query: recallQuery,
|
|
383
|
+
wikiAbs,
|
|
384
|
+
});
|
|
385
|
+
wikiIndex = ctx.indexSummary;
|
|
386
|
+
for (const p of ctx.relevantPages) {
|
|
387
|
+
referencedWiki.push({ slug: p.slug, markdown: p.markdown });
|
|
388
|
+
}
|
|
389
|
+
} catch (err) {
|
|
390
|
+
logger.warn({ msg: 'dream.wiki_ctx.load_failed', agent: args.agent, err: (err as Error).message });
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// Sources block — used by renderBody for the audit section in the
|
|
395
|
+
// dream file's Markdown body. Same shape across all subsequent
|
|
396
|
+
// renderBody calls so the file always shows what was considered.
|
|
397
|
+
const sources = {
|
|
398
|
+
memorySlugs: existingMemory.map((m) => m.slug),
|
|
399
|
+
vaultSlugsWithScore: referencedVault.map((v) => `${v.slug}@${v.score.toFixed(2)}`),
|
|
400
|
+
wikiSlugs: referencedWiki.map((w) => w.slug),
|
|
401
|
+
};
|
|
402
|
+
|
|
403
|
+
// Initial running file. chunks_total is set after the first chunk-plan
|
|
404
|
+
// happens inside extractFromSession; we backfill once we know.
|
|
405
|
+
const meta: DreamMeta = {
|
|
406
|
+
id,
|
|
407
|
+
agent: args.agent,
|
|
408
|
+
source_session: args.sourceSession,
|
|
409
|
+
trigger: args.trigger,
|
|
410
|
+
status: 'running',
|
|
411
|
+
range_from_ts: args.rangeFromTs,
|
|
412
|
+
range_through_ts: args.rangeThroughTs,
|
|
413
|
+
created_at: startedAt,
|
|
414
|
+
chunks_done: 0,
|
|
415
|
+
chunks_total: 0,
|
|
416
|
+
worker_model_ref: `${workerModel.providerName}/${workerModel.modelId}`,
|
|
417
|
+
...(fallbackModels.length > 0
|
|
418
|
+
? { worker_fallback_ref: fallbackModels.map((f) => `${f.providerName}/${f.modelId}`).join(', ') }
|
|
419
|
+
: {}),
|
|
420
|
+
...(startSwitch ? { worker_switch: startSwitch } : {}),
|
|
421
|
+
findings: [],
|
|
422
|
+
};
|
|
423
|
+
let file: DreamFile = {
|
|
424
|
+
meta,
|
|
425
|
+
body: renderBody(meta, args.sourceSession, sources),
|
|
426
|
+
};
|
|
427
|
+
await writeDreamFile(args.agent, file);
|
|
428
|
+
|
|
429
|
+
logger.info({
|
|
430
|
+
msg: 'dream.start',
|
|
431
|
+
agent: args.agent,
|
|
432
|
+
id,
|
|
433
|
+
trigger: args.trigger,
|
|
434
|
+
sourceSession: args.sourceSession,
|
|
435
|
+
eventsInRange: eventsInRange.length,
|
|
436
|
+
existingMemoryCount: existingMemory.length,
|
|
437
|
+
existingMemorySlugs: existingMemory.map((m) => m.slug),
|
|
438
|
+
referencedVaultCount: referencedVault.length,
|
|
439
|
+
referencedVaultSlugs: referencedVault.map((v) => `${v.slug}@${v.score.toFixed(2)}`),
|
|
440
|
+
referencedWikiCount: referencedWiki.length,
|
|
441
|
+
referencedWikiSlugs: referencedWiki.map((w) => w.slug),
|
|
442
|
+
workerModel: meta.worker_model_ref,
|
|
443
|
+
workerFallback: meta.worker_fallback_ref ?? null,
|
|
444
|
+
});
|
|
445
|
+
|
|
446
|
+
try {
|
|
447
|
+
const result = await extractFromSession({
|
|
448
|
+
agent: args.agent,
|
|
449
|
+
events: eventsInRange,
|
|
450
|
+
existingMemory,
|
|
451
|
+
referencedVault,
|
|
452
|
+
wikiIndex,
|
|
453
|
+
relevantWikiPages: referencedWiki,
|
|
454
|
+
workerModel,
|
|
455
|
+
...(fallbackModels.length > 0 ? { fallbackModels } : {}),
|
|
456
|
+
chunkTimeoutMs: args.rem.chunkTimeoutMs,
|
|
457
|
+
chunkTokens: args.rem.chunkTokens,
|
|
458
|
+
thinking: args.rem.thinking,
|
|
459
|
+
signal: args.signal,
|
|
460
|
+
onChunkComplete: async ({ chunkIndex, totalChunks }) => {
|
|
461
|
+
// Persist progress so a crash mid-flight leaves a recoverable file.
|
|
462
|
+
meta.chunks_done = chunkIndex;
|
|
463
|
+
meta.chunks_total = totalChunks;
|
|
464
|
+
file = { meta, body: renderBody(meta, args.sourceSession, sources) };
|
|
465
|
+
await writeDreamFile(args.agent, file);
|
|
466
|
+
},
|
|
467
|
+
onWorkerSwitch: async (sw) => {
|
|
468
|
+
// Persist the switch before the retried chunk runs, so a crash
|
|
469
|
+
// right after still shows which worker was in charge.
|
|
470
|
+
meta.worker_switch = { from: sw.from, to: sw.to, reason: sw.reason, at_chunk: sw.atChunk };
|
|
471
|
+
file = { meta, body: renderBody(meta, args.sourceSession, sources) };
|
|
472
|
+
await writeDreamFile(args.agent, file);
|
|
473
|
+
},
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
// Mechanical dedup against already-persisted knowledge — the worker
|
|
477
|
+
// model gets the same context in its prompt but small models don't
|
|
478
|
+
// reliably act on it (buffet 2026-07-06: 26/27 findings were
|
|
479
|
+
// repeats). Exact slug collisions are dropped, near-duplicates are
|
|
480
|
+
// marked for batch-dismissal. See rem-dedup.ts.
|
|
481
|
+
const dedup = await applyRemDedup({
|
|
482
|
+
agent: args.agent,
|
|
483
|
+
dreamId: id,
|
|
484
|
+
findings: result.findings,
|
|
485
|
+
existingMemorySlugs: existingMemory.map((m) => m.slug),
|
|
486
|
+
loadedWikiSlugs: referencedWiki.map((w) => w.slug),
|
|
487
|
+
mgr: args.mgr,
|
|
488
|
+
config: args.config.rem.dedup,
|
|
489
|
+
...(judgeModel
|
|
490
|
+
? {
|
|
491
|
+
judge: {
|
|
492
|
+
// The judge follows the worker: when the run switched to
|
|
493
|
+
// rem.fallback, the primary is unreachable for the judge
|
|
494
|
+
// too — unless the config names a judge model of its own.
|
|
495
|
+
model: effectiveJudgeModel(
|
|
496
|
+
args.config.rem.dedup.judge.model ? judgeModel : undefined,
|
|
497
|
+
meta.worker_switch?.to,
|
|
498
|
+
workerModel,
|
|
499
|
+
fallbackModels,
|
|
500
|
+
),
|
|
501
|
+
config: args.config.rem.dedup.judge,
|
|
502
|
+
...(args.config.rem.dedup.judge.thinking ? { thinking: args.config.rem.dedup.judge.thinking } : {}),
|
|
503
|
+
},
|
|
504
|
+
}
|
|
505
|
+
: {}),
|
|
506
|
+
});
|
|
507
|
+
|
|
508
|
+
meta.findings = dedup.findings;
|
|
509
|
+
meta.chunks_done = result.chunksProcessed;
|
|
510
|
+
meta.chunks_total = result.totalChunks;
|
|
511
|
+
if (result.failedChunks > 0) meta.chunks_failed = result.failedChunks;
|
|
512
|
+
|
|
513
|
+
// Failed ≠ empty (bug report 2026-07-24): a run with errored chunks
|
|
514
|
+
// must never take the completed/processed path — that would mask
|
|
515
|
+
// backend failures as "no findings" and (via the caller's watermark
|
|
516
|
+
// stamp) permanently mark the range as dreamed. Land as `failed`,
|
|
517
|
+
// stay in .dreams/ root (visible in dream_list), and because the
|
|
518
|
+
// caller only advances the watermark on completed/processed, the
|
|
519
|
+
// same range is retried on the next trigger.
|
|
520
|
+
if (result.completed && result.failedChunks > 0) {
|
|
521
|
+
meta.error =
|
|
522
|
+
`${result.failedChunks}/${result.totalChunks} extraction chunk(s) failed — ` +
|
|
523
|
+
'range NOT marked as dreamed; it will be retried on the next REM trigger. ' +
|
|
524
|
+
'Partial findings (if any) are preserved below for audit.';
|
|
525
|
+
await transitionDreamStatus(
|
|
526
|
+
args.agent,
|
|
527
|
+
// Body rendered from a status-patched copy so the human-readable
|
|
528
|
+
// status line matches the frontmatter; `meta` itself keeps the
|
|
529
|
+
// CURRENT status — transitionDreamStatus derives the old file
|
|
530
|
+
// path from it.
|
|
531
|
+
{ meta, body: renderBody({ ...meta, status: 'failed' }, args.sourceSession, sources) },
|
|
532
|
+
'failed',
|
|
533
|
+
{ error: meta.error, completed_at: new Date().toISOString() },
|
|
534
|
+
);
|
|
535
|
+
// Keep only this newest failure per session — retries would
|
|
536
|
+
// otherwise pile up one failed file per idle cycle.
|
|
537
|
+
await pruneFailedDreams(args.agent, args.sourceSession, { keepId: id });
|
|
538
|
+
logger.warn({
|
|
539
|
+
msg: 'dream.failed_chunks',
|
|
540
|
+
agent: args.agent,
|
|
541
|
+
id,
|
|
542
|
+
failedChunks: result.failedChunks,
|
|
543
|
+
totalChunks: result.totalChunks,
|
|
544
|
+
partialFindings: meta.findings.length,
|
|
545
|
+
});
|
|
546
|
+
return { id, finalStatus: 'failed' };
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
if (result.completed) {
|
|
550
|
+
meta.completed_at = new Date().toISOString();
|
|
551
|
+
// Zero-findings dreams have nothing to review — short-circuit straight
|
|
552
|
+
// to processed/ so they don't loiter forever in .dreams/ active state
|
|
553
|
+
// (dream_apply/dismiss can't fire on an empty findings array). Audit
|
|
554
|
+
// trail is preserved in processed/.
|
|
555
|
+
if (meta.findings.length === 0) {
|
|
556
|
+
meta.processed_at = meta.completed_at;
|
|
557
|
+
await transitionDreamStatus(
|
|
558
|
+
args.agent,
|
|
559
|
+
{ meta, body: renderBody(meta, args.sourceSession, sources) },
|
|
560
|
+
'processed',
|
|
561
|
+
{ completed_at: meta.completed_at, processed_at: meta.processed_at },
|
|
562
|
+
);
|
|
563
|
+
// A clean run supersedes earlier failed attempts on this session
|
|
564
|
+
// — but only as far as it actually read.
|
|
565
|
+
await pruneFailedDreams(args.agent, args.sourceSession, {
|
|
566
|
+
coveredThroughTs: meta.range_through_ts,
|
|
567
|
+
});
|
|
568
|
+
logger.info({
|
|
569
|
+
msg: 'dream.completed_empty',
|
|
570
|
+
agent: args.agent,
|
|
571
|
+
id,
|
|
572
|
+
note: 'no findings — auto-archived to processed/',
|
|
573
|
+
});
|
|
574
|
+
return { id, finalStatus: 'processed' };
|
|
575
|
+
}
|
|
576
|
+
await transitionDreamStatus(
|
|
577
|
+
args.agent,
|
|
578
|
+
{ meta, body: renderBody(meta, args.sourceSession, sources) },
|
|
579
|
+
'completed',
|
|
580
|
+
{ completed_at: meta.completed_at },
|
|
581
|
+
);
|
|
582
|
+
await pruneFailedDreams(args.agent, args.sourceSession, {
|
|
583
|
+
coveredThroughTs: meta.range_through_ts,
|
|
584
|
+
});
|
|
585
|
+
logger.info({
|
|
586
|
+
msg: 'dream.completed',
|
|
587
|
+
agent: args.agent,
|
|
588
|
+
id,
|
|
589
|
+
findings: meta.findings.length,
|
|
590
|
+
});
|
|
591
|
+
return { id, finalStatus: 'completed' };
|
|
592
|
+
}
|
|
593
|
+
// Cancelled mid-way — only auto-trigger should hit this path.
|
|
594
|
+
await transitionDreamStatus(
|
|
595
|
+
args.agent,
|
|
596
|
+
{ meta, body: renderBody(meta, args.sourceSession, sources) },
|
|
597
|
+
'paused',
|
|
598
|
+
);
|
|
599
|
+
logger.info({
|
|
600
|
+
msg: 'dream.paused',
|
|
601
|
+
agent: args.agent,
|
|
602
|
+
id,
|
|
603
|
+
chunksDone: meta.chunks_done,
|
|
604
|
+
chunksTotal: meta.chunks_total,
|
|
605
|
+
});
|
|
606
|
+
return { id, finalStatus: 'paused' };
|
|
607
|
+
} catch (err) {
|
|
608
|
+
meta.error = (err as Error).message;
|
|
609
|
+
await transitionDreamStatus(
|
|
610
|
+
args.agent,
|
|
611
|
+
{ meta, body: renderBody(meta, args.sourceSession, sources) },
|
|
612
|
+
'failed',
|
|
613
|
+
{ error: meta.error },
|
|
614
|
+
);
|
|
615
|
+
await pruneFailedDreams(args.agent, args.sourceSession, { keepId: id });
|
|
616
|
+
logger.error({
|
|
617
|
+
msg: 'dream.failed',
|
|
618
|
+
agent: args.agent,
|
|
619
|
+
id,
|
|
620
|
+
err: meta.error,
|
|
621
|
+
});
|
|
622
|
+
return { id, finalStatus: 'failed' };
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* Resume a previously-paused dream from where it left off. Reads the
|
|
628
|
+
* current state from disk, picks up at chunks_done + 1.
|
|
629
|
+
*/
|
|
630
|
+
export async function resumeDream(args: {
|
|
631
|
+
agent: string;
|
|
632
|
+
id: string;
|
|
633
|
+
rem: RemConfig;
|
|
634
|
+
config: Config;
|
|
635
|
+
mgr: MemoryManager;
|
|
636
|
+
signal?: AbortSignal;
|
|
637
|
+
}): Promise<{ finalStatus: DreamMeta['status']; rangeThroughTs: number }> {
|
|
638
|
+
const file = await readDreamById(args.agent, args.id);
|
|
639
|
+
if (!file) throw new Error(`dream '${args.id}' not found`);
|
|
640
|
+
if (file.meta.status !== 'paused') {
|
|
641
|
+
throw new Error(`dream '${args.id}' is ${file.meta.status}, not paused — can't resume`);
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// Delete the old paused file BEFORE kicking off the rerun. Without this,
|
|
645
|
+
// the stale paused file accumulated indefinitely: runDream generates a
|
|
646
|
+
// fresh timestamp-based id (dreamIdFor()), so a resume creates a new
|
|
647
|
+
// `<new-id>.dream.running.md` and the original `<old-id>.dream.paused.md`
|
|
648
|
+
// was never cleaned up. If the new run got aborted again (typical on
|
|
649
|
+
// active accounts), the result was N+1 paused files instead of N. Across
|
|
650
|
+
// a couple of days of idle cycles + user activity, paused dreams piled up
|
|
651
|
+
// (bug report 2026-05-05: 5 paused, 0 findings, all from the same
|
|
652
|
+
// source-session). Re-run-from-scratch was a deliberate v1 simplification
|
|
653
|
+
// (see comment below) — we just have to take responsibility for the old
|
|
654
|
+
// file's cleanup as part of resume's contract.
|
|
655
|
+
const oldPath = dreamFilePath(args.agent, args.id, 'paused');
|
|
656
|
+
try {
|
|
657
|
+
await unlink(oldPath);
|
|
658
|
+
logger.info({
|
|
659
|
+
msg: 'dream.resume.unlink_old',
|
|
660
|
+
agent: args.agent,
|
|
661
|
+
id: args.id,
|
|
662
|
+
sourceSession: file.meta.source_session,
|
|
663
|
+
});
|
|
664
|
+
} catch (err) {
|
|
665
|
+
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
|
|
666
|
+
logger.warn({
|
|
667
|
+
msg: 'dream.resume.unlink_old_failed',
|
|
668
|
+
agent: args.agent,
|
|
669
|
+
id: args.id,
|
|
670
|
+
err: (err as Error).message,
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
// For v1 we re-run from scratch on resume (don't preserve partial findings).
|
|
676
|
+
// Reason: partial findings without dedup across the full range can produce
|
|
677
|
+
// duplicates we'd then have to reconcile. Cheap for the chunk-cost; not a
|
|
678
|
+
// hot path in any case (auto-trigger gives small deltas).
|
|
679
|
+
return runDream({
|
|
680
|
+
agent: args.agent,
|
|
681
|
+
sourceSession: file.meta.source_session,
|
|
682
|
+
trigger: file.meta.trigger,
|
|
683
|
+
rangeFromTs: file.meta.range_from_ts,
|
|
684
|
+
rangeThroughTs: file.meta.range_through_ts,
|
|
685
|
+
rem: args.rem,
|
|
686
|
+
config: args.config,
|
|
687
|
+
mgr: args.mgr,
|
|
688
|
+
signal: args.signal,
|
|
689
|
+
}).then((r) => ({
|
|
690
|
+
finalStatus: r.finalStatus,
|
|
691
|
+
// The caller stamps the session's dreamed-marker with the range that
|
|
692
|
+
// was ACTUALLY analyzed — for a resume that's the original range end,
|
|
693
|
+
// not "now" (everything after it still needs its own dream).
|
|
694
|
+
rangeThroughTs: file.meta.range_through_ts,
|
|
695
|
+
}));
|
|
696
|
+
}
|