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,941 @@
|
|
|
1
|
+
// grok-cli engine adapter — drives xAI's Grok Build CLI over ACP
|
|
2
|
+
// (Agent Client Protocol: JSON-RPC 2.0, newline-delimited, on stdio).
|
|
3
|
+
//
|
|
4
|
+
// Why ACP and not the public xAI API: a SuperGrok/Premium subscription
|
|
5
|
+
// authenticates the *binary*, not the API. `grok login` writes a session
|
|
6
|
+
// to ~/.grok/auth.json, and the ACP handshake reports it as the
|
|
7
|
+
// `cached_token` auth method — used automatically, no explicit
|
|
8
|
+
// `authenticate` round-trip needed. Talking to api.x.ai instead would
|
|
9
|
+
// bill pay-per-token against a separate xAI API account.
|
|
10
|
+
//
|
|
11
|
+
// Process model: one `grok agent stdio` child per turn, mirroring
|
|
12
|
+
// codex-cli. The child is cheap to start (~1s to handshake) and dying
|
|
13
|
+
// with the turn means no long-lived state to leak or reconcile. Session
|
|
14
|
+
// continuity comes from `session/load` against the persisted
|
|
15
|
+
// grokSessionId, which the ACP handshake advertises via
|
|
16
|
+
// agentCapabilities.loadSession.
|
|
17
|
+
//
|
|
18
|
+
// Wire shapes below are transcribed from a recorded probe against
|
|
19
|
+
// grok 0.2.106 — see the `session/update` variants in mapUpdate().
|
|
20
|
+
|
|
21
|
+
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
|
|
22
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
23
|
+
import { homedir } from 'node:os';
|
|
24
|
+
import { join } from 'node:path';
|
|
25
|
+
import { randomUUID } from 'node:crypto';
|
|
26
|
+
import {
|
|
27
|
+
MCP_SERVER_NAME,
|
|
28
|
+
somoraMcpProxyName,
|
|
29
|
+
somoraMcpProxySpawn,
|
|
30
|
+
somoraMemoryServerSpawn,
|
|
31
|
+
} from '../mcp/config.ts';
|
|
32
|
+
import { logger } from '../server/logger.ts';
|
|
33
|
+
import type { NormalizedEvent } from '../types/events.ts';
|
|
34
|
+
import { grokCliReasoningArgs } from './thinking-params.ts';
|
|
35
|
+
import type { AgentEngine, ResolvedAttachment, TurnInput } from './types.ts';
|
|
36
|
+
|
|
37
|
+
const ENGINE = 'grok-cli';
|
|
38
|
+
|
|
39
|
+
/** Fallback idle window when the server doesn't resolve one. */
|
|
40
|
+
const DEFAULT_IDLE_MS = 300_000;
|
|
41
|
+
|
|
42
|
+
/** Handshake must complete inside this or the binary is considered broken. */
|
|
43
|
+
const HANDSHAKE_TIMEOUT_MS = 30_000;
|
|
44
|
+
|
|
45
|
+
function resolveGrokBin(): string {
|
|
46
|
+
if (process.env.SOMORA_GROK_BIN) return process.env.SOMORA_GROK_BIN;
|
|
47
|
+
const localBin = join(homedir(), '.local', 'bin', 'grok');
|
|
48
|
+
if (existsSync(localBin)) return localBin;
|
|
49
|
+
return 'grok';
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const GROK_BIN = resolveGrokBin();
|
|
53
|
+
|
|
54
|
+
// ---------------------------------------------------------------------
|
|
55
|
+
// ACP wire types (only the fields we consume)
|
|
56
|
+
// ---------------------------------------------------------------------
|
|
57
|
+
|
|
58
|
+
interface JsonRpcFrame {
|
|
59
|
+
jsonrpc: '2.0';
|
|
60
|
+
id?: number | string;
|
|
61
|
+
method?: string;
|
|
62
|
+
params?: unknown;
|
|
63
|
+
result?: unknown;
|
|
64
|
+
error?: { code: number; message: string };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
interface AcpContent {
|
|
68
|
+
type: string;
|
|
69
|
+
text?: string;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface AcpSessionUpdate {
|
|
73
|
+
sessionUpdate: string;
|
|
74
|
+
content?: AcpContent;
|
|
75
|
+
// tool_call / tool_call_update
|
|
76
|
+
toolCallId?: string;
|
|
77
|
+
title?: string;
|
|
78
|
+
kind?: string;
|
|
79
|
+
status?: string;
|
|
80
|
+
rawInput?: unknown;
|
|
81
|
+
rawOutput?: unknown;
|
|
82
|
+
content_?: unknown;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
interface AcpUsage {
|
|
86
|
+
inputTokens?: number;
|
|
87
|
+
outputTokens?: number;
|
|
88
|
+
cachedReadTokens?: number;
|
|
89
|
+
reasoningTokens?: number;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* ACP stdio MCP-server descriptor. Note the env shape: ACP takes an
|
|
94
|
+
* ARRAY of {name, value} pairs, not the {KEY: value} record that
|
|
95
|
+
* somoraMemoryServerSpawn() (and every other engine) hands out. That
|
|
96
|
+
* mismatch is the whole reason this helper exists.
|
|
97
|
+
*/
|
|
98
|
+
interface AcpMcpServer {
|
|
99
|
+
name: string;
|
|
100
|
+
command: string;
|
|
101
|
+
args: string[];
|
|
102
|
+
env: Array<{ name: string; value: string }>;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Build the ACP `mcpServers` entry that gives a grok session somora's
|
|
107
|
+
* own tool surface (memory, files, exec, wiki, subagents — 45 tools as
|
|
108
|
+
* of 2026-07).
|
|
109
|
+
*
|
|
110
|
+
* Grok spawns the child itself and, per the probe on 2026-07-20,
|
|
111
|
+
* exposes the tools to the model behind a search_tool/use_tool
|
|
112
|
+
* indirection rather than listing all 45 up front — so a large surface
|
|
113
|
+
* costs little context.
|
|
114
|
+
*
|
|
115
|
+
* Tool naming: grok presents them as `<server>__<tool>`
|
|
116
|
+
* (`somora__time_now`), NOT with somora's own `mcp__` prefix.
|
|
117
|
+
* See stripToolPrefix() for the normalisation applied before events
|
|
118
|
+
* reach the rest of somora.
|
|
119
|
+
*
|
|
120
|
+
* Beyond somora this also returns one `somora-<name>` proxy
|
|
121
|
+
* child per enabled external MCP server (hub design §4.4) — the same
|
|
122
|
+
* entries claude-cli and codex-cli add. grok-cli is a CLI engine, so
|
|
123
|
+
* it reaches external servers the CLI way: the child serves the hub's
|
|
124
|
+
* catalog snapshot and forwards tools/call to the main server, rather
|
|
125
|
+
* than receiving pre-bridged tools via `tools` like openai-compat.
|
|
126
|
+
* Per-agent gating happens inside the child (SOMORA_AGENT), so the
|
|
127
|
+
* entry list itself is agent-independent.
|
|
128
|
+
*/
|
|
129
|
+
function buildMcpServers(args: {
|
|
130
|
+
agent: string;
|
|
131
|
+
session: string;
|
|
132
|
+
subagentDepth?: number;
|
|
133
|
+
activeModelRef?: string;
|
|
134
|
+
externalMcpServers?: Array<{ name: string; timeoutMs: number }>;
|
|
135
|
+
}): AcpMcpServer[] {
|
|
136
|
+
const toAcpEnv = (env: Record<string, string>) =>
|
|
137
|
+
Object.entries(env).map(([name, value]) => ({ name, value }));
|
|
138
|
+
|
|
139
|
+
const spawnCfg = somoraMemoryServerSpawn({
|
|
140
|
+
agent: args.agent,
|
|
141
|
+
session: args.session,
|
|
142
|
+
subagentDepth: args.subagentDepth,
|
|
143
|
+
activeModelRef: args.activeModelRef,
|
|
144
|
+
});
|
|
145
|
+
const servers: AcpMcpServer[] = [
|
|
146
|
+
{
|
|
147
|
+
name: MCP_SERVER_NAME,
|
|
148
|
+
command: spawnCfg.command,
|
|
149
|
+
args: spawnCfg.args,
|
|
150
|
+
env: toAcpEnv(spawnCfg.env),
|
|
151
|
+
},
|
|
152
|
+
];
|
|
153
|
+
|
|
154
|
+
for (const srv of args.externalMcpServers ?? []) {
|
|
155
|
+
const proxyCfg = somoraMcpProxySpawn({ server: srv.name, agent: args.agent });
|
|
156
|
+
servers.push({
|
|
157
|
+
name: somoraMcpProxyName(srv.name),
|
|
158
|
+
command: proxyCfg.command,
|
|
159
|
+
args: proxyCfg.args,
|
|
160
|
+
env: toAcpEnv(proxyCfg.env),
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return servers;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Resolve what somora should record as "the tool that ran", and
|
|
169
|
+
* normalise it to somora's `mcp__<server>__<tool>` convention.
|
|
170
|
+
*
|
|
171
|
+
* Grok doesn't call MCP tools directly. It funnels them through a
|
|
172
|
+
* two-step indirection — `search_tool` to discover, then `use_tool`
|
|
173
|
+
* with the real name in `rawInput.tool_name`. That keeps a 45-tool
|
|
174
|
+
* surface out of the model's context, but it means the ACP frame's
|
|
175
|
+
* title is the literal string "use_tool" for every single call.
|
|
176
|
+
* Recording that verbatim would make session logs useless: every tool
|
|
177
|
+
* row would read "use_tool" with no indication of what actually ran.
|
|
178
|
+
*
|
|
179
|
+
* So: unwrap use_tool to the inner name, then prefix.
|
|
180
|
+
*
|
|
181
|
+
* use_tool{tool_name:'somora__time_now'}
|
|
182
|
+
* → mcp__somora__time_now
|
|
183
|
+
* somora__memory_list → mcp__somora__memory_list
|
|
184
|
+
* somora-parallel__web_search → mcp__somora-parallel__web_search
|
|
185
|
+
* mcp__somora__time_now → unchanged (already normalised)
|
|
186
|
+
* search_tool, read_file → unchanged (grok's own built-ins)
|
|
187
|
+
*
|
|
188
|
+
* `serverNames` is the set of MCP entries actually handed to this
|
|
189
|
+
* session (somora plus one somora-<name> per external server),
|
|
190
|
+
* so the prefix decision is an exact match against what we registered
|
|
191
|
+
* rather than a guess at what a `somora-`-shaped name might be.
|
|
192
|
+
*/
|
|
193
|
+
function resolveToolName(
|
|
194
|
+
rawTitle: string,
|
|
195
|
+
rawInput: unknown,
|
|
196
|
+
serverNames: ReadonlySet<string>,
|
|
197
|
+
): string {
|
|
198
|
+
let name = rawTitle;
|
|
199
|
+
|
|
200
|
+
if (name === 'use_tool' && rawInput && typeof rawInput === 'object') {
|
|
201
|
+
const inner = (rawInput as { tool_name?: unknown }).tool_name;
|
|
202
|
+
if (typeof inner === 'string' && inner.length > 0) {
|
|
203
|
+
name = inner;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
for (const server of serverNames) {
|
|
208
|
+
if (name.startsWith(`${server}__`)) {
|
|
209
|
+
return `mcp__${name}`;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return name;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Fold user attachments into the prompt.
|
|
217
|
+
*
|
|
218
|
+
* Division of labour: images and PDFs never reach this adapter at all.
|
|
219
|
+
* run-turn.ts applies a capability gate first and hard-refuses them
|
|
220
|
+
* for any model without the `image` / `pdf` capability — grok-4.5 has
|
|
221
|
+
* neither, so the user gets "does not support image inputs" before an
|
|
222
|
+
* engine is even spawned.
|
|
223
|
+
*
|
|
224
|
+
* What DOES arrive here is text, which the gate lets through. Grok
|
|
225
|
+
* Build has no attachment channel over ACP, so the only way to deliver
|
|
226
|
+
* a text file is to inline it — same approach codex-cli takes for its
|
|
227
|
+
* non-image attachments.
|
|
228
|
+
*
|
|
229
|
+
* Anything else reaching this function means the gate let a kind
|
|
230
|
+
* through that we can't render. That should not happen, but saying so
|
|
231
|
+
* beats dropping the file silently, so it becomes a note to the model.
|
|
232
|
+
*/
|
|
233
|
+
function renderAttachments(attachments: ResolvedAttachment[]): string {
|
|
234
|
+
const parts: string[] = [];
|
|
235
|
+
const undeliverable: ResolvedAttachment[] = [];
|
|
236
|
+
|
|
237
|
+
for (const a of attachments) {
|
|
238
|
+
if (a.mime.kind === 'text') {
|
|
239
|
+
try {
|
|
240
|
+
parts.push(`[Attached ${a.name}]\n\n${readFileSync(a.path, 'utf8')}\n[/Attached]`);
|
|
241
|
+
} catch (err) {
|
|
242
|
+
logger.warn(
|
|
243
|
+
{ engine: ENGINE, name: a.name, err: (err as Error).message },
|
|
244
|
+
'attachment unreadable',
|
|
245
|
+
);
|
|
246
|
+
undeliverable.push(a);
|
|
247
|
+
}
|
|
248
|
+
} else {
|
|
249
|
+
undeliverable.push(a);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
if (undeliverable.length > 0) {
|
|
254
|
+
parts.push(
|
|
255
|
+
[
|
|
256
|
+
`[somora] ${undeliverable.length} attachment(s) could not be delivered to this model:`,
|
|
257
|
+
...undeliverable.map((a) => ` - ${a.name} (${a.mime.kind}, ${a.size} bytes)`),
|
|
258
|
+
'',
|
|
259
|
+
'The content was NOT transmitted — you cannot see it. Do not guess',
|
|
260
|
+
'at what it contains. Tell the user plainly, and suggest a model',
|
|
261
|
+
'that supports this attachment kind.',
|
|
262
|
+
].join('\n'),
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
return parts.join('\n\n');
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// ---------------------------------------------------------------------
|
|
270
|
+
// Minimal ACP client over a spawned child
|
|
271
|
+
// ---------------------------------------------------------------------
|
|
272
|
+
|
|
273
|
+
type Notification = { method: string; params: Record<string, unknown> };
|
|
274
|
+
|
|
275
|
+
class AcpClient {
|
|
276
|
+
private child: ChildProcessWithoutNullStreams;
|
|
277
|
+
private buf = '';
|
|
278
|
+
private nextId = 1;
|
|
279
|
+
private pending = new Map<number, (f: JsonRpcFrame) => void>();
|
|
280
|
+
/** Notifications + server->client requests, drained by the turn loop. */
|
|
281
|
+
private queue: Notification[] = [];
|
|
282
|
+
private waiter: (() => void) | null = null;
|
|
283
|
+
private closed = false;
|
|
284
|
+
private exitInfo: string | null = null;
|
|
285
|
+
|
|
286
|
+
constructor(args: string[], cwd: string) {
|
|
287
|
+
this.child = spawn(GROK_BIN, args, {
|
|
288
|
+
cwd,
|
|
289
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
290
|
+
env: process.env,
|
|
291
|
+
}) as ChildProcessWithoutNullStreams;
|
|
292
|
+
|
|
293
|
+
this.child.stdout.on('data', (c: Buffer) => this.onData(c));
|
|
294
|
+
this.child.stderr.on('data', (c: Buffer) => {
|
|
295
|
+
const s = c.toString().trim();
|
|
296
|
+
if (s) logger.debug({ engine: ENGINE, stderr: s }, 'grok stderr');
|
|
297
|
+
});
|
|
298
|
+
this.child.on('exit', (code, signal) => {
|
|
299
|
+
this.closed = true;
|
|
300
|
+
this.exitInfo = `grok exited (code=${code} signal=${signal})`;
|
|
301
|
+
// Unblock anyone waiting so they see the closed state.
|
|
302
|
+
for (const [, res] of this.pending) {
|
|
303
|
+
res({ jsonrpc: '2.0', error: { code: -1, message: this.exitInfo } });
|
|
304
|
+
}
|
|
305
|
+
this.pending.clear();
|
|
306
|
+
this.wake();
|
|
307
|
+
});
|
|
308
|
+
this.child.on('error', (err) => {
|
|
309
|
+
this.closed = true;
|
|
310
|
+
this.exitInfo = `grok spawn failed: ${err.message}`;
|
|
311
|
+
this.wake();
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
private wake(): void {
|
|
316
|
+
const w = this.waiter;
|
|
317
|
+
this.waiter = null;
|
|
318
|
+
if (w) w();
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
private onData(chunk: Buffer): void {
|
|
322
|
+
this.buf += chunk.toString();
|
|
323
|
+
let nl: number;
|
|
324
|
+
while ((nl = this.buf.indexOf('\n')) >= 0) {
|
|
325
|
+
const line = this.buf.slice(0, nl).trim();
|
|
326
|
+
this.buf = this.buf.slice(nl + 1);
|
|
327
|
+
if (!line) continue;
|
|
328
|
+
let frame: JsonRpcFrame;
|
|
329
|
+
try {
|
|
330
|
+
frame = JSON.parse(line) as JsonRpcFrame;
|
|
331
|
+
} catch {
|
|
332
|
+
logger.debug({ engine: ENGINE, line: line.slice(0, 200) }, 'unparseable ACP frame');
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
if (frame.id !== undefined && frame.method === undefined) {
|
|
336
|
+
const res = this.pending.get(frame.id as number);
|
|
337
|
+
if (res) {
|
|
338
|
+
this.pending.delete(frame.id as number);
|
|
339
|
+
res(frame);
|
|
340
|
+
}
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
if (frame.method) {
|
|
344
|
+
this.queue.push({
|
|
345
|
+
method: frame.method,
|
|
346
|
+
params: (frame.params ?? {}) as Record<string, unknown>,
|
|
347
|
+
});
|
|
348
|
+
// Server->client REQUEST (has an id): must be answered or the
|
|
349
|
+
// agent blocks forever. The only one grok issues in practice is
|
|
350
|
+
// session/request_permission; we run with --always-approve so it
|
|
351
|
+
// shouldn't fire, but answer defensively rather than deadlock.
|
|
352
|
+
if (frame.id !== undefined) {
|
|
353
|
+
this.respond(frame.id, {
|
|
354
|
+
outcome: { outcome: 'selected', optionId: 'allow' },
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
this.wake();
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
private write(obj: unknown): void {
|
|
363
|
+
if (this.closed) return;
|
|
364
|
+
try {
|
|
365
|
+
this.child.stdin.write(JSON.stringify(obj) + '\n');
|
|
366
|
+
} catch (err) {
|
|
367
|
+
logger.warn({ engine: ENGINE, err }, 'ACP stdin write failed');
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
private respond(id: number | string, result: unknown): void {
|
|
372
|
+
this.write({ jsonrpc: '2.0', id, result });
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
request(method: string, params: unknown, timeoutMs: number): Promise<JsonRpcFrame> {
|
|
376
|
+
if (this.closed) {
|
|
377
|
+
return Promise.resolve({
|
|
378
|
+
jsonrpc: '2.0',
|
|
379
|
+
error: { code: -1, message: this.exitInfo ?? 'grok not running' },
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
const id = this.nextId++;
|
|
383
|
+
return new Promise<JsonRpcFrame>((resolve) => {
|
|
384
|
+
const timer = setTimeout(() => {
|
|
385
|
+
this.pending.delete(id);
|
|
386
|
+
resolve({
|
|
387
|
+
jsonrpc: '2.0',
|
|
388
|
+
error: { code: -2, message: `ACP ${method} timed out after ${timeoutMs}ms` },
|
|
389
|
+
});
|
|
390
|
+
}, timeoutMs);
|
|
391
|
+
this.pending.set(id, (f) => {
|
|
392
|
+
clearTimeout(timer);
|
|
393
|
+
resolve(f);
|
|
394
|
+
});
|
|
395
|
+
this.write({ jsonrpc: '2.0', id, method, params });
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Drain buffered notifications, waiting up to idleMs for the next one.
|
|
401
|
+
* Returns null when the window elapses with nothing arriving (caller
|
|
402
|
+
* treats that as a watchdog trip) or when the child is gone and the
|
|
403
|
+
* buffer is empty.
|
|
404
|
+
*/
|
|
405
|
+
async next(idleMs: number): Promise<Notification | null> {
|
|
406
|
+
if (this.queue.length > 0) return this.queue.shift() ?? null;
|
|
407
|
+
if (this.closed) return null;
|
|
408
|
+
let timedOut = false;
|
|
409
|
+
await new Promise<void>((resolve) => {
|
|
410
|
+
const timer = setTimeout(() => {
|
|
411
|
+
timedOut = true;
|
|
412
|
+
this.waiter = null;
|
|
413
|
+
resolve();
|
|
414
|
+
}, idleMs);
|
|
415
|
+
this.waiter = () => {
|
|
416
|
+
clearTimeout(timer);
|
|
417
|
+
resolve();
|
|
418
|
+
};
|
|
419
|
+
});
|
|
420
|
+
if (this.queue.length > 0) return this.queue.shift() ?? null;
|
|
421
|
+
if (timedOut) return null;
|
|
422
|
+
return this.closed ? null : this.next(idleMs);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Discard every buffered notification. Called after session/load:
|
|
427
|
+
* ACP replays the entire prior conversation as session/update frames
|
|
428
|
+
* so a fresh client can rebuild its view. We already have that
|
|
429
|
+
* history in somora's own JSONL, and folding the replayed
|
|
430
|
+
* agent_message_chunks into the current turn's text would echo the
|
|
431
|
+
* whole session back at the user (observed: turn 2 answering
|
|
432
|
+
* "pongpong" instead of "pong").
|
|
433
|
+
*/
|
|
434
|
+
drain(): number {
|
|
435
|
+
const n = this.queue.length;
|
|
436
|
+
this.queue.length = 0;
|
|
437
|
+
return n;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
get isClosed(): boolean {
|
|
441
|
+
return this.closed;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
get lastError(): string | null {
|
|
445
|
+
return this.exitInfo;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
kill(): void {
|
|
449
|
+
if (!this.closed) {
|
|
450
|
+
try {
|
|
451
|
+
this.child.kill('SIGTERM');
|
|
452
|
+
} catch {
|
|
453
|
+
/* already gone */
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// ---------------------------------------------------------------------
|
|
460
|
+
// Engine
|
|
461
|
+
// ---------------------------------------------------------------------
|
|
462
|
+
|
|
463
|
+
export const grokCliEngine: AgentEngine = {
|
|
464
|
+
name: ENGINE,
|
|
465
|
+
|
|
466
|
+
async *runTurn(input: TurnInput): AsyncIterable<NormalizedEvent> {
|
|
467
|
+
const turnId = randomUUID();
|
|
468
|
+
const idleMs = input.idleTimeoutMs ?? DEFAULT_IDLE_MS;
|
|
469
|
+
const toolIdleMs = input.toolIdleTimeoutMs ?? idleMs;
|
|
470
|
+
|
|
471
|
+
yield { kind: 'turn_start', ts: Date.now(), engine: ENGINE, turnId };
|
|
472
|
+
|
|
473
|
+
const meta = await input.metaStore.get(input.agent, input.session);
|
|
474
|
+
// After an MCP server rename (`somora-memory` → `somora`, 2026-09-03)
|
|
475
|
+
// the stored grok session knows the tools under the old name — start
|
|
476
|
+
// a fresh ACP session instead of session/load. Same guard as the
|
|
477
|
+
// claude-cli / codex-cli adapters.
|
|
478
|
+
const recordedServer = typeof meta.mcpServerName === 'string' ? meta.mcpServerName : null;
|
|
479
|
+
const mcpRenamed = typeof meta.grokSessionId === 'string' && recordedServer !== MCP_SERVER_NAME;
|
|
480
|
+
const priorSessionId =
|
|
481
|
+
typeof meta.grokSessionId === 'string' && !mcpRenamed ? meta.grokSessionId : null;
|
|
482
|
+
if (mcpRenamed) {
|
|
483
|
+
logger.info({
|
|
484
|
+
msg: 'engine.mcp_rename_resession',
|
|
485
|
+
engine: ENGINE,
|
|
486
|
+
agent: input.agent,
|
|
487
|
+
session: input.session,
|
|
488
|
+
recordedServer,
|
|
489
|
+
currentServer: MCP_SERVER_NAME,
|
|
490
|
+
droppedSessionId: meta.grokSessionId,
|
|
491
|
+
});
|
|
492
|
+
yield {
|
|
493
|
+
kind: 'engine_meta',
|
|
494
|
+
ts: Date.now(),
|
|
495
|
+
engine: ENGINE,
|
|
496
|
+
itemType: 'mcp_server_renamed',
|
|
497
|
+
payload: {
|
|
498
|
+
from: recordedServer,
|
|
499
|
+
to: MCP_SERVER_NAME,
|
|
500
|
+
text: `Grok session restarted because somora's MCP server was renamed (${recordedServer ?? 'somora-memory'} → ${MCP_SERVER_NAME}) — session history carried over.`,
|
|
501
|
+
},
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// cwd: the agent's workspace is what grok's built-in file/shell
|
|
506
|
+
// tools operate on. Falls back to $HOME rather than somora's own
|
|
507
|
+
// process cwd, which would point the agent at the install dir.
|
|
508
|
+
const cwd = process.env.SOMORA_WORKSPACE ?? homedir();
|
|
509
|
+
|
|
510
|
+
const args = [
|
|
511
|
+
'agent',
|
|
512
|
+
'--always-approve',
|
|
513
|
+
...(input.resolvedModel.modelId ? ['-m', input.resolvedModel.modelId] : []),
|
|
514
|
+
...grokCliReasoningArgs(input.thinking, input.resolvedModel.model),
|
|
515
|
+
'stdio',
|
|
516
|
+
];
|
|
517
|
+
|
|
518
|
+
const client = new AcpClient(args, cwd);
|
|
519
|
+
const onAbort = () => client.kill();
|
|
520
|
+
input.signal?.addEventListener('abort', onAbort, { once: true });
|
|
521
|
+
|
|
522
|
+
let assistantText = '';
|
|
523
|
+
|
|
524
|
+
// Reasoning trace from agent_thought_chunk (untested live).
|
|
525
|
+
|
|
526
|
+
let thinkingText = '';
|
|
527
|
+
let emittedAny = false;
|
|
528
|
+
const openTools = new Set<string>();
|
|
529
|
+
|
|
530
|
+
try {
|
|
531
|
+
// --- handshake -------------------------------------------------
|
|
532
|
+
const init = await client.request(
|
|
533
|
+
'initialize',
|
|
534
|
+
{
|
|
535
|
+
protocolVersion: 1,
|
|
536
|
+
clientCapabilities: {
|
|
537
|
+
fs: { readTextFile: false, writeTextFile: false },
|
|
538
|
+
terminal: false,
|
|
539
|
+
},
|
|
540
|
+
},
|
|
541
|
+
HANDSHAKE_TIMEOUT_MS,
|
|
542
|
+
);
|
|
543
|
+
if (init.error) {
|
|
544
|
+
yield {
|
|
545
|
+
kind: 'error',
|
|
546
|
+
ts: Date.now(),
|
|
547
|
+
engine: ENGINE,
|
|
548
|
+
message: `grok handshake failed: ${init.error.message}. Is \`grok\` installed and has \`grok login\` been run?`,
|
|
549
|
+
};
|
|
550
|
+
yield { kind: 'turn_end', ts: Date.now(), engine: ENGINE, turnId };
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
// --- session: load prior, else create --------------------------
|
|
555
|
+
// somora's own MCP surface, spawned by grok as a child of the ACP
|
|
556
|
+
// agent. Scoped to this agent+session so memory tools hit the
|
|
557
|
+
// right inbox and spawn_subagent records the correct parent.
|
|
558
|
+
const mcpServers = buildMcpServers({
|
|
559
|
+
agent: input.agent,
|
|
560
|
+
session: input.session,
|
|
561
|
+
subagentDepth: input.subagentDepth,
|
|
562
|
+
activeModelRef: `${input.resolvedModel.providerName}/${input.resolvedModel.modelId}`,
|
|
563
|
+
externalMcpServers: input.externalMcpServers,
|
|
564
|
+
});
|
|
565
|
+
const mcpServerNames = new Set(mcpServers.map((s) => s.name));
|
|
566
|
+
|
|
567
|
+
let sessionId: string | null = null;
|
|
568
|
+
if (priorSessionId) {
|
|
569
|
+
const loaded = await client.request(
|
|
570
|
+
'session/load',
|
|
571
|
+
{ sessionId: priorSessionId, cwd, mcpServers },
|
|
572
|
+
HANDSHAKE_TIMEOUT_MS,
|
|
573
|
+
);
|
|
574
|
+
if (!loaded.error) {
|
|
575
|
+
sessionId = priorSessionId;
|
|
576
|
+
} else {
|
|
577
|
+
logger.info(
|
|
578
|
+
{ engine: ENGINE, priorSessionId, err: loaded.error.message },
|
|
579
|
+
'grok session/load failed — starting fresh',
|
|
580
|
+
);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
if (!sessionId) {
|
|
584
|
+
const created = await client.request(
|
|
585
|
+
'session/new',
|
|
586
|
+
{ cwd, mcpServers },
|
|
587
|
+
// MCP child startup (tsx + the somora server) adds a few
|
|
588
|
+
// seconds on top of the bare handshake — measured ~3.5s for
|
|
589
|
+
// the single somora child on 2026-07-20. External
|
|
590
|
+
// servers add one more child of the same binary each, so the
|
|
591
|
+
// budget scales per child instead of being a flat doubling.
|
|
592
|
+
// With no external servers configured this is exactly the
|
|
593
|
+
// previous `* 2`.
|
|
594
|
+
HANDSHAKE_TIMEOUT_MS * (1 + mcpServers.length),
|
|
595
|
+
);
|
|
596
|
+
const sid = (created.result as { sessionId?: string } | undefined)?.sessionId;
|
|
597
|
+
if (created.error || !sid) {
|
|
598
|
+
yield {
|
|
599
|
+
kind: 'error',
|
|
600
|
+
ts: Date.now(),
|
|
601
|
+
engine: ENGINE,
|
|
602
|
+
message: `grok session/new failed: ${created.error?.message ?? 'no sessionId returned'}`,
|
|
603
|
+
};
|
|
604
|
+
yield { kind: 'turn_end', ts: Date.now(), engine: ENGINE, turnId };
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
sessionId = sid;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
await input.metaStore.update(input.agent, input.session, (cur) => ({
|
|
611
|
+
...cur,
|
|
612
|
+
grokSessionId: sessionId,
|
|
613
|
+
mcpServerName: MCP_SERVER_NAME,
|
|
614
|
+
engine: ENGINE,
|
|
615
|
+
}));
|
|
616
|
+
|
|
617
|
+
// --- build the prompt ------------------------------------------
|
|
618
|
+
// ACP has no system-prompt slot. On a FRESH session the persona
|
|
619
|
+
// rides in as a preamble on the first user message; on a RESUMED
|
|
620
|
+
// one grok already remembers it, so we send only the per-turn
|
|
621
|
+
// ephemeral context (memory recall / project block), which
|
|
622
|
+
// changes every turn and must always be re-sent.
|
|
623
|
+
const isFresh = sessionId !== priorSessionId;
|
|
624
|
+
const parts: string[] = [];
|
|
625
|
+
if (isFresh && input.systemPrompt.trim()) parts.push(input.systemPrompt.trim());
|
|
626
|
+
if (input.ephemeralContext?.trim()) parts.push(input.ephemeralContext.trim());
|
|
627
|
+
if (!isFresh && input.projectContext?.trim()) parts.push(input.projectContext.trim());
|
|
628
|
+
// Text attachments inline, anything else becomes a note (see
|
|
629
|
+
// renderAttachments) — never a silent drop.
|
|
630
|
+
const attachments = input.attachments ?? [];
|
|
631
|
+
if (attachments.length > 0) {
|
|
632
|
+
const rendered = renderAttachments(attachments);
|
|
633
|
+
if (rendered) parts.push(rendered);
|
|
634
|
+
}
|
|
635
|
+
// The A2A header travels in ephemeralContext (src/server/turn-framing.ts).
|
|
636
|
+
parts.push(input.userMessage);
|
|
637
|
+
const promptText = parts.join('\n\n---\n\n');
|
|
638
|
+
|
|
639
|
+
const undelivered = attachments.filter((a) => a.mime.kind !== 'text');
|
|
640
|
+
if (undelivered.length > 0) {
|
|
641
|
+
logger.info(
|
|
642
|
+
{ engine: ENGINE, count: undelivered.length, kinds: undelivered.map((a) => a.mime.kind) },
|
|
643
|
+
'attachments not deliverable over ACP',
|
|
644
|
+
);
|
|
645
|
+
// Side-channel for clients/history: not an `error`, so the
|
|
646
|
+
// fallback path stays out of it.
|
|
647
|
+
yield {
|
|
648
|
+
kind: 'engine_meta',
|
|
649
|
+
ts: Date.now(),
|
|
650
|
+
engine: ENGINE,
|
|
651
|
+
itemType: 'attachments_unsupported',
|
|
652
|
+
payload: {
|
|
653
|
+
count: undelivered.length,
|
|
654
|
+
files: undelivered.map((a) => ({ name: a.name, kind: a.mime.kind })),
|
|
655
|
+
},
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
// Drop anything session/load replayed at us before we start
|
|
660
|
+
// listening for THIS turn's output.
|
|
661
|
+
const dropped = client.drain();
|
|
662
|
+
if (dropped > 0) {
|
|
663
|
+
logger.debug({ engine: ENGINE, dropped }, 'discarded replayed ACP frames');
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// --- prompt (fire, then stream notifications) ------------------
|
|
667
|
+
const promptDone = client.request(
|
|
668
|
+
'session/prompt',
|
|
669
|
+
{ sessionId, prompt: [{ type: 'text', text: promptText }] },
|
|
670
|
+
// The request resolves only at end-of-turn; the watchdog on the
|
|
671
|
+
// notification stream is what actually bounds a wedged turn, so
|
|
672
|
+
// give this a generous ceiling.
|
|
673
|
+
Math.max(idleMs, toolIdleMs) * 4,
|
|
674
|
+
);
|
|
675
|
+
|
|
676
|
+
let settled = false;
|
|
677
|
+
let usage: AcpUsage | undefined;
|
|
678
|
+
/** Message from an _x.ai API-failure frame, if the turn hit one. */
|
|
679
|
+
let apiError: string | null = null;
|
|
680
|
+
/** Prompt currently executing, learned from _x.ai/queue/changed. */
|
|
681
|
+
let activePromptId: string | null = null;
|
|
682
|
+
void promptDone.then((f) => {
|
|
683
|
+
settled = true;
|
|
684
|
+
const m = (f.result as { _meta?: { usage?: AcpUsage } } | undefined)?._meta;
|
|
685
|
+
if (m?.usage) usage = m.usage;
|
|
686
|
+
if (f.error) {
|
|
687
|
+
logger.warn({ engine: ENGINE, err: f.error.message }, 'session/prompt error');
|
|
688
|
+
}
|
|
689
|
+
});
|
|
690
|
+
|
|
691
|
+
// Stream until the prompt settles, the watchdog trips, the child
|
|
692
|
+
// dies, or the user aborts. `settled` alone isn't a sufficient
|
|
693
|
+
// exit condition — the response frame can land before the last
|
|
694
|
+
// few notifications, so we keep draining and let the null-return
|
|
695
|
+
// from next() (empty queue + closed / timed out) end the loop.
|
|
696
|
+
for (;;) {
|
|
697
|
+
if (input.signal?.aborted) break;
|
|
698
|
+
const window = openTools.size > 0 ? toolIdleMs : idleMs;
|
|
699
|
+
const note = await client.next(window);
|
|
700
|
+
|
|
701
|
+
if (note === null) {
|
|
702
|
+
if (settled) break;
|
|
703
|
+
if (client.isClosed) {
|
|
704
|
+
// A user abort kills the child on purpose (onAbort above), so
|
|
705
|
+
// the resulting "exited (signal=SIGTERM)" is not an engine
|
|
706
|
+
// failure. Yielding it as `error` before any content made
|
|
707
|
+
// run-turn-fallback swallow the turn_end and start the
|
|
708
|
+
// FALLBACK model after the user had just cancelled. The
|
|
709
|
+
// "[somora] aborted by user" assistant_message below covers
|
|
710
|
+
// the abort case; only a genuine crash is an error.
|
|
711
|
+
if (!input.signal?.aborted) {
|
|
712
|
+
yield {
|
|
713
|
+
kind: 'error',
|
|
714
|
+
ts: Date.now(),
|
|
715
|
+
engine: ENGINE,
|
|
716
|
+
message: client.lastError ?? 'grok closed unexpectedly',
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
break;
|
|
720
|
+
}
|
|
721
|
+
yield {
|
|
722
|
+
kind: 'error',
|
|
723
|
+
ts: Date.now(),
|
|
724
|
+
engine: ENGINE,
|
|
725
|
+
message: `grok produced no events for ${window}ms — aborting turn`,
|
|
726
|
+
};
|
|
727
|
+
break;
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
// xAI-proprietary side-channels (_x.ai/*) carry queue state,
|
|
731
|
+
// announcements, settings — and, crucially, API failures.
|
|
732
|
+
if (note.method.startsWith('_x.ai/')) {
|
|
733
|
+
// Replayed history. session/load re-emits every past frame
|
|
734
|
+
// tagged `_meta.isReplay: true`; drain() clears what arrived
|
|
735
|
+
// before the load response, but this guard is what makes
|
|
736
|
+
// reading the error frames below safe — without it a 402
|
|
737
|
+
// from LAST week would abort every resumed turn.
|
|
738
|
+
const replayed = (note.params as { _meta?: { isReplay?: boolean } })._meta?.isReplay;
|
|
739
|
+
if (replayed) continue;
|
|
740
|
+
|
|
741
|
+
if (note.method === '_x.ai/session/prompt_complete') {
|
|
742
|
+
settled = true;
|
|
743
|
+
break;
|
|
744
|
+
}
|
|
745
|
+
if (note.method === '_x.ai/queue/changed') {
|
|
746
|
+
const rp = (note.params as { runningPromptId?: string }).runningPromptId;
|
|
747
|
+
if (typeof rp === 'string') activePromptId = rp;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// API failures live HERE, not in the ACP error channel:
|
|
751
|
+
// `retry_state{type:'failed'}` announces the failed attempt,
|
|
752
|
+
// `turn_completed{stop_reason:'error'}` closes the turn. Both
|
|
753
|
+
// observed carrying the real message, e.g.
|
|
754
|
+
// "API error (status 402 Payment Required): Grok Build
|
|
755
|
+
// usage balance exhausted"
|
|
756
|
+
// Skipping the whole _x.ai/* namespace (as this adapter used
|
|
757
|
+
// to) swallowed those and left the user with a bare
|
|
758
|
+
// "grok returned no content" — a spent subscription looked
|
|
759
|
+
// like an empty reply, and the configured fallback model
|
|
760
|
+
// never kicked in because the placeholder counted as content.
|
|
761
|
+
const xu = (note.params as { update?: Record<string, unknown> }).update;
|
|
762
|
+
if (xu?.sessionUpdate === 'retry_state' && xu.type === 'failed') {
|
|
763
|
+
apiError = typeof xu.message === 'string' ? xu.message : 'grok reported a failed attempt';
|
|
764
|
+
logger.warn({ engine: ENGINE, apiError }, 'grok API failure');
|
|
765
|
+
} else if (xu?.sessionUpdate === 'turn_completed' && xu.stop_reason === 'error') {
|
|
766
|
+
if (typeof xu.agent_result === 'string' && xu.agent_result) apiError = xu.agent_result;
|
|
767
|
+
settled = true;
|
|
768
|
+
break;
|
|
769
|
+
}
|
|
770
|
+
continue;
|
|
771
|
+
}
|
|
772
|
+
if (note.method !== 'session/update') continue;
|
|
773
|
+
|
|
774
|
+
// Second guard against replayed history (see AcpClient.drain):
|
|
775
|
+
// once we know which prompt is executing, frames tagged with a
|
|
776
|
+
// different promptId belong to an earlier turn. Frames without
|
|
777
|
+
// a promptId (user_message_chunk, command lists) are structural
|
|
778
|
+
// and pass through to the switch, which ignores them anyway.
|
|
779
|
+
const framePromptId = (note.params as { _meta?: { promptId?: string } })._meta?.promptId;
|
|
780
|
+
if (activePromptId && framePromptId && framePromptId !== activePromptId) {
|
|
781
|
+
continue;
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
const upd = (note.params as { update?: AcpSessionUpdate }).update;
|
|
785
|
+
if (!upd) continue;
|
|
786
|
+
|
|
787
|
+
switch (upd.sessionUpdate) {
|
|
788
|
+
case 'agent_message_chunk': {
|
|
789
|
+
const t = upd.content?.text ?? '';
|
|
790
|
+
if (t) {
|
|
791
|
+
assistantText += t;
|
|
792
|
+
emittedAny = true;
|
|
793
|
+
// CUMULATIVE, not the bare chunk — see the contract note
|
|
794
|
+
// in src/types/events.ts ("Deltas are cumulative") and
|
|
795
|
+
// how claude-cli/codex-cli do it. Clients REPLACE the
|
|
796
|
+
// rendered bubble with each delta rather than appending,
|
|
797
|
+
// so sending only the fresh fragment makes the reply
|
|
798
|
+
// flicker one word at a time until the final
|
|
799
|
+
// assistant_message lands.
|
|
800
|
+
yield {
|
|
801
|
+
kind: 'assistant_delta',
|
|
802
|
+
ts: Date.now(),
|
|
803
|
+
engine: ENGINE,
|
|
804
|
+
text: assistantText,
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
break;
|
|
808
|
+
}
|
|
809
|
+
case 'agent_thought_chunk': {
|
|
810
|
+
// Reasoning trace (ACP). Cumulative like agent_message_chunk.
|
|
811
|
+
// UNTESTED live — no Grok account here; wired by the ACP
|
|
812
|
+
// schema only (content.text like message chunks).
|
|
813
|
+
const t = upd.content?.text ?? '';
|
|
814
|
+
if (t) {
|
|
815
|
+
thinkingText += t;
|
|
816
|
+
yield { kind: 'thinking_delta', ts: Date.now(), engine: ENGINE, text: thinkingText };
|
|
817
|
+
}
|
|
818
|
+
break;
|
|
819
|
+
}
|
|
820
|
+
case 'tool_call': {
|
|
821
|
+
const id = upd.toolCallId ?? randomUUID();
|
|
822
|
+
openTools.add(id);
|
|
823
|
+
yield {
|
|
824
|
+
kind: 'tool_call',
|
|
825
|
+
ts: Date.now(),
|
|
826
|
+
engine: ENGINE,
|
|
827
|
+
callId: id,
|
|
828
|
+
tool: resolveToolName(
|
|
829
|
+
upd.title ?? upd.kind ?? 'grok_tool',
|
|
830
|
+
upd.rawInput,
|
|
831
|
+
mcpServerNames,
|
|
832
|
+
),
|
|
833
|
+
input: upd.rawInput ?? {},
|
|
834
|
+
};
|
|
835
|
+
break;
|
|
836
|
+
}
|
|
837
|
+
case 'tool_call_update': {
|
|
838
|
+
const id = upd.toolCallId ?? '';
|
|
839
|
+
const done =
|
|
840
|
+
upd.status === 'completed' || upd.status === 'failed' || upd.status === 'error';
|
|
841
|
+
if (done && id) {
|
|
842
|
+
openTools.delete(id);
|
|
843
|
+
yield {
|
|
844
|
+
kind: 'tool_result',
|
|
845
|
+
ts: Date.now(),
|
|
846
|
+
engine: ENGINE,
|
|
847
|
+
callId: id,
|
|
848
|
+
output: upd.rawOutput ?? null,
|
|
849
|
+
...(upd.status !== 'completed' ? { error: String(upd.status) } : {}),
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
break;
|
|
853
|
+
}
|
|
854
|
+
case 'user_message_chunk':
|
|
855
|
+
case 'available_commands_update':
|
|
856
|
+
case 'current_mode_update':
|
|
857
|
+
break;
|
|
858
|
+
case 'plan': {
|
|
859
|
+
yield {
|
|
860
|
+
kind: 'engine_meta',
|
|
861
|
+
ts: Date.now(),
|
|
862
|
+
engine: ENGINE,
|
|
863
|
+
itemType: 'plan',
|
|
864
|
+
payload: upd,
|
|
865
|
+
};
|
|
866
|
+
break;
|
|
867
|
+
}
|
|
868
|
+
default:
|
|
869
|
+
logger.debug(
|
|
870
|
+
{ engine: ENGINE, sessionUpdate: upd.sessionUpdate },
|
|
871
|
+
'unhandled ACP session/update',
|
|
872
|
+
);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
if (!settled) {
|
|
877
|
+
// Loop exited on abort or watchdog — make sure the pending
|
|
878
|
+
// request can't keep a handle alive.
|
|
879
|
+
client.kill();
|
|
880
|
+
}
|
|
881
|
+
await promptDone.catch(() => undefined);
|
|
882
|
+
|
|
883
|
+
const finalText = input.signal?.aborted
|
|
884
|
+
? assistantText || '[somora] aborted by user'
|
|
885
|
+
: assistantText;
|
|
886
|
+
|
|
887
|
+
if (apiError && !emittedAny) {
|
|
888
|
+
// Nothing streamed and grok told us why: surface it as an
|
|
889
|
+
// `error` so run-turn-fallback can reroute to the configured
|
|
890
|
+
// fallback model. Emitting a placeholder assistant_message
|
|
891
|
+
// here (the old behaviour) counted as content and pinned the
|
|
892
|
+
// turn to a provider that had just refused to serve it.
|
|
893
|
+
yield {
|
|
894
|
+
kind: 'error',
|
|
895
|
+
ts: Date.now(),
|
|
896
|
+
engine: ENGINE,
|
|
897
|
+
message: `grok: ${apiError}`,
|
|
898
|
+
};
|
|
899
|
+
} else if (finalText || !emittedAny) {
|
|
900
|
+
if (thinkingText) {
|
|
901
|
+
yield { kind: 'thinking_message', ts: Date.now(), engine: ENGINE, text: thinkingText };
|
|
902
|
+
thinkingText = '';
|
|
903
|
+
}
|
|
904
|
+
yield {
|
|
905
|
+
kind: 'assistant_message',
|
|
906
|
+
ts: Date.now(),
|
|
907
|
+
engine: ENGINE,
|
|
908
|
+
// Partial answer + late failure: keep the text, append the
|
|
909
|
+
// reason rather than dropping either.
|
|
910
|
+
text: apiError
|
|
911
|
+
? `${finalText}\n\n[somora] grok aborted this turn: ${apiError}`
|
|
912
|
+
: finalText || '[somora] grok returned no content',
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
yield {
|
|
917
|
+
kind: 'turn_end',
|
|
918
|
+
ts: Date.now(),
|
|
919
|
+
engine: ENGINE,
|
|
920
|
+
turnId,
|
|
921
|
+
...(usage
|
|
922
|
+
? {
|
|
923
|
+
usage: {
|
|
924
|
+
tokens_in: usage.inputTokens ?? 0,
|
|
925
|
+
tokens_out: usage.outputTokens ?? 0,
|
|
926
|
+
...(usage.cachedReadTokens !== undefined
|
|
927
|
+
? { tokens_in_cached: usage.cachedReadTokens }
|
|
928
|
+
: {}),
|
|
929
|
+
...(usage.reasoningTokens !== undefined
|
|
930
|
+
? { tokens_out_reasoning: usage.reasoningTokens }
|
|
931
|
+
: {}),
|
|
932
|
+
},
|
|
933
|
+
}
|
|
934
|
+
: {}),
|
|
935
|
+
};
|
|
936
|
+
} finally {
|
|
937
|
+
input.signal?.removeEventListener('abort', onAbort);
|
|
938
|
+
client.kill();
|
|
939
|
+
}
|
|
940
|
+
},
|
|
941
|
+
};
|