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,1002 @@
|
|
|
1
|
+
// Dream-Mode tool surface (Phase 2-Stufe-D, DECISIONS pending). Lets the
|
|
2
|
+
// agent walk pending dreams with the user step-by-step, applying or
|
|
3
|
+
// dismissing each finding. dream_apply translates a finding into the
|
|
4
|
+
// equivalent memory_* action — no creative logic at apply-time, just
|
|
5
|
+
// confirmation of the extractor's proposal.
|
|
6
|
+
//
|
|
7
|
+
// dream_list — overview of pending (non-processed) dreams
|
|
8
|
+
// dream_get(dream_id) — full content + per-finding state
|
|
9
|
+
// dream_apply(dream_id, finding_id) — execute a finding's action; auto-archive
|
|
10
|
+
// when all findings resolved
|
|
11
|
+
// dream_dismiss(dream_id, finding_id?) — reject a single finding; without finding_id:
|
|
12
|
+
// whole dream dismissed
|
|
13
|
+
|
|
14
|
+
import { z } from 'zod';
|
|
15
|
+
import {
|
|
16
|
+
dismissEntireDream,
|
|
17
|
+
listDreams,
|
|
18
|
+
readDreamById,
|
|
19
|
+
updateFindingStatus,
|
|
20
|
+
} from '../../dream/storage.ts';
|
|
21
|
+
import type { Finding } from '../../dream/types.ts';
|
|
22
|
+
import { loopbackFetch } from '../../server/loopback-fetch.ts';
|
|
23
|
+
import type { ToolDefinition } from '../types.ts';
|
|
24
|
+
import type { DeepWorker } from '../../dream/deep-worker.ts';
|
|
25
|
+
import type { LucidWorker } from '../../dream/lucid-worker.ts';
|
|
26
|
+
import {
|
|
27
|
+
dismissEntireLucidRun,
|
|
28
|
+
listLucidRuns,
|
|
29
|
+
readLucidRunById,
|
|
30
|
+
setRunStatus,
|
|
31
|
+
updateLucidFindingStatus,
|
|
32
|
+
writeLucidRun,
|
|
33
|
+
} from '../../dream/lucid-storage.ts';
|
|
34
|
+
import { resolveAnyRef } from '../../config/types.ts';
|
|
35
|
+
import type { LucidFinding, LucidRun } from '../../dream/lucid-types.ts';
|
|
36
|
+
import { applyLucidFinding } from '../../dream/lucid-actions.ts';
|
|
37
|
+
import {
|
|
38
|
+
clearLoopState,
|
|
39
|
+
getLoopState,
|
|
40
|
+
getMaxWikiCallsPerTurn,
|
|
41
|
+
setLoopState,
|
|
42
|
+
} from '../../dream/loop-state.ts';
|
|
43
|
+
import { resolveObsidianSource } from '../../memory/registry.ts';
|
|
44
|
+
import { rename } from 'node:fs/promises';
|
|
45
|
+
import { isValidSlug, normalizeSlug } from '../../memory/slug.ts';
|
|
46
|
+
import { join } from 'node:path';
|
|
47
|
+
|
|
48
|
+
// ── Shared helpers ────────────────────────────────────────────────────
|
|
49
|
+
|
|
50
|
+
const DreamIdSchema = z.string().min(1).regex(/^[A-Za-z0-9_-]+$/, 'invalid dream id');
|
|
51
|
+
|
|
52
|
+
function findingSummary(f: Finding): string {
|
|
53
|
+
const parts: string[] = [`#${f.id} ${f.action} → ${f.slug}`];
|
|
54
|
+
if (f.status !== 'pending') parts.push(`(${f.status})`);
|
|
55
|
+
return parts.join(' ');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// ── dream_list ────────────────────────────────────────────────────────
|
|
59
|
+
|
|
60
|
+
const ListInput = z.object({
|
|
61
|
+
include_processed: z.boolean().optional(),
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
export const dreamList: ToolDefinition<z.infer<typeof ListInput>> = {
|
|
65
|
+
name: 'dream_list',
|
|
66
|
+
toolset: 'dream',
|
|
67
|
+
description:
|
|
68
|
+
'List pending dreams awaiting user review. Returns both per-agent memory dreams (REM phase: ' +
|
|
69
|
+
'atomic findings from your sessions, scoped to YOUR agent) and global wiki-cleanup runs ' +
|
|
70
|
+
'(Lucid phase: contradictions, dead links, wanted pages, link suggestions, duplicate pages — and, in a wiki on the folder template, misfiled and oversized pages — in the shared ' +
|
|
71
|
+
"wiki, same for every agent). Each entry has a `kind` field = 'memory' or 'wiki_lucid' so the " +
|
|
72
|
+
'agent can describe them differently to the user. Pass include_processed=true to also see ' +
|
|
73
|
+
'already-resolved entries. Use this first when the user asks "did you dream anything?" or ' +
|
|
74
|
+
'"anything to clean up?" — pick the oldest and walk through it with `dream_get`. ' +
|
|
75
|
+
"Entries with status='failed' are extraction runs that hit backend errors — the same session " +
|
|
76
|
+
'range retries automatically on the next trigger, so prefer waiting for the retried dream; ' +
|
|
77
|
+
'mention the failure (see `error` field) to the user instead of walking a failed dream.',
|
|
78
|
+
inputSchema: ListInput,
|
|
79
|
+
jsonSchema: {
|
|
80
|
+
type: 'object',
|
|
81
|
+
properties: {
|
|
82
|
+
include_processed: {
|
|
83
|
+
type: 'boolean',
|
|
84
|
+
description: 'Include dreams whose findings have all been resolved (default false).',
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
additionalProperties: false,
|
|
88
|
+
},
|
|
89
|
+
async handler(input, ctx) {
|
|
90
|
+
const includeProcessed = input.include_processed === true;
|
|
91
|
+
const memoryDreams = await listDreams(ctx.agent, { includeProcessed });
|
|
92
|
+
const lucidRuns = await listLucidRuns();
|
|
93
|
+
const memEntries = memoryDreams.map((d) => ({
|
|
94
|
+
id: d.meta.id,
|
|
95
|
+
kind: 'memory' as const,
|
|
96
|
+
trigger: d.meta.trigger,
|
|
97
|
+
source_session: d.meta.source_session,
|
|
98
|
+
status: d.meta.status,
|
|
99
|
+
created_at: d.meta.created_at,
|
|
100
|
+
completed_at: d.meta.completed_at,
|
|
101
|
+
findings_total: d.meta.findings.length,
|
|
102
|
+
findings_pending: d.meta.findings.filter((f) => f.status === 'pending').length,
|
|
103
|
+
findings_applied: d.meta.findings.filter((f) => f.status === 'applied').length,
|
|
104
|
+
findings_dismissed: d.meta.findings.filter((f) => f.status === 'dismissed').length,
|
|
105
|
+
findings_resolved_manually: d.meta.findings.filter((f) => f.status === 'resolved_manually')
|
|
106
|
+
.length,
|
|
107
|
+
// Failed extractions stay visible here (failed ≠ empty, report
|
|
108
|
+
// 2026-07-24) — surface why so the agent can tell the user.
|
|
109
|
+
...(d.meta.error ? { error: d.meta.error } : {}),
|
|
110
|
+
...(typeof d.meta.chunks_failed === 'number' && d.meta.chunks_failed > 0
|
|
111
|
+
? { chunks_failed: d.meta.chunks_failed }
|
|
112
|
+
: {}),
|
|
113
|
+
}));
|
|
114
|
+
const lucidEntries = lucidRuns
|
|
115
|
+
.filter((r) => includeProcessed || r.status !== 'processed')
|
|
116
|
+
.map((r) => ({
|
|
117
|
+
id: r.id,
|
|
118
|
+
kind: 'wiki_lucid' as const,
|
|
119
|
+
trigger: r.trigger,
|
|
120
|
+
status: r.status,
|
|
121
|
+
created_at: r.created_at,
|
|
122
|
+
completed_at: r.completed_at,
|
|
123
|
+
pages_scanned: r.pages_scanned,
|
|
124
|
+
findings_total: r.findings.length,
|
|
125
|
+
findings_pending: r.findings.filter((f) => f.status === 'pending').length,
|
|
126
|
+
findings_applied: r.findings.filter((f) => f.status === 'applied').length,
|
|
127
|
+
findings_dismissed: r.findings.filter((f) => f.status === 'dismissed').length,
|
|
128
|
+
findings_resolved_manually: r.findings.filter((f) => f.status === 'resolved_manually')
|
|
129
|
+
.length,
|
|
130
|
+
}));
|
|
131
|
+
return {
|
|
132
|
+
count: memEntries.length + lucidEntries.length,
|
|
133
|
+
by_kind: { memory: memEntries.length, wiki_lucid: lucidEntries.length },
|
|
134
|
+
dreams: [...memEntries, ...lucidEntries],
|
|
135
|
+
};
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
// ── dream_get ─────────────────────────────────────────────────────────
|
|
140
|
+
|
|
141
|
+
const GetInput = z.object({
|
|
142
|
+
dream_id: DreamIdSchema,
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
export const dreamGet: ToolDefinition<z.infer<typeof GetInput>> = {
|
|
146
|
+
name: 'dream_get',
|
|
147
|
+
toolset: 'dream',
|
|
148
|
+
description:
|
|
149
|
+
'Fetch the full content of a dream — all findings with their proposed actions, reasons, and ' +
|
|
150
|
+
'per-finding status. Works for both memory dreams (kind=memory, per-agent) and wiki-cleanup ' +
|
|
151
|
+
"runs (kind=wiki_lucid, global). The output's `kind` field tells the agent which type so it " +
|
|
152
|
+
'can describe findings appropriately. Use after `dream_list`.',
|
|
153
|
+
inputSchema: GetInput,
|
|
154
|
+
jsonSchema: {
|
|
155
|
+
type: 'object',
|
|
156
|
+
properties: {
|
|
157
|
+
dream_id: { type: 'string', description: 'The id of the dream/lucid run to retrieve.' },
|
|
158
|
+
},
|
|
159
|
+
required: ['dream_id'],
|
|
160
|
+
additionalProperties: false,
|
|
161
|
+
},
|
|
162
|
+
async handler(input, ctx) {
|
|
163
|
+
// Try memory-dream first; fall back to lucid run.
|
|
164
|
+
const memFile = await readDreamById(ctx.agent, input.dream_id);
|
|
165
|
+
if (memFile) {
|
|
166
|
+
return {
|
|
167
|
+
id: memFile.meta.id,
|
|
168
|
+
kind: 'memory' as const,
|
|
169
|
+
trigger: memFile.meta.trigger,
|
|
170
|
+
source_session: memFile.meta.source_session,
|
|
171
|
+
status: memFile.meta.status,
|
|
172
|
+
created_at: memFile.meta.created_at,
|
|
173
|
+
completed_at: memFile.meta.completed_at,
|
|
174
|
+
processed_at: memFile.meta.processed_at,
|
|
175
|
+
worker_model_ref: memFile.meta.worker_model_ref,
|
|
176
|
+
...(memFile.meta.worker_fallback_ref ? { worker_fallback_ref: memFile.meta.worker_fallback_ref } : {}),
|
|
177
|
+
...(memFile.meta.worker_switch ? { worker_switch: memFile.meta.worker_switch } : {}),
|
|
178
|
+
...(memFile.meta.error ? { error: memFile.meta.error } : {}),
|
|
179
|
+
...(typeof memFile.meta.chunks_failed === 'number' && memFile.meta.chunks_failed > 0
|
|
180
|
+
? { chunks_failed: memFile.meta.chunks_failed }
|
|
181
|
+
: {}),
|
|
182
|
+
findings: memFile.meta.findings,
|
|
183
|
+
pending_count: memFile.meta.findings.filter((f) => f.status === 'pending').length,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
const lucidRun = await readLucidRunById(input.dream_id);
|
|
187
|
+
if (lucidRun) {
|
|
188
|
+
return {
|
|
189
|
+
id: lucidRun.id,
|
|
190
|
+
kind: 'wiki_lucid' as const,
|
|
191
|
+
trigger: lucidRun.trigger,
|
|
192
|
+
status: lucidRun.status,
|
|
193
|
+
created_at: lucidRun.created_at,
|
|
194
|
+
completed_at: lucidRun.completed_at,
|
|
195
|
+
processed_at: lucidRun.processed_at,
|
|
196
|
+
pages_scanned: lucidRun.pages_scanned,
|
|
197
|
+
worker_model_ref: lucidRun.worker_model_ref,
|
|
198
|
+
...(lucidRun.error ? { error: lucidRun.error } : {}),
|
|
199
|
+
findings: lucidRun.findings,
|
|
200
|
+
pending_count: lucidRun.findings.filter((f) => f.status === 'pending').length,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
throw new Error(`dream '${input.dream_id}' not found (checked memory + wiki_lucid)`);
|
|
204
|
+
},
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
// ── dream_apply ───────────────────────────────────────────────────────
|
|
208
|
+
|
|
209
|
+
const ApplyInput = z.object({
|
|
210
|
+
dream_id: DreamIdSchema,
|
|
211
|
+
finding_id: z.number().int().positive(),
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
export const dreamApply: ToolDefinition<z.infer<typeof ApplyInput>> = {
|
|
215
|
+
name: 'dream_apply',
|
|
216
|
+
toolset: 'dream',
|
|
217
|
+
description:
|
|
218
|
+
'Accept a single finding from a dream — executes its proposed memory action and marks the finding ' +
|
|
219
|
+
'as applied. After the last finding of a dream is resolved, the dream auto-archives to processed/. ' +
|
|
220
|
+
'Returns whether the dream is now fully done so the agent knows when to stop walking. ' +
|
|
221
|
+
'IMPORTANT: pass `dream_id` and `finding_id` EXACTLY as returned by `dream_list` / `dream_get` ' +
|
|
222
|
+
'— do not invent or guess values. Finding ids start at 1.',
|
|
223
|
+
inputSchema: ApplyInput,
|
|
224
|
+
jsonSchema: {
|
|
225
|
+
type: 'object',
|
|
226
|
+
properties: {
|
|
227
|
+
dream_id: { type: 'string', description: 'Dream containing the finding.' },
|
|
228
|
+
finding_id: {
|
|
229
|
+
type: 'integer',
|
|
230
|
+
minimum: 1,
|
|
231
|
+
description: 'Numeric finding id (`id` field within the dream\'s findings array).',
|
|
232
|
+
},
|
|
233
|
+
},
|
|
234
|
+
required: ['dream_id', 'finding_id'],
|
|
235
|
+
additionalProperties: false,
|
|
236
|
+
},
|
|
237
|
+
async handler(input, ctx) {
|
|
238
|
+
// Try memory dream first.
|
|
239
|
+
const memFile = await readDreamById(ctx.agent, input.dream_id);
|
|
240
|
+
if (memFile) {
|
|
241
|
+
return await applyMemoryFinding(memFile, input.dream_id, input.finding_id, ctx);
|
|
242
|
+
}
|
|
243
|
+
// Fall through to lucid run.
|
|
244
|
+
const lucidRun = await readLucidRunById(input.dream_id);
|
|
245
|
+
if (lucidRun) {
|
|
246
|
+
return await applyLucidFindingFromRun(lucidRun, input.dream_id, input.finding_id, ctx);
|
|
247
|
+
}
|
|
248
|
+
// Neither store has it — return a structured, machine-readable error
|
|
249
|
+
// so the model self-corrects deterministically (2026-07-23 report:
|
|
250
|
+
// an agent guessed a dummy id and then improvised from the prose
|
|
251
|
+
// error). Returned (not thrown) on purpose: the shape is the API.
|
|
252
|
+
return await dreamNotFoundResponse(ctx.agent, input.dream_id);
|
|
253
|
+
},
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
/** Shared structured not-found payload for dream_apply / dream_dismiss. */
|
|
257
|
+
async function dreamNotFoundResponse(agent: string, requestedId: string): Promise<unknown> {
|
|
258
|
+
const memDreams = await listDreams(agent);
|
|
259
|
+
const lucidRuns = await listLucidRuns();
|
|
260
|
+
const validIds = [
|
|
261
|
+
...memDreams.map((d) => ({ id: d.meta.id, kind: 'memory' as const })),
|
|
262
|
+
...lucidRuns.map((r) => ({ id: r.id, kind: 'wiki_lucid' as const })),
|
|
263
|
+
];
|
|
264
|
+
return {
|
|
265
|
+
error: 'dream_not_found',
|
|
266
|
+
requested_id: requestedId,
|
|
267
|
+
valid_ids: validIds,
|
|
268
|
+
recommended_next_tool: validIds.length > 0 ? 'dream_get' : 'dream_list',
|
|
269
|
+
message:
|
|
270
|
+
validIds.length > 0
|
|
271
|
+
? 'No dream with that id. Use one of valid_ids EXACTLY as listed — fetch it with dream_get and confirm with the user before applying/dismissing.'
|
|
272
|
+
: 'No dream with that id and no pending dreams exist. Call dream_list to verify — do not invent ids.',
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* When the thing a REM finding records was SAID — the end of the
|
|
278
|
+
* conversation range the dream read, not the moment the finding is
|
|
279
|
+
* applied. A note's `created` is the apply time; for a conversation
|
|
280
|
+
* that was dreamed late (an archive from May read in September) that is
|
|
281
|
+
* months off, and Deep would take a May statement for September news.
|
|
282
|
+
*/
|
|
283
|
+
function statedAtOf(meta: { range_through_ts?: number; source_session?: string }): Record<string, unknown> {
|
|
284
|
+
if (typeof meta.range_through_ts !== 'number' || meta.range_through_ts <= 0) return {};
|
|
285
|
+
return {
|
|
286
|
+
stated_at: new Date(meta.range_through_ts).toISOString(),
|
|
287
|
+
...(meta.source_session ? { stated_in: meta.source_session } : {}),
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async function applyMemoryFinding(
|
|
292
|
+
memFile: NonNullable<Awaited<ReturnType<typeof readDreamById>>>,
|
|
293
|
+
dreamId: string,
|
|
294
|
+
findingId: number,
|
|
295
|
+
ctx: import('../types.ts').ToolContext,
|
|
296
|
+
): Promise<unknown> {
|
|
297
|
+
const finding = memFile.meta.findings.find((f) => f.id === findingId);
|
|
298
|
+
if (!finding) {
|
|
299
|
+
const validIds = memFile.meta.findings.map((f) => f.id);
|
|
300
|
+
throw new Error(
|
|
301
|
+
`finding ${findingId} not in dream '${dreamId}'. Valid finding ids: ${
|
|
302
|
+
validIds.length ? validIds.join(', ') : '(none)'
|
|
303
|
+
}. Note: finding ids start at 1, not 0.`,
|
|
304
|
+
);
|
|
305
|
+
}
|
|
306
|
+
if (finding.status !== 'pending') {
|
|
307
|
+
throw new Error(
|
|
308
|
+
`finding ${findingId} is already ${finding.status} (resolved at ${finding.resolved_at ?? 'unknown'})`,
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
const mgr = await ctx.getMemoryManager();
|
|
312
|
+
let executed: { description: string };
|
|
313
|
+
// Findings extracted before slugs were normalised at the source can
|
|
314
|
+
// still carry umlauts / capitals; fix them here rather than failing
|
|
315
|
+
// the apply (2026-09-03 report). The note lands under the normalised
|
|
316
|
+
// slug and the response says so.
|
|
317
|
+
const slug = isValidSlug(finding.slug) ? finding.slug : normalizeSlug(finding.slug);
|
|
318
|
+
const slugNote = slug !== finding.slug ? ` (slug normalised from '${finding.slug}')` : '';
|
|
319
|
+
if (!slug) {
|
|
320
|
+
throw new Error(`finding ${findingId}: slug '${finding.slug}' cannot be normalised to a valid slug`);
|
|
321
|
+
}
|
|
322
|
+
switch (finding.action) {
|
|
323
|
+
case 'memory_write': {
|
|
324
|
+
if (!finding.proposed_content) {
|
|
325
|
+
throw new Error(`finding ${findingId}: memory_write needs proposed_content`);
|
|
326
|
+
}
|
|
327
|
+
const fm = {
|
|
328
|
+
...(finding.frontmatter_tags && finding.frontmatter_tags.length > 0 ? { tags: finding.frontmatter_tags } : {}),
|
|
329
|
+
...statedAtOf(memFile.meta),
|
|
330
|
+
};
|
|
331
|
+
await mgr.writeNote(slug, finding.proposed_content, fm);
|
|
332
|
+
executed = { description: `wrote memory/${slug}.md${slugNote}` };
|
|
333
|
+
break;
|
|
334
|
+
}
|
|
335
|
+
case 'memory_edit': {
|
|
336
|
+
if (!finding.proposed_content) {
|
|
337
|
+
throw new Error(`finding ${findingId}: memory_edit needs proposed_content`);
|
|
338
|
+
}
|
|
339
|
+
// Between extraction and review Deep may have promoted the target
|
|
340
|
+
// note into the wiki and deleted the memory file. The finding's
|
|
341
|
+
// content is still valid knowledge — write it as a fresh note
|
|
342
|
+
// (Deep picks it up next run) instead of failing with "does not
|
|
343
|
+
// exist" and forcing a manual memory_write + resolved_manually
|
|
344
|
+
// (2026-09-03 report, 2× in one review). Same downgrade the REM
|
|
345
|
+
// dedup stage applies at extraction time.
|
|
346
|
+
const existing = await mgr.getNote(slug).catch(() => null);
|
|
347
|
+
if (existing) {
|
|
348
|
+
await mgr.writeNote(slug, finding.proposed_content, statedAtOf(memFile.meta), { mustExist: true });
|
|
349
|
+
executed = { description: `edited memory/${slug}.md${slugNote}` };
|
|
350
|
+
} else {
|
|
351
|
+
await mgr.writeNote(slug, finding.proposed_content, statedAtOf(memFile.meta));
|
|
352
|
+
executed = {
|
|
353
|
+
description:
|
|
354
|
+
`memory/${slug}.md no longer existed (promoted to the wiki or deleted since extraction) — ` +
|
|
355
|
+
`wrote the proposed content as a fresh note instead${slugNote}`,
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
break;
|
|
359
|
+
}
|
|
360
|
+
case 'memory_delete': {
|
|
361
|
+
const ok = await mgr.deleteNote(slug);
|
|
362
|
+
executed = { description: ok ? `deleted memory/${slug}.md` : `memory/${slug}.md was already gone` };
|
|
363
|
+
break;
|
|
364
|
+
}
|
|
365
|
+
case 'vault_hint': {
|
|
366
|
+
executed = {
|
|
367
|
+
description: `vault hint acknowledged (no auto-write to vault from agents — Deep/Lucid handle vault)`,
|
|
368
|
+
};
|
|
369
|
+
break;
|
|
370
|
+
}
|
|
371
|
+
default: {
|
|
372
|
+
throw new Error(`finding ${findingId}: unknown action '${(finding as { action: string }).action}'`);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
const result = await updateFindingStatus(ctx.agent, dreamId, findingId, 'applied');
|
|
376
|
+
const remaining = result.dream.meta.findings.filter((f) => f.status === 'pending').length;
|
|
377
|
+
return {
|
|
378
|
+
kind: 'memory',
|
|
379
|
+
applied: true,
|
|
380
|
+
finding: findingSummary(finding),
|
|
381
|
+
executed: executed.description,
|
|
382
|
+
remaining,
|
|
383
|
+
dream_done: result.allResolved,
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
async function applyLucidFindingFromRun(
|
|
388
|
+
lucidRun: LucidRun,
|
|
389
|
+
runId: string,
|
|
390
|
+
findingId: number,
|
|
391
|
+
ctx: import('../types.ts').ToolContext,
|
|
392
|
+
): Promise<unknown> {
|
|
393
|
+
const finding: LucidFinding | undefined = lucidRun.findings.find((f) => f.id === findingId);
|
|
394
|
+
if (!finding) {
|
|
395
|
+
const validIds = lucidRun.findings.map((f) => f.id);
|
|
396
|
+
throw new Error(
|
|
397
|
+
`finding ${findingId} not in lucid run '${runId}'. Valid finding ids: ${
|
|
398
|
+
validIds.length ? validIds.join(', ') : '(none)'
|
|
399
|
+
}. Note: finding ids start at 1, not 0.`,
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
if (finding.status !== 'pending') {
|
|
403
|
+
throw new Error(
|
|
404
|
+
`finding ${findingId} is already ${finding.status} (resolved at ${finding.resolved_at ?? 'unknown'})`,
|
|
405
|
+
);
|
|
406
|
+
}
|
|
407
|
+
const obs = resolveObsidianSource(ctx.config.obsidian);
|
|
408
|
+
if (!obs?.vaultPath) {
|
|
409
|
+
throw new Error('lucid apply: no obsidian vault configured');
|
|
410
|
+
}
|
|
411
|
+
const wikiAbs = join(obs.vaultPath, ctx.config.wiki.vaultSubfolder);
|
|
412
|
+
const lucidRef = ctx.config.wiki.lucid.model ?? ctx.config.wiki.deep.model;
|
|
413
|
+
const model = lucidRef ? resolveAnyRef(ctx.config, lucidRef) : null;
|
|
414
|
+
const outcome = await applyLucidFinding(finding, {
|
|
415
|
+
wikiAbs,
|
|
416
|
+
language: ctx.config.wiki.language ?? 'de',
|
|
417
|
+
...(model ? { model } : {}),
|
|
418
|
+
...(ctx.config.wiki.lucid.thinking ? { thinking: ctx.config.wiki.lucid.thinking } : {}),
|
|
419
|
+
});
|
|
420
|
+
if (outcome.kind === 'failed') {
|
|
421
|
+
throw new Error(`lucid apply failed: ${outcome.error}`);
|
|
422
|
+
}
|
|
423
|
+
// Both 'applied' and 'skipped' close the slot — agent reviews the
|
|
424
|
+
// outcome string, user dismisses explicitly if they want to retry.
|
|
425
|
+
const result = await updateLucidFindingStatus(runId, findingId, 'applied');
|
|
426
|
+
const remaining = result?.run.findings.filter((f) => f.status === 'pending').length ?? 0;
|
|
427
|
+
return {
|
|
428
|
+
kind: 'wiki_lucid',
|
|
429
|
+
applied: outcome.kind === 'applied',
|
|
430
|
+
finding: `#${finding.id} ${finding.kind}`,
|
|
431
|
+
executed:
|
|
432
|
+
outcome.kind === 'applied' ? outcome.detail : `skipped: ${outcome.reason}`,
|
|
433
|
+
remaining,
|
|
434
|
+
dream_done: remaining === 0,
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// ── dream_dismiss ─────────────────────────────────────────────────────
|
|
439
|
+
|
|
440
|
+
const DismissInput = z.object({
|
|
441
|
+
dream_id: DreamIdSchema,
|
|
442
|
+
finding_id: z.number().int().positive().optional(),
|
|
443
|
+
reason: z.string().optional(),
|
|
444
|
+
resolved_manually: z.boolean().optional(),
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
export const dreamDismiss: ToolDefinition<z.infer<typeof DismissInput>> = {
|
|
448
|
+
name: 'dream_dismiss',
|
|
449
|
+
toolset: 'dream',
|
|
450
|
+
description:
|
|
451
|
+
'Close a finding without executing its memory action. Pass finding_id to close one; ' +
|
|
452
|
+
'omit it to close the whole dream (all still-pending findings, dream auto-archives). ' +
|
|
453
|
+
'Use the no-finding-id form for "this whole dream was off-base". ' +
|
|
454
|
+
'Two terminal states: default marks the finding(s) `dismissed` (content rejected / wrong). ' +
|
|
455
|
+
'If the content was CORRECT but already handled outside the dream flow (user edited the wiki ' +
|
|
456
|
+
'themselves, it was documented in chat, fixed as part of other work), pass ' +
|
|
457
|
+
'`resolved_manually: true` — the finding is then marked `resolved_manually` instead, so the ' +
|
|
458
|
+
'history reads "done elsewhere", not "rejected". ' +
|
|
459
|
+
'Pass `reason` for anything other than plain content-rejection — it lands in the audit trail. ' +
|
|
460
|
+
'IMPORTANT: pass `dream_id` and (if used) `finding_id` EXACTLY as returned by `dream_list` / ' +
|
|
461
|
+
'`dream_get`. Finding ids start at 1.',
|
|
462
|
+
inputSchema: DismissInput,
|
|
463
|
+
jsonSchema: {
|
|
464
|
+
type: 'object',
|
|
465
|
+
properties: {
|
|
466
|
+
dream_id: { type: 'string', description: 'Dream id.' },
|
|
467
|
+
finding_id: {
|
|
468
|
+
type: 'integer',
|
|
469
|
+
minimum: 1,
|
|
470
|
+
description: 'Optional. Without it, the entire dream is dismissed.',
|
|
471
|
+
},
|
|
472
|
+
reason: {
|
|
473
|
+
type: 'string',
|
|
474
|
+
description:
|
|
475
|
+
'Optional free-text reason recorded on the closed finding(s), e.g. ' +
|
|
476
|
+
'"user updated the wiki page directly". Strongly recommended together ' +
|
|
477
|
+
'with resolved_manually.',
|
|
478
|
+
},
|
|
479
|
+
resolved_manually: {
|
|
480
|
+
type: 'boolean',
|
|
481
|
+
description:
|
|
482
|
+
'Optional. true = the finding content was correct but was handled outside ' +
|
|
483
|
+
'the dream flow — mark it `resolved_manually` instead of `dismissed`.',
|
|
484
|
+
},
|
|
485
|
+
},
|
|
486
|
+
required: ['dream_id'],
|
|
487
|
+
additionalProperties: false,
|
|
488
|
+
},
|
|
489
|
+
async handler(input, ctx) {
|
|
490
|
+
// Both terminal shapes share the whole flow; only the recorded
|
|
491
|
+
// status differs. `status` in the result echoes what was written
|
|
492
|
+
// so the model can phrase its confirmation correctly.
|
|
493
|
+
const finalStatus = input.resolved_manually ? ('resolved_manually' as const) : ('dismissed' as const);
|
|
494
|
+
// Try memory dream first.
|
|
495
|
+
const memFile = await readDreamById(ctx.agent, input.dream_id);
|
|
496
|
+
if (memFile) {
|
|
497
|
+
if (input.finding_id !== undefined) {
|
|
498
|
+
if (!memFile.meta.findings.some((f) => f.id === input.finding_id)) {
|
|
499
|
+
const validIds = memFile.meta.findings.map((f) => f.id);
|
|
500
|
+
throw new Error(
|
|
501
|
+
`finding ${input.finding_id} not in dream '${input.dream_id}'. Valid finding ids: ${
|
|
502
|
+
validIds.length ? validIds.join(', ') : '(none)'
|
|
503
|
+
}. Note: finding ids start at 1, not 0.`,
|
|
504
|
+
);
|
|
505
|
+
}
|
|
506
|
+
const result = await updateFindingStatus(
|
|
507
|
+
ctx.agent,
|
|
508
|
+
input.dream_id,
|
|
509
|
+
input.finding_id,
|
|
510
|
+
finalStatus,
|
|
511
|
+
input.reason,
|
|
512
|
+
);
|
|
513
|
+
const remaining = result.dream.meta.findings.filter((f) => f.status === 'pending').length;
|
|
514
|
+
return {
|
|
515
|
+
kind: 'memory',
|
|
516
|
+
status: finalStatus,
|
|
517
|
+
finding_id: input.finding_id,
|
|
518
|
+
...(input.reason ? { reason_recorded: true } : {}),
|
|
519
|
+
remaining,
|
|
520
|
+
dream_done: result.allResolved,
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
const result = await dismissEntireDream(ctx.agent, input.dream_id, input.reason, finalStatus);
|
|
524
|
+
return {
|
|
525
|
+
kind: 'memory',
|
|
526
|
+
status: finalStatus,
|
|
527
|
+
whole_dream: true,
|
|
528
|
+
closed_count: result.dismissedCount,
|
|
529
|
+
dream_done: true,
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
// Fall through to lucid run.
|
|
533
|
+
const lucidRun = await readLucidRunById(input.dream_id);
|
|
534
|
+
if (lucidRun) {
|
|
535
|
+
if (input.finding_id !== undefined) {
|
|
536
|
+
if (!lucidRun.findings.some((f) => f.id === input.finding_id)) {
|
|
537
|
+
const validIds = lucidRun.findings.map((f) => f.id);
|
|
538
|
+
throw new Error(
|
|
539
|
+
`finding ${input.finding_id} not in lucid run '${input.dream_id}'. Valid finding ids: ${
|
|
540
|
+
validIds.length ? validIds.join(', ') : '(none)'
|
|
541
|
+
}. Note: finding ids start at 1, not 0.`,
|
|
542
|
+
);
|
|
543
|
+
}
|
|
544
|
+
const result = await updateLucidFindingStatus(
|
|
545
|
+
input.dream_id,
|
|
546
|
+
input.finding_id,
|
|
547
|
+
finalStatus,
|
|
548
|
+
input.reason,
|
|
549
|
+
);
|
|
550
|
+
const remaining = result?.run.findings.filter((f) => f.status === 'pending').length ?? 0;
|
|
551
|
+
return {
|
|
552
|
+
kind: 'wiki_lucid',
|
|
553
|
+
status: finalStatus,
|
|
554
|
+
finding_id: input.finding_id,
|
|
555
|
+
...(input.reason ? { reason_recorded: true } : {}),
|
|
556
|
+
remaining,
|
|
557
|
+
dream_done: remaining === 0,
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
const result = await dismissEntireLucidRun(input.dream_id, input.reason, finalStatus);
|
|
561
|
+
const closedCount = result?.findings.filter((f) => f.status === finalStatus).length ?? 0;
|
|
562
|
+
return {
|
|
563
|
+
kind: 'wiki_lucid',
|
|
564
|
+
status: finalStatus,
|
|
565
|
+
whole_dream: true,
|
|
566
|
+
closed_count: closedCount,
|
|
567
|
+
dream_done: true,
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
// Neither — structured not-found, same shape as dream_apply.
|
|
571
|
+
return await dreamNotFoundResponse(ctx.agent, input.dream_id);
|
|
572
|
+
},
|
|
573
|
+
};
|
|
574
|
+
|
|
575
|
+
// ── dream_run ─────────────────────────────────────────────────────────
|
|
576
|
+
//
|
|
577
|
+
// Manual trigger for Deep (memory→wiki consolidation) and Lucid
|
|
578
|
+
// (wiki cleanup). Single tool with `phase` arg covers both — keeps
|
|
579
|
+
// the dream_*-Toolset tight. See `private/dream-system-v2.md` for
|
|
580
|
+
// the full Phase model (REM/Deep/Lucid).
|
|
581
|
+
|
|
582
|
+
interface DreamRunDeps {
|
|
583
|
+
deepWorker: DeepWorker;
|
|
584
|
+
lucidWorker: LucidWorker;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
let injectedDreamRunDeps: DreamRunDeps | null = null;
|
|
588
|
+
|
|
589
|
+
/** Server boot wires the DeepWorker reference here so the in-process
|
|
590
|
+
* tool handler can call runNow() directly. The MCP child doesn't
|
|
591
|
+
* get this — it falls back to the HTTP endpoint. */
|
|
592
|
+
export function configureDreamRunTool(deps: DreamRunDeps): void {
|
|
593
|
+
injectedDreamRunDeps = deps;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
const RunInput = z.object({
|
|
597
|
+
phase: z.enum(['deep', 'lucid', 'rem']).optional(),
|
|
598
|
+
wait: z.boolean().optional(),
|
|
599
|
+
force: z.boolean().optional(),
|
|
600
|
+
});
|
|
601
|
+
|
|
602
|
+
export const dreamRun: ToolDefinition<z.infer<typeof RunInput>> = {
|
|
603
|
+
name: 'dream_run',
|
|
604
|
+
toolset: 'dream',
|
|
605
|
+
description:
|
|
606
|
+
'Manually trigger a platform-wide dream phase.\n' +
|
|
607
|
+
'\n' +
|
|
608
|
+
"phase='deep' (default): Memory → Wiki consolidation. Reads each agent's " +
|
|
609
|
+
'short-term memory, decides via Opus which entries are wiki-worthy, writes them ' +
|
|
610
|
+
'as consolidated wiki pages with cross-references, deletes the source memory ' +
|
|
611
|
+
'files after successful consolidation. Memory entries already covered in the ' +
|
|
612
|
+
'wiki get merged into the existing page; transient/scratchpad entries get skipped.\n' +
|
|
613
|
+
"phase='lucid': Wiki cleanup — a periodic check for contradictions between pages, " +
|
|
614
|
+
'dead links, pages that are linked but missing, and links worth adding. It does NOT ' +
|
|
615
|
+
'judge whether a claim is out of date. Works through the wiki one subfolder at a time ' +
|
|
616
|
+
'plus one pass across folders that sees only the opening lines of each page. ' +
|
|
617
|
+
'Findings need user approval before any wiki edits apply.\n' +
|
|
618
|
+
"phase='rem': Session → Memory for YOUR agent — reads your conversations that REM has " +
|
|
619
|
+
'not covered yet (after a worker outage, or a long stretch without idle time) right ' +
|
|
620
|
+
'now instead of waiting for the idle timer. Runs in the background, one session after ' +
|
|
621
|
+
'another; chat activity pauses it as usual. Returns started / busy / nothing_to_do.\n' +
|
|
622
|
+
'\n' +
|
|
623
|
+
'CALLING CONVENTION — read carefully:\n' +
|
|
624
|
+
'\n' +
|
|
625
|
+
'* Default is fire-and-forget. Just call dream_run({}) (or dream_run({phase:"deep"})). ' +
|
|
626
|
+
'The run starts in the background and the tool returns IMMEDIATELY with ' +
|
|
627
|
+
'`{started: true}`. Hand the response back to the user, the conversation continues, ' +
|
|
628
|
+
'the run finishes in 1-3 minutes (deep) or 5-30s (lucid) in the background. ' +
|
|
629
|
+
'Results land in the Obsidian Vault (Deep) or as pending findings via dream_list (Lucid).\n' +
|
|
630
|
+
'\n' +
|
|
631
|
+
'* DO NOT pass wait:true unless the user EXPLICITLY says "warte bis fertig" / ' +
|
|
632
|
+
'"block until done" / "lauf synchron" / equivalent. ' +
|
|
633
|
+
'Asking the user "did this run?" or wanting to give a comprehensive summary in your ' +
|
|
634
|
+
'reply is NOT a reason to use wait:true — the agent-blocking duration is bad UX. ' +
|
|
635
|
+
'The async response is the correct response in 99% of cases.\n' +
|
|
636
|
+
'\n' +
|
|
637
|
+
"* Use sparingly — Deep's scheduler runs every 12h by default, Lucid weekly. " +
|
|
638
|
+
'Manual triggers are for "I just added several substantial memory notes and want ' +
|
|
639
|
+
'them in the wiki now" or "let me cleanup the wiki right now".\n' +
|
|
640
|
+
'\n' +
|
|
641
|
+
"* force:true — phase='deep': bypasses the per-agent skip-cache so every " +
|
|
642
|
+
"memory file is re-evaluated; phase='lucid': runs although a previous run still has open findings " +
|
|
643
|
+
'(otherwise Lucid waits until that run was reviewed).\n' +
|
|
644
|
+
"* (deep detail) force:true bypasses the per-agent skip-cache so every " +
|
|
645
|
+
'memory file gets re-evaluated with a fresh LLM call. Use when a memory note ' +
|
|
646
|
+
"should have ended up in the wiki but didn't, or after a Deep prompt change. " +
|
|
647
|
+
'Costs extra tokens (no cached skips), so reach for it deliberately.',
|
|
648
|
+
inputSchema: RunInput,
|
|
649
|
+
jsonSchema: {
|
|
650
|
+
type: 'object',
|
|
651
|
+
properties: {
|
|
652
|
+
phase: {
|
|
653
|
+
type: 'string',
|
|
654
|
+
enum: ['deep', 'lucid', 'rem'],
|
|
655
|
+
description:
|
|
656
|
+
"Which dream phase to fire. Default 'deep' (Memory→Wiki). 'lucid' triggers wiki cleanup. " +
|
|
657
|
+
"'rem' catches up YOUR unread conversations now (always in the background; wait/force do not apply).",
|
|
658
|
+
},
|
|
659
|
+
wait: {
|
|
660
|
+
type: 'boolean',
|
|
661
|
+
description:
|
|
662
|
+
'OMIT in normal use. Default behavior is async (fire-and-forget) — the tool returns ' +
|
|
663
|
+
'immediately and the run continues in the background. Set wait:true ONLY when the ' +
|
|
664
|
+
'user has explicitly asked for synchronous/blocking behavior (e.g. "warte bis der ' +
|
|
665
|
+
'Run fertig ist", "lauf synchron", "block this turn until done"). Wanting to ' +
|
|
666
|
+
'summarize results in your reply is NOT a valid reason to use wait:true.',
|
|
667
|
+
},
|
|
668
|
+
force: {
|
|
669
|
+
type: 'boolean',
|
|
670
|
+
description:
|
|
671
|
+
"ONLY for phase='deep'. Default false. When true, ignore the per-agent skip-cache " +
|
|
672
|
+
'and re-evaluate every memory file with the LLM. Use after Deep prompt changes, ' +
|
|
673
|
+
'when debugging why a specific memory was skipped, or when a memory file should ' +
|
|
674
|
+
"have been consolidated but didn't show up in the wiki. Costs extra tokens — " +
|
|
675
|
+
"most runs shouldn't need this.",
|
|
676
|
+
},
|
|
677
|
+
},
|
|
678
|
+
additionalProperties: false,
|
|
679
|
+
},
|
|
680
|
+
async handler(input, ctx) {
|
|
681
|
+
const phase = input.phase ?? 'deep';
|
|
682
|
+
if (phase === 'rem') return runRemViaHttp(ctx.agent);
|
|
683
|
+
const wait = input.wait ?? false;
|
|
684
|
+
const force = input.force ?? false;
|
|
685
|
+
if (!ctx.config.wiki.enabled) {
|
|
686
|
+
throw new Error('config.wiki.enabled is false — wiki layer not active');
|
|
687
|
+
}
|
|
688
|
+
if (phase === 'lucid') {
|
|
689
|
+
if (injectedDreamRunDeps) {
|
|
690
|
+
if (!wait) {
|
|
691
|
+
void injectedDreamRunDeps.lucidWorker.runNow({ force }).catch(() => {
|
|
692
|
+
/* errors logged in worker */
|
|
693
|
+
});
|
|
694
|
+
return {
|
|
695
|
+
phase: 'lucid',
|
|
696
|
+
started: true,
|
|
697
|
+
wait: false,
|
|
698
|
+
message:
|
|
699
|
+
'Lucid started in background. Check ~/.somora/wiki-lucid/ for the run report ' +
|
|
700
|
+
"or call dream_list to see findings once it's complete (~1-3min for a small wiki).",
|
|
701
|
+
via: 'in-process',
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
const result = await injectedDreamRunDeps.lucidWorker.runNow({ force });
|
|
705
|
+
return {
|
|
706
|
+
phase: 'lucid',
|
|
707
|
+
wait: true,
|
|
708
|
+
runId: result.runId,
|
|
709
|
+
findingsCount: result.findingsCount,
|
|
710
|
+
pagesScanned: result.pagesScanned,
|
|
711
|
+
durationMs: result.durationMs,
|
|
712
|
+
status: result.status,
|
|
713
|
+
via: 'in-process',
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
return runLucidViaHttp(wait);
|
|
717
|
+
}
|
|
718
|
+
// phase === 'deep'
|
|
719
|
+
if (injectedDreamRunDeps) {
|
|
720
|
+
if (!wait) {
|
|
721
|
+
void injectedDreamRunDeps.deepWorker.runNow({ force }).catch(() => {
|
|
722
|
+
/* error already logged in worker */
|
|
723
|
+
});
|
|
724
|
+
return {
|
|
725
|
+
phase: 'deep',
|
|
726
|
+
started: true,
|
|
727
|
+
wait: false,
|
|
728
|
+
force,
|
|
729
|
+
message:
|
|
730
|
+
'Deep started in background. Check ~/.somora/logs/server-*.log for ' +
|
|
731
|
+
"'dream.deep.done', or inspect <vault>/<wiki-subfolder>/index.md after ~1-3min.",
|
|
732
|
+
via: 'in-process',
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
const result = await injectedDreamRunDeps.deepWorker.runNow({ force });
|
|
736
|
+
const counts = result.outcomes.reduce(
|
|
737
|
+
(acc, o) => {
|
|
738
|
+
acc[o.kind] = (acc[o.kind] ?? 0) + 1;
|
|
739
|
+
return acc;
|
|
740
|
+
},
|
|
741
|
+
{} as Record<string, number>,
|
|
742
|
+
);
|
|
743
|
+
return {
|
|
744
|
+
phase: 'deep',
|
|
745
|
+
wait: true,
|
|
746
|
+
force,
|
|
747
|
+
candidatesSeen: result.candidatesSeen,
|
|
748
|
+
cachedSkips: result.cachedSkips,
|
|
749
|
+
durationMs: result.durationMs,
|
|
750
|
+
counts,
|
|
751
|
+
outcomes: result.outcomes,
|
|
752
|
+
via: 'in-process',
|
|
753
|
+
};
|
|
754
|
+
}
|
|
755
|
+
return runDeepViaHttp(wait, force);
|
|
756
|
+
},
|
|
757
|
+
};
|
|
758
|
+
|
|
759
|
+
/** REM lives in the main server process (idle timers, abort on chat
|
|
760
|
+
* activity), so every engine reaches it over HTTP. */
|
|
761
|
+
async function runRemViaHttp(agent: string): Promise<unknown> {
|
|
762
|
+
const host = process.env.SOMORA_HOST || '127.0.0.1';
|
|
763
|
+
const port = process.env.SOMORA_PORT || '18737';
|
|
764
|
+
const scheme = process.env.SOMORA_TLS === '1' ? 'https' : 'http';
|
|
765
|
+
const res = await loopbackFetch(`${scheme}://${host}:${port}/agents/${encodeURIComponent(agent)}/dream/run-rem`, {
|
|
766
|
+
method: 'POST',
|
|
767
|
+
headers: { 'Content-Type': 'application/json' },
|
|
768
|
+
body: '{}',
|
|
769
|
+
});
|
|
770
|
+
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
|
771
|
+
if (!res.ok) throw new Error(`dream_run rem: ${String(data.error ?? `HTTP ${res.status}`)}`);
|
|
772
|
+
return { phase: 'rem', ...data };
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
async function runDeepViaHttp(wait: boolean, force: boolean): Promise<unknown> {
|
|
776
|
+
const host = process.env.SOMORA_HOST || '127.0.0.1';
|
|
777
|
+
const port = process.env.SOMORA_PORT || '18737';
|
|
778
|
+
const scheme = process.env.SOMORA_TLS === '1' ? 'https' : 'http';
|
|
779
|
+
const url = `${scheme}://${host}:${port}/dream/run-deep`;
|
|
780
|
+
const res = await loopbackFetch(url, {
|
|
781
|
+
method: 'POST',
|
|
782
|
+
headers: { 'Content-Type': 'application/json' },
|
|
783
|
+
body: JSON.stringify({ wait, force }),
|
|
784
|
+
});
|
|
785
|
+
if (!res.ok) {
|
|
786
|
+
const body = await res.text().catch(() => '');
|
|
787
|
+
throw new Error(`dream_run HTTP fallback ${res.status}: ${body.slice(0, 300)}`);
|
|
788
|
+
}
|
|
789
|
+
const data = (await res.json()) as Record<string, unknown>;
|
|
790
|
+
return { phase: 'deep', ...data, via: 'http' };
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
async function runLucidViaHttp(wait: boolean): Promise<unknown> {
|
|
794
|
+
const host = process.env.SOMORA_HOST || '127.0.0.1';
|
|
795
|
+
const port = process.env.SOMORA_PORT || '18737';
|
|
796
|
+
const scheme = process.env.SOMORA_TLS === '1' ? 'https' : 'http';
|
|
797
|
+
const url = `${scheme}://${host}:${port}/dream/run-lucid`;
|
|
798
|
+
const res = await loopbackFetch(url, {
|
|
799
|
+
method: 'POST',
|
|
800
|
+
headers: { 'Content-Type': 'application/json' },
|
|
801
|
+
body: JSON.stringify({ wait }),
|
|
802
|
+
});
|
|
803
|
+
if (!res.ok) {
|
|
804
|
+
const body = await res.text().catch(() => '');
|
|
805
|
+
throw new Error(`dream_run phase=lucid HTTP fallback ${res.status}: ${body.slice(0, 300)}`);
|
|
806
|
+
}
|
|
807
|
+
const data = (await res.json()) as Record<string, unknown>;
|
|
808
|
+
return { phase: 'lucid', ...data, via: 'http' };
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
// ── dream_review ──────────────────────────────────────────────────────
|
|
812
|
+
|
|
813
|
+
const ReviewInput = z.object({
|
|
814
|
+
dream_id: DreamIdSchema,
|
|
815
|
+
action: z.enum(['start', 'end']),
|
|
816
|
+
summary: z.string().optional(),
|
|
817
|
+
dismiss_rest: z.boolean().optional(),
|
|
818
|
+
});
|
|
819
|
+
|
|
820
|
+
const SOMORA_HOME = process.env.SOMORA_HOME ?? `${process.env.HOME}/.somora`;
|
|
821
|
+
const LUCID_ROOT = join(SOMORA_HOME, 'wiki-lucid');
|
|
822
|
+
|
|
823
|
+
function runFilePath(id: string, processed: boolean): string {
|
|
824
|
+
const dir = processed ? join(LUCID_ROOT, 'processed') : LUCID_ROOT;
|
|
825
|
+
return join(dir, `${id}.json`);
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
export const dreamReview: ToolDefinition<z.infer<typeof ReviewInput>> = {
|
|
829
|
+
name: 'dream_review',
|
|
830
|
+
toolset: 'dream',
|
|
831
|
+
description:
|
|
832
|
+
'Open or close a wiki review loop for a Lucid run. While the loop is active, the calling ' +
|
|
833
|
+
'agent gets the loop-scoped wiki tools (wiki_edit, wiki_create, wiki_delete) AND has its ' +
|
|
834
|
+
'normal file_*/exec_*/agents_*/skill_*/tmux_* tools hidden — the goal is a focused ' +
|
|
835
|
+
'wiki-editing conversation with the user.\n' +
|
|
836
|
+
'\n' +
|
|
837
|
+
"action='start': begin the loop for the named Lucid run id. Each Lucid finding will be " +
|
|
838
|
+
"surfaced in the system context every turn until you call action='end'. Only ONE loop can " +
|
|
839
|
+
'be active per somora instance — concurrent start fails.\n' +
|
|
840
|
+
"action='end': close the loop and clear the active lock. Findings still pending STAY pending " +
|
|
841
|
+
'(the run is archived only when none are left, or with dismiss_rest:true) — a later loop continues ' +
|
|
842
|
+
'where this one stopped, and no new Lucid run starts while findings wait. REQUIRES `summary` arg ' +
|
|
843
|
+
'covering what happened to each finding you touched (applied as edit X, dismissed as no-op, deferred — ' +
|
|
844
|
+
'be explicit, no silent drops).\n' +
|
|
845
|
+
'\n' +
|
|
846
|
+
'Use this when the user asks "schau dir das Lucid-Ergebnis an" or similar — open the loop, ' +
|
|
847
|
+
"walk the findings as a conversation, write changes through wiki_*, close with action='end' " +
|
|
848
|
+
'when the user signals done. The loop auto-expires after 24h idle as a safety net.',
|
|
849
|
+
inputSchema: ReviewInput,
|
|
850
|
+
jsonSchema: {
|
|
851
|
+
type: 'object',
|
|
852
|
+
properties: {
|
|
853
|
+
dream_id: { type: 'string', description: 'Lucid run id from dream_list / dream_get.' },
|
|
854
|
+
action: {
|
|
855
|
+
type: 'string',
|
|
856
|
+
enum: ['start', 'end'],
|
|
857
|
+
description: "'start' opens the loop, 'end' closes it.",
|
|
858
|
+
},
|
|
859
|
+
dismiss_rest: {
|
|
860
|
+
type: 'boolean',
|
|
861
|
+
description: "action='end' only: also dismiss every finding still pending and archive the run. Only when the person said so.",
|
|
862
|
+
},
|
|
863
|
+
summary: {
|
|
864
|
+
type: 'string',
|
|
865
|
+
description:
|
|
866
|
+
"REQUIRED for action='end'. Brief outcome per finding so the user knows nothing was " +
|
|
867
|
+
'silently dropped. Optional / ignored for action=start.',
|
|
868
|
+
},
|
|
869
|
+
},
|
|
870
|
+
required: ['dream_id', 'action'],
|
|
871
|
+
additionalProperties: false,
|
|
872
|
+
},
|
|
873
|
+
async handler(input, ctx) {
|
|
874
|
+
const run = await readLucidRunById(input.dream_id);
|
|
875
|
+
if (!run) {
|
|
876
|
+
throw new Error(
|
|
877
|
+
`dream_review: lucid run '${input.dream_id}' not found (only Lucid runs are loop-eligible; ` +
|
|
878
|
+
'REM dreams are reviewed via dream_apply / dream_dismiss).',
|
|
879
|
+
);
|
|
880
|
+
}
|
|
881
|
+
if (input.action === 'start') {
|
|
882
|
+
const existing = getLoopState();
|
|
883
|
+
if (existing && (existing.agent !== ctx.agent || existing.dreamId !== input.dream_id)) {
|
|
884
|
+
throw new Error(
|
|
885
|
+
`dream_review: another review loop is already active (agent='${existing.agent}', ` +
|
|
886
|
+
`dream_id='${existing.dreamId}', startedAt='${existing.startedAt}'). End it via ` +
|
|
887
|
+
'dream_review action=end before starting a new one.',
|
|
888
|
+
);
|
|
889
|
+
}
|
|
890
|
+
const now = new Date().toISOString();
|
|
891
|
+
setLoopState({
|
|
892
|
+
agent: ctx.agent,
|
|
893
|
+
dreamId: input.dream_id,
|
|
894
|
+
startedAt: existing?.startedAt ?? now,
|
|
895
|
+
lastActivityAt: now,
|
|
896
|
+
});
|
|
897
|
+
const open = run.findings.filter((f) => f.status === 'pending');
|
|
898
|
+
// Surface the EFFECTIVE per-turn wiki cap of THIS process — the one
|
|
899
|
+
// that will actually be enforced on wiki_* calls. The prompt block
|
|
900
|
+
// interpolates the same value, but the loop-start response is the
|
|
901
|
+
// agent's plannable, quotable source (lucid-loop report 2026-07-20).
|
|
902
|
+
const cap = getMaxWikiCallsPerTurn();
|
|
903
|
+
return {
|
|
904
|
+
action: 'start',
|
|
905
|
+
dream_id: input.dream_id,
|
|
906
|
+
agent: ctx.agent,
|
|
907
|
+
pending_findings: open.length,
|
|
908
|
+
total_findings: run.findings.length,
|
|
909
|
+
wiki_calls_per_turn: cap,
|
|
910
|
+
message:
|
|
911
|
+
'Wiki review loop is now active for you. The findings are now in your system context ' +
|
|
912
|
+
'every turn; wiki_edit/wiki_create/wiki_delete are exposed; file_write/file_patch/' +
|
|
913
|
+
"exec_*/agents_*/skill_*/tmux_* are refused until you call dream_review action='end'. " +
|
|
914
|
+
`Hard limit: ${cap} wiki_* calls per user turn — plan batches accordingly. ` +
|
|
915
|
+
'NOTE for MCP-served engines (claude-cli, codex-cli, grok-cli): the tool list is fixed ' +
|
|
916
|
+
'per turn, so wiki_* become callable from your NEXT turn — finish this reply, then continue ' +
|
|
917
|
+
'after the user speaks. Until then, dream_dismiss with resolved_manually=true is available.',
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
// action === 'end'
|
|
921
|
+
const existing = getLoopState();
|
|
922
|
+
if (!existing) {
|
|
923
|
+
throw new Error('dream_review: no review loop is currently active');
|
|
924
|
+
}
|
|
925
|
+
if (existing.agent !== ctx.agent) {
|
|
926
|
+
throw new Error(
|
|
927
|
+
`dream_review: the active loop is held by a different agent ('${existing.agent}'); ` +
|
|
928
|
+
'cannot close it from this agent.',
|
|
929
|
+
);
|
|
930
|
+
}
|
|
931
|
+
if (existing.dreamId !== input.dream_id) {
|
|
932
|
+
throw new Error(
|
|
933
|
+
`dream_review: the active loop is for dream_id='${existing.dreamId}', not '${input.dream_id}'.`,
|
|
934
|
+
);
|
|
935
|
+
}
|
|
936
|
+
const summary = (input.summary ?? '').trim();
|
|
937
|
+
if (!summary) {
|
|
938
|
+
throw new Error(
|
|
939
|
+
"dream_review: action='end' requires a non-empty `summary` describing what happened to " +
|
|
940
|
+
'each finding. Do not silently drop findings.',
|
|
941
|
+
);
|
|
942
|
+
}
|
|
943
|
+
// Mark any still-pending findings as dismissed (the loop is over —
|
|
944
|
+
// they were either addressed in conversation or deferred, both
|
|
945
|
+
// captured in the summary). User can re-open by triggering Lucid
|
|
946
|
+
// anew.
|
|
947
|
+
const now = new Date().toISOString();
|
|
948
|
+
// Open findings stay open unless the caller says dismiss_rest — a
|
|
949
|
+
// review that handled two of sixty must not throw the other 58
|
|
950
|
+
// away (2026-09-29). The run is archived only when nothing waits.
|
|
951
|
+
let stillPending = 0;
|
|
952
|
+
let dismissedRest = 0;
|
|
953
|
+
for (const f of run.findings) {
|
|
954
|
+
if (f.status !== 'pending') continue;
|
|
955
|
+
if (input.dismiss_rest === true) {
|
|
956
|
+
f.status = 'dismissed';
|
|
957
|
+
f.resolved_at = now;
|
|
958
|
+
f.resolution_note = 'dismissed with the rest at review end';
|
|
959
|
+
dismissedRest++;
|
|
960
|
+
} else stillPending++;
|
|
961
|
+
}
|
|
962
|
+
const archive = stillPending === 0;
|
|
963
|
+
if (archive) setRunStatus(run, 'processed');
|
|
964
|
+
// Stash the loop summary into the run record itself so the audit
|
|
965
|
+
// trail in processed/ is self-contained.
|
|
966
|
+
(run as unknown as Record<string, unknown>).loop_summary = summary;
|
|
967
|
+
(run as unknown as Record<string, unknown>).loop_held_by = ctx.agent;
|
|
968
|
+
(run as unknown as Record<string, unknown>).loop_started_at = existing.startedAt;
|
|
969
|
+
(run as unknown as Record<string, unknown>).loop_ended_at = now;
|
|
970
|
+
await writeLucidRun(run);
|
|
971
|
+
if (archive) {
|
|
972
|
+
try {
|
|
973
|
+
await rename(runFilePath(run.id, false), runFilePath(run.id, true));
|
|
974
|
+
} catch (err) {
|
|
975
|
+
// ENOENT is fine — could already be archived; otherwise surface.
|
|
976
|
+
const code = (err as NodeJS.ErrnoException).code;
|
|
977
|
+
if (code !== 'ENOENT') {
|
|
978
|
+
throw err;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
clearLoopState();
|
|
983
|
+
return {
|
|
984
|
+
action: 'end',
|
|
985
|
+
dream_id: input.dream_id,
|
|
986
|
+
agent: ctx.agent,
|
|
987
|
+
still_pending: stillPending,
|
|
988
|
+
dismissed_rest: dismissedRest,
|
|
989
|
+
archived: archive,
|
|
990
|
+
summary,
|
|
991
|
+
message: archive
|
|
992
|
+
? 'Loop closed, run archived to processed/, lock released. Wiki tools and the hidden toolsets revert to normal on the next turn.'
|
|
993
|
+
: `Loop closed, lock released; ${stillPending} finding(s) stay open in this run — start the loop again to continue, or end with dismiss_rest:true to close them. No new Lucid run starts while they wait.`,
|
|
994
|
+
};
|
|
995
|
+
},
|
|
996
|
+
};
|
|
997
|
+
|
|
998
|
+
// ── Bundle ────────────────────────────────────────────────────────────
|
|
999
|
+
|
|
1000
|
+
export function dreamTools(): ToolDefinition[] {
|
|
1001
|
+
return [dreamList, dreamGet, dreamApply, dreamDismiss, dreamRun, dreamReview] as ToolDefinition[];
|
|
1002
|
+
}
|