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,649 @@
|
|
|
1
|
+
// Local-process execution for the `exec` tool. Two paths:
|
|
2
|
+
//
|
|
3
|
+
// 1. localExecSync — spawn process, wait for exit, return aggregated
|
|
4
|
+
// stdout/stderr (capped at 256 KB per stream), exit code, ms.
|
|
5
|
+
// Mirrors the shape of remoteExec from src/ssh/exec.ts. When
|
|
6
|
+
// pty:true, routes through node-pty for real pseudo-terminal
|
|
7
|
+
// allocation so isatty()-checking tools (vim, htop, claude --
|
|
8
|
+
// skip-permissions, codex, color/cursor handling, progress bars)
|
|
9
|
+
// work correctly. With pty on, stdout and stderr merge into one
|
|
10
|
+
// stream — same behavior as a real terminal and as our
|
|
11
|
+
// remote-pty path via ssh2.
|
|
12
|
+
//
|
|
13
|
+
// 2. localExecBackground — spawn detached, register the job in the
|
|
14
|
+
// disk-tracked job-store, stream stdout/stderr to log files,
|
|
15
|
+
// return job_id immediately. Process keeps running after our
|
|
16
|
+
// function returns. process_* tool actions interact with it via
|
|
17
|
+
// the job-store + livePid registry. Background ignores pty:true
|
|
18
|
+
// — TUI tools in the background make no sense (no one's watching);
|
|
19
|
+
// use tmux for "long-running interactive on local" instead.
|
|
20
|
+
|
|
21
|
+
import { spawn } from 'node:child_process';
|
|
22
|
+
import * as pty from 'node-pty';
|
|
23
|
+
import { closeSync, openSync, statSync } from 'node:fs';
|
|
24
|
+
import { homedir } from 'node:os';
|
|
25
|
+
import { isAbsolute, join } from 'node:path';
|
|
26
|
+
import { logger } from '../../server/logger.ts';
|
|
27
|
+
import type { SkillEnvScope } from '../../skills/env-scope.ts';
|
|
28
|
+
import { extendedPath } from '../../skills/path-helpers.ts';
|
|
29
|
+
import { stripSomoraInternalEnv } from './internal-env.ts';
|
|
30
|
+
import {
|
|
31
|
+
clearLivePid,
|
|
32
|
+
clearLiveStdin,
|
|
33
|
+
completeJob,
|
|
34
|
+
ensureJobDir,
|
|
35
|
+
failJob,
|
|
36
|
+
jobDir,
|
|
37
|
+
registerJob,
|
|
38
|
+
registerLivePid,
|
|
39
|
+
registerLiveStdin,
|
|
40
|
+
newJobId,
|
|
41
|
+
type JobMeta,
|
|
42
|
+
} from './job-store.ts';
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Build the env for a spawned subprocess. Always extends PATH with
|
|
46
|
+
* known user-install dirs (linuxbrew, homebrew, ~/.local/bin, …) so
|
|
47
|
+
* that brew/cargo/go binaries are reachable even when somora runs as
|
|
48
|
+
* a systemd user-service with the minimal default PATH. Caller-
|
|
49
|
+
* supplied env entries override on conflict (incl. PATH if explicitly
|
|
50
|
+
* provided).
|
|
51
|
+
*
|
|
52
|
+
* `stripSomoraInternal` removes somora-internal vars that the server
|
|
53
|
+
* (or the MCP tool child) carries on its own process.env for its own
|
|
54
|
+
* subsystems but which leak into user-facing tmux/exec children
|
|
55
|
+
* otherwise — the list lives in ./internal-env.ts. The original two
|
|
56
|
+
* (CLAUDE_CONFIG_DIR, SOMORA_CLAUDE_BIN) made a spawned `claude` miss
|
|
57
|
+
* the user's login state; TSX_TSCONFIG_PATH and NODE_ENV (2026-08-26)
|
|
58
|
+
* broke a user project's own tsx/next in an exec shell. Defaults to
|
|
59
|
+
* false to preserve backwards compatibility for internal callers
|
|
60
|
+
* (dream, engine spawn, MCP children). Tool dispatchers (exec, tmux)
|
|
61
|
+
* pass true unless the agent explicitly opts into env-inheritance.
|
|
62
|
+
*/
|
|
63
|
+
function buildSpawnEnv(
|
|
64
|
+
callerEnv?: Record<string, string>,
|
|
65
|
+
opts?: { stripSomoraInternal?: boolean; skillEnvScope?: SkillEnvScope },
|
|
66
|
+
): NodeJS.ProcessEnv {
|
|
67
|
+
const base: NodeJS.ProcessEnv = { ...process.env, PATH: extendedPath() };
|
|
68
|
+
if (opts?.stripSomoraInternal) stripSomoraInternalEnv(base);
|
|
69
|
+
// Skill-scoped secrets: strip every skill-declared var, then put back
|
|
70
|
+
// only the vars of skills whose bins the command invokes. Applied
|
|
71
|
+
// BEFORE callerEnv so an explicit `env:` from the agent always wins.
|
|
72
|
+
// See src/skills/env-scope.ts for the full design.
|
|
73
|
+
if (opts?.skillEnvScope) {
|
|
74
|
+
for (const name of opts.skillEnvScope.stripVars) delete base[name];
|
|
75
|
+
Object.assign(base, opts.skillEnvScope.injectEnv);
|
|
76
|
+
}
|
|
77
|
+
if (callerEnv) Object.assign(base, callerEnv);
|
|
78
|
+
return base;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const DEFAULT_OUTPUT_CAP_BYTES = 256 * 1024;
|
|
82
|
+
const DEFAULT_SYNC_TIMEOUT_MS = 60_000;
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Resolve a caller-supplied cwd for local spawn. Node's spawn does NOT
|
|
86
|
+
* expand `~` and resolves relative paths against the somora server's
|
|
87
|
+
* own process cwd — and a nonexistent cwd surfaces as the wildly
|
|
88
|
+
* misleading `spawn /bin/sh ENOENT` (the chdir fails, not the shell;
|
|
89
|
+
* 2026-06-10 hans feedback). The tool schema promises
|
|
90
|
+
* "relative-to-target-home", so make that true: expand `~`, resolve
|
|
91
|
+
* relative against the home dir, and verify the directory exists so
|
|
92
|
+
* the error names the actual problem.
|
|
93
|
+
*/
|
|
94
|
+
export function resolveLocalCwd(
|
|
95
|
+
cwd: string,
|
|
96
|
+
): { ok: true; cwd: string } | { ok: false; error: string } {
|
|
97
|
+
let resolved = cwd;
|
|
98
|
+
if (cwd === '~') resolved = homedir();
|
|
99
|
+
else if (cwd.startsWith('~/')) resolved = join(homedir(), cwd.slice(2));
|
|
100
|
+
else if (!isAbsolute(cwd)) resolved = join(homedir(), cwd);
|
|
101
|
+
let isDir = false;
|
|
102
|
+
try {
|
|
103
|
+
isDir = statSync(resolved).isDirectory();
|
|
104
|
+
} catch {
|
|
105
|
+
/* missing → isDir stays false */
|
|
106
|
+
}
|
|
107
|
+
if (!isDir) {
|
|
108
|
+
return {
|
|
109
|
+
ok: false,
|
|
110
|
+
error:
|
|
111
|
+
`[somora] cwd error: '${cwd}'` +
|
|
112
|
+
(resolved !== cwd ? ` (resolved to '${resolved}')` : '') +
|
|
113
|
+
` is not an existing directory on the somora server. Pass an absolute path, ` +
|
|
114
|
+
`'~/...', or a path relative to the server user's home.`,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
return { ok: true, cwd: resolved };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface LocalSyncResult {
|
|
121
|
+
exit_code: number | null;
|
|
122
|
+
stdout: string;
|
|
123
|
+
stderr: string;
|
|
124
|
+
truncated: boolean;
|
|
125
|
+
ms: number;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export interface LocalSyncOptions {
|
|
129
|
+
command: string;
|
|
130
|
+
cwd?: string;
|
|
131
|
+
env?: Record<string, string>;
|
|
132
|
+
timeoutMs?: number;
|
|
133
|
+
/** Allocate a pseudo-terminal via node-pty. Tools that check
|
|
134
|
+
* isatty() (vim, htop, claude --skip-permissions, codex, color
|
|
135
|
+
* output, progress bars) work correctly with pty:true. With pty
|
|
136
|
+
* on, stdout and stderr merge into a single stream (= same
|
|
137
|
+
* behavior as a real terminal). */
|
|
138
|
+
pty?: boolean;
|
|
139
|
+
/** Strip somora-internal env vars (CLAUDE_CONFIG_DIR, SOMORA_CLAUDE_BIN)
|
|
140
|
+
* before spawning. Tool dispatchers set this true so user-facing
|
|
141
|
+
* `exec`/`tmux` children behave like a normal terminal would.
|
|
142
|
+
* See buildSpawnEnv() for the rationale. Default false. */
|
|
143
|
+
stripSomoraInternalEnv?: boolean;
|
|
144
|
+
/** Skill-scoped env decision for this command (strip-all + selective
|
|
145
|
+
* re-inject). Computed by the exec dispatcher via
|
|
146
|
+
* skillEnvScopeForCommand(); absent = legacy full inheritance. */
|
|
147
|
+
skillEnvScope?: SkillEnvScope;
|
|
148
|
+
/** The turn's abort signal: Stop kills the command's process group
|
|
149
|
+
* instead of letting it run to its natural end (or its timeout)
|
|
150
|
+
* while the turn is already over. */
|
|
151
|
+
signal?: AbortSignal;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Killers of the foreground commands running in this process, so a
|
|
155
|
+
* process that is going away (the MCP child when the CLI turn is
|
|
156
|
+
* stopped) can take its commands with it. */
|
|
157
|
+
const runningForeground = new Set<(signal: NodeJS.Signals) => void>();
|
|
158
|
+
|
|
159
|
+
/** Kill every foreground exec still running in this process. Returns
|
|
160
|
+
* how many were signalled. */
|
|
161
|
+
export function killRunningLocalExecs(signal: NodeJS.Signals = 'SIGTERM'): number {
|
|
162
|
+
let n = 0;
|
|
163
|
+
for (const kill of runningForeground) {
|
|
164
|
+
kill(signal);
|
|
165
|
+
n += 1;
|
|
166
|
+
}
|
|
167
|
+
return n;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Run a command locally, wait for it to finish, return the captured
|
|
172
|
+
* output. Hard-blacklist check is the caller's responsibility (done
|
|
173
|
+
* in tools.ts before this gets called). Output above the per-stream
|
|
174
|
+
* cap is truncated; truncated:true tells the model to escalate to
|
|
175
|
+
* file_write+file_read for the full content.
|
|
176
|
+
*
|
|
177
|
+
* When pty:true, dispatches to the node-pty path. Otherwise uses
|
|
178
|
+
* child_process.spawn for plain pipe-based capture (faster startup,
|
|
179
|
+
* separate stdout/stderr streams).
|
|
180
|
+
*/
|
|
181
|
+
export async function localExecSync(opts: LocalSyncOptions): Promise<LocalSyncResult> {
|
|
182
|
+
if (opts.cwd) {
|
|
183
|
+
const r = resolveLocalCwd(opts.cwd);
|
|
184
|
+
if (!r.ok) {
|
|
185
|
+
return { exit_code: null, stdout: '', stderr: r.error, truncated: false, ms: 0 };
|
|
186
|
+
}
|
|
187
|
+
opts = { ...opts, cwd: r.cwd };
|
|
188
|
+
}
|
|
189
|
+
if (opts.pty) {
|
|
190
|
+
return localExecSyncPty(opts);
|
|
191
|
+
}
|
|
192
|
+
const start = Date.now();
|
|
193
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_SYNC_TIMEOUT_MS;
|
|
194
|
+
const env = buildSpawnEnv(opts.env, {
|
|
195
|
+
stripSomoraInternal: opts.stripSomoraInternalEnv === true,
|
|
196
|
+
...(opts.skillEnvScope ? { skillEnvScope: opts.skillEnvScope } : {}),
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
return new Promise<LocalSyncResult>((resolve) => {
|
|
200
|
+
// `detached: true` puts the child in its own process group so
|
|
201
|
+
// `process.kill(-pid, signal)` can take down the whole tree —
|
|
202
|
+
// shell + grandchildren. Without it a `shell: true` invocation
|
|
203
|
+
// leaves grandchildren (like a trapped `sleep`) holding the
|
|
204
|
+
// stdout pipe open, so the `close` event never fires and the
|
|
205
|
+
// promise stalls until the grandchild exits naturally. Audit
|
|
206
|
+
// 2026-05-16: `sh -c 'trap "" TERM; sleep 30'` with timeout=2s
|
|
207
|
+
// sat for the full 30s pre-fix.
|
|
208
|
+
const child = spawn(opts.command, {
|
|
209
|
+
shell: true,
|
|
210
|
+
cwd: opts.cwd,
|
|
211
|
+
env,
|
|
212
|
+
detached: true,
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
let stdoutBytes = 0;
|
|
216
|
+
let stderrBytes = 0;
|
|
217
|
+
let truncated = false;
|
|
218
|
+
const stdoutChunks: Buffer[] = [];
|
|
219
|
+
const stderrChunks: Buffer[] = [];
|
|
220
|
+
|
|
221
|
+
child.stdout?.on('data', (chunk: Buffer) => {
|
|
222
|
+
const remaining = DEFAULT_OUTPUT_CAP_BYTES - stdoutBytes;
|
|
223
|
+
if (remaining <= 0) {
|
|
224
|
+
truncated = true;
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
const slice = chunk.length > remaining ? chunk.subarray(0, remaining) : chunk;
|
|
228
|
+
stdoutChunks.push(slice);
|
|
229
|
+
stdoutBytes += slice.length;
|
|
230
|
+
if (chunk.length > remaining) truncated = true;
|
|
231
|
+
});
|
|
232
|
+
child.stderr?.on('data', (chunk: Buffer) => {
|
|
233
|
+
const remaining = DEFAULT_OUTPUT_CAP_BYTES - stderrBytes;
|
|
234
|
+
if (remaining <= 0) {
|
|
235
|
+
truncated = true;
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
const slice = chunk.length > remaining ? chunk.subarray(0, remaining) : chunk;
|
|
239
|
+
stderrChunks.push(slice);
|
|
240
|
+
stderrBytes += slice.length;
|
|
241
|
+
if (chunk.length > remaining) truncated = true;
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
let timedOut = false;
|
|
245
|
+
let aborted = false;
|
|
246
|
+
const killGroup = (signal: NodeJS.Signals) => {
|
|
247
|
+
// Negative pid → process group (set up by `detached: true`).
|
|
248
|
+
// Falls back to the leader if the group kill rejects.
|
|
249
|
+
try {
|
|
250
|
+
if (child.pid) process.kill(-child.pid, signal);
|
|
251
|
+
} catch {
|
|
252
|
+
try {
|
|
253
|
+
child.kill(signal);
|
|
254
|
+
} catch {
|
|
255
|
+
/* already dead */
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
const timer = setTimeout(() => {
|
|
260
|
+
timedOut = true;
|
|
261
|
+
killGroup('SIGTERM');
|
|
262
|
+
// Give it 2s to clean up, then SIGKILL. `child.killed` flips true
|
|
263
|
+
// as soon as the signal is *sent*, not when the process actually
|
|
264
|
+
// dies — so checking it skips the escalation for any command that
|
|
265
|
+
// traps/ignores SIGTERM. Use `exitCode === null` (process still
|
|
266
|
+
// running) instead. Audit 2026-05-16.
|
|
267
|
+
setTimeout(() => {
|
|
268
|
+
if (child.exitCode === null) {
|
|
269
|
+
killGroup('SIGKILL');
|
|
270
|
+
}
|
|
271
|
+
}, 2000);
|
|
272
|
+
}, timeoutMs);
|
|
273
|
+
// Stop (POST /chat/abort) or the process going away: the command
|
|
274
|
+
// dies with the turn. Measured 2026-09-23: a stopped turn left its
|
|
275
|
+
// `sleep 91` running to the end.
|
|
276
|
+
const onAbort = () => {
|
|
277
|
+
if (child.exitCode !== null) return;
|
|
278
|
+
aborted = true;
|
|
279
|
+
killGroup('SIGTERM');
|
|
280
|
+
setTimeout(() => {
|
|
281
|
+
if (child.exitCode === null) killGroup('SIGKILL');
|
|
282
|
+
}, 2000);
|
|
283
|
+
};
|
|
284
|
+
if (opts.signal?.aborted) onAbort();
|
|
285
|
+
else opts.signal?.addEventListener('abort', onAbort, { once: true });
|
|
286
|
+
runningForeground.add(onAbort as (signal: NodeJS.Signals) => void);
|
|
287
|
+
|
|
288
|
+
child.on('close', (code, signal) => {
|
|
289
|
+
clearTimeout(timer);
|
|
290
|
+
opts.signal?.removeEventListener('abort', onAbort);
|
|
291
|
+
runningForeground.delete(onAbort as (signal: NodeJS.Signals) => void);
|
|
292
|
+
const stdout = Buffer.concat(stdoutChunks).toString('utf8');
|
|
293
|
+
const stderr = Buffer.concat(stderrChunks).toString('utf8');
|
|
294
|
+
const finalStderr = timedOut
|
|
295
|
+
? stderr + `\n[somora] killed: timeout after ${timeoutMs}ms`
|
|
296
|
+
: aborted
|
|
297
|
+
? stderr + '\n[somora] killed: the turn was stopped'
|
|
298
|
+
: stderr;
|
|
299
|
+
resolve({
|
|
300
|
+
exit_code: code,
|
|
301
|
+
stdout,
|
|
302
|
+
stderr: finalStderr,
|
|
303
|
+
truncated,
|
|
304
|
+
ms: Date.now() - start,
|
|
305
|
+
});
|
|
306
|
+
logger.info({
|
|
307
|
+
msg: 'exec.local.sync_done',
|
|
308
|
+
ms: Date.now() - start,
|
|
309
|
+
exit_code: code,
|
|
310
|
+
signal,
|
|
311
|
+
timed_out: timedOut,
|
|
312
|
+
truncated,
|
|
313
|
+
});
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
child.on('error', (err) => {
|
|
317
|
+
clearTimeout(timer);
|
|
318
|
+
opts.signal?.removeEventListener('abort', onAbort);
|
|
319
|
+
runningForeground.delete(onAbort as (signal: NodeJS.Signals) => void);
|
|
320
|
+
resolve({
|
|
321
|
+
exit_code: null,
|
|
322
|
+
stdout: Buffer.concat(stdoutChunks).toString('utf8'),
|
|
323
|
+
stderr: `[somora] spawn error: ${err.message}`,
|
|
324
|
+
truncated,
|
|
325
|
+
ms: Date.now() - start,
|
|
326
|
+
});
|
|
327
|
+
});
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* PTY variant of localExecSync via node-pty. Allocates a pseudo-tty
|
|
333
|
+
* so the spawned process sees `isatty(stdin/stdout) === true` plus
|
|
334
|
+
* a TERM env var — required for vim, htop, color output, progress
|
|
335
|
+
* bars, claude --skip-permissions, codex etc.
|
|
336
|
+
*
|
|
337
|
+
* node-pty merges stdout and stderr into a single stream (the same
|
|
338
|
+
* limitation as on a real terminal) so we collect everything into
|
|
339
|
+
* `stdout` and leave `stderr` empty. Matches the remote-pty path's
|
|
340
|
+
* shape exactly.
|
|
341
|
+
*
|
|
342
|
+
* To run a shell command (with operators, redirects, etc.) we wrap
|
|
343
|
+
* it in `sh -c '...'` — node-pty otherwise just exec's the
|
|
344
|
+
* argv[0] directly.
|
|
345
|
+
*/
|
|
346
|
+
async function localExecSyncPty(opts: LocalSyncOptions): Promise<LocalSyncResult> {
|
|
347
|
+
const start = Date.now();
|
|
348
|
+
const timeoutMs = opts.timeoutMs ?? DEFAULT_SYNC_TIMEOUT_MS;
|
|
349
|
+
const env = buildSpawnEnv(opts.env, {
|
|
350
|
+
stripSomoraInternal: opts.stripSomoraInternalEnv === true,
|
|
351
|
+
...(opts.skillEnvScope ? { skillEnvScope: opts.skillEnvScope } : {}),
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
return new Promise<LocalSyncResult>((resolve) => {
|
|
355
|
+
let term;
|
|
356
|
+
try {
|
|
357
|
+
term = pty.spawn('sh', ['-c', opts.command], {
|
|
358
|
+
name: 'xterm-256color',
|
|
359
|
+
cols: 80,
|
|
360
|
+
rows: 24,
|
|
361
|
+
cwd: opts.cwd,
|
|
362
|
+
env: env as { [key: string]: string },
|
|
363
|
+
});
|
|
364
|
+
} catch (err) {
|
|
365
|
+
resolve({
|
|
366
|
+
exit_code: null,
|
|
367
|
+
stdout: '',
|
|
368
|
+
stderr: `[somora] pty spawn error: ${(err as Error).message}`,
|
|
369
|
+
truncated: false,
|
|
370
|
+
ms: Date.now() - start,
|
|
371
|
+
});
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
let outBytes = 0;
|
|
376
|
+
let truncated = false;
|
|
377
|
+
const outChunks: Buffer[] = [];
|
|
378
|
+
|
|
379
|
+
term.onData((data: string) => {
|
|
380
|
+
const buf = Buffer.from(data, 'utf8');
|
|
381
|
+
const remaining = DEFAULT_OUTPUT_CAP_BYTES - outBytes;
|
|
382
|
+
if (remaining <= 0) {
|
|
383
|
+
truncated = true;
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
const slice = buf.length > remaining ? buf.subarray(0, remaining) : buf;
|
|
387
|
+
outChunks.push(slice);
|
|
388
|
+
outBytes += slice.length;
|
|
389
|
+
if (buf.length > remaining) truncated = true;
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
let timedOut = false;
|
|
393
|
+
let aborted = false;
|
|
394
|
+
const killTerm = () => {
|
|
395
|
+
try {
|
|
396
|
+
term.kill('SIGTERM');
|
|
397
|
+
// 2s grace then SIGKILL.
|
|
398
|
+
setTimeout(() => {
|
|
399
|
+
try {
|
|
400
|
+
term.kill('SIGKILL');
|
|
401
|
+
} catch {
|
|
402
|
+
/* already dead */
|
|
403
|
+
}
|
|
404
|
+
}, 2000);
|
|
405
|
+
} catch {
|
|
406
|
+
/* already dead */
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
const timer = setTimeout(() => {
|
|
410
|
+
timedOut = true;
|
|
411
|
+
killTerm();
|
|
412
|
+
}, timeoutMs);
|
|
413
|
+
// Stop kills the pty command like the pipe path's process group.
|
|
414
|
+
const onAbort = () => {
|
|
415
|
+
if (aborted || timedOut) return;
|
|
416
|
+
aborted = true;
|
|
417
|
+
killTerm();
|
|
418
|
+
};
|
|
419
|
+
if (opts.signal?.aborted) onAbort();
|
|
420
|
+
else opts.signal?.addEventListener('abort', onAbort, { once: true });
|
|
421
|
+
runningForeground.add(onAbort as (signal: NodeJS.Signals) => void);
|
|
422
|
+
|
|
423
|
+
term.onExit(({ exitCode, signal }) => {
|
|
424
|
+
clearTimeout(timer);
|
|
425
|
+
opts.signal?.removeEventListener('abort', onAbort);
|
|
426
|
+
runningForeground.delete(onAbort as (signal: NodeJS.Signals) => void);
|
|
427
|
+
const out = Buffer.concat(outChunks).toString('utf8');
|
|
428
|
+
const stderrTail = timedOut ? `[somora] killed: timeout after ${timeoutMs}ms` : aborted ? '[somora] killed: the turn was stopped' : '';
|
|
429
|
+
resolve({
|
|
430
|
+
exit_code: exitCode,
|
|
431
|
+
stdout: out,
|
|
432
|
+
stderr: stderrTail,
|
|
433
|
+
truncated,
|
|
434
|
+
ms: Date.now() - start,
|
|
435
|
+
});
|
|
436
|
+
logger.info({
|
|
437
|
+
msg: 'exec.local.sync_pty_done',
|
|
438
|
+
ms: Date.now() - start,
|
|
439
|
+
exit_code: exitCode,
|
|
440
|
+
signal,
|
|
441
|
+
timed_out: timedOut,
|
|
442
|
+
truncated,
|
|
443
|
+
});
|
|
444
|
+
});
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
export interface LocalBackgroundOptions {
|
|
449
|
+
agent: string;
|
|
450
|
+
command: string;
|
|
451
|
+
cwd?: string;
|
|
452
|
+
env?: Record<string, string>;
|
|
453
|
+
description?: string;
|
|
454
|
+
pty?: boolean;
|
|
455
|
+
/** Concurrency-slot release callback. Called exactly once when the
|
|
456
|
+
* job ends (any path: clean exit, error, or kill) so the cap
|
|
457
|
+
* counter doesn't leak. */
|
|
458
|
+
releaseSlot?: () => void;
|
|
459
|
+
/** Same semantics as LocalSyncOptions.stripSomoraInternalEnv. */
|
|
460
|
+
stripSomoraInternalEnv?: boolean;
|
|
461
|
+
/** Skill-scoped env decision for this command (strip-all + selective
|
|
462
|
+
* re-inject). Computed by the exec dispatcher via
|
|
463
|
+
* skillEnvScopeForCommand(); absent = legacy full inheritance. */
|
|
464
|
+
skillEnvScope?: SkillEnvScope;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
export interface LocalBackgroundResult {
|
|
468
|
+
job_id: string;
|
|
469
|
+
pid: number;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* Spawn a long-running process detached from the current call. The
|
|
474
|
+
* job is registered in the job-store, output streams to disk-files,
|
|
475
|
+
* and the model can interact via process_* actions later. Caller
|
|
476
|
+
* gets the job_id back immediately.
|
|
477
|
+
*/
|
|
478
|
+
export async function localExecBackground(
|
|
479
|
+
opts: LocalBackgroundOptions,
|
|
480
|
+
): Promise<LocalBackgroundResult> {
|
|
481
|
+
if (opts.cwd) {
|
|
482
|
+
const r = resolveLocalCwd(opts.cwd);
|
|
483
|
+
if (!r.ok) throw new Error(r.error);
|
|
484
|
+
opts = { ...opts, cwd: r.cwd };
|
|
485
|
+
}
|
|
486
|
+
const job_id = newJobId();
|
|
487
|
+
const meta: JobMeta = {
|
|
488
|
+
job_id,
|
|
489
|
+
agent: opts.agent,
|
|
490
|
+
target: 'local',
|
|
491
|
+
command: opts.command,
|
|
492
|
+
...(opts.cwd ? { cwd: opts.cwd } : {}),
|
|
493
|
+
...(opts.description ? { description: opts.description } : {}),
|
|
494
|
+
started_at: Date.now(),
|
|
495
|
+
state: 'running',
|
|
496
|
+
pid: 0, // filled in below
|
|
497
|
+
};
|
|
498
|
+
|
|
499
|
+
// Make sure the job dir exists so the log streams can attach.
|
|
500
|
+
await ensureJobDir(opts.agent, job_id);
|
|
501
|
+
const stdoutPath = join(jobDir(opts.agent, job_id), 'stdout.log');
|
|
502
|
+
const stderrPath = join(jobDir(opts.agent, job_id), 'stderr.log');
|
|
503
|
+
|
|
504
|
+
const env = buildSpawnEnv(opts.env, {
|
|
505
|
+
stripSomoraInternal: opts.stripSomoraInternalEnv === true,
|
|
506
|
+
...(opts.skillEnvScope ? { skillEnvScope: opts.skillEnvScope } : {}),
|
|
507
|
+
});
|
|
508
|
+
// `detached: true` makes the wrapper shell a process-group leader —
|
|
509
|
+
// same rationale as the sync path above: process({action:"kill"})
|
|
510
|
+
// signals the GROUP (-pid), so shell + grandchildren die together.
|
|
511
|
+
// With detached:false the kill only ever reached the wrapper sh; the
|
|
512
|
+
// actual workload survived reparented to init and the job was
|
|
513
|
+
// falsely marked killed (Juni-Audit 2026-06).
|
|
514
|
+
//
|
|
515
|
+
// stdout/stderr go to the log files as RAW FDs, not through pipes in
|
|
516
|
+
// this process. Piping coupled the job to the lifetime of whoever
|
|
517
|
+
// spawned it: when the MCP child (claude-cli/codex-cli tool host)
|
|
518
|
+
// recycled between turns, the pipes closed and the job died on its
|
|
519
|
+
// next write with SIGPIPE — no traceback, no state update, and poll
|
|
520
|
+
// kept reporting 'running' (2026-07-27 feedback report). With file
|
|
521
|
+
// FDs the job only shares the filesystem with us and survives
|
|
522
|
+
// arbitrary somora/MCP restarts.
|
|
523
|
+
//
|
|
524
|
+
// The command is wrapped so the wrapper shell records its exit code
|
|
525
|
+
// in <jobdir>/exit — mirrors the remote nohup/setsid pattern. That
|
|
526
|
+
// file is what lets a DIFFERENT somora process (post-restart poll,
|
|
527
|
+
// boot recovery) resolve the job's real final state.
|
|
528
|
+
const exitPath = join(jobDir(opts.agent, job_id), 'exit');
|
|
529
|
+
const shq = (s: string): string => `'${s.replaceAll("'", `'\\''`)}'`;
|
|
530
|
+
const wrapped =
|
|
531
|
+
`(\n${opts.command}\n)\n` +
|
|
532
|
+
`__somora_ec=$?\n` +
|
|
533
|
+
`printf '%s' "$__somora_ec" > ${shq(exitPath)}\n` +
|
|
534
|
+
`exit "$__somora_ec"`;
|
|
535
|
+
const outFd = openSync(stdoutPath, 'a');
|
|
536
|
+
const errFd = openSync(stderrPath, 'a');
|
|
537
|
+
let child: ReturnType<typeof spawn>;
|
|
538
|
+
try {
|
|
539
|
+
child = spawn(wrapped, {
|
|
540
|
+
shell: true,
|
|
541
|
+
cwd: opts.cwd,
|
|
542
|
+
env,
|
|
543
|
+
detached: true,
|
|
544
|
+
// stdin stays a pipe so process_write can stream into it while
|
|
545
|
+
// THIS process lives (a job adopted after a restart has no live
|
|
546
|
+
// stdin — process_write reports that explicitly).
|
|
547
|
+
stdio: ['pipe', outFd, errFd],
|
|
548
|
+
});
|
|
549
|
+
} finally {
|
|
550
|
+
// The child holds dups of the FDs; close the parent copies so we
|
|
551
|
+
// don't leak two descriptors per background job.
|
|
552
|
+
closeSync(outFd);
|
|
553
|
+
closeSync(errFd);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
if (!child.pid) {
|
|
557
|
+
throw new Error('exec.local.background: spawn returned no pid');
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// Attach exit/error listeners SYNCHRONOUSLY, before any await — a
|
|
561
|
+
// fast command can exit during the registerJob disk write, and a
|
|
562
|
+
// listener attached after that await misses the event forever (the
|
|
563
|
+
// job then sticks at 'running' until a probe resolves it). Events
|
|
564
|
+
// that fire before registration is done are buffered and finalized
|
|
565
|
+
// right after.
|
|
566
|
+
const cleanup = (): void => {
|
|
567
|
+
clearLivePid(job_id);
|
|
568
|
+
clearLiveStdin(job_id);
|
|
569
|
+
opts.releaseSlot?.();
|
|
570
|
+
};
|
|
571
|
+
let registered = false;
|
|
572
|
+
let earlyExit: { code: number | null } | null = null;
|
|
573
|
+
let earlyError: Error | null = null;
|
|
574
|
+
const finalizeExit = (code: number | null): void => {
|
|
575
|
+
void completeJob(opts.agent, job_id, code).finally(cleanup);
|
|
576
|
+
};
|
|
577
|
+
const finalizeError = (err: Error): void => {
|
|
578
|
+
void failJob(opts.agent, job_id, `spawn error: ${err.message}`).finally(cleanup);
|
|
579
|
+
};
|
|
580
|
+
// 'exit' (not 'close') — there are no parent-side stdout/stderr
|
|
581
|
+
// streams anymore, and stdin's parent end must not delay the state
|
|
582
|
+
// update. The wrapper propagates the inner command's exit code.
|
|
583
|
+
child.on('exit', (code, _signal) => {
|
|
584
|
+
if (!registered) {
|
|
585
|
+
earlyExit = { code };
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
finalizeExit(code);
|
|
589
|
+
});
|
|
590
|
+
child.on('error', (err) => {
|
|
591
|
+
if (!registered) {
|
|
592
|
+
earlyError = err;
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
finalizeError(err);
|
|
596
|
+
});
|
|
597
|
+
|
|
598
|
+
meta.pid = child.pid;
|
|
599
|
+
await registerJob(meta);
|
|
600
|
+
registerLivePid(job_id, child.pid);
|
|
601
|
+
if (child.stdin) registerLiveStdin(job_id, child.stdin);
|
|
602
|
+
registered = true;
|
|
603
|
+
if (earlyError !== null) finalizeError(earlyError);
|
|
604
|
+
else if (earlyExit !== null) finalizeExit((earlyExit as { code: number | null }).code);
|
|
605
|
+
|
|
606
|
+
// Let this process exit without waiting for the job. The listeners
|
|
607
|
+
// above still fire while we live; if we die first, the next poll /
|
|
608
|
+
// list / boot recovery resolves the state via probeLocalJob.
|
|
609
|
+
child.unref();
|
|
610
|
+
|
|
611
|
+
logger.info({
|
|
612
|
+
msg: 'exec.local.background_started',
|
|
613
|
+
job_id,
|
|
614
|
+
agent: opts.agent,
|
|
615
|
+
pid: child.pid,
|
|
616
|
+
command_head: opts.command.slice(0, 80),
|
|
617
|
+
});
|
|
618
|
+
|
|
619
|
+
return { job_id, pid: child.pid };
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* Send a signal to a running local job. Returns whether the signal
|
|
624
|
+
* was actually delivered (process still alive) or the process was
|
|
625
|
+
* already gone.
|
|
626
|
+
*
|
|
627
|
+
* Signals the process GROUP first (background jobs spawn detached:true,
|
|
628
|
+
* so the wrapper shell is the group leader and `-pid` reaches shell +
|
|
629
|
+
* grandchildren). Falls back to the single pid for jobs started by a
|
|
630
|
+
* pre-group somora version that survived a server restart.
|
|
631
|
+
*/
|
|
632
|
+
export function killLocalJob(pid: number, signal: NodeJS.Signals): { delivered: boolean } {
|
|
633
|
+
try {
|
|
634
|
+
process.kill(-pid, signal);
|
|
635
|
+
return { delivered: true };
|
|
636
|
+
} catch {
|
|
637
|
+
// No such group (ESRCH) or not permitted — try the single pid
|
|
638
|
+
// before declaring the job gone.
|
|
639
|
+
try {
|
|
640
|
+
process.kill(pid, signal);
|
|
641
|
+
return { delivered: true };
|
|
642
|
+
} catch (err) {
|
|
643
|
+
if ((err as NodeJS.ErrnoException).code === 'ESRCH') {
|
|
644
|
+
return { delivered: false };
|
|
645
|
+
}
|
|
646
|
+
throw err;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
}
|