somora 2026.930.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +364 -0
- package/bin/node-version.d.mts +3 -0
- package/bin/node-version.mjs +45 -0
- package/bin/somora.mjs +77 -0
- package/config.example.yaml +896 -0
- package/docs/agents.md +677 -0
- package/docs/api.md +3194 -0
- package/docs/browser.md +317 -0
- package/docs/builder.md +331 -0
- package/docs/cache-strategy.md +373 -0
- package/docs/compaction.md +253 -0
- package/docs/display.md +154 -0
- package/docs/dream-phases.md +891 -0
- package/docs/files.md +387 -0
- package/docs/imagegen.md +366 -0
- package/docs/images/somora-hero.png +0 -0
- package/docs/images/somora-mobile-2026-05-23.png +0 -0
- package/docs/images/somora-tui-2026-05-23.png +0 -0
- package/docs/images/somora-web-2026-05-23.png +0 -0
- package/docs/index.md +178 -0
- package/docs/lsp.md +93 -0
- package/docs/mcp.md +332 -0
- package/docs/memory.md +407 -0
- package/docs/mobile.md +310 -0
- package/docs/models.md +379 -0
- package/docs/projects.md +425 -0
- package/docs/realtime-voice.md +293 -0
- package/docs/resources.md +230 -0
- package/docs/sampling.md +128 -0
- package/docs/security.md +189 -0
- package/docs/sentinel.md +295 -0
- package/docs/setup.md +1217 -0
- package/docs/skills.md +501 -0
- package/docs/team.md +189 -0
- package/docs/thinking.md +463 -0
- package/docs/tmux.md +399 -0
- package/docs/tools.md +117 -0
- package/docs/videogen.md +191 -0
- package/docs/voice.md +288 -0
- package/docs/web.md +893 -0
- package/docs/wiki.md +583 -0
- package/npm-shrinkwrap.json +5670 -0
- package/package.json +116 -0
- package/src/attachments/store.ts +196 -0
- package/src/browser/change-stream.ts +31 -0
- package/src/browser/display.ts +108 -0
- package/src/browser/policy.ts +121 -0
- package/src/browser/screencast.ts +374 -0
- package/src/browser/service.ts +1337 -0
- package/src/browser/session.ts +15 -0
- package/src/browser/snapshot.ts +40 -0
- package/src/cli/auth.ts +117 -0
- package/src/cli/codex.ts +41 -0
- package/src/cli/lsp.ts +71 -0
- package/src/cli/resolvers/clawhub.ts +400 -0
- package/src/cli/setup.ts +835 -0
- package/src/cli/skill.ts +619 -0
- package/src/cli/somora.ts +548 -0
- package/src/cli/systemd-unit.ts +72 -0
- package/src/cli/team.ts +148 -0
- package/src/cli/tui/activity-stream.ts +121 -0
- package/src/cli/tui/api.ts +479 -0
- package/src/cli/tui/app.tsx +1169 -0
- package/src/cli/tui/autocomplete.tsx +55 -0
- package/src/cli/tui/commands.ts +913 -0
- package/src/cli/tui/dream-glyphs.ts +22 -0
- package/src/cli/tui/footer.tsx +15 -0
- package/src/cli/tui/format.ts +28 -0
- package/src/cli/tui/header.tsx +279 -0
- package/src/cli/tui/index.tsx +120 -0
- package/src/cli/tui/markdown.tsx +63 -0
- package/src/cli/tui/sampling.ts +162 -0
- package/src/cli/tui/separator.tsx +13 -0
- package/src/cli/tui/state.ts +42 -0
- package/src/cli/tui/stream.ts +330 -0
- package/src/cli/tui/thinking-text.ts +54 -0
- package/src/cli/tui/turn-views.tsx +499 -0
- package/src/cli/tui/types.ts +410 -0
- package/src/cli/tui/work-queue.ts +161 -0
- package/src/cli/update-args.ts +55 -0
- package/src/cli/wiki.ts +406 -0
- package/src/compaction/index.ts +28 -0
- package/src/compaction/midturn.ts +210 -0
- package/src/compaction/policy.ts +154 -0
- package/src/compaction/summarize.ts +691 -0
- package/src/compaction/template.ts +90 -0
- package/src/compaction/types.ts +148 -0
- package/src/config/loader.ts +276 -0
- package/src/config/reload.ts +43 -0
- package/src/config/types.ts +2292 -0
- package/src/dream/deep-actions.ts +324 -0
- package/src/dream/deep-dispatcher.ts +237 -0
- package/src/dream/deep-llm.ts +388 -0
- package/src/dream/deep-prompts.ts +106 -0
- package/src/dream/deep-runner.ts +757 -0
- package/src/dream/deep-skip-cache.ts +199 -0
- package/src/dream/deep-worker.ts +229 -0
- package/src/dream/json-salvage.ts +34 -0
- package/src/dream/judge.ts +188 -0
- package/src/dream/loop-state.ts +286 -0
- package/src/dream/lucid-actions.ts +303 -0
- package/src/dream/lucid-batches.ts +94 -0
- package/src/dream/lucid-prompt.ts +82 -0
- package/src/dream/lucid-runner.ts +744 -0
- package/src/dream/lucid-storage.ts +277 -0
- package/src/dream/lucid-structure.ts +102 -0
- package/src/dream/lucid-types.ts +137 -0
- package/src/dream/lucid-worker.ts +224 -0
- package/src/dream/rem-dedup.ts +502 -0
- package/src/dream/rem-extract.ts +782 -0
- package/src/dream/rem-reset-run.ts +67 -0
- package/src/dream/rem-runner.ts +696 -0
- package/src/dream/rem-worker.ts +527 -0
- package/src/dream/review-window.ts +71 -0
- package/src/dream/scheduler-state.ts +129 -0
- package/src/dream/storage.ts +497 -0
- package/src/dream/types.ts +133 -0
- package/src/dream/wiki-context.ts +133 -0
- package/src/engine/a2a.ts +33 -0
- package/src/engine/availability.ts +63 -0
- package/src/engine/claude-cli.ts +969 -0
- package/src/engine/codex-app-server-client.ts +294 -0
- package/src/engine/codex-bin.ts +49 -0
- package/src/engine/codex-cli.ts +1014 -0
- package/src/engine/codex-dynamic-tools.ts +239 -0
- package/src/engine/codex-home.ts +63 -0
- package/src/engine/codex-thread-config.ts +74 -0
- package/src/engine/context-budget.ts +257 -0
- package/src/engine/engine-meta-labels.ts +211 -0
- package/src/engine/grok-cli.ts +941 -0
- package/src/engine/inline-think.ts +59 -0
- package/src/engine/model-availability.ts +105 -0
- package/src/engine/openai-compatible.ts +2464 -0
- package/src/engine/reasoning-retry.ts +83 -0
- package/src/engine/registry.ts +13 -0
- package/src/engine/replay.ts +195 -0
- package/src/engine/sampling.ts +90 -0
- package/src/engine/thinking-params.ts +264 -0
- package/src/engine/types.ts +269 -0
- package/src/engine/user-tag.ts +24 -0
- package/src/imagegen/aspect.ts +128 -0
- package/src/imagegen/generate.ts +642 -0
- package/src/imagegen/references.ts +75 -0
- package/src/imagegen/types.ts +154 -0
- package/src/lsp/client.ts +183 -0
- package/src/lsp/fake-server.helper.mjs +42 -0
- package/src/lsp/format.ts +29 -0
- package/src/lsp/index.ts +21 -0
- package/src/lsp/manager.ts +238 -0
- package/src/lsp/registry.ts +151 -0
- package/src/mcp/config.ts +117 -0
- package/src/mcp/hub/audit.ts +55 -0
- package/src/mcp/hub/bridge.ts +115 -0
- package/src/mcp/hub/catalog.ts +69 -0
- package/src/mcp/hub/credentials.ts +406 -0
- package/src/mcp/hub/env-expand.ts +14 -0
- package/src/mcp/hub/manager.ts +770 -0
- package/src/mcp/hub/normalize.ts +213 -0
- package/src/mcp/server.ts +368 -0
- package/src/mcp/tool-schema.ts +20 -0
- package/src/media/capabilities.ts +392 -0
- package/src/media/records.ts +175 -0
- package/src/media/store.ts +217 -0
- package/src/media/types.ts +69 -0
- package/src/memory/chunking.ts +168 -0
- package/src/memory/embeddings.ts +262 -0
- package/src/memory/index.ts +15 -0
- package/src/memory/inject.ts +197 -0
- package/src/memory/manager.ts +996 -0
- package/src/memory/registry.ts +176 -0
- package/src/memory/rescan.ts +101 -0
- package/src/memory/retrieval.ts +586 -0
- package/src/memory/shared-index.ts +372 -0
- package/src/memory/slug.ts +39 -0
- package/src/memory/storage.ts +385 -0
- package/src/memory/watcher.ts +134 -0
- package/src/multimodal/blocks.ts +101 -0
- package/src/multimodal/dimensions.ts +214 -0
- package/src/multimodal/load.ts +86 -0
- package/src/multimodal/mime.ts +135 -0
- package/src/multimodal/pdf-render.ts +80 -0
- package/src/multimodal/user-content.ts +266 -0
- package/src/persona/files.ts +144 -0
- package/src/persona/loader.ts +598 -0
- package/src/persona/skill-gating-store.ts +59 -0
- package/src/persona/tool-gating-store.ts +113 -0
- package/src/projects/focus.ts +186 -0
- package/src/projects/prompt-block.ts +106 -0
- package/src/projects/scheme.ts +107 -0
- package/src/projects/store.ts +144 -0
- package/src/projects/types.ts +73 -0
- package/src/sentinel/dispatcher.ts +97 -0
- package/src/sentinel/schedule.ts +271 -0
- package/src/sentinel/scheduler.ts +840 -0
- package/src/sentinel/store.ts +259 -0
- package/src/sentinel/types.ts +221 -0
- package/src/server/activity-stream.ts +160 -0
- package/src/server/ask-calls.ts +137 -0
- package/src/server/ask-wait-graph.ts +171 -0
- package/src/server/async-tasks.ts +199 -0
- package/src/server/builder-busy.ts +86 -0
- package/src/server/builder-prompt.ts +204 -0
- package/src/server/builder-questions.ts +117 -0
- package/src/server/builder-session.ts +249 -0
- package/src/server/chat-aborts.ts +83 -0
- package/src/server/claude-config-dir.ts +71 -0
- package/src/server/claude-credential-sync.ts +454 -0
- package/src/server/env-file.ts +100 -0
- package/src/server/env.ts +115 -0
- package/src/server/heal-session.ts +151 -0
- package/src/server/history-page.ts +46 -0
- package/src/server/index.ts +7244 -0
- package/src/server/lockfile.ts +89 -0
- package/src/server/logger.ts +67 -0
- package/src/server/logs.ts +187 -0
- package/src/server/loopback-fetch.ts +130 -0
- package/src/server/openai-client.ts +89 -0
- package/src/server/prompt-assembly.ts +334 -0
- package/src/server/restart-reconcile.ts +139 -0
- package/src/server/run-turn-fallback.ts +275 -0
- package/src/server/run-turn-types.ts +91 -0
- package/src/server/run-turn.ts +1474 -0
- package/src/server/sanitize-assistant-text.ts +112 -0
- package/src/server/session-export.ts +220 -0
- package/src/server/session-queue.ts +376 -0
- package/src/server/session-workdir.ts +49 -0
- package/src/server/sse-h2-safe.ts +61 -0
- package/src/server/sse-liveness.ts +162 -0
- package/src/server/sse-serializer.ts +161 -0
- package/src/server/start-turn.ts +249 -0
- package/src/server/steer-inbox.ts +107 -0
- package/src/server/tls-keeper.ts +153 -0
- package/src/server/tool-format.ts +167 -0
- package/src/server/turn-framing.ts +52 -0
- package/src/server/turn-origin-kind.ts +74 -0
- package/src/server/turn-origin.ts +40 -0
- package/src/server/work-ledger.ts +975 -0
- package/src/server/workspace.ts +114 -0
- package/src/setup/config-edit.ts +201 -0
- package/src/setup/presets.ts +71 -0
- package/src/setup/prompt.ts +163 -0
- package/src/setup/tailscale.ts +44 -0
- package/src/skills/bin-checks.ts +227 -0
- package/src/skills/bootstrap.ts +347 -0
- package/src/skills/env-scope.ts +175 -0
- package/src/skills/gating.ts +71 -0
- package/src/skills/lint.ts +202 -0
- package/src/skills/load.ts +368 -0
- package/src/skills/path-helpers.ts +102 -0
- package/src/skills/registry.ts +178 -0
- package/src/ssh/exec.ts +142 -0
- package/src/ssh/index.ts +12 -0
- package/src/ssh/known-hosts.ts +109 -0
- package/src/ssh/pool.ts +307 -0
- package/src/storage/sessions.ts +602 -0
- package/src/team/render.ts +149 -0
- package/src/team/resolve.ts +122 -0
- package/src/team/store.ts +124 -0
- package/src/team/types.ts +111 -0
- package/src/team/write.ts +95 -0
- package/src/testing/isolated-home.mts +46 -0
- package/src/tmux/attention-watcher.ts +272 -0
- package/src/tmux/attention.ts +336 -0
- package/src/tmux/list.ts +91 -0
- package/src/tmux/origin-store.ts +102 -0
- package/src/tmux/tui-markers.ts +267 -0
- package/src/tools/agents/ask-cancel.ts +94 -0
- package/src/tools/agents/ask-result.ts +235 -0
- package/src/tools/agents/ask.ts +704 -0
- package/src/tools/agents/builder-dispatch.ts +217 -0
- package/src/tools/agents/images.ts +104 -0
- package/src/tools/agents/index.ts +42 -0
- package/src/tools/agents/long-task-timeouts.ts +39 -0
- package/src/tools/agents/session-list.ts +136 -0
- package/src/tools/agents/session-model.ts +106 -0
- package/src/tools/agents/spawn.ts +845 -0
- package/src/tools/agents/status.ts +589 -0
- package/src/tools/browser/index.ts +6 -0
- package/src/tools/browser/ops.ts +145 -0
- package/src/tools/browser/tools.ts +184 -0
- package/src/tools/builder/short-descriptions.ts +80 -0
- package/src/tools/builder/tools.ts +222 -0
- package/src/tools/docs/index.ts +1 -0
- package/src/tools/docs/tools.ts +228 -0
- package/src/tools/dream/index.ts +11 -0
- package/src/tools/dream/tools.ts +1002 -0
- package/src/tools/exec/allowlist.ts +233 -0
- package/src/tools/exec/background-detach.helper.mts +27 -0
- package/src/tools/exec/blacklist.ts +336 -0
- package/src/tools/exec/concurrency.ts +150 -0
- package/src/tools/exec/fit-output.ts +82 -0
- package/src/tools/exec/index.ts +7 -0
- package/src/tools/exec/internal-env.ts +89 -0
- package/src/tools/exec/job-store.ts +403 -0
- package/src/tools/exec/local.ts +649 -0
- package/src/tools/exec/remote.ts +399 -0
- package/src/tools/exec/tools.ts +934 -0
- package/src/tools/file/analyze.ts +378 -0
- package/src/tools/file/index.ts +2 -0
- package/src/tools/file/local.ts +707 -0
- package/src/tools/file/lsp-hook.ts +72 -0
- package/src/tools/file/persona-guard.ts +61 -0
- package/src/tools/file/policy.ts +292 -0
- package/src/tools/file/read-format.ts +129 -0
- package/src/tools/file/remote.ts +680 -0
- package/src/tools/file/replace.ts +507 -0
- package/src/tools/file/search-window.ts +224 -0
- package/src/tools/file/tools.ts +658 -0
- package/src/tools/file/write-scope.ts +182 -0
- package/src/tools/gating.ts +106 -0
- package/src/tools/image/budget.ts +82 -0
- package/src/tools/image/index.ts +7 -0
- package/src/tools/image/tools.ts +601 -0
- package/src/tools/index.ts +99 -0
- package/src/tools/memory/index.ts +12 -0
- package/src/tools/memory/tools.ts +399 -0
- package/src/tools/projects/index.ts +1 -0
- package/src/tools/projects/tools.ts +643 -0
- package/src/tools/registry.ts +427 -0
- package/src/tools/resources/index.ts +8 -0
- package/src/tools/resources/tools.ts +176 -0
- package/src/tools/resources/visibility.ts +60 -0
- package/src/tools/sentinel/index.ts +1 -0
- package/src/tools/sentinel/tools.ts +592 -0
- package/src/tools/skill/index.ts +4 -0
- package/src/tools/skill/tools.ts +285 -0
- package/src/tools/time/index.ts +5 -0
- package/src/tools/time/tools.ts +123 -0
- package/src/tools/tmux/index.ts +1 -0
- package/src/tools/tmux/local.ts +277 -0
- package/src/tools/tmux/remote.ts +168 -0
- package/src/tools/tmux/tools.ts +1064 -0
- package/src/tools/tool-output.ts +97 -0
- package/src/tools/types.ts +227 -0
- package/src/tools/video/index.ts +1 -0
- package/src/tools/video/tools.ts +425 -0
- package/src/tools/web/fetch.ts +337 -0
- package/src/tools/web/index.ts +4 -0
- package/src/tools/web/tools.ts +186 -0
- package/src/tools/wiki/index.ts +1 -0
- package/src/tools/wiki/tools.ts +445 -0
- package/src/tts/cache-gc.ts +128 -0
- package/src/tts/prepare-for-tts.ts +114 -0
- package/src/tts/service.ts +332 -0
- package/src/types/events.ts +695 -0
- package/src/types/turn-origin.ts +53 -0
- package/src/version.ts +21 -0
- package/src/videogen/dialects.ts +222 -0
- package/src/videogen/generate.ts +484 -0
- package/src/videogen/jobs.ts +178 -0
- package/src/videogen/runner.ts +125 -0
- package/src/videogen/wake.ts +119 -0
- package/src/voice/realtime/call.ts +948 -0
- package/src/voice/realtime/consult.ts +293 -0
- package/src/voice/realtime/fake-provider.ts +134 -0
- package/src/voice/realtime/manager.ts +384 -0
- package/src/voice/realtime/openai-provider.ts +471 -0
- package/src/voice/realtime/persona.ts +227 -0
- package/src/voice/realtime/session-match.ts +116 -0
- package/src/voice/realtime/types.ts +182 -0
- package/src/wiki/conflict.ts +113 -0
- package/src/wiki/explorer.ts +578 -0
- package/src/wiki/index-builder.ts +172 -0
- package/src/wiki/language.ts +134 -0
- package/src/wiki/log-builder.ts +150 -0
- package/src/wiki/map.ts +258 -0
- package/src/wiki/migration/analyze.ts +304 -0
- package/src/wiki/migration/execute.ts +689 -0
- package/src/wiki/migration/refine.ts +402 -0
- package/src/wiki/migration/store.ts +100 -0
- package/src/wiki/move-page.ts +57 -0
- package/src/wiki/structure-file.ts +192 -0
- package/src/wiki/taxonomy.ts +140 -0
- package/src/wiki/templates.ts +163 -0
- package/src/wiki/types.ts +133 -0
- package/templates/skills/README.md +24 -0
- package/templates/skills/_templates/api-wrapper/SKILL.md +26 -0
- package/templates/skills/_templates/cli-wrapper/BOOTSTRAP.md +32 -0
- package/templates/skills/_templates/cli-wrapper/SKILL.md +24 -0
- package/templates/skills/_templates/default/SKILL.md +25 -0
- package/templates/skills/builder-handover/SKILL.md +96 -0
- package/templates/skills/builder-handover/assets/ORDER.md +12 -0
- package/templates/skills/skill-author/SKILL.md +110 -0
- package/tsconfig.json +22 -0
- package/web/dist/assets/index-BaVv6pB2.js +631 -0
- package/web/dist/assets/index-BaVv6pB2.js.map +1 -0
- package/web/dist/assets/index-V3FV3Z25.css +32 -0
- package/web/dist/favicon.svg +8 -0
- package/web/dist/index.html +20 -0
- package/web/package.json +36 -0
- package/web/tsconfig.json +25 -0
- package/web-mobile/dist/apple-touch-icon.png +0 -0
- package/web-mobile/dist/assets/index-BqKt7IMx.css +1 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js +88 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js.map +1 -0
- package/web-mobile/dist/favicon.svg +8 -0
- package/web-mobile/dist/icon-192.png +0 -0
- package/web-mobile/dist/icon-512.png +0 -0
- package/web-mobile/dist/index.html +27 -0
- package/web-mobile/dist/manifest.webmanifest +32 -0
- package/web-mobile/dist/service-worker.js +90 -0
- package/web-mobile/package.json +28 -0
- package/web-mobile/tsconfig.json +25 -0
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
// The language servers of this somora: one per (root, server), started
|
|
2
|
+
// when a builder first touches a matching file, stopped after ten idle
|
|
3
|
+
// minutes or at shutdown. `diagnosticsAfterWrite` is what file_write and
|
|
4
|
+
// file_patch call: send the new text, wait for the server's verdict on
|
|
5
|
+
// that file, return the errors — and the errors of other files whose
|
|
6
|
+
// verdict changed since the last delivery (a rename breaks its callers).
|
|
7
|
+
|
|
8
|
+
import { readFile } from 'node:fs/promises';
|
|
9
|
+
import { relative } from 'node:path';
|
|
10
|
+
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
11
|
+
import { logger } from '../server/logger.ts';
|
|
12
|
+
import { LspClient } from './client.ts';
|
|
13
|
+
import { formatFileErrors, MAX_OTHER_FILES, type LspDiagnostic } from './format.ts';
|
|
14
|
+
import { findBinary, rootFor, serverForFile, type LspServerDef } from './registry.ts';
|
|
15
|
+
|
|
16
|
+
export const LSP_IDLE_MS = 10 * 60_000;
|
|
17
|
+
export const LSP_DEBOUNCE_MS = 150;
|
|
18
|
+
const INIT_TIMEOUT_MS = 20_000;
|
|
19
|
+
|
|
20
|
+
export interface LspConfigLike {
|
|
21
|
+
enabled: boolean;
|
|
22
|
+
waitMs: number;
|
|
23
|
+
servers: Record<string, { enabled?: boolean; command?: string }>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface Instance {
|
|
27
|
+
key: string;
|
|
28
|
+
def: LspServerDef;
|
|
29
|
+
root: string;
|
|
30
|
+
client: LspClient;
|
|
31
|
+
ready: Promise<void>;
|
|
32
|
+
docs: Map<string, number>; // uri -> version
|
|
33
|
+
diags: Map<string, LspDiagnostic[]>; // uri -> latest
|
|
34
|
+
/** Version of diags per uri that were already delivered to the model. */
|
|
35
|
+
delivered: Map<string, string>;
|
|
36
|
+
waiters: Set<(uri: string) => void>;
|
|
37
|
+
lastUsed: number;
|
|
38
|
+
firstDiagnosticsSeen: boolean;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface WriteDiagnostics {
|
|
42
|
+
server: string;
|
|
43
|
+
errors: string[];
|
|
44
|
+
errors_in_other_files: Record<string, string[]>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export class LspManager {
|
|
48
|
+
private instances = new Map<string, Instance>();
|
|
49
|
+
private broken = new Map<string, number>(); // key -> until (ms)
|
|
50
|
+
private sweeper: NodeJS.Timeout | null = null;
|
|
51
|
+
|
|
52
|
+
constructor(private readonly config: () => LspConfigLike) {}
|
|
53
|
+
|
|
54
|
+
startSweeper(): void {
|
|
55
|
+
if (this.sweeper) return;
|
|
56
|
+
this.sweeper = setInterval(() => void this.sweepIdle(), 60_000);
|
|
57
|
+
this.sweeper.unref();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Pre-warm: start the server for this file in the background. */
|
|
61
|
+
touch(workdir: string, file: string): void {
|
|
62
|
+
void this.instanceFor(workdir, file).catch(() => undefined);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
status(): Array<{ id: string; root: string; alive: boolean; docs: number; idleMs: number }> {
|
|
66
|
+
return [...this.instances.values()].map((i) => ({ id: i.def.id, root: i.root, alive: i.client.alive, docs: i.docs.size, idleMs: Date.now() - i.lastUsed }));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async diagnosticsAfterWrite(workdir: string, file: string): Promise<WriteDiagnostics | null> {
|
|
70
|
+
const inst = await this.instanceFor(workdir, file);
|
|
71
|
+
if (!inst) return null;
|
|
72
|
+
const uri = pathToFileURL(file).href;
|
|
73
|
+
let text: string;
|
|
74
|
+
try {
|
|
75
|
+
text = await readFile(file, 'utf8');
|
|
76
|
+
} catch {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
const version = (inst.docs.get(uri) ?? 0) + 1;
|
|
80
|
+
if (inst.docs.has(uri)) {
|
|
81
|
+
inst.client.notify('textDocument/didChange', { textDocument: { uri, version }, contentChanges: [{ text }] });
|
|
82
|
+
} else {
|
|
83
|
+
inst.client.notify('textDocument/didOpen', { textDocument: { uri, languageId: inst.def.languageId(file), version, text } });
|
|
84
|
+
}
|
|
85
|
+
inst.docs.set(uri, version);
|
|
86
|
+
inst.lastUsed = Date.now();
|
|
87
|
+
const waitMs = inst.firstDiagnosticsSeen ? this.config().waitMs : Math.max(this.config().waitMs, inst.def.firstWaitMs);
|
|
88
|
+
const got = await this.waitForDiagnostics(inst, uri, waitMs);
|
|
89
|
+
if (!got) {
|
|
90
|
+
logger.info({ msg: 'lsp.no_diagnostics_in_time', server: inst.def.id, file, waitMs });
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
inst.firstDiagnosticsSeen = true;
|
|
94
|
+
const own = formatFileErrors(inst.diags.get(uri) ?? []);
|
|
95
|
+
inst.delivered.set(uri, own.join('\n'));
|
|
96
|
+
const others: Record<string, string[]> = {};
|
|
97
|
+
for (const [otherUri, diags] of inst.diags) {
|
|
98
|
+
if (otherUri === uri) continue;
|
|
99
|
+
const lines = formatFileErrors(diags, 5);
|
|
100
|
+
const key = lines.join('\n');
|
|
101
|
+
if (lines.length === 0 || inst.delivered.get(otherUri) === key) continue;
|
|
102
|
+
inst.delivered.set(otherUri, key);
|
|
103
|
+
let rel: string;
|
|
104
|
+
try {
|
|
105
|
+
rel = relative(workdir, fileURLToPath(otherUri));
|
|
106
|
+
} catch {
|
|
107
|
+
rel = otherUri;
|
|
108
|
+
}
|
|
109
|
+
others[rel] = lines;
|
|
110
|
+
if (Object.keys(others).length >= MAX_OTHER_FILES) break;
|
|
111
|
+
}
|
|
112
|
+
return { server: inst.def.id, errors: own, errors_in_other_files: others };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async shutdownAll(): Promise<void> {
|
|
116
|
+
if (this.sweeper) clearInterval(this.sweeper);
|
|
117
|
+
await Promise.all([...this.instances.values()].map((i) => i.client.stop()));
|
|
118
|
+
this.instances.clear();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
private waitForDiagnostics(inst: Instance, uri: string, timeoutMs: number): Promise<boolean> {
|
|
122
|
+
return new Promise((resolve) => {
|
|
123
|
+
let settle: NodeJS.Timeout | null = null;
|
|
124
|
+
const done = (ok: boolean) => {
|
|
125
|
+
clearTimeout(timer);
|
|
126
|
+
if (settle) clearTimeout(settle);
|
|
127
|
+
inst.waiters.delete(onDiag);
|
|
128
|
+
resolve(ok);
|
|
129
|
+
};
|
|
130
|
+
const onDiag = (u: string) => {
|
|
131
|
+
if (u !== uri) return;
|
|
132
|
+
// The server may publish twice (syntax, then semantics): settle briefly.
|
|
133
|
+
if (settle) clearTimeout(settle);
|
|
134
|
+
settle = setTimeout(() => done(true), LSP_DEBOUNCE_MS);
|
|
135
|
+
};
|
|
136
|
+
const timer = setTimeout(() => done(false), timeoutMs);
|
|
137
|
+
inst.waiters.add(onDiag);
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
private async instanceFor(workdir: string, file: string): Promise<Instance | null> {
|
|
142
|
+
const cfg = this.config();
|
|
143
|
+
if (!cfg.enabled) return null;
|
|
144
|
+
const def = serverForFile(file);
|
|
145
|
+
if (!def) return null;
|
|
146
|
+
const serverCfg = cfg.servers[def.id] ?? {};
|
|
147
|
+
if (serverCfg.enabled === false) return null;
|
|
148
|
+
const root = await rootFor(def, file, workdir);
|
|
149
|
+
const key = `${def.id}:${root}`;
|
|
150
|
+
const existing = this.instances.get(key);
|
|
151
|
+
if (existing) {
|
|
152
|
+
if (existing.client.alive) {
|
|
153
|
+
await existing.ready;
|
|
154
|
+
return existing;
|
|
155
|
+
}
|
|
156
|
+
this.instances.delete(key);
|
|
157
|
+
}
|
|
158
|
+
const until = this.broken.get(key);
|
|
159
|
+
if (until && until > Date.now()) return null;
|
|
160
|
+
const bin = await findBinary(def, serverCfg.command);
|
|
161
|
+
if (!bin.command) {
|
|
162
|
+
logger.debug({ msg: 'lsp.not_installed', server: def.id });
|
|
163
|
+
this.broken.set(key, Date.now() + LSP_IDLE_MS);
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
const client = new LspClient(def.id, bin.command, [...def.args], root);
|
|
167
|
+
const inst: Instance = {
|
|
168
|
+
key,
|
|
169
|
+
def,
|
|
170
|
+
root,
|
|
171
|
+
client,
|
|
172
|
+
ready: Promise.resolve(),
|
|
173
|
+
docs: new Map(),
|
|
174
|
+
diags: new Map(),
|
|
175
|
+
delivered: new Map(),
|
|
176
|
+
waiters: new Set(),
|
|
177
|
+
lastUsed: Date.now(),
|
|
178
|
+
firstDiagnosticsSeen: false,
|
|
179
|
+
};
|
|
180
|
+
client.onNotification('textDocument/publishDiagnostics', (params) => {
|
|
181
|
+
const p = params as { uri: string; diagnostics: LspDiagnostic[] };
|
|
182
|
+
if (!p?.uri) return;
|
|
183
|
+
inst.diags.set(p.uri, Array.isArray(p.diagnostics) ? p.diagnostics : []);
|
|
184
|
+
for (const w of inst.waiters) w(p.uri);
|
|
185
|
+
});
|
|
186
|
+
inst.ready = (async () => {
|
|
187
|
+
client.start();
|
|
188
|
+
const rootUri = pathToFileURL(root).href;
|
|
189
|
+
await client.request(
|
|
190
|
+
'initialize',
|
|
191
|
+
{
|
|
192
|
+
processId: process.pid,
|
|
193
|
+
rootUri,
|
|
194
|
+
rootPath: root,
|
|
195
|
+
workspaceFolders: [{ uri: rootUri, name: root.split('/').pop() ?? root }],
|
|
196
|
+
initializationOptions: def.initializationOptions?.(root) ?? {},
|
|
197
|
+
capabilities: {
|
|
198
|
+
workspace: { configuration: false, workspaceFolders: false },
|
|
199
|
+
textDocument: {
|
|
200
|
+
synchronization: { dynamicRegistration: false, didSave: true },
|
|
201
|
+
publishDiagnostics: { relatedInformation: false, versionSupport: false },
|
|
202
|
+
},
|
|
203
|
+
general: { positionEncodings: ['utf-16'] },
|
|
204
|
+
},
|
|
205
|
+
},
|
|
206
|
+
INIT_TIMEOUT_MS,
|
|
207
|
+
);
|
|
208
|
+
client.notify('initialized', {});
|
|
209
|
+
if (def.settings) client.notify('workspace/didChangeConfiguration', { settings: def.settings(root) });
|
|
210
|
+
logger.info({ msg: 'lsp.started', server: def.id, root, command: bin.command, source: bin.source });
|
|
211
|
+
})();
|
|
212
|
+
this.instances.set(key, inst);
|
|
213
|
+
void client.exit.then(({ code, signal }) => {
|
|
214
|
+
if (this.instances.get(key) === inst) this.instances.delete(key);
|
|
215
|
+
logger.info({ msg: 'lsp.exited', server: def.id, root, code, signal });
|
|
216
|
+
});
|
|
217
|
+
try {
|
|
218
|
+
await inst.ready;
|
|
219
|
+
} catch (err) {
|
|
220
|
+
logger.warn({ msg: 'lsp.init_failed', server: def.id, root, err: (err as Error).message });
|
|
221
|
+
this.instances.delete(key);
|
|
222
|
+
this.broken.set(key, Date.now() + LSP_IDLE_MS);
|
|
223
|
+
client.kill();
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
return inst;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
private async sweepIdle(): Promise<void> {
|
|
230
|
+
const now = Date.now();
|
|
231
|
+
for (const [key, inst] of this.instances) {
|
|
232
|
+
if (now - inst.lastUsed < LSP_IDLE_MS) continue;
|
|
233
|
+
this.instances.delete(key);
|
|
234
|
+
logger.info({ msg: 'lsp.idle_stop', server: inst.def.id, root: inst.root });
|
|
235
|
+
await inst.client.stop();
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// Which language server serves which file, where its binary is, and
|
|
2
|
+
// which folder is its root. Two servers to begin with — the ones a
|
|
3
|
+
// somora installation is most likely to build in — with room for more.
|
|
4
|
+
//
|
|
5
|
+
// Binaries are looked up in this order: the operator's `command` in
|
|
6
|
+
// config (`lsp.servers.<id>.command`), somora's own install prefix
|
|
7
|
+
// (`~/.somora/lsp/node_modules/.bin/`, filled by `somora lsp install`),
|
|
8
|
+
// then PATH. Nothing is downloaded during a turn.
|
|
9
|
+
|
|
10
|
+
import { accessSync } from 'node:fs';
|
|
11
|
+
import { access, constants } from 'node:fs/promises';
|
|
12
|
+
import { homedir } from 'node:os';
|
|
13
|
+
import { delimiter, dirname, extname, join, normalize, resolve } from 'node:path';
|
|
14
|
+
|
|
15
|
+
const SOMORA_HOME = process.env.SOMORA_HOME ?? `${homedir()}/.somora`;
|
|
16
|
+
export const LSP_INSTALL_PREFIX = join(SOMORA_HOME, 'lsp');
|
|
17
|
+
|
|
18
|
+
export interface LspServerDef {
|
|
19
|
+
id: string;
|
|
20
|
+
/** Shown in the environment block and the CLI. */
|
|
21
|
+
title: string;
|
|
22
|
+
extensions: readonly string[];
|
|
23
|
+
/** Files that mark a project root, in order of preference. */
|
|
24
|
+
rootMarkers: readonly string[];
|
|
25
|
+
/** Binary name on PATH / under the install prefix. */
|
|
26
|
+
bin: string;
|
|
27
|
+
args: readonly string[];
|
|
28
|
+
/** npm packages `somora lsp install <id>` installs. */
|
|
29
|
+
npmPackages: readonly string[];
|
|
30
|
+
languageId: (file: string) => string;
|
|
31
|
+
initializationOptions?: (root: string) => Record<string, unknown>;
|
|
32
|
+
/** `workspace/didChangeConfiguration` settings sent after initialize. */
|
|
33
|
+
settings?: (root: string) => Record<string, unknown>;
|
|
34
|
+
/** First diagnostics of a root take longer (project load). */
|
|
35
|
+
firstWaitMs: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const TS_EXT = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts'];
|
|
39
|
+
|
|
40
|
+
export const LSP_SERVERS: readonly LspServerDef[] = [
|
|
41
|
+
{
|
|
42
|
+
id: 'typescript',
|
|
43
|
+
title: 'TypeScript / JavaScript',
|
|
44
|
+
extensions: TS_EXT,
|
|
45
|
+
rootMarkers: ['tsconfig.json', 'jsconfig.json', 'package.json', '.git'],
|
|
46
|
+
bin: 'typescript-language-server',
|
|
47
|
+
args: ['--stdio'],
|
|
48
|
+
// typescript 7 is the Go compiler without lib/tsserver.js; the
|
|
49
|
+
// language server needs the classic 5.x tsserver.
|
|
50
|
+
npmPackages: ['typescript-language-server', 'typescript@5'],
|
|
51
|
+
languageId: (file) => {
|
|
52
|
+
const e = extname(file);
|
|
53
|
+
if (e === '.tsx') return 'typescriptreact';
|
|
54
|
+
if (e === '.jsx') return 'javascriptreact';
|
|
55
|
+
return e.startsWith('.j') || e === '.mjs' || e === '.cjs' ? 'javascript' : 'typescript';
|
|
56
|
+
},
|
|
57
|
+
initializationOptions: (root) => ({
|
|
58
|
+
// The server needs a tsserver: the project's own typescript when it
|
|
59
|
+
// has one (its version, its lib), else the one installed next to
|
|
60
|
+
// the server by `somora lsp install`.
|
|
61
|
+
tsserver: { path: tsserverFor(root) },
|
|
62
|
+
preferences: { includeCompletionsForModuleExports: false },
|
|
63
|
+
}),
|
|
64
|
+
firstWaitMs: 8000,
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
id: 'pyright',
|
|
68
|
+
title: 'Python (pyright)',
|
|
69
|
+
extensions: ['.py', '.pyi'],
|
|
70
|
+
rootMarkers: ['pyproject.toml', 'setup.py', 'setup.cfg', 'requirements.txt', 'pyrightconfig.json', '.git'],
|
|
71
|
+
bin: 'pyright-langserver',
|
|
72
|
+
args: ['--stdio'],
|
|
73
|
+
npmPackages: ['pyright'],
|
|
74
|
+
languageId: () => 'python',
|
|
75
|
+
initializationOptions: (root) => ({ pythonPath: pythonFor(root) }),
|
|
76
|
+
settings: (root) => ({ python: { pythonPath: pythonFor(root), analysis: { diagnosticMode: 'openFilesOnly', typeCheckingMode: 'standard' } } }),
|
|
77
|
+
firstWaitMs: 10000,
|
|
78
|
+
},
|
|
79
|
+
];
|
|
80
|
+
|
|
81
|
+
/** The project's `node_modules/typescript/lib/tsserver.js`, else somora's own. */
|
|
82
|
+
export function tsserverFor(root: string): string {
|
|
83
|
+
const own = join(root, 'node_modules', 'typescript', 'lib', 'tsserver.js');
|
|
84
|
+
try {
|
|
85
|
+
accessSync(own, constants.R_OK);
|
|
86
|
+
return own;
|
|
87
|
+
} catch {
|
|
88
|
+
return join(LSP_INSTALL_PREFIX, 'node_modules', 'typescript', 'lib', 'tsserver.js');
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** `<root>/.venv/bin/python` when the project has one, else python3. */
|
|
93
|
+
export function pythonFor(root: string): string {
|
|
94
|
+
const venv = join(root, '.venv', 'bin', 'python');
|
|
95
|
+
try {
|
|
96
|
+
accessSync(venv, constants.X_OK); // once per server start
|
|
97
|
+
return venv;
|
|
98
|
+
} catch {
|
|
99
|
+
return 'python3';
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function serverForFile(file: string): LspServerDef | null {
|
|
104
|
+
const e = extname(file).toLowerCase();
|
|
105
|
+
return LSP_SERVERS.find((s) => s.extensions.includes(e)) ?? null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function exists(p: string): Promise<boolean> {
|
|
109
|
+
try {
|
|
110
|
+
await access(p, constants.F_OK);
|
|
111
|
+
return true;
|
|
112
|
+
} catch {
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The root a server is started in for `file`: the nearest folder at or
|
|
119
|
+
* above the file that holds one of the markers, never above `workdir`
|
|
120
|
+
* (the pinned project is the outer limit), else `workdir` itself.
|
|
121
|
+
*/
|
|
122
|
+
export async function rootFor(def: LspServerDef, file: string, workdir: string): Promise<string> {
|
|
123
|
+
const top = normalize(workdir).replace(/\/+$/, '');
|
|
124
|
+
let dir = dirname(resolve(file));
|
|
125
|
+
while (dir.startsWith(top)) {
|
|
126
|
+
for (const marker of def.rootMarkers) {
|
|
127
|
+
if (await exists(join(dir, marker))) return dir;
|
|
128
|
+
}
|
|
129
|
+
if (dir === top) break;
|
|
130
|
+
dir = dirname(dir);
|
|
131
|
+
}
|
|
132
|
+
return top;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export interface BinaryLookup {
|
|
136
|
+
command: string | null;
|
|
137
|
+
source: 'config' | 'somora' | 'path' | null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Where the server's executable is, if anywhere. */
|
|
141
|
+
export async function findBinary(def: LspServerDef, configured?: string): Promise<BinaryLookup> {
|
|
142
|
+
if (configured) return { command: configured, source: 'config' };
|
|
143
|
+
const own = join(LSP_INSTALL_PREFIX, 'node_modules', '.bin', def.bin);
|
|
144
|
+
if (await exists(own)) return { command: own, source: 'somora' };
|
|
145
|
+
for (const dir of (process.env.PATH ?? '').split(delimiter)) {
|
|
146
|
+
if (!dir) continue;
|
|
147
|
+
const p = join(dir, def.bin);
|
|
148
|
+
if (await exists(p)) return { command: p, source: 'path' };
|
|
149
|
+
}
|
|
150
|
+
return { command: null, source: null };
|
|
151
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// Shared helper for engine adapters that need to spawn the somora
|
|
2
|
+
// MCP server as a child process. Both claude-cli and codex-cli adapters
|
|
3
|
+
// import this so the spawn config is consistent (path, env, name).
|
|
4
|
+
|
|
5
|
+
import { existsSync } from 'node:fs';
|
|
6
|
+
import { dirname, join } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
|
|
9
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
10
|
+
// .../src/mcp -> .../src -> .../somora
|
|
11
|
+
const REPO_ROOT = join(__dirname, '..', '..');
|
|
12
|
+
|
|
13
|
+
const TSX_BIN_REPO = join(REPO_ROOT, 'node_modules', '.bin', 'tsx');
|
|
14
|
+
const MCP_SERVER_TS = join(REPO_ROOT, 'src', 'mcp', 'server.ts');
|
|
15
|
+
|
|
16
|
+
/** MCP-server name as it appears in claude-cli/codex-cli configs.
|
|
17
|
+
* Renamed from `somora-memory` (v2026.09.03.05): the server carries
|
|
18
|
+
* every somora tool, not only memory. External-server proxy children
|
|
19
|
+
* register as `somora-<name>` and stay distinct. CLI sessions recorded
|
|
20
|
+
* under the old name are restarted once — see the `mcpServerName`
|
|
21
|
+
* resume guard in each CLI adapter. */
|
|
22
|
+
export const MCP_SERVER_NAME = 'somora';
|
|
23
|
+
|
|
24
|
+
/** Tool-name prefix in the LLM's view: `mcp__somora__memory_search` etc. */
|
|
25
|
+
export const MCP_TOOL_PREFIX = `mcp__${MCP_SERVER_NAME}__`;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Build the stdio-spawn config for the somora MCP server, scoped
|
|
29
|
+
* to the given agent + session + sub-depth. SOMORA_AGENT scopes memory
|
|
30
|
+
* tools, SOMORA_SESSION lets spawn_subagent record parent_session for
|
|
31
|
+
* traceability, and SOMORA_SUBAGENT_DEPTH enforces the recursion cap
|
|
32
|
+
* when a sub itself tries to spawn further subs.
|
|
33
|
+
*/
|
|
34
|
+
export function somoraMemoryServerSpawn(args: {
|
|
35
|
+
agent: string;
|
|
36
|
+
session?: string;
|
|
37
|
+
subagentDepth?: number;
|
|
38
|
+
/** Active model for this turn as `<provider>/<modelId>`. The MCP
|
|
39
|
+
* child surfaces this via ToolContext.activeModel so capability-
|
|
40
|
+
* gated tools (file_read polymorph) can decide whether to return
|
|
41
|
+
* multimodal content blocks. */
|
|
42
|
+
activeModelRef?: string;
|
|
43
|
+
}): {
|
|
44
|
+
command: string;
|
|
45
|
+
args: string[];
|
|
46
|
+
env: Record<string, string>;
|
|
47
|
+
} {
|
|
48
|
+
// Prefer the locally-installed tsx binary so we don't depend on what's
|
|
49
|
+
// on PATH for the spawned process. Falls back to npx if missing.
|
|
50
|
+
const useLocalTsx = existsSync(TSX_BIN_REPO);
|
|
51
|
+
return {
|
|
52
|
+
command: useLocalTsx ? TSX_BIN_REPO : 'npx',
|
|
53
|
+
args: useLocalTsx ? [MCP_SERVER_TS] : ['tsx', MCP_SERVER_TS],
|
|
54
|
+
env: {
|
|
55
|
+
...filterEnv(process.env),
|
|
56
|
+
SOMORA_AGENT: args.agent,
|
|
57
|
+
...(args.session ? { SOMORA_SESSION: args.session } : {}),
|
|
58
|
+
...(args.subagentDepth !== undefined && args.subagentDepth > 0
|
|
59
|
+
? { SOMORA_SUBAGENT_DEPTH: String(args.subagentDepth) }
|
|
60
|
+
: {}),
|
|
61
|
+
...(args.activeModelRef ? { SOMORA_ACTIVE_MODEL: args.activeModelRef } : {}),
|
|
62
|
+
// SOMORA_HOST/PORT/TLS are inherited via filterEnv (the parent
|
|
63
|
+
// server process has them), so spawn_subagent's HTTP-fallback can
|
|
64
|
+
// find the endpoint and pick the right scheme. Belt-and-suspenders
|
|
65
|
+
// explicit:
|
|
66
|
+
...(process.env.SOMORA_HOST ? { SOMORA_HOST: process.env.SOMORA_HOST } : {}),
|
|
67
|
+
...(process.env.SOMORA_PORT ? { SOMORA_PORT: process.env.SOMORA_PORT } : {}),
|
|
68
|
+
...(process.env.SOMORA_TLS ? { SOMORA_TLS: process.env.SOMORA_TLS } : {}),
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function filterEnv(env: NodeJS.ProcessEnv): Record<string, string> {
|
|
74
|
+
// Forward only string-valued vars (TS env can have undefineds).
|
|
75
|
+
const out: Record<string, string> = {};
|
|
76
|
+
for (const [k, v] of Object.entries(env)) {
|
|
77
|
+
if (typeof v === 'string') out[k] = v;
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* External-MCP proxy children (design: private/mcp-hub-design.md §4.4).
|
|
84
|
+
* Same binary as somora, switched into proxy mode by the
|
|
85
|
+
* SOMORA_MCP_PROXY_SERVER env var: it then serves ONE upstream server's
|
|
86
|
+
* tools from the catalog snapshot and forwards tools/call via HTTP to
|
|
87
|
+
* the main server's hub (the single real MCP client). CLI-side entry
|
|
88
|
+
* name is `somora-<server>`, so the model sees
|
|
89
|
+
* `mcp__somora-<server>__<tool>`.
|
|
90
|
+
*/
|
|
91
|
+
export function somoraMcpProxyName(server: string): string {
|
|
92
|
+
return `somora-${server}`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function somoraMcpProxySpawn(args: {
|
|
96
|
+
server: string;
|
|
97
|
+
agent: string;
|
|
98
|
+
}): { command: string; args: string[]; env: Record<string, string> } {
|
|
99
|
+
const useLocalTsx = existsSync(TSX_BIN_REPO);
|
|
100
|
+
return {
|
|
101
|
+
command: useLocalTsx ? TSX_BIN_REPO : 'npx',
|
|
102
|
+
args: useLocalTsx ? [MCP_SERVER_TS] : ['tsx', MCP_SERVER_TS],
|
|
103
|
+
env: {
|
|
104
|
+
// filterEnv carries SOMORA_HOME (catalog path) and SOMORA_HOST/
|
|
105
|
+
// PORT/TLS (HTTP-forward endpoint) from the parent server.
|
|
106
|
+
...filterEnv(process.env),
|
|
107
|
+
SOMORA_AGENT: args.agent,
|
|
108
|
+
SOMORA_MCP_PROXY_SERVER: args.server,
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// The `codex exec` flag builders (somoraMemoryCodexFlags,
|
|
114
|
+
// somoraMcpProxyCodexFlags) were removed 2026-09-05: the codex-cli engine
|
|
115
|
+
// now drives the Codex app-server and hands somora's tools over as dynamic
|
|
116
|
+
// tools (src/engine/codex-dynamic-tools.ts), so Codex never spawns this
|
|
117
|
+
// MCP server. claude-cli keeps using somoraMemoryServerSpawn above.
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Audit trail for NOTABLE external-MCP calls (design §5) — upstream
|
|
2
|
+
// isError, transport failures, calls against non-connected servers.
|
|
3
|
+
// Routine successful calls only get the Pino `mcp.hub.call` line.
|
|
4
|
+
//
|
|
5
|
+
// Same fire-and-forget posture as the exec audit
|
|
6
|
+
// (src/tools/exec/allowlist.ts): audit I/O must never block or fail the
|
|
7
|
+
// actual call. UNLIKE the exec audit this one rotates: rotate-on-write
|
|
8
|
+
// at 5 MB, one `.1` generation kept (decided 2026-08-06 — external
|
|
9
|
+
// servers can produce far more entries than privileged execs).
|
|
10
|
+
|
|
11
|
+
import { existsSync } from 'node:fs';
|
|
12
|
+
import { appendFile, mkdir, rename, stat } from 'node:fs/promises';
|
|
13
|
+
import { homedir } from 'node:os';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
|
|
16
|
+
const SOMORA_HOME = process.env.SOMORA_HOME ?? join(homedir(), '.somora');
|
|
17
|
+
const AUDIT_DIR = join(SOMORA_HOME, 'audit');
|
|
18
|
+
export const MCP_AUDIT_PATH = join(AUDIT_DIR, 'mcp-calls.jsonl');
|
|
19
|
+
const MAX_AUDIT_BYTES = 5 * 1024 * 1024;
|
|
20
|
+
|
|
21
|
+
export interface McpAuditEntry {
|
|
22
|
+
ts: number;
|
|
23
|
+
server: string;
|
|
24
|
+
tool: string;
|
|
25
|
+
/** First 200 chars of the JSON-stringified args — full args never persisted. */
|
|
26
|
+
args_head: string;
|
|
27
|
+
kind: 'is_error' | 'call_failed' | 'server_unavailable';
|
|
28
|
+
detail: string;
|
|
29
|
+
ms?: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function auditMcpCall(entry: McpAuditEntry): Promise<void> {
|
|
33
|
+
try {
|
|
34
|
+
if (!existsSync(AUDIT_DIR)) await mkdir(AUDIT_DIR, { recursive: true });
|
|
35
|
+
try {
|
|
36
|
+
const s = await stat(MCP_AUDIT_PATH);
|
|
37
|
+
if (s.size > MAX_AUDIT_BYTES) {
|
|
38
|
+
await rename(MCP_AUDIT_PATH, `${MCP_AUDIT_PATH}.1`);
|
|
39
|
+
}
|
|
40
|
+
} catch {
|
|
41
|
+
// ENOENT — first write.
|
|
42
|
+
}
|
|
43
|
+
await appendFile(MCP_AUDIT_PATH, `${JSON.stringify(entry)}\n`, 'utf8');
|
|
44
|
+
} catch {
|
|
45
|
+
// Intentional swallow — audit logging must NOT block the call path.
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function argsHead(args: Record<string, unknown>): string {
|
|
50
|
+
try {
|
|
51
|
+
return JSON.stringify(args).slice(0, 200);
|
|
52
|
+
} catch {
|
|
53
|
+
return '[unserializable]';
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// Registry bridge — turns the hub's discovered external tools into
|
|
2
|
+
// somora ToolDefinitions so the in-process engine path (openai-compat)
|
|
3
|
+
// sees them exactly like built-in tools. Design doc §4.2.
|
|
4
|
+
//
|
|
5
|
+
// Registration is dynamic: the hub calls refresh() whenever its catalog
|
|
6
|
+
// changes (connect, listChanged, disconnect). ToolRegistry.register is
|
|
7
|
+
// replace-on-name, and tools of disconnected servers stay registered but
|
|
8
|
+
// report available() === false — so the model never sees them, and we
|
|
9
|
+
// don't need a registry-remove primitive.
|
|
10
|
+
|
|
11
|
+
import { z } from 'zod';
|
|
12
|
+
import { logger } from '../../server/logger.ts';
|
|
13
|
+
import type { ToolRegistry } from '../../tools/registry.ts';
|
|
14
|
+
import type { ToolDefinition } from '../../tools/types.ts';
|
|
15
|
+
import type { HubCallResult, McpHubManager } from './manager.ts';
|
|
16
|
+
|
|
17
|
+
/** External tools accept whatever object the model sends — argument
|
|
18
|
+
* validation is the upstream server's job (claude-code precedent:
|
|
19
|
+
* z.object({}).passthrough()). Non-objects still fail fast. */
|
|
20
|
+
const PASSTHROUGH_INPUT = z.object({}).passthrough();
|
|
21
|
+
|
|
22
|
+
export function bridgeMcpTools(manager: McpHubManager, registry: ToolRegistry): void {
|
|
23
|
+
// fullName → fingerprint of what the model sees. A tool whose
|
|
24
|
+
// description or input schema changed upstream is registered again
|
|
25
|
+
// (ToolRegistry.register replaces on name); until 2026-09-26 a known
|
|
26
|
+
// name was skipped for good, so a changed tool reached the in-process
|
|
27
|
+
// engines only after a somora restart (naxon's networth report).
|
|
28
|
+
const registered = new Map<string, string>();
|
|
29
|
+
|
|
30
|
+
const refresh = (): void => {
|
|
31
|
+
for (const [server, tools] of manager.connectedTools()) {
|
|
32
|
+
for (const tool of tools) {
|
|
33
|
+
const fingerprint = toolFingerprint(tool);
|
|
34
|
+
const before = registered.get(tool.fullName);
|
|
35
|
+
if (before === fingerprint) continue;
|
|
36
|
+
registered.set(tool.fullName, fingerprint);
|
|
37
|
+
registry.register(buildDefinition(manager, server, tool.rawName, tool.fullName, tool));
|
|
38
|
+
if (before !== undefined) {
|
|
39
|
+
logger.info({ msg: 'mcp.bridge_tool_updated', server, tool: tool.fullName });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
manager.addCatalogListener(refresh);
|
|
46
|
+
refresh();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** What the model sees of a tool — the bridge re-registers when it changes. */
|
|
50
|
+
export function toolFingerprint(tool: { description: string; inputSchema: Record<string, unknown> }): string {
|
|
51
|
+
return JSON.stringify([tool.description, tool.inputSchema]);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function buildDefinition(
|
|
55
|
+
manager: McpHubManager,
|
|
56
|
+
server: string,
|
|
57
|
+
rawName: string,
|
|
58
|
+
fullName: string,
|
|
59
|
+
tool: { description: string; inputSchema: Record<string, unknown> },
|
|
60
|
+
): ToolDefinition {
|
|
61
|
+
const serverCfg = manager.serverConfig(server);
|
|
62
|
+
return {
|
|
63
|
+
name: fullName,
|
|
64
|
+
description: tool.description || `Tool ${rawName} on MCP server ${server}.`,
|
|
65
|
+
inputSchema: PASSTHROUGH_INPUT as z.ZodType<unknown>,
|
|
66
|
+
jsonSchema: tool.inputSchema,
|
|
67
|
+
toolset: 'mcp',
|
|
68
|
+
origin: { mcpServer: server },
|
|
69
|
+
...(serverCfg?.maxResultChars ? { maxResultSizeChars: serverCfg.maxResultChars } : {}),
|
|
70
|
+
// Engine-level per-call race: give the engine the same budget the
|
|
71
|
+
// hub call gets, plus a 2s round-trip buffer.
|
|
72
|
+
defaultTimeoutMs: (serverCfg?.timeoutMs ?? 60_000) + 2_000,
|
|
73
|
+
// Hidden while the upstream server is anything but connected AND
|
|
74
|
+
// while the tool vanished from a listChanged refetch.
|
|
75
|
+
available: () => {
|
|
76
|
+
const tools = manager.connectedTools().get(server);
|
|
77
|
+
return tools !== undefined && tools.some((t) => t.fullName === fullName);
|
|
78
|
+
},
|
|
79
|
+
handler: async (input: unknown) => {
|
|
80
|
+
const args = (input ?? {}) as Record<string, unknown>;
|
|
81
|
+
const result = await manager.callTool(server, rawName, args);
|
|
82
|
+
return mapHubResult(result);
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Map a HubCallResult into what the registry expects from a handler:
|
|
88
|
+
* throw on upstream isError, multimodal shape when images are present,
|
|
89
|
+
* parsed JSON (or raw text) otherwise. */
|
|
90
|
+
export function mapHubResult(
|
|
91
|
+
result: HubCallResult,
|
|
92
|
+
): unknown {
|
|
93
|
+
if (result.isError) {
|
|
94
|
+
throw new Error(result.text || 'MCP tool reported an error');
|
|
95
|
+
}
|
|
96
|
+
if (result.images.length > 0) {
|
|
97
|
+
return {
|
|
98
|
+
_somoraMultimodal: true as const,
|
|
99
|
+
contentBlocks: [
|
|
100
|
+
...(result.text ? [{ type: 'text' as const, text: result.text }] : []),
|
|
101
|
+
...result.images.map((img) => ({
|
|
102
|
+
type: 'image' as const,
|
|
103
|
+
source: { kind: 'base64' as const, mediaType: img.mimeType, data: img.data },
|
|
104
|
+
})),
|
|
105
|
+
],
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
// Servers overwhelmingly return JSON-in-text; hand the model the
|
|
109
|
+
// parsed object when it parses, the raw text otherwise.
|
|
110
|
+
try {
|
|
111
|
+
return JSON.parse(result.text);
|
|
112
|
+
} catch {
|
|
113
|
+
return result.text;
|
|
114
|
+
}
|
|
115
|
+
}
|