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
package/src/cli/wiki.ts
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
// `somora wiki migrate …` — moving a grown wiki onto the folder template,
|
|
2
|
+
// from the shell, against the running server (docs/wiki.md, "Migrating
|
|
3
|
+
// a grown wiki"). The command itself never touches the wiki: every step
|
|
4
|
+
// is one of the server's /wiki/migration routes, and the server takes
|
|
5
|
+
// the backup before it moves a file. Without a subcommand the command
|
|
6
|
+
// walks a person through all four steps; the subcommands take flags so
|
|
7
|
+
// a script — or an agent that read the docs — can drive them without a
|
|
8
|
+
// keyboard. The real run needs the words "move my wiki", from a human.
|
|
9
|
+
|
|
10
|
+
import { cp, mkdir, readdir, rename, stat } from 'node:fs/promises';
|
|
11
|
+
import { homedir } from 'node:os';
|
|
12
|
+
import { join } from 'node:path';
|
|
13
|
+
import { createInterface } from 'node:readline/promises';
|
|
14
|
+
|
|
15
|
+
const SOMORA_HOME = process.env.SOMORA_HOME ?? join(homedir(), '.somora');
|
|
16
|
+
const CONFIRM = 'move my wiki';
|
|
17
|
+
|
|
18
|
+
export function usage(): string {
|
|
19
|
+
return [
|
|
20
|
+
'usage: somora wiki migrate [<step> [<plan-id>]] [options]',
|
|
21
|
+
'',
|
|
22
|
+
' (no step) guided: plan → judge → approve → dry run → run',
|
|
23
|
+
' plan read the wiki, write what a migration would do (touches nothing)',
|
|
24
|
+
' judge <id> the model judges every page; groups the answers for approval',
|
|
25
|
+
' status <id> the plan, the groups and what is approved',
|
|
26
|
+
' approve <id> … --action move|fold|unclear --twins --group <key> [--dismiss]',
|
|
27
|
+
' dry-run <id> walk the approved steps, write dry-run.md, touch nothing',
|
|
28
|
+
' run <id> --confirm "move my wiki" full copy of the wiki first, then the approved steps',
|
|
29
|
+
' undo <id> [--yes] put the backup of that plan back over the wiki',
|
|
30
|
+
' relink <id> second pass: point links and related: at the moved pages (for runs before .07)',
|
|
31
|
+
'',
|
|
32
|
+
'options: --url <server> (default: from config — https://<publicHost>:<port> or http://127.0.0.1:<port>)',
|
|
33
|
+
'',
|
|
34
|
+
].join('\n');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// ── the server ───────────────────────────────────────────────────────
|
|
38
|
+
|
|
39
|
+
export interface Api {
|
|
40
|
+
get(path: string): Promise<Record<string, unknown>>;
|
|
41
|
+
post(path: string, body?: unknown): Promise<Record<string, unknown>>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function resolveServerUrl(explicit?: string): Promise<string> {
|
|
45
|
+
if (explicit) return explicit.replace(/\/+$/, '');
|
|
46
|
+
if (process.env.SOMORA_URL) return process.env.SOMORA_URL.replace(/\/+$/, '');
|
|
47
|
+
const { loadConfig } = await import('../config/loader.ts');
|
|
48
|
+
const config = await loadConfig();
|
|
49
|
+
const port = process.env.SOMORA_PORT ?? config.server.port;
|
|
50
|
+
const tls = config.server.tls;
|
|
51
|
+
return tls ? `https://${tls.publicHost}:${port}` : `http://127.0.0.1:${port}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function httpApi(base: string): Api {
|
|
55
|
+
const call = async (method: string, path: string, body?: unknown): Promise<Record<string, unknown>> => {
|
|
56
|
+
let res: Response;
|
|
57
|
+
try {
|
|
58
|
+
res = await fetch(`${base}${path}`, { method, headers: { 'Content-Type': 'application/json' }, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) });
|
|
59
|
+
} catch (err) {
|
|
60
|
+
throw new Error(`cannot reach ${base}: ${(err as Error).message} — is the server running? (somora server status)`);
|
|
61
|
+
}
|
|
62
|
+
const text = await res.text();
|
|
63
|
+
let json: Record<string, unknown> = {};
|
|
64
|
+
try {
|
|
65
|
+
json = JSON.parse(text) as Record<string, unknown>;
|
|
66
|
+
} catch {
|
|
67
|
+
json = { raw: text };
|
|
68
|
+
}
|
|
69
|
+
if (!res.ok) throw new Error(typeof json.error === 'string' ? json.error : `${method} ${path} → ${res.status}`);
|
|
70
|
+
return json;
|
|
71
|
+
};
|
|
72
|
+
return { get: (p) => call('GET', p), post: (p, b) => call('POST', p, b ?? {}) };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ── printing ─────────────────────────────────────────────────────────
|
|
76
|
+
|
|
77
|
+
type Out = (line: string) => void;
|
|
78
|
+
|
|
79
|
+
interface Group {
|
|
80
|
+
action: string;
|
|
81
|
+
target: string | null;
|
|
82
|
+
pages: number;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const groupKey = (g: Group): string => `${g.action}:${g.target ?? ''}`;
|
|
86
|
+
|
|
87
|
+
function describeGroup(g: Group): string {
|
|
88
|
+
switch (g.action) {
|
|
89
|
+
case 'move':
|
|
90
|
+
return `move ${g.pages} page${g.pages === 1 ? '' : 's'} to ${g.target}/`;
|
|
91
|
+
case 'fold':
|
|
92
|
+
return `fold ${g.pages} page${g.pages === 1 ? '' : 's'} into ${g.target}`;
|
|
93
|
+
case 'keep':
|
|
94
|
+
return `keep ${g.pages} page${g.pages === 1 ? '' : 's'} where they are`;
|
|
95
|
+
default:
|
|
96
|
+
return `${g.pages} page${g.pages === 1 ? '' : 's'} unclear`;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function summaryLine(sum: Record<string, { items: number; pages: number }>): string {
|
|
101
|
+
return `rule moves ${sum.move_folder?.pages ?? 0} · same-name pages ${sum.unite_twins?.pages ?? 0} · dated reports ${sum.fold_report?.pages ?? 0} · pages for the model ${sum.review_pages?.pages ?? 0} · unclear ${sum.unclear?.pages ?? 0}`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ── steps ────────────────────────────────────────────────────────────
|
|
105
|
+
|
|
106
|
+
export async function stepPlan(api: Api, out: Out): Promise<string> {
|
|
107
|
+
const r = await api.post('/wiki/migration/plan');
|
|
108
|
+
out(`Plan ${r.id}: ${r.pagesTotal} pages in ${r.foldersTotal} folders — ${summaryLine(r.summary as never)}`);
|
|
109
|
+
out(` written to ${r.plan}`);
|
|
110
|
+
return String(r.id);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export async function stepJudge(api: Api, id: string, out: Out, pollMs = 10_000): Promise<Group[]> {
|
|
114
|
+
const st = await api.get(`/wiki/migration/plans/${id}`);
|
|
115
|
+
if (!st.refined) {
|
|
116
|
+
const r = await api.post('/wiki/migration/refine', { id });
|
|
117
|
+
out(`Judging every page with the model (${r.message ?? 'started'}) …`);
|
|
118
|
+
let last = '';
|
|
119
|
+
for (;;) {
|
|
120
|
+
await new Promise((res) => setTimeout(res, pollMs));
|
|
121
|
+
const s = await api.get(`/wiki/migration/plans/${id}`);
|
|
122
|
+
const p = s.refine as { done: number; total: number; finished?: string; error?: string } | null;
|
|
123
|
+
if (p?.error) throw new Error(`judging failed: ${p.error}`);
|
|
124
|
+
const line = p ? ` ${p.done} of ${p.total} batches` : ' …';
|
|
125
|
+
if (line !== last) {
|
|
126
|
+
out(line);
|
|
127
|
+
last = line;
|
|
128
|
+
}
|
|
129
|
+
if (p?.finished || s.refined) break;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const s = await api.get(`/wiki/migration/plans/${id}`);
|
|
133
|
+
const refined = s.refined as { model: string; pagesJudged: number; batchesFailed: number; groups: Group[] } | null;
|
|
134
|
+
if (!refined) throw new Error('no judged result — run `somora wiki migrate judge <id>` again');
|
|
135
|
+
out(`Judged ${refined.pagesJudged} pages with ${refined.model}${refined.batchesFailed ? ` — ${refined.batchesFailed} batches FAILED, their pages are "unclear"` : ''}`);
|
|
136
|
+
out(` details in ${SOMORA_HOME}/wiki-migration/${id}/refined.md`);
|
|
137
|
+
return refined.groups;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export async function stepStatus(api: Api, id: string, out: Out): Promise<{ groups: Group[]; approvals: Record<string, { status: string }>; twins: Record<string, { status: string }> }> {
|
|
141
|
+
const s = await api.get(`/wiki/migration/plans/${id}`);
|
|
142
|
+
const plan = s.plan as { pagesTotal: number; foldersTotal: number; summary: Record<string, { items: number; pages: number }> };
|
|
143
|
+
const refined = s.refined as { groups: Group[]; pagesJudged: number } | null;
|
|
144
|
+
const approvals = (s.approvals as { groups: Record<string, { status: string }>; twins: Record<string, { status: string }> }) ?? { groups: {}, twins: {} };
|
|
145
|
+
out(`Plan ${id}: ${plan.pagesTotal} pages in ${plan.foldersTotal} folders — ${summaryLine(plan.summary)}`);
|
|
146
|
+
if (!refined) {
|
|
147
|
+
out(' not judged yet — `somora wiki migrate judge ' + id + '`');
|
|
148
|
+
return { groups: [], approvals: approvals.groups, twins: approvals.twins };
|
|
149
|
+
}
|
|
150
|
+
out(` ${refined.groups.length} groups from ${refined.pagesJudged} judged pages:`);
|
|
151
|
+
for (const g of refined.groups) {
|
|
152
|
+
if (g.action === 'keep') continue;
|
|
153
|
+
const st = approvals.groups[groupKey(g)]?.status ?? 'pending';
|
|
154
|
+
out(` [${st === 'approved' ? 'x' : st === 'dismissed' ? '-' : ' '}] ${describeGroup(g)}`);
|
|
155
|
+
}
|
|
156
|
+
const keep = refined.groups.filter((g) => g.action === 'keep').reduce((n, g) => n + g.pages, 0);
|
|
157
|
+
if (keep > 0) out(` ${keep} pages stay where they are`);
|
|
158
|
+
const twins = Object.values(approvals.twins).filter((t) => t.status === 'approved').length;
|
|
159
|
+
out(` same-name unions approved: ${twins}`);
|
|
160
|
+
const ex = s.execute as { done: number; total: number; dryRun: boolean; finished?: string; error?: string } | null;
|
|
161
|
+
if (ex) out(` last ${ex.dryRun ? 'dry run' : 'run'}: ${ex.done}/${ex.total}${ex.finished ? ' finished ' + ex.finished : ' running'}${ex.error ? ' ERROR ' + ex.error : ''}`);
|
|
162
|
+
return { groups: refined.groups, approvals: approvals.groups, twins: approvals.twins };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export async function stepApprove(api: Api, id: string, sel: { actions: string[]; groups: string[]; twins: boolean; dismiss: boolean }, out: Out): Promise<void> {
|
|
166
|
+
const status = sel.dismiss ? 'dismissed' : 'approved';
|
|
167
|
+
let last: Record<string, unknown> = {};
|
|
168
|
+
for (const action of sel.actions) last = await api.post(`/wiki/migration/plans/${id}/approve`, { action, status });
|
|
169
|
+
if (sel.groups.length > 0) last = await api.post(`/wiki/migration/plans/${id}/approve`, { groups: sel.groups, status });
|
|
170
|
+
if (sel.twins) last = await api.post(`/wiki/migration/plans/${id}/approve`, { twins: 'all', status });
|
|
171
|
+
if (sel.actions.length === 0 && sel.groups.length === 0 && !sel.twins) throw new Error('nothing selected — use --action, --group or --twins');
|
|
172
|
+
out(`${status}: now ${last.approvedGroups} groups (${last.approvedPages} pages) and ${last.approvedTwins} same-name unions approved`);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export async function stepDryRun(api: Api, id: string, out: Out): Promise<Record<string, unknown>> {
|
|
176
|
+
const r = await api.post(`/wiki/migration/plans/${id}/execute`, { dryRun: true, wait: true });
|
|
177
|
+
// A dry run plans every step and does none — the counts are all
|
|
178
|
+
// zero, so the number of steps is the item count (2026-09-29: the
|
|
179
|
+
// first real dry run said "0 steps planned").
|
|
180
|
+
const steps = typeof r.steps === 'number' ? r.steps : 0;
|
|
181
|
+
out(`Dry run: ${steps} steps planned, ${r.linksRewritten} links would change — nothing written`);
|
|
182
|
+
out(` report: ${r.report}`);
|
|
183
|
+
return r;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export async function stepRun(api: Api, id: string, confirm: string, out: Out, pollMs = 10_000): Promise<Record<string, unknown>> {
|
|
187
|
+
if (confirm !== CONFIRM) throw new Error(`a real run needs --confirm "${CONFIRM}"`);
|
|
188
|
+
const r = await api.post(`/wiki/migration/plans/${id}/execute`, { dryRun: false, confirm });
|
|
189
|
+
out(`Running — the server copies the whole wiki first, then moves. ${r.message ?? ''}`);
|
|
190
|
+
let last = '';
|
|
191
|
+
for (;;) {
|
|
192
|
+
await new Promise((res) => setTimeout(res, pollMs));
|
|
193
|
+
const s = await api.get(`/wiki/migration/plans/${id}`);
|
|
194
|
+
const ex = s.execute as { done: number; total: number; finished?: string; error?: string; last?: string } | null;
|
|
195
|
+
if (ex?.error) throw new Error(`run failed: ${ex.error}`);
|
|
196
|
+
const line = ex ? ` ${ex.done} of ${ex.total}${ex.last ? ' — ' + ex.last : ''}` : ' …';
|
|
197
|
+
if (line !== last) {
|
|
198
|
+
out(line);
|
|
199
|
+
last = line;
|
|
200
|
+
}
|
|
201
|
+
if (ex?.finished) break;
|
|
202
|
+
}
|
|
203
|
+
const files = await readdir(join(SOMORA_HOME, 'wiki-migration', id)).catch(() => [] as string[]);
|
|
204
|
+
const report = files.filter((f) => /^execution-.*\.md$/.test(f)).sort().pop();
|
|
205
|
+
out(`Done. Report: ${report ? join(SOMORA_HOME, 'wiki-migration', id, report) : '(see the plan folder)'}`);
|
|
206
|
+
const backup = files.filter((f) => f.startsWith('backup-')).sort().pop();
|
|
207
|
+
if (backup) out(`Backup: ${join(SOMORA_HOME, 'wiki-migration', id, backup)} — \`somora wiki migrate undo ${id}\` puts it back`);
|
|
208
|
+
return { report, backup };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Put the newest backup of a plan back: the current wiki folder is
|
|
213
|
+
* moved aside (never deleted), the backup copied to the wiki's place,
|
|
214
|
+
* and the server asked to sweep the search index.
|
|
215
|
+
*/
|
|
216
|
+
export async function stepUndo(args: { id: string; wikiAbs: string; api?: Api; yes: boolean; ask?: (q: string) => Promise<string>; out: Out; now?: Date }): Promise<{ restoredFrom: string; movedAsideTo: string }> {
|
|
217
|
+
const dir = join(SOMORA_HOME, 'wiki-migration', args.id);
|
|
218
|
+
const backups = (await readdir(dir).catch(() => [] as string[])).filter((f) => f.startsWith('backup-')).sort();
|
|
219
|
+
const backup = backups.pop();
|
|
220
|
+
if (!backup) throw new Error(`no backup under ${dir}`);
|
|
221
|
+
const from = join(dir, backup);
|
|
222
|
+
const stamp = (args.now ?? new Date()).toISOString().slice(0, 19).replace(/[-:]/g, '').replace('T', '-');
|
|
223
|
+
const aside = `${args.wikiAbs.replace(/\/+$/, '')}.before-undo-${stamp}`;
|
|
224
|
+
args.out(`Restore ${from}\n over ${args.wikiAbs}\n (the current wiki is moved to ${aside}, nothing is deleted)`);
|
|
225
|
+
if (!args.yes) {
|
|
226
|
+
const a = (await (args.ask ?? defaultAsk)('Type "yes" to restore: ')).trim().toLowerCase();
|
|
227
|
+
if (a !== 'yes') throw new Error('cancelled');
|
|
228
|
+
}
|
|
229
|
+
await rename(args.wikiAbs, aside);
|
|
230
|
+
await mkdir(args.wikiAbs, { recursive: true });
|
|
231
|
+
await cp(from, args.wikiAbs, { recursive: true });
|
|
232
|
+
const [a, b] = await Promise.all([countFiles(from), countFiles(args.wikiAbs)]);
|
|
233
|
+
if (a !== b) throw new Error(`restore incomplete: ${b} of ${a} files — the previous state is still at ${aside}`);
|
|
234
|
+
args.out(`Restored ${b} files.`);
|
|
235
|
+
if (args.api) {
|
|
236
|
+
try {
|
|
237
|
+
const r = await args.api.post('/wiki/migration/reindex');
|
|
238
|
+
args.out(`Search index swept: ${r.indexed} indexed, ${r.skipped} unchanged.`);
|
|
239
|
+
} catch (err) {
|
|
240
|
+
args.out(`Search index not swept (${(err as Error).message}) — the 10-minute rescan will catch up.`);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return { restoredFrom: from, movedAsideTo: aside };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async function countFiles(dir: string): Promise<number> {
|
|
247
|
+
let n = 0;
|
|
248
|
+
for (const e of await readdir(dir, { withFileTypes: true })) {
|
|
249
|
+
if (e.isDirectory()) n += await countFiles(join(dir, e.name));
|
|
250
|
+
else n++;
|
|
251
|
+
}
|
|
252
|
+
return n;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async function defaultAsk(q: string): Promise<string> {
|
|
256
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
257
|
+
try {
|
|
258
|
+
return await rl.question(q);
|
|
259
|
+
} finally {
|
|
260
|
+
rl.close();
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// ── guided mode ──────────────────────────────────────────────────────
|
|
265
|
+
|
|
266
|
+
export async function guided(api: Api, out: Out, ask: (q: string) => Promise<string> = defaultAsk, pollMs = 10_000): Promise<number> {
|
|
267
|
+
out('Step 1 of 4 — the plan');
|
|
268
|
+
const id = await stepPlan(api, out);
|
|
269
|
+
out('');
|
|
270
|
+
out('Step 2 of 4 — the model judges every page');
|
|
271
|
+
const groups = await stepJudge(api, id, out, pollMs);
|
|
272
|
+
out('');
|
|
273
|
+
out('Step 3 of 4 — approve');
|
|
274
|
+
const acting = groups.filter((g) => g.action === 'move' || g.action === 'fold');
|
|
275
|
+
acting.forEach((g, i) => out(` ${String(i + 1).padStart(3)} ${describeGroup(g)}`));
|
|
276
|
+
const unclear = groups.filter((g) => g.action === 'unclear').reduce((n, g) => n + g.pages, 0);
|
|
277
|
+
if (unclear > 0) out(` (${unclear} unclear pages stay where they are — see refined.md)`);
|
|
278
|
+
const answer = (await ask('Numbers to leave OUT (space-separated), "none" to approve everything, or "q" to stop here: ')).trim().toLowerCase();
|
|
279
|
+
if (answer === 'q') {
|
|
280
|
+
out(`Stopped. Continue later with: somora wiki migrate status ${id}`);
|
|
281
|
+
return 0;
|
|
282
|
+
}
|
|
283
|
+
const leaveOut = new Set(answer === '' || answer === 'none' ? [] : answer.split(/[\s,]+/).map((n) => Number(n)).filter((n) => Number.isInteger(n) && n >= 1 && n <= acting.length));
|
|
284
|
+
const approvedKeys = acting.filter((_, i) => !leaveOut.has(i + 1)).map(groupKey);
|
|
285
|
+
const dismissedKeys = acting.filter((_, i) => leaveOut.has(i + 1)).map(groupKey);
|
|
286
|
+
if (approvedKeys.length > 0) await stepApprove(api, id, { actions: [], groups: approvedKeys, twins: true, dismiss: false }, out);
|
|
287
|
+
if (dismissedKeys.length > 0) await stepApprove(api, id, { actions: [], groups: dismissedKeys, twins: false, dismiss: true }, out);
|
|
288
|
+
out('');
|
|
289
|
+
out('Step 4 of 4 — dry run, then the real run');
|
|
290
|
+
await stepDryRun(api, id, out);
|
|
291
|
+
const word = (await ask(`Type "${CONFIRM}" to run for real (a full copy of the wiki is taken first), anything else to stop: `)).trim();
|
|
292
|
+
if (word !== CONFIRM) {
|
|
293
|
+
out(`Stopped before any change. Run later with: somora wiki migrate run ${id} --confirm "${CONFIRM}"`);
|
|
294
|
+
return 0;
|
|
295
|
+
}
|
|
296
|
+
await stepRun(api, id, word, out, pollMs);
|
|
297
|
+
return 0;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// ── argv ─────────────────────────────────────────────────────────────
|
|
301
|
+
|
|
302
|
+
export interface Parsed {
|
|
303
|
+
step: string;
|
|
304
|
+
id?: string;
|
|
305
|
+
url?: string;
|
|
306
|
+
actions: string[];
|
|
307
|
+
groups: string[];
|
|
308
|
+
twins: boolean;
|
|
309
|
+
dismiss: boolean;
|
|
310
|
+
confirm?: string;
|
|
311
|
+
yes: boolean;
|
|
312
|
+
help: boolean;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
export function parseArgs(argv: string[]): Parsed {
|
|
316
|
+
const p: Parsed = { step: '', actions: [], groups: [], twins: false, dismiss: false, yes: false, help: false };
|
|
317
|
+
const rest: string[] = [];
|
|
318
|
+
for (let i = 0; i < argv.length; i++) {
|
|
319
|
+
const a = argv[i]!;
|
|
320
|
+
const next = (): string => {
|
|
321
|
+
const v = argv[++i];
|
|
322
|
+
if (v === undefined) throw new Error(`${a} needs a value`);
|
|
323
|
+
return v;
|
|
324
|
+
};
|
|
325
|
+
if (a === '--help' || a === '-h') p.help = true;
|
|
326
|
+
else if (a === '--url') p.url = next();
|
|
327
|
+
else if (a === '--action') p.actions.push(next());
|
|
328
|
+
else if (a === '--group') p.groups.push(next());
|
|
329
|
+
else if (a === '--twins') p.twins = true;
|
|
330
|
+
else if (a === '--dismiss') p.dismiss = true;
|
|
331
|
+
else if (a === '--confirm') p.confirm = next();
|
|
332
|
+
else if (a === '--yes' || a === '-y') p.yes = true;
|
|
333
|
+
else if (a.startsWith('--')) throw new Error(`unknown option ${a}`);
|
|
334
|
+
else rest.push(a);
|
|
335
|
+
}
|
|
336
|
+
p.step = rest[0] ?? '';
|
|
337
|
+
if (rest[1]) p.id = rest[1];
|
|
338
|
+
return p;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export async function runWikiCli(argv: string[], deps: { api?: Api; out?: Out; ask?: (q: string) => Promise<string>; pollMs?: number } = {}): Promise<number> {
|
|
342
|
+
const out: Out = deps.out ?? ((l) => process.stdout.write(`${l}\n`));
|
|
343
|
+
if (argv[0] !== 'migrate') {
|
|
344
|
+
process.stderr.write(usage());
|
|
345
|
+
return argv[0] === '--help' || argv[0] === '-h' ? 0 : 2;
|
|
346
|
+
}
|
|
347
|
+
let p: Parsed;
|
|
348
|
+
try {
|
|
349
|
+
p = parseArgs(argv.slice(1));
|
|
350
|
+
} catch (err) {
|
|
351
|
+
process.stderr.write(`${(err as Error).message}\n${usage()}`);
|
|
352
|
+
return 2;
|
|
353
|
+
}
|
|
354
|
+
if (p.help) {
|
|
355
|
+
out(usage());
|
|
356
|
+
return 0;
|
|
357
|
+
}
|
|
358
|
+
try {
|
|
359
|
+
const api = deps.api ?? httpApi(await resolveServerUrl(p.url));
|
|
360
|
+
const needId = (): string => {
|
|
361
|
+
if (!p.id) throw new Error(`${p.step} needs a plan id (from \`somora wiki migrate plan\`)`);
|
|
362
|
+
return p.id;
|
|
363
|
+
};
|
|
364
|
+
switch (p.step) {
|
|
365
|
+
case '':
|
|
366
|
+
return await guided(api, out, deps.ask, deps.pollMs);
|
|
367
|
+
case 'plan':
|
|
368
|
+
await stepPlan(api, out);
|
|
369
|
+
return 0;
|
|
370
|
+
case 'judge':
|
|
371
|
+
await stepJudge(api, needId(), out, deps.pollMs);
|
|
372
|
+
return 0;
|
|
373
|
+
case 'status':
|
|
374
|
+
await stepStatus(api, needId(), out);
|
|
375
|
+
return 0;
|
|
376
|
+
case 'approve':
|
|
377
|
+
await stepApprove(api, needId(), { actions: p.actions, groups: p.groups, twins: p.twins, dismiss: p.dismiss }, out);
|
|
378
|
+
return 0;
|
|
379
|
+
case 'dry-run':
|
|
380
|
+
await stepDryRun(api, needId(), out);
|
|
381
|
+
return 0;
|
|
382
|
+
case 'run':
|
|
383
|
+
await stepRun(api, needId(), p.confirm ?? '', out, deps.pollMs);
|
|
384
|
+
return 0;
|
|
385
|
+
case 'relink': {
|
|
386
|
+
const r = await api.post(`/wiki/migration/plans/${needId()}/relink`, {});
|
|
387
|
+
out(`Relinked: ${r.refsRewritten} references in ${r.pagesTouched} pages (${r.renames} renames from the run)`);
|
|
388
|
+
return 0;
|
|
389
|
+
}
|
|
390
|
+
case 'undo': {
|
|
391
|
+
const id = needId();
|
|
392
|
+
const st = await api.get('/wiki/status').catch(() => ({} as Record<string, unknown>));
|
|
393
|
+
const wikiAbs = typeof st.wikiAbs === 'string' ? st.wikiAbs : typeof st.root === 'string' ? st.root : '';
|
|
394
|
+
if (!wikiAbs) throw new Error('the server did not tell where the wiki is (GET /wiki/status) — is the wiki enabled?');
|
|
395
|
+
await stepUndo({ id, wikiAbs, api, yes: p.yes, ...(deps.ask ? { ask: deps.ask } : {}), out });
|
|
396
|
+
return 0;
|
|
397
|
+
}
|
|
398
|
+
default:
|
|
399
|
+
process.stderr.write(`unknown step: ${p.step}\n${usage()}`);
|
|
400
|
+
return 2;
|
|
401
|
+
}
|
|
402
|
+
} catch (err) {
|
|
403
|
+
process.stderr.write(`${(err as Error).message}\n`);
|
|
404
|
+
return 1;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Compaction module — public surface.
|
|
2
|
+
//
|
|
3
|
+
// Architecture (DECISIONS #21):
|
|
4
|
+
// - JSONL stays append-only, ground truth.
|
|
5
|
+
// - meta.compactions[] is the index of compaction events.
|
|
6
|
+
// - Each compaction has a throughTs marker + a structured summary.
|
|
7
|
+
// - Engines consult compactions[] when building messages so that
|
|
8
|
+
// events with ts <= throughTs are replaced by the summary.
|
|
9
|
+
//
|
|
10
|
+
// CLI engines (claude-cli, codex-cli) get the same benefit transparently
|
|
11
|
+
// for their delta-replay (replay.ts is compaction-aware).
|
|
12
|
+
|
|
13
|
+
export type { Compaction, CompactionConfig } from './types.ts';
|
|
14
|
+
export {
|
|
15
|
+
DEFAULT_COMPACTION_CONFIG,
|
|
16
|
+
resolveCompactionConfig,
|
|
17
|
+
pickLatest,
|
|
18
|
+
pickLatestApplicable,
|
|
19
|
+
} from './types.ts';
|
|
20
|
+
export {
|
|
21
|
+
estimateContextSize,
|
|
22
|
+
estimateTokens,
|
|
23
|
+
inputBudget,
|
|
24
|
+
shouldCompact,
|
|
25
|
+
type ShouldCompactDecision,
|
|
26
|
+
} from './policy.ts';
|
|
27
|
+
export { extractCompactionRange, runCompaction } from './summarize.ts';
|
|
28
|
+
export { buildSummaryPrompt } from './template.ts';
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
// Mid-turn compaction for builder turns (openai-compatible engine).
|
|
2
|
+
//
|
|
3
|
+
// A chat turn ends after a few rounds; the pre-turn compaction sizes the
|
|
4
|
+
// conversation once, and when a turn still grows past the window the
|
|
5
|
+
// oldest tool results are shortened (context-budget.ts). A builder's
|
|
6
|
+
// turn is hundreds of rounds, and its state — which file was patched,
|
|
7
|
+
// which test went red, what the plan says now — lives in exactly those
|
|
8
|
+
// tool results. Shortening them blank is how a build forgets what it
|
|
9
|
+
// did.
|
|
10
|
+
//
|
|
11
|
+
// So a builder turn compacts itself the way opencode does: when the
|
|
12
|
+
// estimate for the next request exceeds the budget, the older rounds of
|
|
13
|
+
// THIS turn (from the turn's user message up to the last `keepRounds`
|
|
14
|
+
// rounds) are summarised by a worker model into a work-state block, and
|
|
15
|
+
// replaced by one user message carrying that block. The last rounds stay
|
|
16
|
+
// verbatim so the model keeps its immediate context. The session file is
|
|
17
|
+
// untouched — this shapes the request, not the record.
|
|
18
|
+
|
|
19
|
+
import type { ResolvedModel } from '../config/types.ts';
|
|
20
|
+
import { isAvailabilityError } from '../engine/availability.ts';
|
|
21
|
+
import { markModelAvailable, markModelUnavailable } from '../engine/model-availability.ts';
|
|
22
|
+
import { logger } from '../server/logger.ts';
|
|
23
|
+
import { dropUnavailable, rankCompactionModels, summarizeViaEngine, SUMMARIZE_ENGINES } from './summarize.ts';
|
|
24
|
+
import type { CompactionConfig } from './types.ts';
|
|
25
|
+
|
|
26
|
+
/** Any chat message shape the engine keeps in its loop. */
|
|
27
|
+
export interface LoopMessage {
|
|
28
|
+
role: 'system' | 'user' | 'assistant' | 'tool';
|
|
29
|
+
content?: unknown;
|
|
30
|
+
tool_calls?: Array<{ id?: string; function?: { name?: string; arguments?: string } }>;
|
|
31
|
+
tool_call_id?: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const RESULT_MAX_CHARS = 1500;
|
|
35
|
+
const TEXT_MAX_CHARS = 3000;
|
|
36
|
+
|
|
37
|
+
function asText(content: unknown): string {
|
|
38
|
+
if (typeof content === 'string') return content;
|
|
39
|
+
if (Array.isArray(content)) {
|
|
40
|
+
return content
|
|
41
|
+
.map((p) => (p && typeof p === 'object' && 'text' in p && typeof (p as { text: unknown }).text === 'string' ? (p as { text: string }).text : '[non-text part]'))
|
|
42
|
+
.join('\n');
|
|
43
|
+
}
|
|
44
|
+
if (content == null) return '';
|
|
45
|
+
return JSON.stringify(content);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const cut = (s: string, n: number): string => (s.length > n ? `${s.slice(0, n)} … [cut ${s.length - n} chars]` : s);
|
|
49
|
+
|
|
50
|
+
/** The rounds to compact, rendered as a transcript for the worker. */
|
|
51
|
+
export function renderRoundsTranscript(messages: LoopMessage[]): string {
|
|
52
|
+
const names = new Map<string, string>();
|
|
53
|
+
const out: string[] = [];
|
|
54
|
+
for (const m of messages) {
|
|
55
|
+
if (m.role === 'user') out.push(`[User]: ${cut(asText(m.content), TEXT_MAX_CHARS)}`);
|
|
56
|
+
else if (m.role === 'assistant') {
|
|
57
|
+
const text = asText(m.content).trim();
|
|
58
|
+
if (text) out.push(`[Assistant]: ${cut(text, TEXT_MAX_CHARS)}`);
|
|
59
|
+
for (const c of m.tool_calls ?? []) {
|
|
60
|
+
const name = c.function?.name ?? 'tool';
|
|
61
|
+
if (c.id) names.set(c.id, name);
|
|
62
|
+
out.push(`[Assistant tool call]: ${name}(${cut(c.function?.arguments ?? '', 600)})`);
|
|
63
|
+
}
|
|
64
|
+
} else if (m.role === 'tool') {
|
|
65
|
+
const name = (m.tool_call_id && names.get(m.tool_call_id)) ?? 'tool';
|
|
66
|
+
out.push(`[Tool result ${name}]: ${cut(asText(m.content), RESULT_MAX_CHARS)}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return out.join('\n');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export const WORK_STATE_TEMPLATE = [
|
|
73
|
+
'You summarise the work an engineering agent did so far in ONE turn, so',
|
|
74
|
+
'that the same agent can continue with the summary in place of the',
|
|
75
|
+
'transcript. Output exactly the Markdown structure below, section order',
|
|
76
|
+
'unchanged, terse bullets, exact file paths, symbols, commands and error',
|
|
77
|
+
'strings preserved. Invent nothing. Do not mention the summarising.',
|
|
78
|
+
'',
|
|
79
|
+
'## Objective',
|
|
80
|
+
'- [what the turn is trying to accomplish]',
|
|
81
|
+
'',
|
|
82
|
+
'## Important Details',
|
|
83
|
+
'- [constraints, decisions and why, facts needed to continue, or "(none)"]',
|
|
84
|
+
'',
|
|
85
|
+
'## Work State',
|
|
86
|
+
'### Completed',
|
|
87
|
+
'- [finished, verified work and changes made, or "(none)"]',
|
|
88
|
+
'### Active',
|
|
89
|
+
'- [current work, partial changes, investigation state, or "(none)"]',
|
|
90
|
+
'### Blocked',
|
|
91
|
+
'- [blockers, failing commands, unknowns, or "(none)"]',
|
|
92
|
+
'',
|
|
93
|
+
'## Next Move',
|
|
94
|
+
'1. [immediate concrete action, or "(none)"]',
|
|
95
|
+
'2. [next action if known, or "(none)"]',
|
|
96
|
+
'',
|
|
97
|
+
'## Relevant Files',
|
|
98
|
+
'- [file or directory path: why it matters, or "(none)"]',
|
|
99
|
+
].join('\n');
|
|
100
|
+
|
|
101
|
+
/** Find the loop-message index where the last `keepRounds` rounds start
|
|
102
|
+
* (a round starts with an assistant message carrying tool_calls). */
|
|
103
|
+
export function lastRoundsStart(messages: LoopMessage[], from: number, keepRounds: number): number {
|
|
104
|
+
const starts: number[] = [];
|
|
105
|
+
for (let i = from; i < messages.length; i++) {
|
|
106
|
+
const m = messages[i]!;
|
|
107
|
+
if (m.role === 'assistant' && (m.tool_calls?.length ?? 0) > 0) starts.push(i);
|
|
108
|
+
}
|
|
109
|
+
if (starts.length <= keepRounds) return -1;
|
|
110
|
+
return starts[starts.length - keepRounds]!;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface MidturnCompactionInput {
|
|
114
|
+
messages: LoopMessage[];
|
|
115
|
+
/** Index of this turn's user message in `messages`. */
|
|
116
|
+
turnStartIdx: number;
|
|
117
|
+
keepRounds: number;
|
|
118
|
+
resolvedModel: ResolvedModel;
|
|
119
|
+
availableModels: ResolvedModel[];
|
|
120
|
+
config: CompactionConfig;
|
|
121
|
+
agent: string;
|
|
122
|
+
/** The builder's task list as last written with todo_write. It goes
|
|
123
|
+
* into the block verbatim: a summary tends to drop it, and a model
|
|
124
|
+
* that no longer sees its list stops keeping it (observed 2026-09-23:
|
|
125
|
+
* one todo_write before the compaction, none after). */
|
|
126
|
+
todos?: ReadonlyArray<{ content: string; status: string; priority?: string }>;
|
|
127
|
+
/** Test seam. */
|
|
128
|
+
summarize?: (worker: ResolvedModel, system: string, user: string) => Promise<{ text: string }>;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export interface MidturnCompactionResult {
|
|
132
|
+
messages: LoopMessage[];
|
|
133
|
+
summary: string;
|
|
134
|
+
compactedMessages: number;
|
|
135
|
+
worker: string;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Replace the older rounds of the running turn with a work-state
|
|
140
|
+
* summary. Returns null when there is nothing to compact yet (fewer
|
|
141
|
+
* than keepRounds + 1 rounds) or no worker fits.
|
|
142
|
+
*/
|
|
143
|
+
/** The task list, appended to the compaction block so the model keeps it. */
|
|
144
|
+
export function renderTodoReminder(todos: MidturnCompactionInput['todos']): string {
|
|
145
|
+
if (!todos || todos.length === 0) return '';
|
|
146
|
+
const lines = todos.map((t) => `- [${t.status}] ${t.content}`);
|
|
147
|
+
return (
|
|
148
|
+
'\n\nYour task list as last written with todo_write (the person sees it):\n' +
|
|
149
|
+
lines.join('\n') +
|
|
150
|
+
'\nKeep it current: mark what is done completed, the step you take next in_progress, and rewrite it with todo_write as you go.'
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export async function compactTurnMidway(input: MidturnCompactionInput): Promise<MidturnCompactionResult | null> {
|
|
155
|
+
const { messages, turnStartIdx, keepRounds } = input;
|
|
156
|
+
const cutAt = lastRoundsStart(messages, turnStartIdx + 1, keepRounds);
|
|
157
|
+
if (cutAt < 0 || cutAt <= turnStartIdx + 1) return null;
|
|
158
|
+
const older = messages.slice(turnStartIdx, cutAt);
|
|
159
|
+
const transcript = renderRoundsTranscript(older);
|
|
160
|
+
const user = [
|
|
161
|
+
'Here is the transcript of the work so far in this turn:',
|
|
162
|
+
'',
|
|
163
|
+
'<transcript>',
|
|
164
|
+
transcript,
|
|
165
|
+
'</transcript>',
|
|
166
|
+
'',
|
|
167
|
+
'Write the work-state summary now.',
|
|
168
|
+
].join('\n');
|
|
169
|
+
const estimate = Math.ceil((WORK_STATE_TEMPLATE.length + user.length) / 4);
|
|
170
|
+
const candidates = input.availableModels.filter((m) => SUMMARIZE_ENGINES.has(m.provider.engine));
|
|
171
|
+
const ranked = rankCompactionModels(estimate, candidates, {
|
|
172
|
+
workers: input.config.workers,
|
|
173
|
+
...(input.config.preferSessionModel ? { sessionModel: input.resolvedModel } : {}),
|
|
174
|
+
});
|
|
175
|
+
let summary: string | null = null;
|
|
176
|
+
let workerName = '';
|
|
177
|
+
for (const worker of dropUnavailable(ranked).slice(0, 3)) {
|
|
178
|
+
try {
|
|
179
|
+
const r = input.summarize
|
|
180
|
+
? await input.summarize(worker, WORK_STATE_TEMPLATE, user)
|
|
181
|
+
: await summarizeViaEngine(worker.provider.engine, {
|
|
182
|
+
systemPrompt: WORK_STATE_TEMPLATE,
|
|
183
|
+
userPrompt: user,
|
|
184
|
+
resolvedModel: worker,
|
|
185
|
+
agent: input.agent,
|
|
186
|
+
});
|
|
187
|
+
if (r.text.trim()) {
|
|
188
|
+
summary = r.text.trim();
|
|
189
|
+
workerName = `${worker.providerName}/${worker.modelId}`;
|
|
190
|
+
markModelAvailable(workerName);
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
} catch (err) {
|
|
194
|
+
if (isAvailabilityError(err)) markModelUnavailable(`${worker.providerName}/${worker.modelId}`, (err as Error).message);
|
|
195
|
+
logger.warn({ msg: 'compaction.midturn_worker_failed', agent: input.agent, worker: `${worker.providerName}/${worker.modelId}`, err: (err as Error).message });
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (!summary) return null;
|
|
199
|
+
const original = messages[turnStartIdx]!;
|
|
200
|
+
const block: LoopMessage = {
|
|
201
|
+
role: 'user',
|
|
202
|
+
content:
|
|
203
|
+
'[somora] The earlier part of this turn was compacted to keep the conversation inside the model\'s context window. ' +
|
|
204
|
+
'The tools listed there already ran — do not run them again. Continue from "Next Move".\n\n' +
|
|
205
|
+
summary +
|
|
206
|
+
renderTodoReminder(input.todos),
|
|
207
|
+
};
|
|
208
|
+
const next = [...messages.slice(0, turnStartIdx), original, block, ...messages.slice(cutAt)];
|
|
209
|
+
return { messages: next, summary, compactedMessages: older.length - 1, worker: workerName };
|
|
210
|
+
}
|