@otium-team/negotium 0.0.0-stage → 0.23.13
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 +202 -0
- package/README.md +329 -2
- package/bin/codex-sdk-window-hide.mjs +40 -0
- package/bin/negotium.mjs +22 -0
- package/dist/agent-helpers.js +23090 -0
- package/dist/agent-helpers.js.map +171 -0
- package/dist/background-bash.js +535 -0
- package/dist/background-bash.js.map +16 -0
- package/dist/browser-runtime.js +2334 -0
- package/dist/browser-runtime.js.map +35 -0
- package/dist/canonical-mcp-bridge.js +13 -0
- package/dist/canonical-mcp-bridge.js.map +9 -0
- package/dist/chunk-22kg3fsw.js +79 -0
- package/dist/chunk-22kg3fsw.js.map +9 -0
- package/dist/chunk-d4j77adx.js +336 -0
- package/dist/chunk-d4j77adx.js.map +13 -0
- package/dist/chunk-mk9x18jn.js +172 -0
- package/dist/chunk-mk9x18jn.js.map +12 -0
- package/dist/chunk-qd0vtfm2.js +3923 -0
- package/dist/chunk-qd0vtfm2.js.map +47 -0
- package/dist/chunk-wf7ny8eq.js +206 -0
- package/dist/chunk-wf7ny8eq.js.map +10 -0
- package/dist/chunk-ww8a4ej4.js +54 -0
- package/dist/chunk-ww8a4ej4.js.map +10 -0
- package/dist/cron.js +1 -0
- package/dist/hosted-agent.js +5982 -0
- package/dist/hosted-agent.js.map +62 -0
- package/dist/main.js +60229 -0
- package/dist/main.js.map +340 -0
- package/dist/mcp-catalog.js +39 -0
- package/dist/mcp-catalog.js.map +10 -0
- package/dist/mcp-factories.js +25767 -0
- package/dist/mcp-factories.js.map +181 -0
- package/dist/mcp-servers.js +50 -0
- package/dist/mcp-servers.js.map +10 -0
- package/dist/media.js +570 -0
- package/dist/media.js.map +15 -0
- package/dist/outbox.js +354 -0
- package/dist/outbox.js.map +15 -0
- package/dist/platform-runtime.js +73 -0
- package/dist/platform-runtime.js.map +12 -0
- package/dist/prompts.js +892 -0
- package/dist/prompts.js.map +15 -0
- package/dist/query-runtime.js +1071 -0
- package/dist/query-runtime.js.map +26 -0
- package/dist/registry.js +335 -0
- package/dist/registry.js.map +14 -0
- package/dist/rollout.js +57 -0
- package/dist/rollout.js.map +10 -0
- package/dist/runtime/cron/background-sessions.ts +119 -0
- package/dist/runtime/cron/context.ts +123 -0
- package/dist/runtime/cron/host.ts +67 -0
- package/dist/runtime/cron/index.ts +95 -0
- package/dist/runtime/cron/mcp-server.ts +556 -0
- package/dist/runtime/cron/module.ts +174 -0
- package/dist/runtime/cron/package.json +6 -0
- package/dist/runtime/cron/schedule.ts +211 -0
- package/dist/runtime/cron/scheduler.ts +444 -0
- package/dist/runtime/cron/scripts.ts +203 -0
- package/dist/runtime/cron/store.ts +1163 -0
- package/dist/runtime/cron/summarize.ts +115 -0
- package/dist/runtime/package.json +6 -0
- package/dist/runtime/scripts/faster-whisper-wrapper.py +87 -0
- package/dist/runtime/src/agents/api-topic-agent-switch.ts +179 -0
- package/dist/runtime/src/agents/archiver.ts +677 -0
- package/dist/runtime/src/agents/auth-check.ts +156 -0
- package/dist/runtime/src/agents/claude-notices.ts +130 -0
- package/dist/runtime/src/agents/claude-provider.ts +941 -0
- package/dist/runtime/src/agents/claude-registry.ts +117 -0
- package/dist/runtime/src/agents/claude-runtime-inspection.ts +43 -0
- package/dist/runtime/src/agents/codex-app-server.ts +138 -0
- package/dist/runtime/src/agents/codex-native-multi-agent.ts +360 -0
- package/dist/runtime/src/agents/codex-provider.ts +1193 -0
- package/dist/runtime/src/agents/codex-registry.ts +116 -0
- package/dist/runtime/src/agents/codex-tier-resolver.ts +74 -0
- package/dist/runtime/src/agents/codex-tree-kill.ts +54 -0
- package/dist/runtime/src/agents/codex-tree-manager.ts +230 -0
- package/dist/runtime/src/agents/codex-vault-hook-bridge.ts +240 -0
- package/dist/runtime/src/agents/codex-vault-hook.mjs +50 -0
- package/dist/runtime/src/agents/codex-windows-wrapper.ts +174 -0
- package/dist/runtime/src/agents/compaction-support.ts +75 -0
- package/dist/runtime/src/agents/compaction-tool-projection.ts +125 -0
- package/dist/runtime/src/agents/contracts.ts +75 -0
- package/dist/runtime/src/agents/deep-map.ts +13 -0
- package/dist/runtime/src/agents/execution-host.ts +118 -0
- package/dist/runtime/src/agents/explicit-agent-switch.ts +106 -0
- package/dist/runtime/src/agents/fixtures/claude-attachments.jsonl +2 -0
- package/dist/runtime/src/agents/fixtures/codex-shell.jsonl +5 -0
- package/dist/runtime/src/agents/fork.ts +100 -0
- package/dist/runtime/src/agents/hosted-agent.ts +78 -0
- package/dist/runtime/src/agents/idle-archiver.ts +225 -0
- package/dist/runtime/src/agents/idle-compact.ts +225 -0
- package/dist/runtime/src/agents/index.ts +225 -0
- package/dist/runtime/src/agents/maestro-provider.ts +246 -0
- package/dist/runtime/src/agents/maestro-registry.ts +189 -0
- package/dist/runtime/src/agents/mcp-tools/ask-user.ts +653 -0
- package/dist/runtime/src/agents/mcp-tools/common.ts +23 -0
- package/dist/runtime/src/agents/mcp-tools/inline-assets.ts +203 -0
- package/dist/runtime/src/agents/mcp-tools/publish-html.ts +183 -0
- package/dist/runtime/src/agents/mcp-tools/request-vault.ts +684 -0
- package/dist/runtime/src/agents/mcp-tools/self-config.ts +353 -0
- package/dist/runtime/src/agents/mcp-tools/spawn-subagent.ts +1349 -0
- package/dist/runtime/src/agents/mcp-tools/visual-compat.ts +18 -0
- package/dist/runtime/src/agents/mcp-tools/visuals.ts +60 -0
- package/dist/runtime/src/agents/memory-archive-policy.ts +54 -0
- package/dist/runtime/src/agents/model-catalog.ts +439 -0
- package/dist/runtime/src/agents/public-helpers.ts +149 -0
- package/dist/runtime/src/agents/registry.ts +35 -0
- package/dist/runtime/src/agents/rollout/claude.ts +336 -0
- package/dist/runtime/src/agents/rollout/codex.ts +910 -0
- package/dist/runtime/src/agents/rollout/index.ts +26 -0
- package/dist/runtime/src/agents/rollout/shared.ts +293 -0
- package/dist/runtime/src/agents/self-config-core.ts +704 -0
- package/dist/runtime/src/agents/task-events.ts +59 -0
- package/dist/runtime/src/agents/tool-format.ts +613 -0
- package/dist/runtime/src/agents/topic-agent-switch.ts +189 -0
- package/dist/runtime/src/agents/topic-cleanup.ts +285 -0
- package/dist/runtime/src/agents/vault-tool-policy.ts +36 -0
- package/dist/runtime/src/application/execute-external-user-turn.ts +23 -0
- package/dist/runtime/src/application/submit-runtime-gateway-turn.ts +484 -0
- package/dist/runtime/src/application/submit-user-message.ts +60 -0
- package/dist/runtime/src/application/switch-topic-effort.ts +48 -0
- package/dist/runtime/src/application/switch-topic-model.ts +79 -0
- package/dist/runtime/src/application/topic-service.ts +190 -0
- package/dist/runtime/src/application/turn-follow-ups.ts +291 -0
- package/dist/runtime/src/application/vault-command.ts +170 -0
- package/dist/runtime/src/bus.ts +409 -0
- package/dist/runtime/src/config-public.ts +2 -0
- package/dist/runtime/src/cron-host.ts +33 -0
- package/dist/runtime/src/cron-mcp-host.ts +5 -0
- package/dist/runtime/src/identifiers.ts +49 -0
- package/dist/runtime/src/index.ts +573 -0
- package/dist/runtime/src/mcp/agent-health-server.ts +8 -0
- package/dist/runtime/src/mcp/canonical-bridge-config.ts +84 -0
- package/dist/runtime/src/mcp/canonical-proxy-server.ts +308 -0
- package/dist/runtime/src/mcp/compaction-log-server.ts +25 -0
- package/dist/runtime/src/mcp/decision-server.ts +21 -0
- package/dist/runtime/src/mcp/dm-ipc.ts +60 -0
- package/dist/runtime/src/mcp/factories/agent-health.ts +394 -0
- package/dist/runtime/src/mcp/factories/compaction-log.ts +135 -0
- package/dist/runtime/src/mcp/factories/decision.ts +186 -0
- package/dist/runtime/src/mcp/factories/index.ts +73 -0
- package/dist/runtime/src/mcp/factories/session-comm.ts +184 -0
- package/dist/runtime/src/mcp/factories/session-history.ts +103 -0
- package/dist/runtime/src/mcp/factories/stdio-protection.ts +24 -0
- package/dist/runtime/src/mcp/factories/system-health.ts +259 -0
- package/dist/runtime/src/mcp/factories/task.ts +185 -0
- package/dist/runtime/src/mcp/factories/token-stats.ts +145 -0
- package/dist/runtime/src/mcp/factories/vault.ts +32 -0
- package/dist/runtime/src/mcp/mcp-helpers.ts +40 -0
- package/dist/runtime/src/mcp/peer-bridge.ts +119 -0
- package/dist/runtime/src/mcp/runtime-spec.ts +473 -0
- package/dist/runtime/src/mcp/session-comm/actor-policy.ts +160 -0
- package/dist/runtime/src/mcp/session-comm/bridge-ipc-config.ts +27 -0
- package/dist/runtime/src/mcp/session-comm/context.ts +113 -0
- package/dist/runtime/src/mcp/session-comm/default-host.ts +723 -0
- package/dist/runtime/src/mcp/session-comm/history-target.ts +89 -0
- package/dist/runtime/src/mcp/session-comm/history-tools.ts +113 -0
- package/dist/runtime/src/mcp/session-comm/hub-remote-session.ts +553 -0
- package/dist/runtime/src/mcp/session-comm/limits.ts +8 -0
- package/dist/runtime/src/mcp/session-comm/peer-forward.ts +251 -0
- package/dist/runtime/src/mcp/session-comm/runtime.ts +128 -0
- package/dist/runtime/src/mcp/session-comm/server.ts +1036 -0
- package/dist/runtime/src/mcp/session-comm/tell-permissions.ts +79 -0
- package/dist/runtime/src/mcp/session-comm/topic-catalog.ts +155 -0
- package/dist/runtime/src/mcp/session-comm/topic-config.ts +137 -0
- package/dist/runtime/src/mcp/session-comm/topics.ts +313 -0
- package/dist/runtime/src/mcp/session-history-limits.ts +36 -0
- package/dist/runtime/src/mcp/session-history-reader.ts +359 -0
- package/dist/runtime/src/mcp/session-history-server.ts +19 -0
- package/dist/runtime/src/mcp/stdio-protect.ts +7 -0
- package/dist/runtime/src/mcp/system-health-server.ts +5 -0
- package/dist/runtime/src/mcp/task-server.ts +17 -0
- package/dist/runtime/src/mcp/token-stats-server.ts +10 -0
- package/dist/runtime/src/mcp/vault-server.ts +12 -0
- package/dist/runtime/src/mcp/wiki-search-index.ts +359 -0
- package/dist/runtime/src/mcp/wiki-server.ts +2386 -0
- package/dist/runtime/src/mcp-runtime-host.ts +81 -0
- package/dist/runtime/src/media/file-events.ts +33 -0
- package/dist/runtime/src/media/text-extractor.ts +334 -0
- package/dist/runtime/src/media/video.ts +92 -0
- package/dist/runtime/src/node-host.ts +211 -0
- package/dist/runtime/src/outbox/coalescing-runner.ts +157 -0
- package/dist/runtime/src/outbox/file-ops.ts +267 -0
- package/dist/runtime/src/outbox/index.ts +26 -0
- package/dist/runtime/src/outbox/utils.ts +74 -0
- package/dist/runtime/src/platform/background-bash/context.ts +9 -0
- package/dist/runtime/src/platform/background-bash/manager.ts +292 -0
- package/dist/runtime/src/platform/background-bash/output-buffer.ts +323 -0
- package/dist/runtime/src/platform/config-helpers.ts +47 -0
- package/dist/runtime/src/platform/config.ts +618 -0
- package/dist/runtime/src/platform/constants.ts +30 -0
- package/dist/runtime/src/platform/debug-users.ts +14 -0
- package/dist/runtime/src/platform/delay.ts +1 -0
- package/dist/runtime/src/platform/error.ts +9 -0
- package/dist/runtime/src/platform/file-utils.ts +35 -0
- package/dist/runtime/src/platform/ipc.ts +55 -0
- package/dist/runtime/src/platform/jsonl.ts +277 -0
- package/dist/runtime/src/platform/lifecycle.ts +176 -0
- package/dist/runtime/src/platform/log-rotation.ts +45 -0
- package/dist/runtime/src/platform/logger.ts +42 -0
- package/dist/runtime/src/platform/maestro-bootstrap-env.ts +3 -0
- package/dist/runtime/src/platform/mcp-catalog-policy.ts +63 -0
- package/dist/runtime/src/platform/mcp-config.ts +1329 -0
- package/dist/runtime/src/platform/memoize-import.ts +26 -0
- package/dist/runtime/src/platform/modules.ts +145 -0
- package/dist/runtime/src/platform/node-plugins.ts +46 -0
- package/dist/runtime/src/platform/paths.ts +62 -0
- package/dist/runtime/src/platform/playwright/browser-processes.ts +300 -0
- package/dist/runtime/src/platform/playwright/capability.ts +5 -0
- package/dist/runtime/src/platform/playwright/headed-launch.ts +61 -0
- package/dist/runtime/src/platform/playwright/manager-utils.ts +128 -0
- package/dist/runtime/src/platform/playwright/manager.ts +1502 -0
- package/dist/runtime/src/platform/playwright/mcp-transport.ts +35 -0
- package/dist/runtime/src/platform/playwright/profile-management.ts +33 -0
- package/dist/runtime/src/platform/playwright/public-runtime.ts +52 -0
- package/dist/runtime/src/platform/playwright/transport-probe.ts +89 -0
- package/dist/runtime/src/platform/playwright/vault-broker.ts +261 -0
- package/dist/runtime/src/platform/public-runtime.ts +18 -0
- package/dist/runtime/src/prompts/agents/wiki-archiver.md +194 -0
- package/dist/runtime/src/prompts/builders.ts +696 -0
- package/dist/runtime/src/prompts/sessions/_shared-tools.md +38 -0
- package/dist/runtime/src/prompts/sessions/channel-system.md +13 -0
- package/dist/runtime/src/prompts/sessions/manager-system.md +34 -0
- package/dist/runtime/src/prompts/sessions/surfaces/cli.md +6 -0
- package/dist/runtime/src/prompts/sessions/surfaces/otium-manager.md +18 -0
- package/dist/runtime/src/prompts/sessions/surfaces/otium.md +6 -0
- package/dist/runtime/src/prompts/sessions/surfaces/telegram.md +5 -0
- package/dist/runtime/src/prompts/sessions/surfaces/terminal.md +6 -0
- package/dist/runtime/src/prompts/sessions/topic-system.md +9 -0
- package/dist/runtime/src/prompts/sessions/visual-design.md +38 -0
- package/dist/runtime/src/query/active-rooms.ts +514 -0
- package/dist/runtime/src/query/index.ts +23 -0
- package/dist/runtime/src/query/public-runtime.ts +28 -0
- package/dist/runtime/src/query/room-query-registry.ts +217 -0
- package/dist/runtime/src/query/session-inbox-cleanup.ts +45 -0
- package/dist/runtime/src/query/session-inbox-path.ts +42 -0
- package/dist/runtime/src/query/state.ts +116 -0
- package/dist/runtime/src/query/types.ts +8 -0
- package/dist/runtime/src/runtime/actor-topic-reach.ts +123 -0
- package/dist/runtime/src/runtime/actor-topic-scope.ts +255 -0
- package/dist/runtime/src/runtime/ask-callbacks.ts +217 -0
- package/dist/runtime/src/runtime/attachments.ts +149 -0
- package/dist/runtime/src/runtime/background-session-policy.ts +1 -0
- package/dist/runtime/src/runtime/background-sessions.ts +288 -0
- package/dist/runtime/src/runtime/bashrs-completions.ts +350 -0
- package/dist/runtime/src/runtime/channel-context.ts +115 -0
- package/dist/runtime/src/runtime/context-warning.ts +131 -0
- package/dist/runtime/src/runtime/cron-sessions.ts +35 -0
- package/dist/runtime/src/runtime/delivery-ack.ts +112 -0
- package/dist/runtime/src/runtime/errors.ts +70 -0
- package/dist/runtime/src/runtime/event-heartbeat.ts +77 -0
- package/dist/runtime/src/runtime/file-hooks.ts +81 -0
- package/dist/runtime/src/runtime/footer.ts +23 -0
- package/dist/runtime/src/runtime/gateway-capabilities.ts +22 -0
- package/dist/runtime/src/runtime/inbox.ts +1307 -0
- package/dist/runtime/src/runtime/playwright-turn-abort.ts +59 -0
- package/dist/runtime/src/runtime/public-helpers.ts +78 -0
- package/dist/runtime/src/runtime/remote-session-grant.ts +221 -0
- package/dist/runtime/src/runtime/remote-session-inbox.ts +943 -0
- package/dist/runtime/src/runtime/remote-session-reply-outbox.ts +168 -0
- package/dist/runtime/src/runtime/task-format.ts +18 -0
- package/dist/runtime/src/runtime/tasks.ts +53 -0
- package/dist/runtime/src/runtime/thread-context.ts +123 -0
- package/dist/runtime/src/runtime/thread-read.ts +67 -0
- package/dist/runtime/src/runtime/topic-config.ts +29 -0
- package/dist/runtime/src/runtime/turn-event-stream.ts +1051 -0
- package/dist/runtime/src/runtime/turn-runner.ts +2311 -0
- package/dist/runtime/src/runtime/turn-session.ts +116 -0
- package/dist/runtime/src/runtime/usage-alert.ts +51 -0
- package/dist/runtime/src/runtime/user-turn-envelope.ts +94 -0
- package/dist/runtime/src/runtime/visual-html.ts +175 -0
- package/dist/runtime/src/runtime/visual-store.ts +480 -0
- package/dist/runtime/src/runtime/visuals.ts +209 -0
- package/dist/runtime/src/runtime-gateway.ts +1045 -0
- package/dist/runtime/src/security/sanitize.ts +27 -0
- package/dist/runtime/src/security/sensitive-path.ts +41 -0
- package/dist/runtime/src/storage/activity-log.ts +167 -0
- package/dist/runtime/src/storage/api-messages.ts +766 -0
- package/dist/runtime/src/storage/api-topic-brief.ts +134 -0
- package/dist/runtime/src/storage/api-topic-config.ts +197 -0
- package/dist/runtime/src/storage/api-topics.ts +1647 -0
- package/dist/runtime/src/storage/app-settings.ts +50 -0
- package/dist/runtime/src/storage/ask-user-gates.ts +359 -0
- package/dist/runtime/src/storage/browser-profiles.ts +186 -0
- package/dist/runtime/src/storage/conversation-migration.ts +180 -0
- package/dist/runtime/src/storage/conversations.ts +377 -0
- package/dist/runtime/src/storage/decisions.ts +231 -0
- package/dist/runtime/src/storage/forum/agent-settings.ts +20 -0
- package/dist/runtime/src/storage/forum/index.ts +4 -0
- package/dist/runtime/src/storage/forum/repository.ts +283 -0
- package/dist/runtime/src/storage/forum/schema.ts +314 -0
- package/dist/runtime/src/storage/forum-db.ts +4 -0
- package/dist/runtime/src/storage/remote-session.ts +1028 -0
- package/dist/runtime/src/storage/runtime-events.ts +209 -0
- package/dist/runtime/src/storage/runtime-follow-ups.ts +212 -0
- package/dist/runtime/src/storage/runtime-gateway-submissions.ts +132 -0
- package/dist/runtime/src/storage/runtime-leases.ts +190 -0
- package/dist/runtime/src/storage/runtime-process-leases.ts +288 -0
- package/dist/runtime/src/storage/runtime-topic-state.ts +181 -0
- package/dist/runtime/src/storage/runtime-turn-requests.ts +846 -0
- package/dist/runtime/src/storage/self-schedules.ts +306 -0
- package/dist/runtime/src/storage/session-asks.ts +468 -0
- package/dist/runtime/src/storage/session-inbox-signal.ts +76 -0
- package/dist/runtime/src/storage/session-inbox.ts +161 -0
- package/dist/runtime/src/storage/sqlite.ts +154 -0
- package/dist/runtime/src/storage/storage-contract.ts +54 -0
- package/dist/runtime/src/storage/storage-host.ts +336 -0
- package/dist/runtime/src/storage/storage-public-host.ts +16 -0
- package/dist/runtime/src/storage/storage-public.ts +66 -0
- package/dist/runtime/src/storage/tasks.ts +172 -0
- package/dist/runtime/src/storage/token-stats.ts +432 -0
- package/dist/runtime/src/storage/topic-archive-state.ts +226 -0
- package/dist/runtime/src/storage/topic-archive.ts +169 -0
- package/dist/runtime/src/storage/topic-host-mcp-grants.ts +54 -0
- package/dist/runtime/src/storage/topic-link-records.ts +1085 -0
- package/dist/runtime/src/storage/topic-settings.ts +67 -0
- package/dist/runtime/src/storage/topic-tool-capabilities.ts +89 -0
- package/dist/runtime/src/storage/topic-transcript.ts +98 -0
- package/dist/runtime/src/storage/vault-crypto-core.ts +65 -0
- package/dist/runtime/src/storage/vault-crypto.ts +31 -0
- package/dist/runtime/src/storage/vault-public.ts +27 -0
- package/dist/runtime/src/storage/vault-request-gates.ts +359 -0
- package/dist/runtime/src/storage/vault.ts +388 -0
- package/dist/runtime/src/storage/wiki-summary-names.ts +52 -0
- package/dist/runtime/src/storage/wiki.ts +90 -0
- package/dist/runtime/src/topics/claim-abort.ts +190 -0
- package/dist/runtime/src/topics/create.ts +192 -0
- package/dist/runtime/src/topics/derive.ts +600 -0
- package/dist/runtime/src/topics/lifecycle.ts +425 -0
- package/dist/runtime/src/topics/links.ts +7 -0
- package/dist/runtime/src/topics/personal-general.ts +91 -0
- package/dist/runtime/src/topics/session.ts +1041 -0
- package/dist/runtime/src/topics/update.ts +287 -0
- package/dist/runtime/src/types/api.ts +591 -0
- package/dist/runtime/src/types.ts +418 -0
- package/dist/runtime/src/version.ts +1 -0
- package/dist/runtime/tsconfig.json +13 -0
- package/dist/runtime-gateway.js +514 -0
- package/dist/runtime-gateway.js.map +10 -0
- package/dist/runtime-helpers.js +1792 -0
- package/dist/runtime-helpers.js.map +40 -0
- package/dist/sqlite.js +66 -0
- package/dist/sqlite.js.map +10 -0
- package/dist/storage.js +5223 -0
- package/dist/storage.js.map +47 -0
- package/dist/types/apps/negotium/src/mcp-servers.d.ts +20 -0
- package/dist/types/packages/core/src/agents/api-topic-agent-switch.d.ts +38 -0
- package/dist/types/packages/core/src/agents/archiver.d.ts +87 -0
- package/dist/types/packages/core/src/agents/auth-check.d.ts +19 -0
- package/dist/types/packages/core/src/agents/claude-notices.d.ts +15 -0
- package/dist/types/packages/core/src/agents/claude-provider.d.ts +25 -0
- package/dist/types/packages/core/src/agents/claude-registry.d.ts +3 -0
- package/dist/types/packages/core/src/agents/claude-runtime-inspection.d.ts +9 -0
- package/dist/types/packages/core/src/agents/codex-app-server.d.ts +13 -0
- package/dist/types/packages/core/src/agents/codex-native-multi-agent.d.ts +20 -0
- package/dist/types/packages/core/src/agents/codex-provider.d.ts +64 -0
- package/dist/types/packages/core/src/agents/codex-registry.d.ts +3 -0
- package/dist/types/packages/core/src/agents/codex-tier-resolver.d.ts +10 -0
- package/dist/types/packages/core/src/agents/codex-tree-kill.d.ts +13 -0
- package/dist/types/packages/core/src/agents/codex-tree-manager.d.ts +28 -0
- package/dist/types/packages/core/src/agents/codex-vault-hook-bridge.d.ts +28 -0
- package/dist/types/packages/core/src/agents/codex-windows-wrapper.d.ts +30 -0
- package/dist/types/packages/core/src/agents/compaction-support.d.ts +5 -0
- package/dist/types/packages/core/src/agents/compaction-tool-projection.d.ts +9 -0
- package/dist/types/packages/core/src/agents/contracts.d.ts +68 -0
- package/dist/types/packages/core/src/agents/deep-map.d.ts +2 -0
- package/dist/types/packages/core/src/agents/execution-host.d.ts +33 -0
- package/dist/types/packages/core/src/agents/explicit-agent-switch.d.ts +26 -0
- package/dist/types/packages/core/src/agents/fork.d.ts +50 -0
- package/dist/types/packages/core/src/agents/hosted-agent.d.ts +15 -0
- package/dist/types/packages/core/src/agents/idle-archiver.d.ts +35 -0
- package/dist/types/packages/core/src/agents/idle-compact.d.ts +37 -0
- package/dist/types/packages/core/src/agents/index.d.ts +8 -0
- package/dist/types/packages/core/src/agents/maestro-provider.d.ts +75 -0
- package/dist/types/packages/core/src/agents/maestro-registry.d.ts +3 -0
- package/dist/types/packages/core/src/agents/mcp-tools/ask-user.d.ts +147 -0
- package/dist/types/packages/core/src/agents/mcp-tools/common.d.ts +14 -0
- package/dist/types/packages/core/src/agents/mcp-tools/inline-assets.d.ts +24 -0
- package/dist/types/packages/core/src/agents/mcp-tools/publish-html.d.ts +18 -0
- package/dist/types/packages/core/src/agents/mcp-tools/request-vault.d.ts +124 -0
- package/dist/types/packages/core/src/agents/mcp-tools/self-config.d.ts +45 -0
- package/dist/types/packages/core/src/agents/mcp-tools/spawn-subagent.d.ts +148 -0
- package/dist/types/packages/core/src/agents/mcp-tools/visual-compat.d.ts +55 -0
- package/dist/types/packages/core/src/agents/mcp-tools/visuals.d.ts +70 -0
- package/dist/types/packages/core/src/agents/memory-archive-policy.d.ts +24 -0
- package/dist/types/packages/core/src/agents/model-catalog.d.ts +132 -0
- package/dist/types/packages/core/src/agents/public-helpers.d.ts +17 -0
- package/dist/types/packages/core/src/agents/registry.d.ts +5 -0
- package/dist/types/packages/core/src/agents/rollout/claude.d.ts +77 -0
- package/dist/types/packages/core/src/agents/rollout/codex.d.ts +119 -0
- package/dist/types/packages/core/src/agents/rollout/index.d.ts +6 -0
- package/dist/types/packages/core/src/agents/rollout/shared.d.ts +56 -0
- package/dist/types/packages/core/src/agents/self-config-core.d.ts +199 -0
- package/dist/types/packages/core/src/agents/task-events.d.ts +19 -0
- package/dist/types/packages/core/src/agents/tool-format.d.ts +25 -0
- package/dist/types/packages/core/src/agents/topic-cleanup.d.ts +83 -0
- package/dist/types/packages/core/src/agents/vault-tool-policy.d.ts +2 -0
- package/dist/types/packages/core/src/bus.d.ts +141 -0
- package/dist/types/packages/core/src/identifiers.d.ts +27 -0
- package/dist/types/packages/core/src/mcp/canonical-bridge-config.d.ts +21 -0
- package/dist/types/packages/core/src/mcp/factories/agent-health.d.ts +5 -0
- package/dist/types/packages/core/src/mcp/factories/compaction-log.d.ts +8 -0
- package/dist/types/packages/core/src/mcp/factories/decision.d.ts +18 -0
- package/dist/types/packages/core/src/mcp/factories/index.d.ts +13 -0
- package/dist/types/packages/core/src/mcp/factories/session-comm.d.ts +38 -0
- package/dist/types/packages/core/src/mcp/factories/session-history.d.ts +11 -0
- package/dist/types/packages/core/src/mcp/factories/stdio-protection.d.ts +10 -0
- package/dist/types/packages/core/src/mcp/factories/system-health.d.ts +37 -0
- package/dist/types/packages/core/src/mcp/factories/task.d.ts +13 -0
- package/dist/types/packages/core/src/mcp/factories/token-stats.d.ts +20 -0
- package/dist/types/packages/core/src/mcp/factories/vault.d.ts +9 -0
- package/dist/types/packages/core/src/mcp/mcp-helpers.d.ts +26 -0
- package/dist/types/packages/core/src/mcp/peer-bridge.d.ts +92 -0
- package/dist/types/packages/core/src/mcp/runtime-spec.d.ts +147 -0
- package/dist/types/packages/core/src/mcp/session-comm/actor-policy.d.ts +120 -0
- package/dist/types/packages/core/src/mcp/session-comm/bridge-ipc-config.d.ts +6 -0
- package/dist/types/packages/core/src/mcp/session-comm/context.d.ts +44 -0
- package/dist/types/packages/core/src/mcp/session-comm/history-tools.d.ts +31 -0
- package/dist/types/packages/core/src/mcp/session-comm/hub-remote-session.d.ts +149 -0
- package/dist/types/packages/core/src/mcp/session-comm/limits.d.ts +8 -0
- package/dist/types/packages/core/src/mcp/session-comm/peer-forward.d.ts +85 -0
- package/dist/types/packages/core/src/mcp/session-comm/tell-permissions.d.ts +29 -0
- package/dist/types/packages/core/src/mcp/session-comm/topic-catalog.d.ts +59 -0
- package/dist/types/packages/core/src/mcp/session-history-limits.d.ts +20 -0
- package/dist/types/packages/core/src/mcp/session-history-reader.d.ts +35 -0
- package/dist/types/packages/core/src/mcp/wiki-search-index.d.ts +59 -0
- package/dist/types/packages/core/src/mcp/wiki-server.d.ts +53 -0
- package/dist/types/packages/core/src/media/file-events.d.ts +14 -0
- package/dist/types/packages/core/src/media/text-extractor.d.ts +34 -0
- package/dist/types/packages/core/src/outbox/coalescing-runner.d.ts +68 -0
- package/dist/types/packages/core/src/outbox/file-ops.d.ts +79 -0
- package/dist/types/packages/core/src/outbox/index.d.ts +3 -0
- package/dist/types/packages/core/src/outbox/utils.d.ts +16 -0
- package/dist/types/packages/core/src/platform/background-bash/context.d.ts +1 -0
- package/dist/types/packages/core/src/platform/background-bash/manager.d.ts +34 -0
- package/dist/types/packages/core/src/platform/config-helpers.d.ts +20 -0
- package/dist/types/packages/core/src/platform/config.d.ts +178 -0
- package/dist/types/packages/core/src/platform/constants.d.ts +20 -0
- package/dist/types/packages/core/src/platform/delay.d.ts +1 -0
- package/dist/types/packages/core/src/platform/error.d.ts +6 -0
- package/dist/types/packages/core/src/platform/file-utils.d.ts +16 -0
- package/dist/types/packages/core/src/platform/ipc.d.ts +32 -0
- package/dist/types/packages/core/src/platform/jsonl.d.ts +46 -0
- package/dist/types/packages/core/src/platform/lifecycle.d.ts +40 -0
- package/dist/types/packages/core/src/platform/logger.d.ts +20 -0
- package/dist/types/packages/core/src/platform/maestro-bootstrap-env.d.ts +0 -0
- package/dist/types/packages/core/src/platform/mcp-catalog-policy.d.ts +73 -0
- package/dist/types/packages/core/src/platform/mcp-config.d.ts +286 -0
- package/dist/types/packages/core/src/platform/memoize-import.d.ts +15 -0
- package/dist/types/packages/core/src/platform/paths.d.ts +18 -0
- package/dist/types/packages/core/src/platform/playwright/browser-processes.d.ts +60 -0
- package/dist/types/packages/core/src/platform/playwright/capability.d.ts +1 -0
- package/dist/types/packages/core/src/platform/playwright/headed-launch.d.ts +13 -0
- package/dist/types/packages/core/src/platform/playwright/manager-utils.d.ts +34 -0
- package/dist/types/packages/core/src/platform/playwright/manager.d.ts +194 -0
- package/dist/types/packages/core/src/platform/playwright/mcp-transport.d.ts +4 -0
- package/dist/types/packages/core/src/platform/playwright/profile-management.d.ts +8 -0
- package/dist/types/packages/core/src/platform/playwright/public-runtime.d.ts +6 -0
- package/dist/types/packages/core/src/platform/playwright/transport-probe.d.ts +13 -0
- package/dist/types/packages/core/src/platform/playwright/vault-broker.d.ts +6 -0
- package/dist/types/packages/core/src/platform/public-runtime.d.ts +3 -0
- package/dist/types/packages/core/src/prompts/builders.d.ts +78 -0
- package/dist/types/packages/core/src/query/active-rooms.d.ts +240 -0
- package/dist/types/packages/core/src/query/public-runtime.d.ts +4 -0
- package/dist/types/packages/core/src/query/room-query-registry.d.ts +71 -0
- package/dist/types/packages/core/src/query/session-inbox-cleanup.d.ts +5 -0
- package/dist/types/packages/core/src/query/session-inbox-path.d.ts +8 -0
- package/dist/types/packages/core/src/query/state.d.ts +25 -0
- package/dist/types/packages/core/src/query/types.d.ts +6 -0
- package/dist/types/packages/core/src/runtime/actor-topic-reach.d.ts +63 -0
- package/dist/types/packages/core/src/runtime/actor-topic-scope.d.ts +127 -0
- package/dist/types/packages/core/src/runtime/ask-callbacks.d.ts +53 -0
- package/dist/types/packages/core/src/runtime/attachments.d.ts +36 -0
- package/dist/types/packages/core/src/runtime/background-session-policy.d.ts +1 -0
- package/dist/types/packages/core/src/runtime/background-sessions.d.ts +27 -0
- package/dist/types/packages/core/src/runtime/bashrs-completions.d.ts +50 -0
- package/dist/types/packages/core/src/runtime/channel-context.d.ts +13 -0
- package/dist/types/packages/core/src/runtime/context-warning.d.ts +46 -0
- package/dist/types/packages/core/src/runtime/cron-sessions.d.ts +9 -0
- package/dist/types/packages/core/src/runtime/errors.d.ts +6 -0
- package/dist/types/packages/core/src/runtime/event-heartbeat.d.ts +17 -0
- package/dist/types/packages/core/src/runtime/file-hooks.d.ts +38 -0
- package/dist/types/packages/core/src/runtime/playwright-turn-abort.d.ts +12 -0
- package/dist/types/packages/core/src/runtime/public-helpers.d.ts +17 -0
- package/dist/types/packages/core/src/runtime/remote-session-grant.d.ts +91 -0
- package/dist/types/packages/core/src/runtime/remote-session-inbox.d.ts +206 -0
- package/dist/types/packages/core/src/runtime/remote-session-reply-outbox.d.ts +37 -0
- package/dist/types/packages/core/src/runtime/task-format.d.ts +4 -0
- package/dist/types/packages/core/src/runtime/tasks.d.ts +3 -0
- package/dist/types/packages/core/src/runtime/thread-context.d.ts +62 -0
- package/dist/types/packages/core/src/runtime/topic-config.d.ts +24 -0
- package/dist/types/packages/core/src/runtime/turn-event-stream.d.ts +47 -0
- package/dist/types/packages/core/src/runtime/turn-runner.d.ts +284 -0
- package/dist/types/packages/core/src/runtime/turn-session.d.ts +49 -0
- package/dist/types/packages/core/src/runtime/usage-alert.d.ts +11 -0
- package/dist/types/packages/core/src/runtime/user-turn-envelope.d.ts +37 -0
- package/dist/types/packages/core/src/runtime/visual-html.d.ts +13 -0
- package/dist/types/packages/core/src/runtime/visual-store.d.ts +71 -0
- package/dist/types/packages/core/src/runtime/visuals.d.ts +33 -0
- package/dist/types/packages/core/src/runtime-gateway.d.ts +282 -0
- package/dist/types/packages/core/src/security/sanitize.d.ts +16 -0
- package/dist/types/packages/core/src/security/sensitive-path.d.ts +1 -0
- package/dist/types/packages/core/src/storage/activity-log.d.ts +25 -0
- package/dist/types/packages/core/src/storage/api-messages.d.ts +156 -0
- package/dist/types/packages/core/src/storage/api-topic-brief.d.ts +39 -0
- package/dist/types/packages/core/src/storage/api-topic-config.d.ts +23 -0
- package/dist/types/packages/core/src/storage/api-topics.d.ts +274 -0
- package/dist/types/packages/core/src/storage/app-settings.d.ts +4 -0
- package/dist/types/packages/core/src/storage/ask-user-gates.d.ts +65 -0
- package/dist/types/packages/core/src/storage/browser-profiles.d.ts +31 -0
- package/dist/types/packages/core/src/storage/conversations.d.ts +149 -0
- package/dist/types/packages/core/src/storage/decisions.d.ts +45 -0
- package/dist/types/packages/core/src/storage/forum/agent-settings.d.ts +3 -0
- package/dist/types/packages/core/src/storage/forum/index.d.ts +4 -0
- package/dist/types/packages/core/src/storage/forum/repository.d.ts +42 -0
- package/dist/types/packages/core/src/storage/forum/schema.d.ts +38 -0
- package/dist/types/packages/core/src/storage/forum-db.d.ts +2 -0
- package/dist/types/packages/core/src/storage/remote-session.d.ts +318 -0
- package/dist/types/packages/core/src/storage/runtime-events.d.ts +33 -0
- package/dist/types/packages/core/src/storage/runtime-leases.d.ts +27 -0
- package/dist/types/packages/core/src/storage/runtime-process-leases.d.ts +47 -0
- package/dist/types/packages/core/src/storage/runtime-topic-state.d.ts +39 -0
- package/dist/types/packages/core/src/storage/runtime-turn-requests.d.ts +163 -0
- package/dist/types/packages/core/src/storage/self-schedules.d.ts +54 -0
- package/dist/types/packages/core/src/storage/session-asks.d.ts +78 -0
- package/dist/types/packages/core/src/storage/session-inbox-signal.d.ts +35 -0
- package/dist/types/packages/core/src/storage/session-inbox.d.ts +36 -0
- package/dist/types/packages/core/src/storage/sqlite.d.ts +20 -0
- package/dist/types/packages/core/src/storage/storage-contract.d.ts +46 -0
- package/dist/types/packages/core/src/storage/storage-host.d.ts +41 -0
- package/dist/types/packages/core/src/storage/storage-public-host.d.ts +7 -0
- package/dist/types/packages/core/src/storage/storage-public.d.ts +45 -0
- package/dist/types/packages/core/src/storage/tasks.d.ts +49 -0
- package/dist/types/packages/core/src/storage/token-stats.d.ts +69 -0
- package/dist/types/packages/core/src/storage/topic-archive-state.d.ts +33 -0
- package/dist/types/packages/core/src/storage/topic-archive.d.ts +42 -0
- package/dist/types/packages/core/src/storage/topic-host-mcp-grants.d.ts +5 -0
- package/dist/types/packages/core/src/storage/topic-link-records.d.ts +281 -0
- package/dist/types/packages/core/src/storage/topic-settings.d.ts +19 -0
- package/dist/types/packages/core/src/storage/topic-tool-capabilities.d.ts +37 -0
- package/dist/types/packages/core/src/storage/topic-transcript.d.ts +38 -0
- package/dist/types/packages/core/src/storage/vault-crypto-core.d.ts +6 -0
- package/dist/types/packages/core/src/storage/vault-crypto.d.ts +12 -0
- package/dist/types/packages/core/src/storage/vault-public.d.ts +3 -0
- package/dist/types/packages/core/src/storage/vault-request-gates.d.ts +69 -0
- package/dist/types/packages/core/src/storage/vault.d.ts +49 -0
- package/dist/types/packages/core/src/storage/wiki-summary-names.d.ts +13 -0
- package/dist/types/packages/core/src/storage/wiki.d.ts +15 -0
- package/dist/types/packages/core/src/topics/derive.d.ts +83 -0
- package/dist/types/packages/core/src/topics/lifecycle.d.ts +75 -0
- package/dist/types/packages/core/src/topics/links.d.ts +2 -0
- package/dist/types/packages/core/src/topics/personal-general.d.ts +15 -0
- package/dist/types/packages/core/src/topics/session.d.ts +70 -0
- package/dist/types/packages/core/src/types/api.d.ts +551 -0
- package/dist/types/packages/core/src/types.d.ts +405 -0
- package/dist/types/packages/core/src/version.d.ts +1 -0
- package/dist/types/packages/module-cron/src/background-sessions.d.ts +2 -0
- package/dist/types/packages/module-cron/src/context.d.ts +15 -0
- package/dist/types/packages/module-cron/src/host.d.ts +23 -0
- package/dist/types/packages/module-cron/src/index.d.ts +14 -0
- package/dist/types/packages/module-cron/src/module.d.ts +13 -0
- package/dist/types/packages/module-cron/src/schedule.d.ts +23 -0
- package/dist/types/packages/module-cron/src/scheduler.d.ts +46 -0
- package/dist/types/packages/module-cron/src/scripts.d.ts +29 -0
- package/dist/types/packages/module-cron/src/store.d.ts +152 -0
- package/dist/types/packages/module-cron/src/summarize.d.ts +4 -0
- package/dist/vault.js +848 -0
- package/dist/vault.js.map +18 -0
- package/install-bash-rs.mjs +90 -0
- package/install-browser-rs.mjs +83 -0
- package/package.json +171 -4
|
@@ -0,0 +1,2386 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
|
|
3
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import {
|
|
6
|
+
closeSync,
|
|
7
|
+
type Dirent,
|
|
8
|
+
existsSync,
|
|
9
|
+
mkdirSync,
|
|
10
|
+
openSync,
|
|
11
|
+
readdirSync,
|
|
12
|
+
readFileSync,
|
|
13
|
+
renameSync,
|
|
14
|
+
statSync,
|
|
15
|
+
unlinkSync,
|
|
16
|
+
writeFileSync,
|
|
17
|
+
} from "node:fs";
|
|
18
|
+
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
19
|
+
import { argv, exit } from "node:process";
|
|
20
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
21
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
22
|
+
import {
|
|
23
|
+
CallToolRequestSchema,
|
|
24
|
+
type CallToolResult,
|
|
25
|
+
ListToolsRequestSchema,
|
|
26
|
+
type ListToolsResult,
|
|
27
|
+
type Tool,
|
|
28
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
29
|
+
import {
|
|
30
|
+
type IndexedWikiKind,
|
|
31
|
+
type PreparedWikiSearchDocument,
|
|
32
|
+
resetCorruptWikiSearchIndex,
|
|
33
|
+
WikiSearchIndex,
|
|
34
|
+
type WikiSearchIndexSource,
|
|
35
|
+
} from "#mcp/wiki-search-index";
|
|
36
|
+
import { SHARED_WIKI_DIR } from "#platform/config";
|
|
37
|
+
import {
|
|
38
|
+
wikiBriefStorageKey,
|
|
39
|
+
wikiSummaryFilename,
|
|
40
|
+
wikiSummarySlug,
|
|
41
|
+
} from "#storage/wiki-summary-names";
|
|
42
|
+
|
|
43
|
+
// --- CLI parsing -----------------------------------------------------------
|
|
44
|
+
|
|
45
|
+
export type WikiSurface = "all" | "wiki" | "skills";
|
|
46
|
+
|
|
47
|
+
export interface WikiTopicBrief {
|
|
48
|
+
briefMd: string;
|
|
49
|
+
latestSummaryMd?: string;
|
|
50
|
+
summaryDate?: string;
|
|
51
|
+
updatedAt: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface WikiMcpHost {
|
|
55
|
+
wikiRoot: string;
|
|
56
|
+
/** Filters `wiki_query` topic results to the memories `resolveTopicBrief` would return. */
|
|
57
|
+
canReadTopicMemory?(selection: string, userId: string, boundTopicId?: string): boolean;
|
|
58
|
+
getTopicBrief?(topicId: string): WikiTopicBrief | null;
|
|
59
|
+
/** `boundTopicId` is the room this server runs for; its own memory is always readable. */
|
|
60
|
+
resolveTopicBrief?(
|
|
61
|
+
selection: string,
|
|
62
|
+
userId: string,
|
|
63
|
+
boundTopicId?: string,
|
|
64
|
+
): WikiTopicBrief | null;
|
|
65
|
+
setTopicBrief?(
|
|
66
|
+
topicId: string,
|
|
67
|
+
fields: {
|
|
68
|
+
briefMd?: string;
|
|
69
|
+
latestSummaryMd?: string;
|
|
70
|
+
summaryDate?: string;
|
|
71
|
+
},
|
|
72
|
+
): void;
|
|
73
|
+
/** The memory key a room was given; its summaries and brief may be written under no other name. */
|
|
74
|
+
fixedMemoryKey?(topicId: string): string | undefined;
|
|
75
|
+
adoptTopicMemory?(topicId: string, userId: string, memoryKey: string): boolean;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface WikiMcpContext {
|
|
79
|
+
userId: string;
|
|
80
|
+
/** The room executing the tool, even when topicId points at inherited memory. */
|
|
81
|
+
currentTopicId?: string;
|
|
82
|
+
topicId?: string;
|
|
83
|
+
surface?: WikiSurface;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
interface WikiMemoryTopic {
|
|
87
|
+
id: string;
|
|
88
|
+
title: string;
|
|
89
|
+
memoryKey?: string;
|
|
90
|
+
visibility?: string;
|
|
91
|
+
participants: Array<{ userId: string }>;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The name a room's memory is stored under: its memory key, else its title. */
|
|
95
|
+
function topicMemoryName(topic: WikiMemoryTopic): string {
|
|
96
|
+
return topic.memoryKey?.trim() || topic.title;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Find a room whose memory the caller may read. A room is found by id, title,
|
|
101
|
+
* memory name, or the slug `wiki_write` stored that name under. The room the
|
|
102
|
+
* server runs for is always readable, even when the caller is not one of its
|
|
103
|
+
* participants (an archiver acting for a person in a room another principal
|
|
104
|
+
* owns).
|
|
105
|
+
*/
|
|
106
|
+
function findAccessibleMemoryTopic(
|
|
107
|
+
selection: string,
|
|
108
|
+
userId: string,
|
|
109
|
+
topics: WikiMemoryTopic[],
|
|
110
|
+
boundTopicId?: string,
|
|
111
|
+
): WikiMemoryTopic | undefined {
|
|
112
|
+
const normalize = (value: string) => value.trim().toLowerCase();
|
|
113
|
+
const wanted = normalize(selection.replace(/^topic\//, "").replace(/\.md$/i, ""));
|
|
114
|
+
const accessible = topics.filter(
|
|
115
|
+
(topic) =>
|
|
116
|
+
topic.id === boundTopicId ||
|
|
117
|
+
(topic.visibility !== "hidden" &&
|
|
118
|
+
topic.participants.some((participant) => participant.userId === userId)),
|
|
119
|
+
);
|
|
120
|
+
const named = (topic: WikiMemoryTopic) => {
|
|
121
|
+
const memoryName = topicMemoryName(topic);
|
|
122
|
+
return [topic.title, memoryName, wikiSummarySlug(memoryName)].some(
|
|
123
|
+
(name) => normalize(name) === wanted,
|
|
124
|
+
);
|
|
125
|
+
};
|
|
126
|
+
return (
|
|
127
|
+
accessible.find((candidate) => candidate.id === selection) ??
|
|
128
|
+
accessible.find((candidate) => candidate.id === boundTopicId && named(candidate)) ??
|
|
129
|
+
accessible.find(named)
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Read the brief stored under the memory name of the room `selection` finds. */
|
|
134
|
+
export function resolveAccessibleWikiTopicBrief(
|
|
135
|
+
selection: string,
|
|
136
|
+
userId: string,
|
|
137
|
+
topics: WikiMemoryTopic[],
|
|
138
|
+
resolveBrief: (topicId: string, memoryName: string) => { brief: WikiTopicBrief } | null,
|
|
139
|
+
boundTopicId?: string,
|
|
140
|
+
): WikiTopicBrief | null {
|
|
141
|
+
const topic = findAccessibleMemoryTopic(selection, userId, topics, boundTopicId);
|
|
142
|
+
return topic ? (resolveBrief(topic.id, topicMemoryName(topic))?.brief ?? null) : null;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
interface WikiRuntime extends Required<Pick<WikiMcpContext, "userId" | "surface">> {
|
|
146
|
+
currentTopicId?: string;
|
|
147
|
+
topicId?: string;
|
|
148
|
+
host: WikiMcpHost;
|
|
149
|
+
wikiDir: string;
|
|
150
|
+
skillsDir: string;
|
|
151
|
+
topicsDir: string;
|
|
152
|
+
summariesDir: string;
|
|
153
|
+
articlesDir: string;
|
|
154
|
+
archiveDir: string;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const wikiRuntime = new AsyncLocalStorage<WikiRuntime>();
|
|
158
|
+
|
|
159
|
+
function runtime(): WikiRuntime {
|
|
160
|
+
const current = wikiRuntime.getStore();
|
|
161
|
+
if (!current) throw new Error("wiki MCP handler called without a runtime context");
|
|
162
|
+
return current;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function parseArgv(): {
|
|
166
|
+
userId: string;
|
|
167
|
+
currentTopicId?: string;
|
|
168
|
+
topicId?: string;
|
|
169
|
+
surface: WikiSurface;
|
|
170
|
+
} {
|
|
171
|
+
let userId = "local";
|
|
172
|
+
let currentTopicId: string | undefined;
|
|
173
|
+
let topicId: string | undefined;
|
|
174
|
+
let surface: WikiSurface = "all";
|
|
175
|
+
|
|
176
|
+
for (let i = 2; i < argv.length; i++) {
|
|
177
|
+
const a = argv[i];
|
|
178
|
+
if (a.startsWith("--user-id=")) userId = a.slice("--user-id=".length);
|
|
179
|
+
else if (a.startsWith("--current-topic-id=")) {
|
|
180
|
+
currentTopicId = a.slice("--current-topic-id=".length);
|
|
181
|
+
} else if (a.startsWith("--topic-id=")) topicId = a.slice("--topic-id=".length);
|
|
182
|
+
else if (a === "--surface=wiki") surface = "wiki";
|
|
183
|
+
else if (a === "--surface=skills") surface = "skills";
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return { userId, currentTopicId, topicId, surface };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// --- Helpers ---------------------------------------------------------------
|
|
190
|
+
|
|
191
|
+
function ensureDir(dir: string): void {
|
|
192
|
+
mkdirSync(dir, { recursive: true });
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const FILE_LOCK_WAIT_MS = 10;
|
|
196
|
+
const FILE_LOCK_TIMEOUT_MS = 5_000;
|
|
197
|
+
const FILE_LOCK_STALE_MS = 30_000;
|
|
198
|
+
const lockWaitArray = new Int32Array(new SharedArrayBuffer(4));
|
|
199
|
+
|
|
200
|
+
function acquireRecoveryGuard(lockPath: string): () => void {
|
|
201
|
+
const guardPath = `${lockPath}.reclaim`;
|
|
202
|
+
const ownerToken = randomUUID();
|
|
203
|
+
const deadline = Date.now() + FILE_LOCK_TIMEOUT_MS;
|
|
204
|
+
while (true) {
|
|
205
|
+
try {
|
|
206
|
+
const fd = openSync(guardPath, "wx");
|
|
207
|
+
try {
|
|
208
|
+
writeFileSync(fd, ownerToken, "utf-8");
|
|
209
|
+
} catch (error) {
|
|
210
|
+
closeSync(fd);
|
|
211
|
+
try {
|
|
212
|
+
unlinkSync(guardPath);
|
|
213
|
+
} catch {
|
|
214
|
+
// Preserve the original write failure.
|
|
215
|
+
}
|
|
216
|
+
throw error;
|
|
217
|
+
}
|
|
218
|
+
return () => {
|
|
219
|
+
closeSync(fd);
|
|
220
|
+
try {
|
|
221
|
+
if (readFileSync(guardPath, "utf-8") === ownerToken) unlinkSync(guardPath);
|
|
222
|
+
} catch {
|
|
223
|
+
// The guard is already gone.
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
} catch (error) {
|
|
227
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
228
|
+
if (Date.now() >= deadline) {
|
|
229
|
+
throw new Error(`Timed out waiting for wiki lock recovery guard: ${basename(lockPath)}`);
|
|
230
|
+
}
|
|
231
|
+
Atomics.wait(lockWaitArray, 0, 0, FILE_LOCK_WAIT_MS);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function acquireFileLock(path: string): () => void {
|
|
237
|
+
const lockPath = `${path}.lock`;
|
|
238
|
+
const ownerToken = randomUUID();
|
|
239
|
+
const deadline = Date.now() + FILE_LOCK_TIMEOUT_MS;
|
|
240
|
+
while (true) {
|
|
241
|
+
try {
|
|
242
|
+
const fd = openSync(lockPath, "wx");
|
|
243
|
+
try {
|
|
244
|
+
writeFileSync(fd, ownerToken, "utf-8");
|
|
245
|
+
} catch (error) {
|
|
246
|
+
closeSync(fd);
|
|
247
|
+
try {
|
|
248
|
+
unlinkSync(lockPath);
|
|
249
|
+
} catch {
|
|
250
|
+
// Preserve the original write failure.
|
|
251
|
+
}
|
|
252
|
+
throw error;
|
|
253
|
+
}
|
|
254
|
+
return () => {
|
|
255
|
+
closeSync(fd);
|
|
256
|
+
const releaseGuard = acquireRecoveryGuard(lockPath);
|
|
257
|
+
try {
|
|
258
|
+
if (readFileSync(lockPath, "utf-8") === ownerToken) unlinkSync(lockPath);
|
|
259
|
+
} catch {
|
|
260
|
+
// A stale-lock recovery may already have replaced it.
|
|
261
|
+
} finally {
|
|
262
|
+
releaseGuard();
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
} catch (error) {
|
|
266
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
267
|
+
const releaseGuard = acquireRecoveryGuard(lockPath);
|
|
268
|
+
try {
|
|
269
|
+
try {
|
|
270
|
+
const staleToken = readFileSync(lockPath, "utf-8");
|
|
271
|
+
if (
|
|
272
|
+
Date.now() - statSync(lockPath).mtimeMs > FILE_LOCK_STALE_MS &&
|
|
273
|
+
readFileSync(lockPath, "utf-8") === staleToken
|
|
274
|
+
) {
|
|
275
|
+
unlinkSync(lockPath);
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
} catch {
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
} finally {
|
|
282
|
+
releaseGuard();
|
|
283
|
+
}
|
|
284
|
+
if (Date.now() >= deadline) {
|
|
285
|
+
throw new Error(`Timed out waiting for wiki file lock: ${basename(path)}`);
|
|
286
|
+
}
|
|
287
|
+
Atomics.wait(lockWaitArray, 0, 0, FILE_LOCK_WAIT_MS);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function atomicWriteFile(path: string, content: string): void {
|
|
293
|
+
const temporaryPath = `${path}.tmp.${process.pid}.${Date.now()}`;
|
|
294
|
+
writeFileSync(temporaryPath, content, "utf-8");
|
|
295
|
+
try {
|
|
296
|
+
renameSync(temporaryPath, path);
|
|
297
|
+
} catch (error) {
|
|
298
|
+
try {
|
|
299
|
+
unlinkSync(temporaryPath);
|
|
300
|
+
} catch {
|
|
301
|
+
// Best-effort cleanup.
|
|
302
|
+
}
|
|
303
|
+
throw error;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function safeExt<T, K extends string = string>(
|
|
308
|
+
obj: Record<string, unknown> | undefined | null,
|
|
309
|
+
keys: readonly K[],
|
|
310
|
+
fallback: T,
|
|
311
|
+
): T {
|
|
312
|
+
if (!obj || typeof obj !== "object") return fallback;
|
|
313
|
+
for (const key of keys) {
|
|
314
|
+
const value = obj[key];
|
|
315
|
+
if (value !== undefined && value !== null) return value as T;
|
|
316
|
+
}
|
|
317
|
+
return fallback;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function topicNameFrom(topicIdStr: string): string {
|
|
321
|
+
return topicIdStr;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function slugify(topic: string): string {
|
|
325
|
+
return wikiSummarySlug(topic);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// --- Tool handlers (file-based) -------------------------------------------
|
|
329
|
+
|
|
330
|
+
type WikiQueryKind = "all" | "topic" | "article" | "summary";
|
|
331
|
+
|
|
332
|
+
interface WikiIndexCandidate {
|
|
333
|
+
kind: Exclude<WikiQueryKind, "all">;
|
|
334
|
+
key: string;
|
|
335
|
+
description: string;
|
|
336
|
+
date?: string;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
type WikiSearchResultKind = Exclude<WikiQueryKind, "all"> | "skill";
|
|
340
|
+
|
|
341
|
+
interface WikiSearchResult {
|
|
342
|
+
kind: WikiSearchResultKind;
|
|
343
|
+
key: string;
|
|
344
|
+
score: number;
|
|
345
|
+
keyScore: number;
|
|
346
|
+
description?: string;
|
|
347
|
+
date?: string;
|
|
348
|
+
path?: string;
|
|
349
|
+
text?: string;
|
|
350
|
+
title?: string;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function normalizeSearchText(value: string): string {
|
|
354
|
+
return value
|
|
355
|
+
.toLowerCase()
|
|
356
|
+
.replaceAll(/[^a-z0-9가-힣]+/g, " ")
|
|
357
|
+
.trim()
|
|
358
|
+
.replaceAll(/\s+/g, " ");
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function compactSearchText(value: string): string {
|
|
362
|
+
return normalizeSearchText(value).replaceAll(" ", "");
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function trigrams(value: string): Set<string> {
|
|
366
|
+
const compact = compactSearchText(value);
|
|
367
|
+
if (compact.length < 3) return new Set(compact ? [compact] : []);
|
|
368
|
+
const result = new Set<string>();
|
|
369
|
+
for (let i = 0; i <= compact.length - 3; i += 1) result.add(compact.slice(i, i + 3));
|
|
370
|
+
return result;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function fuzzySearchScore(query: string, candidate: string, maximum: number): number {
|
|
374
|
+
const compactQuery = compactSearchText(query);
|
|
375
|
+
const compactCandidate = compactSearchText(candidate);
|
|
376
|
+
if (compactQuery.length < 3 || compactCandidate.length < 3) return 0;
|
|
377
|
+
const similarity = trigramSimilarity(compactQuery, compactCandidate);
|
|
378
|
+
const minimumSimilarity = compactQuery.length <= 4 ? 0.6 : 0.45;
|
|
379
|
+
return similarity >= minimumSimilarity ? similarity * maximum : 0;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const SEARCH_STOP_WORDS = new Set([
|
|
383
|
+
"a",
|
|
384
|
+
"an",
|
|
385
|
+
"and",
|
|
386
|
+
"are",
|
|
387
|
+
"as",
|
|
388
|
+
"at",
|
|
389
|
+
"be",
|
|
390
|
+
"by",
|
|
391
|
+
"for",
|
|
392
|
+
"from",
|
|
393
|
+
"in",
|
|
394
|
+
"is",
|
|
395
|
+
"it",
|
|
396
|
+
"of",
|
|
397
|
+
"on",
|
|
398
|
+
"or",
|
|
399
|
+
"that",
|
|
400
|
+
"the",
|
|
401
|
+
"to",
|
|
402
|
+
"with",
|
|
403
|
+
]);
|
|
404
|
+
|
|
405
|
+
const SEARCH_MONTHS = new Map([
|
|
406
|
+
["january", "01"],
|
|
407
|
+
["jan", "01"],
|
|
408
|
+
["1월", "01"],
|
|
409
|
+
["february", "02"],
|
|
410
|
+
["feb", "02"],
|
|
411
|
+
["2월", "02"],
|
|
412
|
+
["march", "03"],
|
|
413
|
+
["mar", "03"],
|
|
414
|
+
["3월", "03"],
|
|
415
|
+
["april", "04"],
|
|
416
|
+
["apr", "04"],
|
|
417
|
+
["4월", "04"],
|
|
418
|
+
["may", "05"],
|
|
419
|
+
["5월", "05"],
|
|
420
|
+
["june", "06"],
|
|
421
|
+
["jun", "06"],
|
|
422
|
+
["6월", "06"],
|
|
423
|
+
["july", "07"],
|
|
424
|
+
["jul", "07"],
|
|
425
|
+
["7월", "07"],
|
|
426
|
+
["august", "08"],
|
|
427
|
+
["aug", "08"],
|
|
428
|
+
["8월", "08"],
|
|
429
|
+
["september", "09"],
|
|
430
|
+
["sep", "09"],
|
|
431
|
+
["sept", "09"],
|
|
432
|
+
["9월", "09"],
|
|
433
|
+
["october", "10"],
|
|
434
|
+
["oct", "10"],
|
|
435
|
+
["10월", "10"],
|
|
436
|
+
["november", "11"],
|
|
437
|
+
["nov", "11"],
|
|
438
|
+
["11월", "11"],
|
|
439
|
+
["december", "12"],
|
|
440
|
+
["dec", "12"],
|
|
441
|
+
["12월", "12"],
|
|
442
|
+
]);
|
|
443
|
+
|
|
444
|
+
const SEARCH_RECENCY_TERMS = new Set([
|
|
445
|
+
"latest",
|
|
446
|
+
"newest",
|
|
447
|
+
"recent",
|
|
448
|
+
"earliest",
|
|
449
|
+
"oldest",
|
|
450
|
+
"최근",
|
|
451
|
+
"최신",
|
|
452
|
+
"최초",
|
|
453
|
+
"오래된",
|
|
454
|
+
]);
|
|
455
|
+
|
|
456
|
+
function meaningfulSearchTokens(value: string): string[] {
|
|
457
|
+
return normalizeSearchText(value)
|
|
458
|
+
.split(" ")
|
|
459
|
+
.filter((token) => (token.length >= 2 || /^\d+$/.test(token)) && !SEARCH_STOP_WORDS.has(token));
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function canonicalSearchToken(token: string): string {
|
|
463
|
+
return token.length > 4 && token.endsWith("s") ? token.slice(0, -1) : token;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function canonicalSearchTokens(value: string): string[] {
|
|
467
|
+
return meaningfulSearchTokens(value).map(canonicalSearchToken);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function countToken(tokens: string[], token: string): number {
|
|
471
|
+
let count = 0;
|
|
472
|
+
for (const candidate of tokens) if (candidate === token) count += 1;
|
|
473
|
+
return count;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function countPhrase(text: string, phrase: string): number {
|
|
477
|
+
if (!phrase) return 0;
|
|
478
|
+
let count = 0;
|
|
479
|
+
let offset = 0;
|
|
480
|
+
let match = text.indexOf(phrase, offset);
|
|
481
|
+
while (match >= 0) {
|
|
482
|
+
count += 1;
|
|
483
|
+
offset = match + phrase.length;
|
|
484
|
+
match = text.indexOf(phrase, offset);
|
|
485
|
+
}
|
|
486
|
+
return count;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
function summaryTopicIdentity(key: string): string {
|
|
490
|
+
return normalizeSearchText(key.replace(/^\d{4}-\d{2}-\d{2}-/, ""));
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
function scoreSummaryTime(query: string, key: string, title: string): number | null {
|
|
494
|
+
const date = key.match(/^(\d{4})-(\d{2})-(\d{2})/);
|
|
495
|
+
if (!date) return 0;
|
|
496
|
+
const tokens = meaningfulSearchTokens(query);
|
|
497
|
+
const documentDate = `${date[1]}-${date[2]}-${date[3]}`;
|
|
498
|
+
const requestedDateMatch = query.match(/\b(\d{4}) (\d{2}) (\d{2})\b/);
|
|
499
|
+
const requestedDate = requestedDateMatch
|
|
500
|
+
? `${requestedDateMatch[1]}-${requestedDateMatch[2]}-${requestedDateMatch[3]}`
|
|
501
|
+
: undefined;
|
|
502
|
+
const beforeDate = /\bbefore\b/.test(query);
|
|
503
|
+
const afterDate = /\bafter\b/.test(query);
|
|
504
|
+
if (requestedDate && beforeDate && documentDate >= requestedDate) return null;
|
|
505
|
+
if (requestedDate && afterDate && documentDate <= requestedDate) return null;
|
|
506
|
+
const queryYear = tokens.find((token) => /^\d{4}(?:년)?$/.test(token))?.replace(/년$/, "");
|
|
507
|
+
const queryMonth = tokens.map((token) => SEARCH_MONTHS.get(token)).find(Boolean);
|
|
508
|
+
const hasRecencyTerm = tokens.some((token) => SEARCH_RECENCY_TERMS.has(token));
|
|
509
|
+
const yearMatches = !queryYear || queryYear === date[1];
|
|
510
|
+
const monthMatches = !queryMonth || queryMonth === date[2];
|
|
511
|
+
if ((!queryYear && !queryMonth && !hasRecencyTerm) || !yearMatches || !monthMatches) return 0;
|
|
512
|
+
|
|
513
|
+
const normalizedMetadata = `${normalizeSearchText(key)} ${normalizeSearchText(title)}`;
|
|
514
|
+
const contentTokens = tokens.filter(
|
|
515
|
+
(token) =>
|
|
516
|
+
!/^\d{4}(?:년)?$/.test(token) &&
|
|
517
|
+
!SEARCH_MONTHS.has(token) &&
|
|
518
|
+
!SEARCH_RECENCY_TERMS.has(token),
|
|
519
|
+
);
|
|
520
|
+
const contentMatches = contentTokens.filter((token) => normalizedMetadata.includes(token)).length;
|
|
521
|
+
const relationScore = requestedDate && (beforeDate || afterDate) ? 60 : 0;
|
|
522
|
+
const exactDateScore = requestedDate === documentDate ? 90 : 0;
|
|
523
|
+
return 30 + relationScore + exactDateScore + contentMatches * 15;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function trigramSimilarity(left: string, right: string): number {
|
|
527
|
+
const a = trigrams(left);
|
|
528
|
+
const b = trigrams(right);
|
|
529
|
+
if (a.size === 0 || b.size === 0) return 0;
|
|
530
|
+
let overlap = 0;
|
|
531
|
+
for (const gram of a) if (b.has(gram)) overlap += 1;
|
|
532
|
+
return (2 * overlap) / (a.size + b.size);
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const WIKI_SEARCH_INDEX_FILENAME = ".wiki-search-index.sqlite";
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* Open the derived body-search index.
|
|
539
|
+
*
|
|
540
|
+
* The index is a rebuildable cache that is written only by the wiki write path,
|
|
541
|
+
* so a missing or unreadable file is a normal cold state rather than an error:
|
|
542
|
+
* catalog retrieval still works, and `wiki_reindex` refills the bodies.
|
|
543
|
+
*/
|
|
544
|
+
function openWikiSearchIndex(): WikiSearchIndex | undefined {
|
|
545
|
+
const path = resolve(runtime().wikiDir, WIKI_SEARCH_INDEX_FILENAME);
|
|
546
|
+
try {
|
|
547
|
+
return new WikiSearchIndex(path);
|
|
548
|
+
} catch (error) {
|
|
549
|
+
if (!/malformed|not a database|schema/i.test(String(error))) return undefined;
|
|
550
|
+
try {
|
|
551
|
+
resetCorruptWikiSearchIndex(path);
|
|
552
|
+
return new WikiSearchIndex(path);
|
|
553
|
+
} catch {
|
|
554
|
+
return undefined;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** Derive the indexed fields for one document body. */
|
|
560
|
+
function prepareWikiSearchDocument(
|
|
561
|
+
kind: IndexedWikiKind,
|
|
562
|
+
key: string,
|
|
563
|
+
text: string,
|
|
564
|
+
): PreparedWikiSearchDocument {
|
|
565
|
+
const titleLine = text.split("\n").find((line) => /^#+\s*/.test(line)) ?? "";
|
|
566
|
+
const title = titleLine ? titleLine.replace(/^#+\s*/, "") : basename(key);
|
|
567
|
+
return {
|
|
568
|
+
title,
|
|
569
|
+
text,
|
|
570
|
+
tokens: canonicalSearchTokens(`${key} ${title} ${text}`),
|
|
571
|
+
...(kind === "summary" && /^\d{4}-\d{2}-\d{2}/.test(key)
|
|
572
|
+
? { date: key.slice(0, 10), family: summaryTopicIdentity(key) }
|
|
573
|
+
: {}),
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* Mirror a freshly written document into the derived body index.
|
|
579
|
+
*
|
|
580
|
+
* Returns false when the cache could not be updated. The document and its
|
|
581
|
+
* catalog row are already durable at this point, so a cache miss degrades
|
|
582
|
+
* retrieval to catalog-only rather than failing the write.
|
|
583
|
+
*/
|
|
584
|
+
function indexWikiSearchDocument(kind: IndexedWikiKind, key: string, text: string): boolean {
|
|
585
|
+
const root = kind === "article" ? runtime().articlesDir : runtime().summariesDir;
|
|
586
|
+
const path = resolve(root, `${key}.md`);
|
|
587
|
+
const index = openWikiSearchIndex();
|
|
588
|
+
if (!index) return false;
|
|
589
|
+
try {
|
|
590
|
+
const stat = statSync(path);
|
|
591
|
+
index.upsert(
|
|
592
|
+
{ kind, key, path, mtimeMs: stat.mtimeMs, size: stat.size },
|
|
593
|
+
prepareWikiSearchDocument(kind, key, text),
|
|
594
|
+
);
|
|
595
|
+
return true;
|
|
596
|
+
} catch {
|
|
597
|
+
return false;
|
|
598
|
+
} finally {
|
|
599
|
+
index.close();
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
type WikiIndexKind = "article" | "summary" | "topic" | "skill";
|
|
604
|
+
|
|
605
|
+
const WIKI_INDEX_FILENAMES: Record<WikiIndexKind, string> = {
|
|
606
|
+
article: "article-index.md",
|
|
607
|
+
summary: "summary-index.md",
|
|
608
|
+
topic: "topic-index.md",
|
|
609
|
+
skill: "skill-index.md",
|
|
610
|
+
};
|
|
611
|
+
|
|
612
|
+
const WIKI_INDEX_NAMESPACES: Record<WikiIndexKind, string> = {
|
|
613
|
+
article: "articles",
|
|
614
|
+
summary: "summaries",
|
|
615
|
+
topic: "topic",
|
|
616
|
+
skill: "skills",
|
|
617
|
+
};
|
|
618
|
+
|
|
619
|
+
/** Resolve the human-readable catalog that owns a given entry kind. */
|
|
620
|
+
function wikiIndexPath(kind: WikiIndexKind): string {
|
|
621
|
+
return resolve(runtime().wikiDir, WIKI_INDEX_FILENAMES[kind]);
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
const MAX_INDEX_DESCRIPTION_LENGTH = 400;
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* Reduce a caller-supplied description to a single catalog line.
|
|
628
|
+
*
|
|
629
|
+
* Catalog rows are line-oriented, so an embedded newline would split one entry
|
|
630
|
+
* into an unparsable fragment. Rejecting empty text here is what keeps index
|
|
631
|
+
* quality a schema guarantee rather than a prompt convention.
|
|
632
|
+
*/
|
|
633
|
+
function normalizeIndexDescription(raw: string): { description: string } | { error: string } {
|
|
634
|
+
const description = raw.replaceAll(/\s+/g, " ").trim();
|
|
635
|
+
if (!description) return { error: "A non-empty one-line description is required." };
|
|
636
|
+
if (description.length > MAX_INDEX_DESCRIPTION_LENGTH) {
|
|
637
|
+
return {
|
|
638
|
+
error: `Description must be at most ${MAX_INDEX_DESCRIPTION_LENGTH} characters (got ${description.length}).`,
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
return { description };
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/** Reject slugs that would escape their content directory or break a wikilink. */
|
|
645
|
+
function normalizeWikiSlug(raw: string): { slug: string } | { error: string } {
|
|
646
|
+
const slug = raw.trim().replace(/\.md$/i, "").replace(/^\/+/, "");
|
|
647
|
+
if (!slug) return { error: "A non-empty slug is required." };
|
|
648
|
+
if (/[[\]|\\]/.test(slug)) return { error: "Slug must not contain [ ] | or backslashes." };
|
|
649
|
+
if (slug.split("/").some((segment) => segment === "" || segment === "." || segment === "..")) {
|
|
650
|
+
return { error: "Slug must not contain empty or relative path segments." };
|
|
651
|
+
}
|
|
652
|
+
return { slug };
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
function parseWikiIndex(path: string): WikiIndexCandidate[] {
|
|
656
|
+
let text: string;
|
|
657
|
+
try {
|
|
658
|
+
text = readFileSync(path, "utf-8");
|
|
659
|
+
} catch {
|
|
660
|
+
return [];
|
|
661
|
+
}
|
|
662
|
+
const candidates: WikiIndexCandidate[] = [];
|
|
663
|
+
const entryPattern = /^\s*-\s*\[\[(topic|articles|summaries)\/([^\]]+)\]\]\s*(.*)$/;
|
|
664
|
+
for (const line of text.split("\n")) {
|
|
665
|
+
const match = line.match(entryPattern);
|
|
666
|
+
if (!match) continue;
|
|
667
|
+
const namespace = match[1]!;
|
|
668
|
+
const key = match[2]!.replace(/\.md$/i, "");
|
|
669
|
+
const tail = match[3]!.trim();
|
|
670
|
+
const dateMatch = tail.match(/\((\d{4}-\d{2}-\d{2})(?:[^)]*)\)\s*$/);
|
|
671
|
+
const description = dateMatch ? tail.slice(0, dateMatch.index).trim() : tail;
|
|
672
|
+
candidates.push({
|
|
673
|
+
kind: namespace === "topic" ? "topic" : namespace === "articles" ? "article" : "summary",
|
|
674
|
+
key,
|
|
675
|
+
description,
|
|
676
|
+
...(dateMatch ? { date: dateMatch[1] } : {}),
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
return candidates;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
function indexCandidateExists(candidate: WikiIndexCandidate): boolean {
|
|
683
|
+
// Topic indexes may point at canonical DB-backed memories rather than local files.
|
|
684
|
+
if (candidate.kind === "topic") return true;
|
|
685
|
+
const root = candidate.kind === "article" ? runtime().articlesDir : runtime().summariesDir;
|
|
686
|
+
const filePath = resolve(root, `${candidate.key}.md`);
|
|
687
|
+
const relativePath = relative(root, filePath);
|
|
688
|
+
if (relativePath.startsWith("..") || relativePath.startsWith("/")) return false;
|
|
689
|
+
try {
|
|
690
|
+
return statSync(filePath).isFile();
|
|
691
|
+
} catch {
|
|
692
|
+
return false;
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
function scoreIndexKey(query: string, key: string): number {
|
|
697
|
+
const normalizedQuery = normalizeSearchText(query);
|
|
698
|
+
const compactQuery = compactSearchText(normalizedQuery);
|
|
699
|
+
const normalizedKey = normalizeSearchText(key);
|
|
700
|
+
const compactKey = compactSearchText(normalizedKey);
|
|
701
|
+
const tokens = meaningfulSearchTokens(normalizedQuery);
|
|
702
|
+
let score = 0;
|
|
703
|
+
if (normalizedKey === normalizedQuery) score += 120;
|
|
704
|
+
else if (compactKey === compactQuery) score += 110;
|
|
705
|
+
else {
|
|
706
|
+
if (
|
|
707
|
+
compactQuery.length >= 2 &&
|
|
708
|
+
(compactKey.startsWith(compactQuery) || compactQuery.startsWith(compactKey))
|
|
709
|
+
) {
|
|
710
|
+
score += 65;
|
|
711
|
+
}
|
|
712
|
+
if (tokens.length > 0 && compactQuery.length >= 3 && compactKey.includes(compactQuery)) {
|
|
713
|
+
score += 45;
|
|
714
|
+
}
|
|
715
|
+
score += fuzzySearchScore(compactQuery, compactKey, 55);
|
|
716
|
+
}
|
|
717
|
+
for (const token of tokens) {
|
|
718
|
+
if (normalizedKey.includes(token)) score += 10;
|
|
719
|
+
}
|
|
720
|
+
return score;
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
function scoreIndexCandidate(query: string, candidate: WikiIndexCandidate): number {
|
|
724
|
+
const normalizedQuery = normalizeSearchText(query);
|
|
725
|
+
if (!normalizedQuery) return 0;
|
|
726
|
+
const normalizedDescription = normalizeSearchText(candidate.description);
|
|
727
|
+
const tokens = canonicalSearchTokens(normalizedQuery);
|
|
728
|
+
const descriptionTokens = new Set(canonicalSearchTokens(normalizedDescription));
|
|
729
|
+
let score = scoreIndexKey(normalizedQuery, candidate.key);
|
|
730
|
+
if (tokens.length > 0 && normalizedDescription.includes(normalizedQuery)) score += 30;
|
|
731
|
+
let descriptionMatches = 0;
|
|
732
|
+
for (const token of tokens) {
|
|
733
|
+
if (descriptionTokens.has(token)) {
|
|
734
|
+
score += 5;
|
|
735
|
+
descriptionMatches += 1;
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
if (tokens.length > 1 && descriptionMatches === tokens.length) score += 25;
|
|
739
|
+
if (candidate.kind === "topic") {
|
|
740
|
+
const requestsCurrent = /\b(?:current|active|ongoing|open)\b|현재|진행 중/.test(
|
|
741
|
+
normalizedQuery,
|
|
742
|
+
);
|
|
743
|
+
const archivedCandidate = /\b(?:archive|archived|historical|closed)\b|보관|종료/.test(
|
|
744
|
+
`${normalizeSearchText(candidate.key)} ${normalizedDescription}`,
|
|
745
|
+
);
|
|
746
|
+
if (requestsCurrent && archivedCandidate) score -= 40;
|
|
747
|
+
}
|
|
748
|
+
return score;
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
function wikiQuery(args: Record<string, unknown>): CallToolResult {
|
|
752
|
+
const question = String(safeExt(args, ["question", "query", "q", "text"], "")).trim();
|
|
753
|
+
const requestedKind = String(safeExt(args, ["kind", "type"], "all"));
|
|
754
|
+
const kind: WikiQueryKind =
|
|
755
|
+
requestedKind === "topic" || requestedKind === "article" || requestedKind === "summary"
|
|
756
|
+
? requestedKind
|
|
757
|
+
: "all";
|
|
758
|
+
const requestedLimit = Number(safeExt(args, ["limit", "maxResults"], 8));
|
|
759
|
+
const limit = Math.min(Math.max(Number.isFinite(requestedLimit) ? requestedLimit : 8, 1), 20);
|
|
760
|
+
if (!question) {
|
|
761
|
+
return {
|
|
762
|
+
content: [{ type: "text", text: "A non-empty wiki query is required." }],
|
|
763
|
+
isError: true,
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
const normalizedQuery = normalizeSearchText(question);
|
|
767
|
+
if (!normalizedQuery) {
|
|
768
|
+
return { content: [{ type: "text", text: "No matching wiki articles found." }] };
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
const canReadTopicMemory = runtime().host.canReadTopicMemory;
|
|
772
|
+
const temporalDirection = /\b(?:latest|newest|recent)\b|최근|최신/.test(normalizedQuery)
|
|
773
|
+
? "newest"
|
|
774
|
+
: /\b(?:earliest|oldest)\b|가장 오래된|최초/.test(normalizedQuery)
|
|
775
|
+
? "oldest"
|
|
776
|
+
: undefined;
|
|
777
|
+
|
|
778
|
+
const visibleIndexCandidates = [
|
|
779
|
+
...parseWikiIndex(resolve(runtime().wikiDir, "topic-index.md")),
|
|
780
|
+
...parseWikiIndex(resolve(runtime().wikiDir, "article-index.md")),
|
|
781
|
+
]
|
|
782
|
+
.filter((candidate) => kind === "all" || candidate.kind === kind)
|
|
783
|
+
.filter(
|
|
784
|
+
(candidate) =>
|
|
785
|
+
candidate.kind !== "topic" ||
|
|
786
|
+
!canReadTopicMemory ||
|
|
787
|
+
canReadTopicMemory(candidate.key, runtime().userId, runtime().topicId),
|
|
788
|
+
);
|
|
789
|
+
const hasStaleExactIndexMatch = visibleIndexCandidates.some(
|
|
790
|
+
(candidate) =>
|
|
791
|
+
!indexCandidateExists(candidate) && scoreIndexKey(question, candidate.key) >= 100,
|
|
792
|
+
);
|
|
793
|
+
const indexCandidates = visibleIndexCandidates
|
|
794
|
+
.filter(indexCandidateExists)
|
|
795
|
+
.map((candidate) => ({
|
|
796
|
+
candidate,
|
|
797
|
+
keyScore: scoreIndexKey(question, candidate.key),
|
|
798
|
+
score: scoreIndexCandidate(question, candidate),
|
|
799
|
+
}))
|
|
800
|
+
.filter(({ keyScore, score }) => keyScore >= 25 || score >= 40)
|
|
801
|
+
.sort(
|
|
802
|
+
(left, right) =>
|
|
803
|
+
right.score - left.score || left.candidate.key.localeCompare(right.candidate.key),
|
|
804
|
+
);
|
|
805
|
+
|
|
806
|
+
const strongestIndex = indexCandidates[0];
|
|
807
|
+
if (
|
|
808
|
+
kind === "topic" &&
|
|
809
|
+
strongestIndex &&
|
|
810
|
+
(strongestIndex.keyScore >= 25 || strongestIndex.score >= 40)
|
|
811
|
+
) {
|
|
812
|
+
const runnerUp = indexCandidates[1];
|
|
813
|
+
const ambiguous =
|
|
814
|
+
strongestIndex.keyScore < 100 &&
|
|
815
|
+
runnerUp !== undefined &&
|
|
816
|
+
runnerUp.score >= strongestIndex.score * 0.9;
|
|
817
|
+
if (ambiguous) {
|
|
818
|
+
const lines = ["Found 2 ambiguous wiki candidates:", ""];
|
|
819
|
+
for (const { candidate, score } of [strongestIndex, runnerUp]) {
|
|
820
|
+
lines.push(
|
|
821
|
+
`- kind: ${candidate.kind}`,
|
|
822
|
+
` key: ${candidate.key}`,
|
|
823
|
+
` score: ${score.toFixed(2)}`,
|
|
824
|
+
` description: ${candidate.description || "(none)"}`,
|
|
825
|
+
...(candidate.date ? [` date: ${candidate.date}`] : []),
|
|
826
|
+
);
|
|
827
|
+
}
|
|
828
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
829
|
+
}
|
|
830
|
+
const lines = ["Found 1 wiki candidate:", ""];
|
|
831
|
+
for (const { candidate, score } of [strongestIndex]) {
|
|
832
|
+
lines.push(
|
|
833
|
+
`- kind: ${candidate.kind}`,
|
|
834
|
+
` key: ${candidate.key}`,
|
|
835
|
+
` score: ${score.toFixed(2)}`,
|
|
836
|
+
` description: ${candidate.description || "(none)"}`,
|
|
837
|
+
...(candidate.date ? [` date: ${candidate.date}`] : []),
|
|
838
|
+
);
|
|
839
|
+
}
|
|
840
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
const results: string[] = [];
|
|
844
|
+
const scored: WikiSearchResult[] = [];
|
|
845
|
+
|
|
846
|
+
function scan(dir: string, label: string): void {
|
|
847
|
+
ensureDir(dir);
|
|
848
|
+
try {
|
|
849
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
850
|
+
if (entry.isDirectory()) {
|
|
851
|
+
const sub = join(dir, entry.name);
|
|
852
|
+
// Limit depth: only go one level deep for articles/skills
|
|
853
|
+
if (label === "articles" || label === "skills") {
|
|
854
|
+
try {
|
|
855
|
+
for (const f of readdirSync(sub, { withFileTypes: true })) {
|
|
856
|
+
if (!f.isFile() || !f.name.endsWith(".md")) continue;
|
|
857
|
+
const fp = join(sub, f.name);
|
|
858
|
+
try {
|
|
859
|
+
const text = readFileSync(fp, "utf-8");
|
|
860
|
+
const key = `${entry.name}/${f.name.replace(/\.md$/i, "")}`;
|
|
861
|
+
scored.push({
|
|
862
|
+
kind: label === "articles" ? "article" : "skill",
|
|
863
|
+
key,
|
|
864
|
+
keyScore: scoreIndexKey(question, key),
|
|
865
|
+
score: scoreMatch(text, key, label === "articles" ? "article" : "skill"),
|
|
866
|
+
path: `${label}/${entry.name}/${f.name}`,
|
|
867
|
+
text,
|
|
868
|
+
title: titleFromDocument(text, key),
|
|
869
|
+
});
|
|
870
|
+
} catch {
|
|
871
|
+
/* skip unreadable */
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
} catch {
|
|
875
|
+
/* skip unreadable dir */
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
} else if (entry.isFile() && entry.name.endsWith(".md")) {
|
|
879
|
+
if (
|
|
880
|
+
label === "topic" &&
|
|
881
|
+
canReadTopicMemory &&
|
|
882
|
+
!canReadTopicMemory(entry.name.replace(/\.md$/i, ""), runtime().userId)
|
|
883
|
+
) {
|
|
884
|
+
continue;
|
|
885
|
+
}
|
|
886
|
+
const fp = join(dir, entry.name);
|
|
887
|
+
try {
|
|
888
|
+
const text = readFileSync(fp, "utf-8");
|
|
889
|
+
const key = entry.name.replace(/\.md$/i, "");
|
|
890
|
+
const resultKind =
|
|
891
|
+
label === "articles"
|
|
892
|
+
? "article"
|
|
893
|
+
: label === "topic"
|
|
894
|
+
? "topic"
|
|
895
|
+
: label === "summaries"
|
|
896
|
+
? "summary"
|
|
897
|
+
: "skill";
|
|
898
|
+
scored.push({
|
|
899
|
+
kind: resultKind,
|
|
900
|
+
key,
|
|
901
|
+
keyScore: scoreIndexKey(question, key),
|
|
902
|
+
score: scoreMatch(text, key, resultKind),
|
|
903
|
+
path: `${label}/${entry.name}`,
|
|
904
|
+
text,
|
|
905
|
+
title: titleFromDocument(text, key),
|
|
906
|
+
...(label === "summaries" && /^\d{4}-\d{2}-\d{2}/.test(key)
|
|
907
|
+
? { date: key.slice(0, 10) }
|
|
908
|
+
: {}),
|
|
909
|
+
});
|
|
910
|
+
} catch {
|
|
911
|
+
/* skip unreadable */
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
} catch {
|
|
916
|
+
/* dir may not exist */
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
function titleFromDocument(text: string, key: string): string {
|
|
921
|
+
const titleLine = text.split("\n").find((line) => /^#+\s*/.test(line));
|
|
922
|
+
return titleLine ? titleLine.replace(/^#+\s*/, "") : basename(key);
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
function scoreMatch(text: string, key: string, resultKind: WikiSearchResultKind): number {
|
|
926
|
+
const titleLine = text.split("\n").find((line) => /^#+\s*/.test(line)) ?? "";
|
|
927
|
+
const title = titleLine.replace(/^#+\s*/, "");
|
|
928
|
+
const normalizedKey = normalizeSearchText(key);
|
|
929
|
+
const normalizedTitle = normalizeSearchText(title);
|
|
930
|
+
const normalizedBody = normalizeSearchText(text.replace(titleLine, ""));
|
|
931
|
+
const compactQuery = compactSearchText(normalizedQuery);
|
|
932
|
+
const compactKey = compactSearchText(normalizedKey);
|
|
933
|
+
const compactTitle = compactSearchText(normalizedTitle);
|
|
934
|
+
const tokens = canonicalSearchTokens(normalizedQuery);
|
|
935
|
+
const keyTokens = new Set(canonicalSearchTokens(normalizedKey));
|
|
936
|
+
const titleTokens = new Set(canonicalSearchTokens(normalizedTitle));
|
|
937
|
+
const bodyTokens = canonicalSearchTokens(normalizedBody);
|
|
938
|
+
let score = 0;
|
|
939
|
+
let strongMetadataEvidence = false;
|
|
940
|
+
|
|
941
|
+
if (normalizedKey === normalizedQuery) {
|
|
942
|
+
score += 120;
|
|
943
|
+
strongMetadataEvidence = true;
|
|
944
|
+
} else if (compactKey === compactQuery) {
|
|
945
|
+
score += 110;
|
|
946
|
+
strongMetadataEvidence = true;
|
|
947
|
+
} else if (
|
|
948
|
+
compactQuery.length >= 2 &&
|
|
949
|
+
(compactKey.startsWith(compactQuery) || compactQuery.startsWith(compactKey))
|
|
950
|
+
) {
|
|
951
|
+
score += 65;
|
|
952
|
+
strongMetadataEvidence = true;
|
|
953
|
+
}
|
|
954
|
+
if (tokens.length > 0 && compactQuery.length >= 3 && compactKey.includes(compactQuery)) {
|
|
955
|
+
score += 45;
|
|
956
|
+
strongMetadataEvidence = true;
|
|
957
|
+
}
|
|
958
|
+
const fuzzyKeyScore = fuzzySearchScore(compactQuery, compactKey, 55);
|
|
959
|
+
score += fuzzyKeyScore;
|
|
960
|
+
if (fuzzyKeyScore > 0) strongMetadataEvidence = true;
|
|
961
|
+
|
|
962
|
+
if (normalizedTitle === normalizedQuery) {
|
|
963
|
+
score += 115;
|
|
964
|
+
strongMetadataEvidence = true;
|
|
965
|
+
} else if (compactTitle === compactQuery) {
|
|
966
|
+
score += 105;
|
|
967
|
+
strongMetadataEvidence = true;
|
|
968
|
+
} else if (compactQuery.length >= 2 && compactTitle.startsWith(compactQuery)) {
|
|
969
|
+
score += 60;
|
|
970
|
+
strongMetadataEvidence = true;
|
|
971
|
+
}
|
|
972
|
+
const fuzzyTitleScore = fuzzySearchScore(compactQuery, compactTitle, 50);
|
|
973
|
+
score += fuzzyTitleScore;
|
|
974
|
+
if (fuzzyTitleScore > 0) strongMetadataEvidence = true;
|
|
975
|
+
if (resultKind === "summary") {
|
|
976
|
+
const temporalScore = scoreSummaryTime(normalizedQuery, key, title);
|
|
977
|
+
if (temporalScore === null) return 0;
|
|
978
|
+
score += temporalScore;
|
|
979
|
+
if (temporalScore > 0) strongMetadataEvidence = true;
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
const isMultiToken = tokens.length > 1;
|
|
983
|
+
if (tokens.length > 0 && normalizedTitle.includes(normalizedQuery)) {
|
|
984
|
+
score += 35;
|
|
985
|
+
strongMetadataEvidence = true;
|
|
986
|
+
}
|
|
987
|
+
const phraseMatches = isMultiToken ? countPhrase(normalizedBody, normalizedQuery) : 0;
|
|
988
|
+
if (phraseMatches > 0) score += phraseMatches * 12;
|
|
989
|
+
else if (tokens.length === 1 && tokens[0]!.length >= 5 && normalizedBody.includes(tokens[0]!)) {
|
|
990
|
+
score += 16;
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
let bodyMatches = 0;
|
|
994
|
+
let minimumBodyFrequency = Number.POSITIVE_INFINITY;
|
|
995
|
+
for (const token of tokens) {
|
|
996
|
+
if (keyTokens.has(token)) score += 10;
|
|
997
|
+
if (titleTokens.has(token)) score += 12;
|
|
998
|
+
const bodyFrequency = countToken(bodyTokens, token);
|
|
999
|
+
if (bodyFrequency > 0) {
|
|
1000
|
+
score += Math.min(bodyFrequency, 3) * 4;
|
|
1001
|
+
bodyMatches += 1;
|
|
1002
|
+
minimumBodyFrequency = Math.min(minimumBodyFrequency, bodyFrequency);
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
if (isMultiToken && bodyMatches === tokens.length) {
|
|
1006
|
+
score += 8 * Math.min(minimumBodyFrequency, 3);
|
|
1007
|
+
}
|
|
1008
|
+
const minimumBodyTokens = hasStaleExactIndexMatch ? 3 : 2;
|
|
1009
|
+
const partialArticleEvidence =
|
|
1010
|
+
resultKind === "article" && bodyMatches >= 3 && bodyMatches / tokens.length >= 0.6;
|
|
1011
|
+
const strongBodyEvidence =
|
|
1012
|
+
tokens.length >= minimumBodyTokens &&
|
|
1013
|
+
((bodyMatches === tokens.length && (phraseMatches > 0 || minimumBodyFrequency >= 1)) ||
|
|
1014
|
+
partialArticleEvidence);
|
|
1015
|
+
if (!strongMetadataEvidence && !strongBodyEvidence) return 0;
|
|
1016
|
+
return score;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
// Article and summary bodies come from the derived index, which the write path
|
|
1020
|
+
// keeps current. Reading every file here is what made retrieval cost grow with
|
|
1021
|
+
// the size of the wiki.
|
|
1022
|
+
const bodyKinds: IndexedWikiKind[] = [
|
|
1023
|
+
...(kind === "all" || kind === "article" ? (["article"] as const) : []),
|
|
1024
|
+
...(kind === "all" || kind === "summary" ? (["summary"] as const) : []),
|
|
1025
|
+
];
|
|
1026
|
+
if (bodyKinds.length > 0) {
|
|
1027
|
+
const searchIndex = openWikiSearchIndex();
|
|
1028
|
+
if (searchIndex) {
|
|
1029
|
+
try {
|
|
1030
|
+
const terms = canonicalSearchTokens(normalizedQuery);
|
|
1031
|
+
const ids = searchIndex.matchingDocumentIds(bodyKinds, terms);
|
|
1032
|
+
// "latest summary" carries no term any document contains, so a purely
|
|
1033
|
+
// temporal question is answered from the indexed dates instead.
|
|
1034
|
+
if (temporalDirection && bodyKinds.includes("summary")) {
|
|
1035
|
+
for (const item of searchIndex.summaryMetadataByDate({
|
|
1036
|
+
direction: temporalDirection === "newest" ? "latest" : "oldest",
|
|
1037
|
+
limit,
|
|
1038
|
+
})) {
|
|
1039
|
+
ids.add(item.id);
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
for (const document of searchIndex.documents(ids)) {
|
|
1043
|
+
scored.push({
|
|
1044
|
+
kind: document.kind,
|
|
1045
|
+
key: document.key,
|
|
1046
|
+
keyScore: scoreIndexKey(question, document.key),
|
|
1047
|
+
score: scoreMatch(document.text, document.key, document.kind),
|
|
1048
|
+
path: `${document.kind === "article" ? "articles" : "summaries"}/${document.key}.md`,
|
|
1049
|
+
text: document.text,
|
|
1050
|
+
title: document.title,
|
|
1051
|
+
...(document.date ? { date: document.date } : {}),
|
|
1052
|
+
});
|
|
1053
|
+
}
|
|
1054
|
+
} catch {
|
|
1055
|
+
// A damaged cache must not make catalog retrieval unavailable.
|
|
1056
|
+
} finally {
|
|
1057
|
+
searchIndex.close();
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
// Topic briefs and skills are small, node-local sets that no derived index
|
|
1062
|
+
// covers, so they are still read directly. Skills stay out of the explicit
|
|
1063
|
+
// wiki surface: they are node runtime knowledge, not canonical memory.
|
|
1064
|
+
if (kind === "all" && runtime().surface === "all") scan(runtime().skillsDir, "skills");
|
|
1065
|
+
if (kind === "all" || kind === "topic") scan(runtime().topicsDir, "topic");
|
|
1066
|
+
|
|
1067
|
+
const merged = new Map<string, WikiSearchResult>();
|
|
1068
|
+
for (const { candidate, keyScore, score } of indexCandidates) {
|
|
1069
|
+
merged.set(`${candidate.kind}:${candidate.key}`, {
|
|
1070
|
+
kind: candidate.kind,
|
|
1071
|
+
key: candidate.key,
|
|
1072
|
+
keyScore,
|
|
1073
|
+
score,
|
|
1074
|
+
description: candidate.description,
|
|
1075
|
+
date: candidate.date,
|
|
1076
|
+
});
|
|
1077
|
+
}
|
|
1078
|
+
const documentThreshold = kind === "topic" ? 24 : 16;
|
|
1079
|
+
for (const document of scored) {
|
|
1080
|
+
if (document.score < documentThreshold) continue;
|
|
1081
|
+
const id = `${document.kind}:${document.key}`;
|
|
1082
|
+
const indexed = merged.get(id);
|
|
1083
|
+
merged.set(
|
|
1084
|
+
id,
|
|
1085
|
+
indexed
|
|
1086
|
+
? { ...indexed, ...document, score: Math.max(indexed.score, document.score) }
|
|
1087
|
+
: document,
|
|
1088
|
+
);
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
let ranked = [...merged.values()].sort(
|
|
1092
|
+
(left, right) =>
|
|
1093
|
+
right.score - left.score ||
|
|
1094
|
+
(left.kind === "summary" && right.kind === "summary"
|
|
1095
|
+
? temporalDirection === "oldest"
|
|
1096
|
+
? (left.date ?? "").localeCompare(right.date ?? "")
|
|
1097
|
+
: (right.date ?? "").localeCompare(left.date ?? "")
|
|
1098
|
+
: 0) ||
|
|
1099
|
+
left.key.localeCompare(right.key),
|
|
1100
|
+
);
|
|
1101
|
+
|
|
1102
|
+
if (kind === "summary") {
|
|
1103
|
+
const sameTopic = ranked.filter((result) => {
|
|
1104
|
+
const identity = summaryTopicIdentity(result.key);
|
|
1105
|
+
return identity.length >= 3 && normalizedQuery.includes(identity);
|
|
1106
|
+
});
|
|
1107
|
+
if (sameTopic.length > 0) ranked = sameTopic;
|
|
1108
|
+
|
|
1109
|
+
const requestedDateMatch = normalizedQuery.match(/\b(\d{4}) (\d{2}) (\d{2})\b/);
|
|
1110
|
+
const requestedDate = requestedDateMatch
|
|
1111
|
+
? `${requestedDateMatch[1]}-${requestedDateMatch[2]}-${requestedDateMatch[3]}`
|
|
1112
|
+
: undefined;
|
|
1113
|
+
const beforeDate = /\bbefore\b/.test(normalizedQuery);
|
|
1114
|
+
const afterDate = /\bafter\b/.test(normalizedQuery);
|
|
1115
|
+
if (requestedDate && beforeDate) {
|
|
1116
|
+
ranked = ranked.filter((result) => !result.date || result.date < requestedDate);
|
|
1117
|
+
} else if (requestedDate && afterDate) {
|
|
1118
|
+
ranked = ranked.filter((result) => !result.date || result.date > requestedDate);
|
|
1119
|
+
}
|
|
1120
|
+
ranked.sort((left, right) => {
|
|
1121
|
+
if (beforeDate) {
|
|
1122
|
+
return (right.date ?? "").localeCompare(left.date ?? "") || right.score - left.score;
|
|
1123
|
+
}
|
|
1124
|
+
if (afterDate) {
|
|
1125
|
+
return (left.date ?? "").localeCompare(right.date ?? "") || right.score - left.score;
|
|
1126
|
+
}
|
|
1127
|
+
if (requestedDate) {
|
|
1128
|
+
const dateDifference =
|
|
1129
|
+
Number(right.date === requestedDate) - Number(left.date === requestedDate);
|
|
1130
|
+
if (dateDifference !== 0) return dateDifference;
|
|
1131
|
+
}
|
|
1132
|
+
if (temporalDirection) {
|
|
1133
|
+
const dateDifference =
|
|
1134
|
+
temporalDirection === "oldest"
|
|
1135
|
+
? (left.date ?? "").localeCompare(right.date ?? "")
|
|
1136
|
+
: (right.date ?? "").localeCompare(left.date ?? "");
|
|
1137
|
+
if (dateDifference !== 0) return dateDifference;
|
|
1138
|
+
}
|
|
1139
|
+
return (
|
|
1140
|
+
right.score - left.score ||
|
|
1141
|
+
(right.date ?? "").localeCompare(left.date ?? "") ||
|
|
1142
|
+
left.key.localeCompare(right.key)
|
|
1143
|
+
);
|
|
1144
|
+
});
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
if (kind === "topic" && ranked[0]) {
|
|
1148
|
+
const runnerUp = ranked[1];
|
|
1149
|
+
const ambiguous =
|
|
1150
|
+
ranked[0].keyScore < 100 && runnerUp !== undefined && runnerUp.score >= ranked[0].score * 0.9;
|
|
1151
|
+
if (ambiguous) {
|
|
1152
|
+
ranked = ranked.slice(0, 2);
|
|
1153
|
+
} else {
|
|
1154
|
+
ranked = ranked.slice(0, 1);
|
|
1155
|
+
}
|
|
1156
|
+
} else {
|
|
1157
|
+
ranked = ranked.slice(0, limit);
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
if (ranked.length === 0) {
|
|
1161
|
+
results.push("No matching wiki articles found.");
|
|
1162
|
+
} else {
|
|
1163
|
+
results.push(`Found ${ranked.length} matching result(s):\n`);
|
|
1164
|
+
for (const result of ranked) {
|
|
1165
|
+
if (result.kind === "skill") {
|
|
1166
|
+
const body = (result.text ?? "").trim().slice(0, 400);
|
|
1167
|
+
results.push(
|
|
1168
|
+
`## ${result.title ?? result.key}\nPath: ${result.path}\n\n${body}${(result.text?.length ?? 0) > 400 ? "\n...(truncated)" : ""}\n`,
|
|
1169
|
+
);
|
|
1170
|
+
continue;
|
|
1171
|
+
}
|
|
1172
|
+
results.push(
|
|
1173
|
+
`- kind: ${result.kind}`,
|
|
1174
|
+
` key: ${result.key}`,
|
|
1175
|
+
` score: ${result.score.toFixed(2)}`,
|
|
1176
|
+
...(result.title ? [` title: ${result.title}`] : []),
|
|
1177
|
+
` description: ${result.description || "(none)"}`,
|
|
1178
|
+
...(result.date ? [` date: ${result.date}`] : []),
|
|
1179
|
+
...(result.path ? [` path: ${result.path}`, ` Path: ${result.path}`] : []),
|
|
1180
|
+
...(result.text
|
|
1181
|
+
? [
|
|
1182
|
+
` excerpt: ${result.text
|
|
1183
|
+
.replace(/^---[\s\S]*?---\n?/, "")
|
|
1184
|
+
.replace(/^#.*$/m, "")
|
|
1185
|
+
.trim()
|
|
1186
|
+
.slice(0, 400)}`,
|
|
1187
|
+
]
|
|
1188
|
+
: []),
|
|
1189
|
+
);
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
return { content: [{ type: "text", text: results.join("\n") }] };
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
function wikiTopicBrief(args: Record<string, unknown>): CallToolResult {
|
|
1197
|
+
const rawTopic = safeExt<string | undefined>(
|
|
1198
|
+
args,
|
|
1199
|
+
["topic", "topicName", "topicId"],
|
|
1200
|
+
runtime().topicId,
|
|
1201
|
+
);
|
|
1202
|
+
if (!rawTopic) {
|
|
1203
|
+
return {
|
|
1204
|
+
content: [
|
|
1205
|
+
{
|
|
1206
|
+
type: "text",
|
|
1207
|
+
text: "No topic specified (provide --topic-id or topic arg).",
|
|
1208
|
+
},
|
|
1209
|
+
],
|
|
1210
|
+
};
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
const { getTopicBrief, resolveTopicBrief } = runtime().host;
|
|
1214
|
+
const hasAuthorizedBridge = Boolean(runtime().topicId && (getTopicBrief || resolveTopicBrief));
|
|
1215
|
+
if (hasAuthorizedBridge) {
|
|
1216
|
+
try {
|
|
1217
|
+
const brief = resolveTopicBrief
|
|
1218
|
+
? resolveTopicBrief(rawTopic, runtime().userId, runtime().topicId)
|
|
1219
|
+
: getTopicBrief!(rawTopic);
|
|
1220
|
+
if (brief) {
|
|
1221
|
+
const lines = [
|
|
1222
|
+
`# Topic Brief: ${topicNameFrom(rawTopic)}`,
|
|
1223
|
+
"",
|
|
1224
|
+
brief.briefMd || "(empty brief)",
|
|
1225
|
+
];
|
|
1226
|
+
if (brief.latestSummaryMd) {
|
|
1227
|
+
lines.push("", "## Latest Summary", "", brief.latestSummaryMd);
|
|
1228
|
+
}
|
|
1229
|
+
if (brief.summaryDate) {
|
|
1230
|
+
lines.push("", `Summary date: ${brief.summaryDate}`);
|
|
1231
|
+
}
|
|
1232
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
1233
|
+
}
|
|
1234
|
+
} catch {
|
|
1235
|
+
// The SQLite mirror is optional; fall through to the canonical file.
|
|
1236
|
+
}
|
|
1237
|
+
return {
|
|
1238
|
+
content: [{ type: "text", text: `No brief found for topic: ${rawTopic}` }],
|
|
1239
|
+
};
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
const topicKey = wikiSummarySlug(rawTopic.replace(/^topic\//, "").replace(/\.md$/i, ""));
|
|
1243
|
+
const filePath = resolve(runtime().topicsDir, `${topicKey}.md`);
|
|
1244
|
+
try {
|
|
1245
|
+
const content = readFileSync(filePath, "utf-8");
|
|
1246
|
+
return {
|
|
1247
|
+
content: [{ type: "text", text: `# Topic Brief: ${topicKey}\n\n${content}` }],
|
|
1248
|
+
};
|
|
1249
|
+
} catch {
|
|
1250
|
+
// Report the same not-found result for DB- and file-backed lookups.
|
|
1251
|
+
}
|
|
1252
|
+
return {
|
|
1253
|
+
content: [{ type: "text", text: `No brief found for topic: ${rawTopic}` }],
|
|
1254
|
+
};
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
function wikiRead(args: Record<string, unknown>): CallToolResult {
|
|
1258
|
+
const rawKind = String(safeExt(args, ["kind", "type"], "article"));
|
|
1259
|
+
const kind = rawKind === "topic" || rawKind === "summary" ? rawKind : "article";
|
|
1260
|
+
const rawKey = String(safeExt(args, ["key", "slug", "topic"], "")).trim();
|
|
1261
|
+
if (!rawKey) {
|
|
1262
|
+
return { content: [{ type: "text", text: "A wiki document key is required." }], isError: true };
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
if (kind === "topic") {
|
|
1266
|
+
const result = wikiTopicBrief({ topic: rawKey });
|
|
1267
|
+
const resultText = result.content
|
|
1268
|
+
.map((entry) => (entry.type === "text" ? entry.text : ""))
|
|
1269
|
+
.join("\n");
|
|
1270
|
+
const adopt = safeExt<boolean>(args, ["adopt", "use", "select"], false);
|
|
1271
|
+
if (!adopt || resultText.startsWith("No brief found for topic")) return result;
|
|
1272
|
+
|
|
1273
|
+
const currentTopicId = runtime().currentTopicId;
|
|
1274
|
+
const memoryKey = wikiSummarySlug(rawKey.replace(/^topic\//, "").replace(/\.md$/i, ""));
|
|
1275
|
+
if (
|
|
1276
|
+
!currentTopicId ||
|
|
1277
|
+
!runtime().host.adoptTopicMemory?.(currentTopicId, runtime().userId, memoryKey)
|
|
1278
|
+
) {
|
|
1279
|
+
return {
|
|
1280
|
+
content: [
|
|
1281
|
+
...result.content,
|
|
1282
|
+
{ type: "text", text: "\nMemory was read but could not be adopted by this topic." },
|
|
1283
|
+
],
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
return {
|
|
1287
|
+
content: [...result.content, { type: "text", text: `\nAdopted topic memory: ${memoryKey}` }],
|
|
1288
|
+
};
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
if (
|
|
1292
|
+
rawKey.includes("\\") ||
|
|
1293
|
+
rawKey.split("/").some((part) => part === "..") ||
|
|
1294
|
+
rawKey.startsWith("/")
|
|
1295
|
+
) {
|
|
1296
|
+
return { content: [{ type: "text", text: "Invalid wiki document key." }], isError: true };
|
|
1297
|
+
}
|
|
1298
|
+
const root = kind === "summary" ? runtime().summariesDir : runtime().articlesDir;
|
|
1299
|
+
const key = rawKey
|
|
1300
|
+
.replace(new RegExp(`^(?:${kind === "summary" ? "summaries" : "articles"})/`), "")
|
|
1301
|
+
.replace(/\.md$/i, "");
|
|
1302
|
+
const filePath = resolve(root, `${key}.md`);
|
|
1303
|
+
const relativePath = relative(root, filePath);
|
|
1304
|
+
if (relativePath.startsWith("..") || relativePath.startsWith("/")) {
|
|
1305
|
+
return { content: [{ type: "text", text: "Invalid wiki document key." }], isError: true };
|
|
1306
|
+
}
|
|
1307
|
+
try {
|
|
1308
|
+
const content = readFileSync(filePath, "utf-8");
|
|
1309
|
+
return {
|
|
1310
|
+
content: [{ type: "text", text: `# Wiki ${kind}: ${key}\n\n${content}` }],
|
|
1311
|
+
};
|
|
1312
|
+
} catch {
|
|
1313
|
+
return { content: [{ type: "text", text: `No ${kind} found for: ${rawKey}` }] };
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
function wikiLastConversation(args: Record<string, unknown>): CallToolResult {
|
|
1318
|
+
const rawTopic = safeExt<string | undefined>(
|
|
1319
|
+
args,
|
|
1320
|
+
["topic", "topicName", "topicId"],
|
|
1321
|
+
runtime().topicId,
|
|
1322
|
+
);
|
|
1323
|
+
const turns = safeExt(args, ["turns", "limit", "n"], 5);
|
|
1324
|
+
const maxTurns = Math.min(Math.max(1, Number(turns) || 5), 10);
|
|
1325
|
+
|
|
1326
|
+
if (!rawTopic) {
|
|
1327
|
+
return { content: [{ type: "text", text: "No topic specified." }] };
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
const name = slugify(topicNameFrom(rawTopic));
|
|
1331
|
+
|
|
1332
|
+
// Try per-topic archive dir first, then flat file. This is a read path —
|
|
1333
|
+
// it must never create directories on lookup (that previously left an
|
|
1334
|
+
// empty `wiki/archive/<topic>/` behind for every topic name ever queried,
|
|
1335
|
+
// even when nothing was ever archived under the per-topic layout).
|
|
1336
|
+
const archiveDir = resolve(runtime().archiveDir, name);
|
|
1337
|
+
|
|
1338
|
+
try {
|
|
1339
|
+
// List archive files sorted by name (which should be date-sorted)
|
|
1340
|
+
let files = existsSync(archiveDir)
|
|
1341
|
+
? readdirSync(archiveDir)
|
|
1342
|
+
.filter((f) => f.endsWith(".jsonl"))
|
|
1343
|
+
.sort()
|
|
1344
|
+
.reverse()
|
|
1345
|
+
: [];
|
|
1346
|
+
if (files.length === 0) {
|
|
1347
|
+
files = existsSync(runtime().archiveDir)
|
|
1348
|
+
? readdirSync(runtime().archiveDir)
|
|
1349
|
+
.filter((f) => f.startsWith(name) && f.endsWith(".jsonl"))
|
|
1350
|
+
.sort()
|
|
1351
|
+
.reverse()
|
|
1352
|
+
: [];
|
|
1353
|
+
}
|
|
1354
|
+
if (files.length === 0) {
|
|
1355
|
+
return {
|
|
1356
|
+
content: [{ type: "text", text: `No archive found for topic: ${rawTopic}` }],
|
|
1357
|
+
};
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
const actualPath = files[0].includes("/")
|
|
1361
|
+
? files[0]
|
|
1362
|
+
: resolve(
|
|
1363
|
+
existsSync(archiveDir) && readdirSync(archiveDir).includes(files[0])
|
|
1364
|
+
? archiveDir
|
|
1365
|
+
: runtime().archiveDir,
|
|
1366
|
+
files[0],
|
|
1367
|
+
);
|
|
1368
|
+
|
|
1369
|
+
try {
|
|
1370
|
+
const raw = readFileSync(actualPath, "utf-8");
|
|
1371
|
+
const lines = raw.trim().split("\n").filter(Boolean);
|
|
1372
|
+
|
|
1373
|
+
// Reconstruct turns from UnifiedEvent JSONL: pair user_message with following text/result
|
|
1374
|
+
const turns: string[] = [];
|
|
1375
|
+
let currentUser = "";
|
|
1376
|
+
let currentAssistant = "";
|
|
1377
|
+
|
|
1378
|
+
const truncate = (s: string, max: number) =>
|
|
1379
|
+
s.length > max ? `${s.slice(0, max)}\n...(truncated)` : s;
|
|
1380
|
+
|
|
1381
|
+
const flush = () => {
|
|
1382
|
+
if (currentUser || currentAssistant) {
|
|
1383
|
+
turns.push(
|
|
1384
|
+
`**User**: ${truncate(currentUser || "(no prompt)", 500)}\n\n**Assistant**: ${truncate(currentAssistant || "(no response)", 1000)}`,
|
|
1385
|
+
);
|
|
1386
|
+
currentUser = "";
|
|
1387
|
+
currentAssistant = "";
|
|
1388
|
+
}
|
|
1389
|
+
};
|
|
1390
|
+
|
|
1391
|
+
for (const line of lines) {
|
|
1392
|
+
try {
|
|
1393
|
+
// Archives are written by archiveTopicMessages → TopicArchiveTranscriptRecord:
|
|
1394
|
+
// { type: "message", role: "user"|"assistant"|"system", text: "..." }
|
|
1395
|
+
const record = JSON.parse(line) as {
|
|
1396
|
+
type: string;
|
|
1397
|
+
role?: string;
|
|
1398
|
+
text?: string;
|
|
1399
|
+
};
|
|
1400
|
+
if (record.type === "message" && record.role === "user") {
|
|
1401
|
+
flush();
|
|
1402
|
+
currentUser = record.text ?? "";
|
|
1403
|
+
} else if (record.type === "message" && record.role === "assistant") {
|
|
1404
|
+
currentAssistant += record.text ?? "";
|
|
1405
|
+
}
|
|
1406
|
+
} catch {
|
|
1407
|
+
// skip malformed lines
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
flush();
|
|
1411
|
+
|
|
1412
|
+
if (turns.length === 0) {
|
|
1413
|
+
return {
|
|
1414
|
+
content: [{ type: "text", text: `Archive file found but no valid entries.` }],
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
const recent = turns.slice(-maxTurns);
|
|
1419
|
+
return {
|
|
1420
|
+
content: [
|
|
1421
|
+
{
|
|
1422
|
+
type: "text",
|
|
1423
|
+
text: `## Last ${recent.length} turns from "${rawTopic}" (${files[0]})\n\n${recent.join("\n\n---\n\n")}`,
|
|
1424
|
+
},
|
|
1425
|
+
],
|
|
1426
|
+
};
|
|
1427
|
+
} catch {
|
|
1428
|
+
return {
|
|
1429
|
+
content: [{ type: "text", text: `Could not read archive for: ${rawTopic}` }],
|
|
1430
|
+
};
|
|
1431
|
+
}
|
|
1432
|
+
} catch {
|
|
1433
|
+
return {
|
|
1434
|
+
content: [{ type: "text", text: `No archive found for: ${rawTopic}` }],
|
|
1435
|
+
};
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
function skillQuery(args: Record<string, unknown>): CallToolResult {
|
|
1440
|
+
const question = safeExt(args, ["question", "query", "q"], "");
|
|
1441
|
+
const query = question.toLowerCase();
|
|
1442
|
+
|
|
1443
|
+
ensureDir(runtime().skillsDir);
|
|
1444
|
+
|
|
1445
|
+
const matches: { name: string; path: string; desc: string }[] = [];
|
|
1446
|
+
|
|
1447
|
+
try {
|
|
1448
|
+
for (const entry of readdirSync(runtime().skillsDir, {
|
|
1449
|
+
withFileTypes: true,
|
|
1450
|
+
})) {
|
|
1451
|
+
if (!entry.isDirectory()) continue;
|
|
1452
|
+
const skillFile = resolve(runtime().skillsDir, entry.name, "skill.md");
|
|
1453
|
+
try {
|
|
1454
|
+
const text = readFileSync(skillFile, "utf-8");
|
|
1455
|
+
const lower = text.toLowerCase();
|
|
1456
|
+
let score = 0;
|
|
1457
|
+
for (const w of query.split(/\s+/).filter(Boolean)) {
|
|
1458
|
+
if (lower.includes(w)) score += w.length >= 3 ? 3 : 1;
|
|
1459
|
+
}
|
|
1460
|
+
if (score > 0) {
|
|
1461
|
+
// Extract name/description from frontmatter
|
|
1462
|
+
const fmMatch = text.match(/^---\n([\s\S]*?)\n---/);
|
|
1463
|
+
let name = entry.name;
|
|
1464
|
+
let desc = "";
|
|
1465
|
+
if (fmMatch) {
|
|
1466
|
+
const fm = fmMatch[1];
|
|
1467
|
+
const nMatch = fm.match(/^name:\s*(.+)$/m);
|
|
1468
|
+
const dMatch = fm.match(/^description:\s*(.+)$/m);
|
|
1469
|
+
if (nMatch) name = nMatch[1].trim();
|
|
1470
|
+
if (dMatch) desc = dMatch[1].trim();
|
|
1471
|
+
}
|
|
1472
|
+
matches.push({ name, path: `skills/${entry.name}/skill.md`, desc });
|
|
1473
|
+
}
|
|
1474
|
+
} catch {
|
|
1475
|
+
/* skip */
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
} catch {
|
|
1479
|
+
/* dir may not exist */
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
if (matches.length === 0) {
|
|
1483
|
+
return { content: [{ type: "text", text: "No matching skills found." }] };
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
const lines = matches.map((m) => `- **${m.name}** (${m.path})${m.desc ? ` — ${m.desc}` : ""}`);
|
|
1487
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
function skillSave(args: Record<string, unknown>): CallToolResult {
|
|
1491
|
+
const name = safeExt(args, ["name", "skill_name"], "");
|
|
1492
|
+
const content: string = safeExt(args, ["content", "text", "body"], "");
|
|
1493
|
+
|
|
1494
|
+
if (!name) return { content: [{ type: "text", text: "Missing skill name." }] };
|
|
1495
|
+
if (!content) return { content: [{ type: "text", text: "Missing skill content." }] };
|
|
1496
|
+
|
|
1497
|
+
function extractGotchas(md: string): string[] {
|
|
1498
|
+
// No `m` flag: `$` anchors to end-of-string so lazy [\s\S]*? isn't fooled
|
|
1499
|
+
// by mid-section newlines the way it would be in multiline mode.
|
|
1500
|
+
const m = md.match(/(?:^|\n)## Gotchas\s*\n([\s\S]*?)(?=\n## |$)/);
|
|
1501
|
+
if (!m) return [];
|
|
1502
|
+
return m[1].split("\n").filter((l) => l.trim().startsWith("-"));
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
function mergeGotchas(target: string, extra: string[]): string {
|
|
1506
|
+
const existing = new Set(extractGotchas(target).map((l) => l.toLowerCase()));
|
|
1507
|
+
const fresh = extra.filter((l) => !existing.has(l.toLowerCase()));
|
|
1508
|
+
if (fresh.length === 0) return target;
|
|
1509
|
+
const sectionMatch = target.match(/(?:^|\n)(## Gotchas\s*\n[\s\S]*?)(?=\n## |$)/);
|
|
1510
|
+
if (sectionMatch) {
|
|
1511
|
+
const block = sectionMatch[1];
|
|
1512
|
+
const insert = `${block.trimEnd()}\n${fresh.join("\n")}`;
|
|
1513
|
+
return target.replace(block, insert);
|
|
1514
|
+
}
|
|
1515
|
+
return `${target.trimEnd()}\n\n## Gotchas\n${fresh.join("\n")}\n`;
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
const skillDir = resolve(runtime().skillsDir, name);
|
|
1519
|
+
ensureDir(skillDir);
|
|
1520
|
+
const skillPath = resolve(skillDir, "skill.md");
|
|
1521
|
+
|
|
1522
|
+
let finalContent = content;
|
|
1523
|
+
try {
|
|
1524
|
+
const existing = readFileSync(skillPath, "utf-8");
|
|
1525
|
+
finalContent = mergeGotchas(content, extractGotchas(existing));
|
|
1526
|
+
} catch {
|
|
1527
|
+
// new skill — no existing file to merge from
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
writeFileSync(skillPath, finalContent, "utf-8");
|
|
1531
|
+
|
|
1532
|
+
return {
|
|
1533
|
+
content: [
|
|
1534
|
+
{
|
|
1535
|
+
type: "text",
|
|
1536
|
+
text: `Skill "${name}" saved at skills/${name}/skill.md`,
|
|
1537
|
+
},
|
|
1538
|
+
],
|
|
1539
|
+
};
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
/** Write a write-once session summary and report the slug the catalog must use. */
|
|
1543
|
+
function writeSummaryDocument(
|
|
1544
|
+
rawTopic: string,
|
|
1545
|
+
content: string,
|
|
1546
|
+
dateStr: string,
|
|
1547
|
+
): { slug: string; sqliteUpdated: boolean } {
|
|
1548
|
+
const topicId = runtime().topicId;
|
|
1549
|
+
const fileSlug = wikiBriefStorageKey(rawTopic, topicId);
|
|
1550
|
+
|
|
1551
|
+
// Save to summaries directory
|
|
1552
|
+
ensureDir(runtime().summariesDir);
|
|
1553
|
+
const baseSummaryName = wikiSummaryFilename(dateStr, rawTopic, topicId);
|
|
1554
|
+
let summaryName = baseSummaryName;
|
|
1555
|
+
let counter = 1;
|
|
1556
|
+
while (true) {
|
|
1557
|
+
try {
|
|
1558
|
+
writeFileSync(resolve(runtime().summariesDir, summaryName), content, {
|
|
1559
|
+
encoding: "utf-8",
|
|
1560
|
+
flag: "wx",
|
|
1561
|
+
});
|
|
1562
|
+
break;
|
|
1563
|
+
} catch (error) {
|
|
1564
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
1565
|
+
counter += 1;
|
|
1566
|
+
summaryName = baseSummaryName.replace(/\.md$/, `~${counter}.md`);
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
// Record the latest summary. The fresh brief is written authoritatively by
|
|
1571
|
+
// wiki_write(kind="topic") (called after this step). We only backfill brief_md
|
|
1572
|
+
// here so a summary-only write — e.g. the no-substance path, which skips the
|
|
1573
|
+
// brief — can't create a title-key row with an empty brief_md that
|
|
1574
|
+
// shadows an existing brief (see resolveTopicBrief precedence). Backfill order:
|
|
1575
|
+
// an existing brief file, else a legacy id-keyed row migrated forward. We
|
|
1576
|
+
// never overwrite an existing title brief_md with empty.
|
|
1577
|
+
const setTopicBrief = runtime().host.setTopicBrief;
|
|
1578
|
+
const getTopicBrief = runtime().host.getTopicBrief;
|
|
1579
|
+
let sqliteUpdated = false;
|
|
1580
|
+
if (topicId && setTopicBrief) {
|
|
1581
|
+
try {
|
|
1582
|
+
const briefPath = resolve(runtime().topicsDir, `${fileSlug}.md`);
|
|
1583
|
+
let briefMd = existsSync(briefPath) ? readFileSync(briefPath, "utf-8") : undefined;
|
|
1584
|
+
if (briefMd === undefined && getTopicBrief && !getTopicBrief(fileSlug)?.briefMd) {
|
|
1585
|
+
// No brief file and no title-keyed brief yet: carry a legacy id-keyed
|
|
1586
|
+
// brief into the title row so this write cannot hide it.
|
|
1587
|
+
const legacy = getTopicBrief(topicId)?.briefMd;
|
|
1588
|
+
if (legacy) briefMd = legacy;
|
|
1589
|
+
}
|
|
1590
|
+
setTopicBrief(fileSlug, {
|
|
1591
|
+
latestSummaryMd: content,
|
|
1592
|
+
summaryDate: dateStr,
|
|
1593
|
+
...(briefMd !== undefined ? { briefMd } : {}),
|
|
1594
|
+
});
|
|
1595
|
+
sqliteUpdated = true;
|
|
1596
|
+
} catch {
|
|
1597
|
+
// DB update failed — file save succeeded, not critical.
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1601
|
+
return { slug: summaryName.replace(/\.md$/i, ""), sqliteUpdated };
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
/** Write the accumulated persona brief and mirror it for the next session start. */
|
|
1605
|
+
function writeTopicDocument(
|
|
1606
|
+
rawTopic: string,
|
|
1607
|
+
content: string,
|
|
1608
|
+
): { slug: string; existed: boolean; sqliteUpdated: boolean } {
|
|
1609
|
+
const topicId = runtime().topicId;
|
|
1610
|
+
const fileSlug = wikiBriefStorageKey(rawTopic, topicId);
|
|
1611
|
+
|
|
1612
|
+
// Write the canonical accumulated persona brief file.
|
|
1613
|
+
const briefPath = resolve(runtime().topicsDir, `${fileSlug}.md`);
|
|
1614
|
+
ensureDir(dirname(briefPath));
|
|
1615
|
+
const existed = existsSync(briefPath);
|
|
1616
|
+
writeFileSync(briefPath, content, "utf-8");
|
|
1617
|
+
|
|
1618
|
+
// Mirror the brief into SQLite so it is injected at the next session start.
|
|
1619
|
+
// Partial upsert: only brief_md is touched, leaving latest_summary_md and
|
|
1620
|
+
// summary_date (written by the summary path) intact.
|
|
1621
|
+
const setTopicBrief = runtime().host.setTopicBrief;
|
|
1622
|
+
let sqliteUpdated = false;
|
|
1623
|
+
if (topicId && setTopicBrief) {
|
|
1624
|
+
try {
|
|
1625
|
+
setTopicBrief(fileSlug, { briefMd: content });
|
|
1626
|
+
sqliteUpdated = true;
|
|
1627
|
+
} catch {
|
|
1628
|
+
// DB update failed — file save succeeded, not critical.
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
|
|
1632
|
+
return { slug: fileSlug, existed, sqliteUpdated };
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
/** Write a curated concept page. Articles are mergeable, so this overwrites. */
|
|
1636
|
+
function writeArticleDocument(slug: string, content: string): { existed: boolean } {
|
|
1637
|
+
const articlePath = resolve(runtime().articlesDir, `${slug}.md`);
|
|
1638
|
+
ensureDir(dirname(articlePath));
|
|
1639
|
+
const existed = existsSync(articlePath);
|
|
1640
|
+
atomicWriteFile(articlePath, content);
|
|
1641
|
+
return { existed };
|
|
1642
|
+
}
|
|
1643
|
+
|
|
1644
|
+
/**
|
|
1645
|
+
* Write a wiki document and its catalog row in one call.
|
|
1646
|
+
*
|
|
1647
|
+
* This is the only way to create a wiki entry. Pairing the two writes here is
|
|
1648
|
+
* what makes an unindexed document impossible to produce through the tool
|
|
1649
|
+
* surface: a document write that cannot be indexed is reported as a failure so
|
|
1650
|
+
* the caller retries, and the row upsert is idempotent.
|
|
1651
|
+
*/
|
|
1652
|
+
function wikiWrite(args: Record<string, unknown>): CallToolResult {
|
|
1653
|
+
const rawKind: string = safeExt(args, ["kind", "type"], "");
|
|
1654
|
+
const content: string = safeExt(args, ["content", "text", "body", "brief"], "");
|
|
1655
|
+
const rawDescription = safeExt(args, ["description", "desc"], "");
|
|
1656
|
+
const rawTopic = safeExt(args, ["topic", "topicName"], "");
|
|
1657
|
+
const rawSlug = safeExt(args, ["slug", "id"], "");
|
|
1658
|
+
const section = safeExt<string | undefined>(args, ["section", "category"], undefined);
|
|
1659
|
+
const rawDate = safeExt<string | undefined>(args, ["date", "created"], undefined);
|
|
1660
|
+
|
|
1661
|
+
if (rawKind !== "summary" && rawKind !== "article" && rawKind !== "topic") {
|
|
1662
|
+
return {
|
|
1663
|
+
content: [{ type: "text", text: 'kind must be one of "summary", "article", "topic".' }],
|
|
1664
|
+
isError: true,
|
|
1665
|
+
};
|
|
1666
|
+
}
|
|
1667
|
+
if (!content.trim()) {
|
|
1668
|
+
return { content: [{ type: "text", text: "Missing content." }], isError: true };
|
|
1669
|
+
}
|
|
1670
|
+
const descriptionResult = normalizeIndexDescription(rawDescription);
|
|
1671
|
+
if ("error" in descriptionResult) {
|
|
1672
|
+
return { content: [{ type: "text", text: descriptionResult.error }], isError: true };
|
|
1673
|
+
}
|
|
1674
|
+
const { description } = descriptionResult;
|
|
1675
|
+
const today = new Date().toISOString().slice(0, 10);
|
|
1676
|
+
|
|
1677
|
+
if (rawKind === "article") {
|
|
1678
|
+
const slugResult = normalizeWikiSlug(rawSlug);
|
|
1679
|
+
if ("error" in slugResult) {
|
|
1680
|
+
return { content: [{ type: "text", text: slugResult.error }], isError: true };
|
|
1681
|
+
}
|
|
1682
|
+
if (!section?.trim()) {
|
|
1683
|
+
return {
|
|
1684
|
+
content: [
|
|
1685
|
+
{ type: "text", text: "An article requires a section so the catalog stays navigable." },
|
|
1686
|
+
],
|
|
1687
|
+
isError: true,
|
|
1688
|
+
};
|
|
1689
|
+
}
|
|
1690
|
+
const { existed } = writeArticleDocument(slugResult.slug, content);
|
|
1691
|
+
const link = indexRowOrPartialWrite("article", {
|
|
1692
|
+
kind: "article",
|
|
1693
|
+
slug: slugResult.slug,
|
|
1694
|
+
description,
|
|
1695
|
+
date: rawDate ?? today,
|
|
1696
|
+
section: section.trim(),
|
|
1697
|
+
});
|
|
1698
|
+
if (typeof link !== "string") return link;
|
|
1699
|
+
const searched = indexWikiSearchDocument("article", slugResult.slug, content);
|
|
1700
|
+
return {
|
|
1701
|
+
content: [
|
|
1702
|
+
{
|
|
1703
|
+
type: "text",
|
|
1704
|
+
text:
|
|
1705
|
+
`Saved article: articles/${slugResult.slug}.md (${existed ? "updated" : "created"})\nIndexed: ${link}` +
|
|
1706
|
+
(searched ? "" : `\n${SEARCH_CACHE_SKIPPED_NOTE}`),
|
|
1707
|
+
},
|
|
1708
|
+
],
|
|
1709
|
+
};
|
|
1710
|
+
}
|
|
1711
|
+
|
|
1712
|
+
const topic = rawTopic.trim();
|
|
1713
|
+
if (!topic) {
|
|
1714
|
+
return { content: [{ type: "text", text: "Missing topic." }], isError: true };
|
|
1715
|
+
}
|
|
1716
|
+
const boundTopicId = runtime().topicId;
|
|
1717
|
+
const fixedKey = boundTopicId ? runtime().host.fixedMemoryKey?.(boundTopicId) : undefined;
|
|
1718
|
+
if (fixedKey && wikiSummarySlug(topic) !== wikiSummarySlug(fixedKey)) {
|
|
1719
|
+
return {
|
|
1720
|
+
content: [
|
|
1721
|
+
{
|
|
1722
|
+
type: "text",
|
|
1723
|
+
text: `This topic's memory key is fixed. Write its ${rawKind} with topic: "${fixedKey}".`,
|
|
1724
|
+
},
|
|
1725
|
+
],
|
|
1726
|
+
isError: true,
|
|
1727
|
+
};
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
if (rawKind === "summary") {
|
|
1731
|
+
const dateStr = rawDate ?? today;
|
|
1732
|
+
const written = writeSummaryDocument(topic, content, dateStr);
|
|
1733
|
+
const link = indexRowOrPartialWrite("summary", {
|
|
1734
|
+
kind: "summary",
|
|
1735
|
+
slug: written.slug,
|
|
1736
|
+
description,
|
|
1737
|
+
date: dateStr,
|
|
1738
|
+
});
|
|
1739
|
+
if (typeof link !== "string") return link;
|
|
1740
|
+
const searched = indexWikiSearchDocument("summary", written.slug, content);
|
|
1741
|
+
return {
|
|
1742
|
+
content: [
|
|
1743
|
+
{
|
|
1744
|
+
type: "text",
|
|
1745
|
+
text:
|
|
1746
|
+
`Saved summary: summaries/${written.slug}.md\nIndexed: ${link}` +
|
|
1747
|
+
(written.sqliteUpdated ? "\nSQLite latest-summary also updated." : "") +
|
|
1748
|
+
(searched ? "" : `\n${SEARCH_CACHE_SKIPPED_NOTE}`),
|
|
1749
|
+
},
|
|
1750
|
+
],
|
|
1751
|
+
};
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
const written = writeTopicDocument(topic, content);
|
|
1755
|
+
const link = indexRowOrPartialWrite("topic", {
|
|
1756
|
+
kind: "topic",
|
|
1757
|
+
slug: written.slug,
|
|
1758
|
+
description,
|
|
1759
|
+
date: rawDate ?? today,
|
|
1760
|
+
});
|
|
1761
|
+
if (typeof link !== "string") return link;
|
|
1762
|
+
return {
|
|
1763
|
+
content: [
|
|
1764
|
+
{
|
|
1765
|
+
type: "text",
|
|
1766
|
+
text:
|
|
1767
|
+
`Saved brief: topic/${written.slug}.md (${written.existed ? "updated" : "created"})\nIndexed: ${link}` +
|
|
1768
|
+
(written.sqliteUpdated ? "\nSQLite brief also updated." : ""),
|
|
1769
|
+
},
|
|
1770
|
+
],
|
|
1771
|
+
};
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
/** Collect the article and summary documents currently on disk. */
|
|
1775
|
+
function collectIndexableDocuments(): WikiSearchIndexSource[] {
|
|
1776
|
+
const sources: WikiSearchIndexSource[] = [];
|
|
1777
|
+
function add(kind: IndexedWikiKind, key: string, path: string): void {
|
|
1778
|
+
try {
|
|
1779
|
+
const stat = statSync(path);
|
|
1780
|
+
if (!stat.isFile()) return;
|
|
1781
|
+
sources.push({ kind, key, path, mtimeMs: stat.mtimeMs, size: stat.size });
|
|
1782
|
+
} catch {
|
|
1783
|
+
// A file that vanished mid-walk is simply absent from this pass.
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
for (const [root, kind, allowSubdirectories] of [
|
|
1787
|
+
[runtime().articlesDir, "article", true],
|
|
1788
|
+
[runtime().summariesDir, "summary", false],
|
|
1789
|
+
] as const) {
|
|
1790
|
+
let entries: Dirent<string>[];
|
|
1791
|
+
try {
|
|
1792
|
+
entries = readdirSync(root, { withFileTypes: true });
|
|
1793
|
+
} catch {
|
|
1794
|
+
continue;
|
|
1795
|
+
}
|
|
1796
|
+
for (const entry of entries) {
|
|
1797
|
+
if (entry.isFile() && entry.name.endsWith(".md")) {
|
|
1798
|
+
add(kind, entry.name.replace(/\.md$/i, ""), join(root, entry.name));
|
|
1799
|
+
continue;
|
|
1800
|
+
}
|
|
1801
|
+
if (!entry.isDirectory() || !allowSubdirectories) continue;
|
|
1802
|
+
let nested: Dirent<string>[];
|
|
1803
|
+
try {
|
|
1804
|
+
nested = readdirSync(join(root, entry.name), { withFileTypes: true });
|
|
1805
|
+
} catch {
|
|
1806
|
+
continue;
|
|
1807
|
+
}
|
|
1808
|
+
for (const file of nested) {
|
|
1809
|
+
if (!file.isFile() || !file.name.endsWith(".md")) continue;
|
|
1810
|
+
add(
|
|
1811
|
+
kind,
|
|
1812
|
+
`${entry.name}/${file.name.replace(/\.md$/i, "")}`,
|
|
1813
|
+
join(root, entry.name, file.name),
|
|
1814
|
+
);
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
return sources;
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
/**
|
|
1822
|
+
* Refill the derived body index and report catalog gaps.
|
|
1823
|
+
*
|
|
1824
|
+
* This is the only place that walks the content directories, and it runs only
|
|
1825
|
+
* when asked. Retrieval never scans, and this command deliberately does not
|
|
1826
|
+
* invent catalog rows: it names the documents that need one so a description is
|
|
1827
|
+
* written by whoever knows what the document is for.
|
|
1828
|
+
*/
|
|
1829
|
+
function wikiReindex(): CallToolResult {
|
|
1830
|
+
const documents = collectIndexableDocuments();
|
|
1831
|
+
const index = openWikiSearchIndex();
|
|
1832
|
+
if (!index) {
|
|
1833
|
+
return {
|
|
1834
|
+
content: [{ type: "text", text: "Could not open the wiki search index." }],
|
|
1835
|
+
isError: true,
|
|
1836
|
+
};
|
|
1837
|
+
}
|
|
1838
|
+
let synced: { added: number; updated: number; removed: number };
|
|
1839
|
+
try {
|
|
1840
|
+
synced = index.sync(documents, (source, text) =>
|
|
1841
|
+
prepareWikiSearchDocument(source.kind, source.key, text),
|
|
1842
|
+
);
|
|
1843
|
+
} catch (error) {
|
|
1844
|
+
return {
|
|
1845
|
+
content: [{ type: "text", text: `Failed to rebuild the search index: ${String(error)}` }],
|
|
1846
|
+
isError: true,
|
|
1847
|
+
};
|
|
1848
|
+
} finally {
|
|
1849
|
+
index.close();
|
|
1850
|
+
}
|
|
1851
|
+
|
|
1852
|
+
// Compare the documents on disk against the catalogs. A document with no row
|
|
1853
|
+
// is invisible to retrieval; a row with no document is a harmless tombstone.
|
|
1854
|
+
const lines = [
|
|
1855
|
+
`Search index: ${synced.added} added, ${synced.updated} updated, ${synced.removed} removed (${documents.length} documents).`,
|
|
1856
|
+
];
|
|
1857
|
+
for (const kind of ["article", "summary"] as const) {
|
|
1858
|
+
const rows = new Set(
|
|
1859
|
+
parseWikiIndex(wikiIndexPath(kind))
|
|
1860
|
+
.filter((candidate) => candidate.kind === kind)
|
|
1861
|
+
.map((candidate) => candidate.key),
|
|
1862
|
+
);
|
|
1863
|
+
const keys = documents.filter((source) => source.kind === kind).map((source) => source.key);
|
|
1864
|
+
const unindexed = keys.filter((key) => !rows.has(key));
|
|
1865
|
+
const tombstones = [...rows].filter((key) => !keys.includes(key));
|
|
1866
|
+
lines.push(
|
|
1867
|
+
`${WIKI_INDEX_FILENAMES[kind]}: ${rows.size} rows for ${keys.length} documents` +
|
|
1868
|
+
(unindexed.length > 0 ? `; missing rows: ${unindexed.join(", ")}` : "") +
|
|
1869
|
+
(tombstones.length > 0 ? `; tombstones: ${tombstones.join(", ")}` : ""),
|
|
1870
|
+
);
|
|
1871
|
+
}
|
|
1872
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
const SEARCH_CACHE_SKIPPED_NOTE =
|
|
1876
|
+
"Body-search cache was not updated; catalog retrieval still works. Run wiki_reindex to refill it.";
|
|
1877
|
+
|
|
1878
|
+
/**
|
|
1879
|
+
* Index a freshly written document, turning an index failure into an explicit
|
|
1880
|
+
* partial-write error naming the document that still needs a catalog row.
|
|
1881
|
+
*/
|
|
1882
|
+
function indexRowOrPartialWrite(
|
|
1883
|
+
label: string,
|
|
1884
|
+
options: Parameters<typeof upsertIndexRow>[0],
|
|
1885
|
+
): string | CallToolResult {
|
|
1886
|
+
try {
|
|
1887
|
+
return upsertIndexRow(options);
|
|
1888
|
+
} catch (error) {
|
|
1889
|
+
return {
|
|
1890
|
+
content: [
|
|
1891
|
+
{
|
|
1892
|
+
type: "text",
|
|
1893
|
+
text: `Wrote the ${label} document but failed to index it (${String(error)}). Retry the same wiki_write call: both writes are idempotent.`,
|
|
1894
|
+
},
|
|
1895
|
+
],
|
|
1896
|
+
isError: true,
|
|
1897
|
+
};
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1900
|
+
|
|
1901
|
+
/**
|
|
1902
|
+
* Insert or update one catalog row in the index that owns `kind`.
|
|
1903
|
+
*
|
|
1904
|
+
* Shared by `wiki_write` (which pairs it with the document write) and
|
|
1905
|
+
* `index_upsert` (which only curates an existing entry). Throwing here is what
|
|
1906
|
+
* lets `wiki_write` report a partial write instead of silently leaving a
|
|
1907
|
+
* document unindexed.
|
|
1908
|
+
*/
|
|
1909
|
+
function upsertIndexRow(options: {
|
|
1910
|
+
kind: WikiIndexKind;
|
|
1911
|
+
slug: string;
|
|
1912
|
+
description: string;
|
|
1913
|
+
date: string;
|
|
1914
|
+
section?: string | undefined;
|
|
1915
|
+
}): string {
|
|
1916
|
+
const { kind, slug, description, date, section } = options;
|
|
1917
|
+
const indexPath = wikiIndexPath(kind);
|
|
1918
|
+
|
|
1919
|
+
ensureDir(dirname(indexPath));
|
|
1920
|
+
const releaseLock = acquireFileLock(indexPath);
|
|
1921
|
+
|
|
1922
|
+
try {
|
|
1923
|
+
let index: string;
|
|
1924
|
+
try {
|
|
1925
|
+
index = readFileSync(indexPath, "utf-8");
|
|
1926
|
+
} catch {
|
|
1927
|
+
index = "";
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
const lines = index.split("\n");
|
|
1931
|
+
const target = `${WIKI_INDEX_NAMESPACES[kind]}/${slug}`;
|
|
1932
|
+
const link = `- [[${target}]] ${description} (${date})`;
|
|
1933
|
+
// Find every existing entry for this canonical target. Historical versions
|
|
1934
|
+
// appended duplicates because they searched for [[slug]] while writing
|
|
1935
|
+
// [[topic/slug]].
|
|
1936
|
+
const slugPattern = `[[${target}]]`;
|
|
1937
|
+
let replaced = false;
|
|
1938
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
1939
|
+
if (lines[i].includes(slugPattern)) {
|
|
1940
|
+
if (!replaced) {
|
|
1941
|
+
lines[i] = link;
|
|
1942
|
+
replaced = true;
|
|
1943
|
+
} else {
|
|
1944
|
+
lines.splice(i, 1);
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
|
|
1949
|
+
if (!replaced) {
|
|
1950
|
+
// Append to appropriate section
|
|
1951
|
+
if (section) {
|
|
1952
|
+
let sectionIdx = -1;
|
|
1953
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1954
|
+
if (lines[i].startsWith("## ") && lines[i].includes(section)) {
|
|
1955
|
+
sectionIdx = i;
|
|
1956
|
+
break;
|
|
1957
|
+
}
|
|
1958
|
+
}
|
|
1959
|
+
if (sectionIdx >= 0) {
|
|
1960
|
+
// Insert after section heading, before next section
|
|
1961
|
+
let insertAt = sectionIdx + 1;
|
|
1962
|
+
while (
|
|
1963
|
+
insertAt < lines.length &&
|
|
1964
|
+
lines[insertAt].trim() !== "" &&
|
|
1965
|
+
!lines[insertAt].startsWith("## ")
|
|
1966
|
+
) {
|
|
1967
|
+
insertAt++;
|
|
1968
|
+
}
|
|
1969
|
+
lines.splice(insertAt, 0, link);
|
|
1970
|
+
} else {
|
|
1971
|
+
lines.push(`\n## ${section}`, link);
|
|
1972
|
+
}
|
|
1973
|
+
} else {
|
|
1974
|
+
lines.push(link);
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
|
|
1978
|
+
atomicWriteFile(indexPath, lines.join("\n"));
|
|
1979
|
+
|
|
1980
|
+
return link;
|
|
1981
|
+
} finally {
|
|
1982
|
+
releaseLock();
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
|
|
1986
|
+
/** Does the document backing a catalog row exist on disk? */
|
|
1987
|
+
function wikiDocumentExists(kind: WikiIndexKind, slug: string): boolean {
|
|
1988
|
+
const root =
|
|
1989
|
+
kind === "article"
|
|
1990
|
+
? runtime().articlesDir
|
|
1991
|
+
: kind === "summary"
|
|
1992
|
+
? runtime().summariesDir
|
|
1993
|
+
: kind === "topic"
|
|
1994
|
+
? runtime().topicsDir
|
|
1995
|
+
: runtime().skillsDir;
|
|
1996
|
+
const filePath = resolve(root, `${slug}.md`);
|
|
1997
|
+
if (relative(root, filePath).startsWith("..")) return false;
|
|
1998
|
+
try {
|
|
1999
|
+
return statSync(filePath).isFile();
|
|
2000
|
+
} catch {
|
|
2001
|
+
return false;
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
|
|
2005
|
+
/**
|
|
2006
|
+
* Curate an existing catalog row.
|
|
2007
|
+
*
|
|
2008
|
+
* This tool deliberately cannot introduce a row for a document that does not
|
|
2009
|
+
* exist: `wiki_write` is the only way to create an entry, so a description fix
|
|
2010
|
+
* can never be the step that invents an unbacked row.
|
|
2011
|
+
*/
|
|
2012
|
+
function indexUpsert(args: Record<string, unknown>): CallToolResult {
|
|
2013
|
+
const rawSlug = safeExt(args, ["slug", "id"], "");
|
|
2014
|
+
const rawDescription = safeExt(args, ["description", "desc", "text"], "");
|
|
2015
|
+
const rawKind: string = safeExt(args, ["kind", "type"], "article");
|
|
2016
|
+
const section = safeExt<string | undefined>(args, ["section", "category"], undefined);
|
|
2017
|
+
const date = safeExt<string | undefined>(args, ["date", "created"], undefined);
|
|
2018
|
+
|
|
2019
|
+
if (!(rawKind in WIKI_INDEX_FILENAMES)) {
|
|
2020
|
+
return {
|
|
2021
|
+
content: [{ type: "text", text: `Unsupported kind: ${rawKind}` }],
|
|
2022
|
+
isError: true,
|
|
2023
|
+
};
|
|
2024
|
+
}
|
|
2025
|
+
const kind = rawKind as WikiIndexKind;
|
|
2026
|
+
|
|
2027
|
+
const slugResult = normalizeWikiSlug(rawSlug);
|
|
2028
|
+
if ("error" in slugResult) {
|
|
2029
|
+
return { content: [{ type: "text", text: slugResult.error }], isError: true };
|
|
2030
|
+
}
|
|
2031
|
+
const descriptionResult = normalizeIndexDescription(rawDescription);
|
|
2032
|
+
if ("error" in descriptionResult) {
|
|
2033
|
+
return { content: [{ type: "text", text: descriptionResult.error }], isError: true };
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
// Topic rows may point at a DB-backed brief rather than a local file.
|
|
2037
|
+
if (kind !== "topic" && !wikiDocumentExists(kind, slugResult.slug)) {
|
|
2038
|
+
return {
|
|
2039
|
+
content: [
|
|
2040
|
+
{
|
|
2041
|
+
type: "text",
|
|
2042
|
+
text: `No ${kind} document named ${slugResult.slug}. Use wiki_write to create the document and its catalog row together.`,
|
|
2043
|
+
},
|
|
2044
|
+
],
|
|
2045
|
+
isError: true,
|
|
2046
|
+
};
|
|
2047
|
+
}
|
|
2048
|
+
|
|
2049
|
+
const link = upsertIndexRow({
|
|
2050
|
+
kind,
|
|
2051
|
+
slug: slugResult.slug,
|
|
2052
|
+
description: descriptionResult.description,
|
|
2053
|
+
date: date ?? new Date().toISOString().slice(0, 10),
|
|
2054
|
+
section,
|
|
2055
|
+
});
|
|
2056
|
+
return { content: [{ type: "text", text: `Index updated: ${link}` }] };
|
|
2057
|
+
}
|
|
2058
|
+
|
|
2059
|
+
// --- MCP Tool definitions -------------------------------------------------
|
|
2060
|
+
|
|
2061
|
+
const WIKI_TOOLS: Tool[] = [
|
|
2062
|
+
{
|
|
2063
|
+
name: "wiki_query",
|
|
2064
|
+
description: "Search topic, article, or summary indexes and return relevant candidates.",
|
|
2065
|
+
inputSchema: {
|
|
2066
|
+
type: "object",
|
|
2067
|
+
properties: {
|
|
2068
|
+
question: {
|
|
2069
|
+
type: "string",
|
|
2070
|
+
description: "The question or topic to search for",
|
|
2071
|
+
},
|
|
2072
|
+
topic: {
|
|
2073
|
+
type: "string",
|
|
2074
|
+
description: "Optional topic name to narrow the search",
|
|
2075
|
+
},
|
|
2076
|
+
kind: {
|
|
2077
|
+
type: "string",
|
|
2078
|
+
enum: ["all", "topic", "article", "summary"],
|
|
2079
|
+
description: "Document kind to search; defaults to all",
|
|
2080
|
+
},
|
|
2081
|
+
limit: {
|
|
2082
|
+
type: "number",
|
|
2083
|
+
minimum: 1,
|
|
2084
|
+
maximum: 20,
|
|
2085
|
+
description: "Maximum number of candidates; defaults to 8",
|
|
2086
|
+
},
|
|
2087
|
+
},
|
|
2088
|
+
required: ["question"],
|
|
2089
|
+
},
|
|
2090
|
+
},
|
|
2091
|
+
{
|
|
2092
|
+
name: "wiki_read",
|
|
2093
|
+
description:
|
|
2094
|
+
"Read one topic, article, or summary returned by wiki_query. For a clearly matching continuing persona, set adopt=true when reading a topic.",
|
|
2095
|
+
inputSchema: {
|
|
2096
|
+
type: "object",
|
|
2097
|
+
properties: {
|
|
2098
|
+
kind: { type: "string", enum: ["topic", "article", "summary"] },
|
|
2099
|
+
key: { type: "string", description: "Canonical key returned by wiki_query" },
|
|
2100
|
+
adopt: {
|
|
2101
|
+
type: "boolean",
|
|
2102
|
+
description:
|
|
2103
|
+
"For kind=topic, persist this canonical memory key for the current room. A room that already has a memory key keeps it.",
|
|
2104
|
+
},
|
|
2105
|
+
},
|
|
2106
|
+
required: ["kind", "key"],
|
|
2107
|
+
},
|
|
2108
|
+
},
|
|
2109
|
+
{
|
|
2110
|
+
name: "wiki_topic_brief",
|
|
2111
|
+
description: "Get the lightweight topic brief for a specific topic.",
|
|
2112
|
+
inputSchema: {
|
|
2113
|
+
type: "object",
|
|
2114
|
+
properties: {
|
|
2115
|
+
topic: {
|
|
2116
|
+
type: "string",
|
|
2117
|
+
description: "Topic name (e.g. 'dev', 'trading', 'research')",
|
|
2118
|
+
},
|
|
2119
|
+
},
|
|
2120
|
+
required: ["topic"],
|
|
2121
|
+
},
|
|
2122
|
+
},
|
|
2123
|
+
{
|
|
2124
|
+
name: "wiki_last_conversation",
|
|
2125
|
+
description: "Read the last N turns from the most recent archived session log for a topic.",
|
|
2126
|
+
inputSchema: {
|
|
2127
|
+
type: "object",
|
|
2128
|
+
properties: {
|
|
2129
|
+
topic: {
|
|
2130
|
+
type: "string",
|
|
2131
|
+
description: "Topic name (e.g. 'dev', 'trading')",
|
|
2132
|
+
},
|
|
2133
|
+
turns: {
|
|
2134
|
+
type: "number",
|
|
2135
|
+
description: "Number of recent turns (max 10), default 5",
|
|
2136
|
+
minimum: 1,
|
|
2137
|
+
maximum: 10,
|
|
2138
|
+
},
|
|
2139
|
+
},
|
|
2140
|
+
required: ["topic"],
|
|
2141
|
+
},
|
|
2142
|
+
},
|
|
2143
|
+
{
|
|
2144
|
+
name: "wiki_write",
|
|
2145
|
+
description:
|
|
2146
|
+
"Write a wiki document and its catalog row together. The only way to create a summary, article, or topic brief: summaries go to wiki/summaries/ + summary-index.md, articles to wiki/articles/ + article-index.md, briefs to wiki/topic/ + topic-index.md (also mirrored into SQLite for next-session injection). Never write wiki files by any other means.",
|
|
2147
|
+
inputSchema: {
|
|
2148
|
+
type: "object",
|
|
2149
|
+
properties: {
|
|
2150
|
+
kind: {
|
|
2151
|
+
type: "string",
|
|
2152
|
+
enum: ["summary", "article", "topic"],
|
|
2153
|
+
description: "Which document to write",
|
|
2154
|
+
},
|
|
2155
|
+
content: { type: "string", description: "Document body in markdown" },
|
|
2156
|
+
description: {
|
|
2157
|
+
type: "string",
|
|
2158
|
+
description: "Single-line catalog description; required so the index stays useful",
|
|
2159
|
+
},
|
|
2160
|
+
topic: {
|
|
2161
|
+
type: "string",
|
|
2162
|
+
description:
|
|
2163
|
+
"Topic name; required for kind=summary and kind=topic. A room with a memory key accepts only that key.",
|
|
2164
|
+
},
|
|
2165
|
+
slug: {
|
|
2166
|
+
type: "string",
|
|
2167
|
+
description: "Article slug in kebab-case; required for kind=article",
|
|
2168
|
+
},
|
|
2169
|
+
section: {
|
|
2170
|
+
type: "string",
|
|
2171
|
+
description: "H2 catalog section; required for kind=article",
|
|
2172
|
+
},
|
|
2173
|
+
date: { type: "string", description: "Override entry date YYYY-MM-DD (default: today)" },
|
|
2174
|
+
},
|
|
2175
|
+
required: ["kind", "content", "description"],
|
|
2176
|
+
},
|
|
2177
|
+
},
|
|
2178
|
+
{
|
|
2179
|
+
name: "wiki_reindex",
|
|
2180
|
+
description:
|
|
2181
|
+
"Rebuild the derived body-search cache from the documents on disk and report catalog gaps. Run this once after adding documents outside wiki_write; retrieval itself never scans the wiki.",
|
|
2182
|
+
inputSchema: { type: "object", properties: {} },
|
|
2183
|
+
},
|
|
2184
|
+
{
|
|
2185
|
+
name: "index_upsert",
|
|
2186
|
+
description:
|
|
2187
|
+
"Correct the description or section of an entry that already exists. Cannot create an entry — use wiki_write for that.",
|
|
2188
|
+
inputSchema: {
|
|
2189
|
+
type: "object",
|
|
2190
|
+
properties: {
|
|
2191
|
+
slug: {
|
|
2192
|
+
type: "string",
|
|
2193
|
+
description: "Article/summary slug or topic name",
|
|
2194
|
+
},
|
|
2195
|
+
description: {
|
|
2196
|
+
type: "string",
|
|
2197
|
+
description: "Single-line description for the index row",
|
|
2198
|
+
},
|
|
2199
|
+
kind: {
|
|
2200
|
+
type: "string",
|
|
2201
|
+
enum: ["article", "summary", "topic", "skill"],
|
|
2202
|
+
description: "Which index to update",
|
|
2203
|
+
},
|
|
2204
|
+
section: {
|
|
2205
|
+
type: "string",
|
|
2206
|
+
description: "For kind='article': H2 section title",
|
|
2207
|
+
},
|
|
2208
|
+
date: {
|
|
2209
|
+
type: "string",
|
|
2210
|
+
description: "Override entry date YYYY-MM-DD (default: today)",
|
|
2211
|
+
},
|
|
2212
|
+
},
|
|
2213
|
+
required: ["slug", "description", "kind"],
|
|
2214
|
+
},
|
|
2215
|
+
},
|
|
2216
|
+
];
|
|
2217
|
+
|
|
2218
|
+
const SKILL_TOOLS: Tool[] = [
|
|
2219
|
+
{
|
|
2220
|
+
name: "skill_query",
|
|
2221
|
+
description: "Search this node's local skill library and return matching definitions.",
|
|
2222
|
+
inputSchema: {
|
|
2223
|
+
type: "object",
|
|
2224
|
+
properties: {
|
|
2225
|
+
question: {
|
|
2226
|
+
type: "string",
|
|
2227
|
+
description: "The skill name or description of what you want to do",
|
|
2228
|
+
},
|
|
2229
|
+
},
|
|
2230
|
+
required: ["question"],
|
|
2231
|
+
},
|
|
2232
|
+
},
|
|
2233
|
+
{
|
|
2234
|
+
name: "skill_save",
|
|
2235
|
+
description: "Create or update a skill on this node.",
|
|
2236
|
+
inputSchema: {
|
|
2237
|
+
type: "object",
|
|
2238
|
+
properties: {
|
|
2239
|
+
name: {
|
|
2240
|
+
type: "string",
|
|
2241
|
+
description: "Skill folder name in kebab-case",
|
|
2242
|
+
},
|
|
2243
|
+
content: {
|
|
2244
|
+
type: "string",
|
|
2245
|
+
description: "Skill definition in markdown (with frontmatter name+description)",
|
|
2246
|
+
},
|
|
2247
|
+
},
|
|
2248
|
+
required: ["name", "content"],
|
|
2249
|
+
},
|
|
2250
|
+
},
|
|
2251
|
+
];
|
|
2252
|
+
|
|
2253
|
+
// --- Server ----------------------------------------------------------------
|
|
2254
|
+
|
|
2255
|
+
export function createWikiMcpServer(context: WikiMcpContext, host: WikiMcpHost): Server {
|
|
2256
|
+
const surface = context.surface ?? "all";
|
|
2257
|
+
const wikiDir = resolve(host.wikiRoot);
|
|
2258
|
+
const current: WikiRuntime = {
|
|
2259
|
+
userId: context.userId,
|
|
2260
|
+
currentTopicId: context.currentTopicId ?? context.topicId,
|
|
2261
|
+
topicId: context.topicId,
|
|
2262
|
+
surface,
|
|
2263
|
+
host,
|
|
2264
|
+
wikiDir,
|
|
2265
|
+
skillsDir: resolve(wikiDir, "skills"),
|
|
2266
|
+
topicsDir: resolve(wikiDir, "topic"),
|
|
2267
|
+
summariesDir: resolve(wikiDir, "summaries"),
|
|
2268
|
+
articlesDir: resolve(wikiDir, "articles"),
|
|
2269
|
+
archiveDir: resolve(wikiDir, "archive"),
|
|
2270
|
+
};
|
|
2271
|
+
const baseTools =
|
|
2272
|
+
surface === "wiki"
|
|
2273
|
+
? WIKI_TOOLS
|
|
2274
|
+
: surface === "skills"
|
|
2275
|
+
? SKILL_TOOLS
|
|
2276
|
+
: [...WIKI_TOOLS, ...SKILL_TOOLS];
|
|
2277
|
+
const tools = baseTools;
|
|
2278
|
+
for (const directory of [
|
|
2279
|
+
current.skillsDir,
|
|
2280
|
+
current.topicsDir,
|
|
2281
|
+
current.summariesDir,
|
|
2282
|
+
current.articlesDir,
|
|
2283
|
+
current.archiveDir,
|
|
2284
|
+
]) {
|
|
2285
|
+
ensureDir(directory);
|
|
2286
|
+
}
|
|
2287
|
+
|
|
2288
|
+
const server = new Server(
|
|
2289
|
+
{ name: "wiki-server", version: "2.0.0" },
|
|
2290
|
+
{ capabilities: { tools: {} } },
|
|
2291
|
+
);
|
|
2292
|
+
server.setRequestHandler(
|
|
2293
|
+
ListToolsRequestSchema,
|
|
2294
|
+
async (): Promise<ListToolsResult> => ({
|
|
2295
|
+
tools,
|
|
2296
|
+
}),
|
|
2297
|
+
);
|
|
2298
|
+
server.setRequestHandler(CallToolRequestSchema, async (request): Promise<CallToolResult> => {
|
|
2299
|
+
return wikiRuntime.run(current, () => {
|
|
2300
|
+
const { name, arguments: args } = request.params;
|
|
2301
|
+
const handlers: Record<string, (a: Record<string, unknown>) => CallToolResult> = {
|
|
2302
|
+
wiki_query: wikiQuery,
|
|
2303
|
+
wiki_read: wikiRead,
|
|
2304
|
+
wiki_topic_brief: wikiTopicBrief,
|
|
2305
|
+
wiki_last_conversation: wikiLastConversation,
|
|
2306
|
+
skill_query: skillQuery,
|
|
2307
|
+
skill_save: skillSave,
|
|
2308
|
+
wiki_write: wikiWrite,
|
|
2309
|
+
wiki_reindex: wikiReindex,
|
|
2310
|
+
index_upsert: indexUpsert,
|
|
2311
|
+
};
|
|
2312
|
+
const handler = tools.some((tool) => tool.name === name) ? handlers[name] : undefined;
|
|
2313
|
+
return handler
|
|
2314
|
+
? handler((args ?? {}) as Record<string, unknown>)
|
|
2315
|
+
: { content: [{ type: "text", text: `Unknown tool: ${name}` }] };
|
|
2316
|
+
});
|
|
2317
|
+
});
|
|
2318
|
+
return server;
|
|
2319
|
+
}
|
|
2320
|
+
|
|
2321
|
+
// --- Entrypoint ------------------------------------------------------------
|
|
2322
|
+
|
|
2323
|
+
/**
|
|
2324
|
+
* The room-memory half of a wiki host, backed by node storage. Both the stdio
|
|
2325
|
+
* entrypoint and the hosted wiki surface use it, so a room reads, writes, and
|
|
2326
|
+
* adopts memory the same way whichever transport serves it.
|
|
2327
|
+
*/
|
|
2328
|
+
export async function loadTopicMemoryHost(): Promise<Omit<WikiMcpHost, "wikiRoot">> {
|
|
2329
|
+
const [briefs, topics, topicLifecycle] = await Promise.all([
|
|
2330
|
+
import("#storage/api-topic-brief"),
|
|
2331
|
+
import("#storage/api-topics"),
|
|
2332
|
+
import("#topics/derive"),
|
|
2333
|
+
]);
|
|
2334
|
+
return {
|
|
2335
|
+
canReadTopicMemory: (selection, userId, boundTopicId) =>
|
|
2336
|
+
findAccessibleMemoryTopic(selection, userId, topics.listTopics(), boundTopicId) !== undefined,
|
|
2337
|
+
getTopicBrief: briefs.getTopicBrief,
|
|
2338
|
+
resolveTopicBrief: (selection, userId, boundTopicId) =>
|
|
2339
|
+
resolveAccessibleWikiTopicBrief(
|
|
2340
|
+
selection,
|
|
2341
|
+
userId,
|
|
2342
|
+
topics.listTopics(),
|
|
2343
|
+
briefs.resolveTopicBrief,
|
|
2344
|
+
boundTopicId,
|
|
2345
|
+
),
|
|
2346
|
+
setTopicBrief: briefs.setTopicBrief,
|
|
2347
|
+
fixedMemoryKey: (topicId) => topics.getTopic(topicId)?.memoryKey?.trim() || undefined,
|
|
2348
|
+
adoptTopicMemory: (topicId, userId, memoryKey) => {
|
|
2349
|
+
const topic = topics.getTopic(topicId);
|
|
2350
|
+
if (
|
|
2351
|
+
!topic?.participants.some(
|
|
2352
|
+
(participant) => participant.userId === userId && participant.role === "owner",
|
|
2353
|
+
)
|
|
2354
|
+
) {
|
|
2355
|
+
return false;
|
|
2356
|
+
}
|
|
2357
|
+
const current = topic.memoryKey?.trim();
|
|
2358
|
+
if (current) return wikiSummarySlug(current) === memoryKey;
|
|
2359
|
+
return topicLifecycle.updateTopic(topicId, { memoryKey });
|
|
2360
|
+
},
|
|
2361
|
+
};
|
|
2362
|
+
}
|
|
2363
|
+
|
|
2364
|
+
async function main() {
|
|
2365
|
+
const context = parseArgv();
|
|
2366
|
+
let bridge: Partial<WikiMcpHost> = {};
|
|
2367
|
+
if (context.topicId) {
|
|
2368
|
+
try {
|
|
2369
|
+
bridge = await loadTopicMemoryHost();
|
|
2370
|
+
} catch {
|
|
2371
|
+
// DB not available — degrade gracefully (file-only).
|
|
2372
|
+
}
|
|
2373
|
+
}
|
|
2374
|
+
const transport = new StdioServerTransport();
|
|
2375
|
+
await createWikiMcpServer(context, {
|
|
2376
|
+
wikiRoot: SHARED_WIKI_DIR,
|
|
2377
|
+
...bridge,
|
|
2378
|
+
}).connect(transport);
|
|
2379
|
+
}
|
|
2380
|
+
|
|
2381
|
+
if (import.meta.main) {
|
|
2382
|
+
main().catch((err) => {
|
|
2383
|
+
console.error("wiki-server fatal:", err);
|
|
2384
|
+
exit(1);
|
|
2385
|
+
});
|
|
2386
|
+
}
|