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,114 @@
|
|
|
1
|
+
// Workspace directory resolution + auto-mkdir at server start.
|
|
2
|
+
//
|
|
3
|
+
// Hierarchy:
|
|
4
|
+
// 1. agent.yaml `workspace.path` (per-agent override, expanded ~ on
|
|
5
|
+
// load — surfaced as persona.workspace)
|
|
6
|
+
// 2. config.yaml `workspace.default` (server-global fallback)
|
|
7
|
+
//
|
|
8
|
+
// Both are materialised at startup so the user sees the dirs whether
|
|
9
|
+
// or not anyone has chatted yet, and so file_* tools never have to
|
|
10
|
+
// race a first-write mkdir.
|
|
11
|
+
|
|
12
|
+
import { mkdir, stat } from 'node:fs/promises';
|
|
13
|
+
import { homedir } from 'node:os';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
import type { Config } from '../config/types.ts';
|
|
16
|
+
import type { Persona } from '../persona/loader.ts';
|
|
17
|
+
import { logger } from './logger.ts';
|
|
18
|
+
|
|
19
|
+
export function expandHome(p: string): string {
|
|
20
|
+
if (p === '~') return homedir();
|
|
21
|
+
if (p.startsWith('~/')) return join(homedir(), p.slice(2));
|
|
22
|
+
return p;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Effective workspace path for an agent: per-agent override beats
|
|
27
|
+
* server-global default. Both pre-expanded (no ~ in the return).
|
|
28
|
+
*/
|
|
29
|
+
export function effectiveWorkspace(persona: Persona, config: Config): string {
|
|
30
|
+
if (persona.workspace) return persona.workspace;
|
|
31
|
+
return expandHome(config.workspace.default);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Create the global default workspace plus every per-agent override
|
|
36
|
+
* if not already there. Logs once per dir created. Idempotent.
|
|
37
|
+
*/
|
|
38
|
+
export async function ensureWorkspaceDirs(personas: Persona[], config: Config): Promise<void> {
|
|
39
|
+
const seen = new Set<string>();
|
|
40
|
+
const queue: { path: string; label: string }[] = [];
|
|
41
|
+
|
|
42
|
+
const globalPath = expandHome(config.workspace.default);
|
|
43
|
+
queue.push({ path: globalPath, label: 'global default' });
|
|
44
|
+
seen.add(globalPath);
|
|
45
|
+
|
|
46
|
+
for (const p of personas) {
|
|
47
|
+
if (!p.workspace) continue;
|
|
48
|
+
if (seen.has(p.workspace)) continue;
|
|
49
|
+
queue.push({ path: p.workspace, label: `agent '${p.name}' override` });
|
|
50
|
+
seen.add(p.workspace);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
for (const { path, label } of queue) {
|
|
54
|
+
try {
|
|
55
|
+
const existed = await pathExists(path);
|
|
56
|
+
await mkdir(path, { recursive: true });
|
|
57
|
+
if (!existed) {
|
|
58
|
+
logger.info({ msg: 'workspace.created', path, source: label });
|
|
59
|
+
} else {
|
|
60
|
+
logger.debug({ msg: 'workspace.ok', path, source: label });
|
|
61
|
+
}
|
|
62
|
+
} catch (err) {
|
|
63
|
+
logger.warn({
|
|
64
|
+
msg: 'workspace.ensure_failed',
|
|
65
|
+
path,
|
|
66
|
+
source: label,
|
|
67
|
+
err: (err as Error).message,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function pathExists(p: string): Promise<boolean> {
|
|
74
|
+
try {
|
|
75
|
+
await stat(p);
|
|
76
|
+
return true;
|
|
77
|
+
} catch {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Self-pointer block prepended to the persona system prompt at chat
|
|
84
|
+
* time. Tells the agent who it is, where its files live, and which
|
|
85
|
+
* resources are configured — so it can self-edit its persona, find
|
|
86
|
+
* its config, and address remote targets without guessing paths.
|
|
87
|
+
*
|
|
88
|
+
* Stable per session (no per-turn data) so engines that cache
|
|
89
|
+
* systemPrompt (claude-cli, codex-cli prefix-cache) keep their cache
|
|
90
|
+
* intact.
|
|
91
|
+
*/
|
|
92
|
+
export function buildSelfPointer(persona: Persona, config: Config, somoraHome: string): string {
|
|
93
|
+
const ws = effectiveWorkspace(persona, config);
|
|
94
|
+
const agentDir = join(somoraHome, 'agents', persona.name);
|
|
95
|
+
const visibleResources = Object.entries(config.resources)
|
|
96
|
+
.filter(([name]) => !persona.resourceDeny.includes(name))
|
|
97
|
+
.map(([name, r]) => `${name} (${r.type}, ${r.host})`);
|
|
98
|
+
const resourceLine =
|
|
99
|
+
visibleResources.length > 0
|
|
100
|
+
? visibleResources.join(', ')
|
|
101
|
+
: '(none configured — `resource_list` would return empty)';
|
|
102
|
+
return [
|
|
103
|
+
'# System context',
|
|
104
|
+
`- You are agent \`${persona.name}\` in a somora server.`,
|
|
105
|
+
`- Your persona files: ${agentDir}/{AGENTS,SOUL,USER}.md`,
|
|
106
|
+
`- Your agent config: ${agentDir}/agent.yaml`,
|
|
107
|
+
`- Your default workspace: ${ws}`,
|
|
108
|
+
`- Global server config: ${join(somoraHome, 'config.yaml')}`,
|
|
109
|
+
`- Read somora's own docs via \`somora_docs_list\` and \`somora_docs_read\` to learn how the system works.`,
|
|
110
|
+
`- Configured remote resources: ${resourceLine}`,
|
|
111
|
+
`- Reference local files with markdown links carrying the bare absolute path: \`[label](/home/.../file.md)\`. The web client routes those to a FileView window. \`file://\` URLs, \`https://<host>/files/view?path=...\`, or any other wrapping bypass the FileView and break the link.`,
|
|
112
|
+
`- Show a local image inline with the same bare absolute path in image syntax: \`\`. Works for images generated by you or by a subagent (use the path from its result).`,
|
|
113
|
+
].join('\n');
|
|
114
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// Comment-preserving edits of config.yaml and agent.yaml for the setup
|
|
2
|
+
// assistant. Every write goes through `commit`: backup first, then the
|
|
3
|
+
// new text is parsed and validated BEFORE it replaces the file — a
|
|
4
|
+
// config the server would refuse is never left on disk.
|
|
5
|
+
|
|
6
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { dirname } from 'node:path';
|
|
8
|
+
import { load as parseYamlStrict } from 'js-yaml';
|
|
9
|
+
import { Document, isMap, isNode, isScalar, isSeq, parseDocument, type Scalar, type YAMLMap } from 'yaml';
|
|
10
|
+
|
|
11
|
+
import { assertUniqueAliases, ConfigSchema } from '../config/types.ts';
|
|
12
|
+
import type { ModelPreset } from './presets.ts';
|
|
13
|
+
|
|
14
|
+
export const BASE_CONFIG = `# somora server config. Written by \`somora setup\`; edit by hand any time
|
|
15
|
+
# (gear menu → Reload config, or restart). Every option, with comments:
|
|
16
|
+
# config.example.yaml in the package and docs/setup.md.
|
|
17
|
+
|
|
18
|
+
server:
|
|
19
|
+
host: 127.0.0.1
|
|
20
|
+
port: 18737
|
|
21
|
+
|
|
22
|
+
providers: {}
|
|
23
|
+
`;
|
|
24
|
+
|
|
25
|
+
export interface YamlFile {
|
|
26
|
+
path: string;
|
|
27
|
+
doc: Document;
|
|
28
|
+
/** Text on disk when loaded; '' for a file that does not exist yet. */
|
|
29
|
+
original: string;
|
|
30
|
+
/** The document as it renders untouched — re-rendering alone may
|
|
31
|
+
* normalise whitespace, which is not a change worth a backup. */
|
|
32
|
+
baseline: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function openYaml(path: string, fallbackText = ''): YamlFile {
|
|
36
|
+
const original = existsSync(path) ? readFileSync(path, 'utf8') : '';
|
|
37
|
+
const doc = parseDocument(original || fallbackText);
|
|
38
|
+
if (doc.errors.length > 0) {
|
|
39
|
+
throw new Error(`${path} is not valid YAML: ${doc.errors[0]!.message}`);
|
|
40
|
+
}
|
|
41
|
+
if (doc.contents === null) doc.contents = doc.createNode({}) as never;
|
|
42
|
+
return { path, doc, original, baseline: original ? doc.toString({ lineWidth: 0, flowCollectionPadding: false }) : '' };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function render(file: YamlFile): string {
|
|
46
|
+
return file.doc.toString({ lineWidth: 0, flowCollectionPadding: false });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Set a nested value, creating maps on the way. An empty flow map
|
|
50
|
+
* (`providers: {}`) is turned into a block map so additions read well. */
|
|
51
|
+
export function setIn(file: YamlFile, path: string[], value: unknown): void {
|
|
52
|
+
const newSection = !file.doc.has(path[0]!);
|
|
53
|
+
for (let i = 1; i < path.length; i++) {
|
|
54
|
+
const parent = file.doc.getIn(path.slice(0, i));
|
|
55
|
+
if (isMap(parent) && parent.items.length === 0) parent.flow = false;
|
|
56
|
+
// `key:` with nothing behind it parses as null — make it a map.
|
|
57
|
+
if (parent === null || parent === undefined) file.doc.setIn(path.slice(0, i), file.doc.createNode({}));
|
|
58
|
+
}
|
|
59
|
+
// A plain object must become a node, or later reads inside it miss.
|
|
60
|
+
const node = value !== null && typeof value === 'object' && !isNode(value) ? file.doc.createNode(value) : value;
|
|
61
|
+
file.doc.setIn(path, node);
|
|
62
|
+
// A new top-level section gets a blank line above it.
|
|
63
|
+
if (newSection && isMap(file.doc.contents) && file.doc.contents.items.length > 1) {
|
|
64
|
+
const pair = file.doc.contents.items.find((it) => (isScalar(it.key) ? it.key.value : it.key) === path[0]);
|
|
65
|
+
if (pair) {
|
|
66
|
+
if (!isScalar(pair.key)) pair.key = file.doc.createNode(path[0]) as never;
|
|
67
|
+
(pair.key as Scalar).spaceBefore = true;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function getIn(file: YamlFile, path: string[]): unknown {
|
|
73
|
+
const node = file.doc.getIn(path);
|
|
74
|
+
return node && typeof node === 'object' && 'toJSON' in node ? (node as { toJSON(): unknown }).toJSON() : node;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function deleteIn(file: YamlFile, path: string[]): void {
|
|
78
|
+
if (file.doc.hasIn(path)) file.doc.deleteIn(path);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function modelNode(doc: Document, m: ModelPreset): YAMLMap {
|
|
82
|
+
const node = doc.createNode({
|
|
83
|
+
id: m.id,
|
|
84
|
+
alias: m.alias,
|
|
85
|
+
contextWindow: m.contextWindow,
|
|
86
|
+
capabilities: m.capabilities,
|
|
87
|
+
...(m.reasoning ? { reasoning: m.reasoning } : {}),
|
|
88
|
+
}) as YAMLMap;
|
|
89
|
+
const caps = node.get('capabilities', true);
|
|
90
|
+
if (isSeq(caps)) caps.flow = true;
|
|
91
|
+
const levels = node.getIn(['reasoning', 'levels'], true);
|
|
92
|
+
if (isMap(levels)) levels.flow = true;
|
|
93
|
+
return node;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface ProviderInput {
|
|
97
|
+
key: string;
|
|
98
|
+
engine: string;
|
|
99
|
+
baseUrl?: string;
|
|
100
|
+
apiKey?: string;
|
|
101
|
+
models: ModelPreset[];
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Add a provider, or add the missing models to an existing one.
|
|
105
|
+
* Models already present (same id) are left exactly as they are.
|
|
106
|
+
* Returns the aliases that were added. */
|
|
107
|
+
export function upsertProvider(file: YamlFile, p: ProviderInput): string[] {
|
|
108
|
+
const added: string[] = [];
|
|
109
|
+
const existing = file.doc.getIn(['providers', p.key]);
|
|
110
|
+
if (!isMap(existing)) {
|
|
111
|
+
const node = file.doc.createNode({
|
|
112
|
+
engine: p.engine,
|
|
113
|
+
...(p.baseUrl ? { baseUrl: p.baseUrl } : {}),
|
|
114
|
+
...(p.apiKey ? { apiKey: p.apiKey } : {}),
|
|
115
|
+
models: [],
|
|
116
|
+
}) as YAMLMap;
|
|
117
|
+
setIn(file, ['providers', p.key], node);
|
|
118
|
+
} else {
|
|
119
|
+
if (p.baseUrl) existing.set('baseUrl', p.baseUrl);
|
|
120
|
+
if (p.apiKey) existing.set('apiKey', p.apiKey);
|
|
121
|
+
}
|
|
122
|
+
const provider = file.doc.getIn(['providers', p.key]) as YAMLMap;
|
|
123
|
+
let models = provider.get('models', true);
|
|
124
|
+
if (!isSeq(models)) {
|
|
125
|
+
provider.set('models', file.doc.createNode([]));
|
|
126
|
+
models = provider.get('models', true);
|
|
127
|
+
}
|
|
128
|
+
if (!isSeq(models)) throw new Error(`providers.${p.key}.models is not a list`);
|
|
129
|
+
models.flow = false;
|
|
130
|
+
const have = new Set((models.toJSON() as Array<{ id?: string }>).map((m) => m?.id));
|
|
131
|
+
for (const m of p.models) {
|
|
132
|
+
if (have.has(m.id)) continue;
|
|
133
|
+
models.add(modelNode(file.doc, m));
|
|
134
|
+
added.push(m.alias);
|
|
135
|
+
}
|
|
136
|
+
return added;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Every alias in the config, in file order. */
|
|
140
|
+
export function configuredAliases(file: YamlFile): Array<{ alias: string; provider: string; engine: string; id: string; capabilities: string[] }> {
|
|
141
|
+
const providers = getIn(file, ['providers']) as Record<string, { engine?: string; models?: Array<{ id?: string; alias?: string; capabilities?: string[] }> }> | null;
|
|
142
|
+
const out: Array<{ alias: string; provider: string; engine: string; id: string; capabilities: string[] }> = [];
|
|
143
|
+
for (const [provider, p] of Object.entries(providers ?? {})) {
|
|
144
|
+
for (const m of p?.models ?? []) {
|
|
145
|
+
if (m?.alias && m.id) out.push({ alias: m.alias, provider, engine: p.engine ?? '', id: m.id, capabilities: m.capabilities ?? [] });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function validateConfigText(text: string): string | null {
|
|
152
|
+
let parsed: unknown;
|
|
153
|
+
try {
|
|
154
|
+
parsed = parseYamlStrict(text);
|
|
155
|
+
} catch (err) {
|
|
156
|
+
return `not valid YAML: ${(err as Error).message}`;
|
|
157
|
+
}
|
|
158
|
+
const result = ConfigSchema.safeParse(parsed);
|
|
159
|
+
if (!result.success) {
|
|
160
|
+
return result.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`).join('; ');
|
|
161
|
+
}
|
|
162
|
+
try {
|
|
163
|
+
assertUniqueAliases(result.data);
|
|
164
|
+
} catch (err) {
|
|
165
|
+
return (err as Error).message;
|
|
166
|
+
}
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export interface CommitResult {
|
|
171
|
+
changed: boolean;
|
|
172
|
+
backup: string | null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Write the document. `kind: 'config'` validates against the server's
|
|
176
|
+
* schema first and throws (leaving the file untouched) when the result
|
|
177
|
+
* would not load. The previous file is kept beside it as
|
|
178
|
+
* `<name>.bak-setup-<stamp>`. */
|
|
179
|
+
export function commit(file: YamlFile, kind: 'config' | 'plain', now: Date = new Date(), keepBackup = true): CommitResult {
|
|
180
|
+
const text = render(file);
|
|
181
|
+
if (text === file.original || text === file.baseline) return { changed: false, backup: null };
|
|
182
|
+
if (kind === 'config') {
|
|
183
|
+
const problem = validateConfigText(text);
|
|
184
|
+
if (problem) throw new Error(`refusing to write ${file.path} — the result would not load: ${problem}`);
|
|
185
|
+
} else {
|
|
186
|
+
parseYamlStrict(text);
|
|
187
|
+
}
|
|
188
|
+
mkdirSync(dirname(file.path), { recursive: true });
|
|
189
|
+
let backup: string | null = null;
|
|
190
|
+
if (file.original && keepBackup) {
|
|
191
|
+
const stamp = now.toISOString().replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
|
|
192
|
+
backup = `${file.path}.bak-setup-${stamp}`;
|
|
193
|
+
copyFileSync(file.path, backup);
|
|
194
|
+
}
|
|
195
|
+
const tmp = `${file.path}.tmp-setup`;
|
|
196
|
+
writeFileSync(tmp, text, { encoding: 'utf8', mode: 0o600 });
|
|
197
|
+
renameSync(tmp, file.path);
|
|
198
|
+
file.original = text;
|
|
199
|
+
file.baseline = text;
|
|
200
|
+
return { changed: true, backup };
|
|
201
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Provider blocks the setup assistant writes. They mirror the tested
|
|
2
|
+
// blocks in docs/models.md — presets.test.mts fails when an id here is
|
|
3
|
+
// not in that document, so the two cannot drift apart silently.
|
|
4
|
+
|
|
5
|
+
export interface ModelPreset {
|
|
6
|
+
id: string;
|
|
7
|
+
alias: string;
|
|
8
|
+
contextWindow: number;
|
|
9
|
+
capabilities: string[];
|
|
10
|
+
/** One line for the picker. */
|
|
11
|
+
note: string;
|
|
12
|
+
reasoning?: { levels: Record<string, string> };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface ProviderPreset {
|
|
16
|
+
/** Key under `providers:`. */
|
|
17
|
+
key: string;
|
|
18
|
+
engine: 'claude-cli' | 'codex-cli' | 'openai-compatible';
|
|
19
|
+
baseUrl?: string;
|
|
20
|
+
models: ModelPreset[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const FULL = ['text', 'image', 'pdf', 'reasoning'];
|
|
24
|
+
|
|
25
|
+
export const CLAUDE_PRESET: ProviderPreset = {
|
|
26
|
+
key: 'anthropic',
|
|
27
|
+
engine: 'claude-cli',
|
|
28
|
+
models: [
|
|
29
|
+
{ id: 'claude-fable-5-1', alias: 'fable', contextWindow: 1000000, capabilities: FULL, note: 'frontier model' },
|
|
30
|
+
{ id: 'claude-opus-5', alias: 'opus', contextWindow: 1000000, capabilities: FULL, note: 'recommended for most work' },
|
|
31
|
+
{ id: 'claude-sonnet-5', alias: 'sonnet', contextWindow: 1000000, capabilities: FULL, note: 'lighter on the subscription budget' },
|
|
32
|
+
{ id: 'claude-haiku-4-5', alias: 'haiku', contextWindow: 200000, capabilities: FULL, note: 'fast and cheap — good for background work' },
|
|
33
|
+
],
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export const CODEX_PRESET: ProviderPreset = {
|
|
37
|
+
key: 'openai',
|
|
38
|
+
engine: 'codex-cli',
|
|
39
|
+
models: [
|
|
40
|
+
{ id: 'gpt-6-astra', alias: 'astra', contextWindow: 258400, capabilities: FULL, note: 'frontier model', reasoning: { levels: { off: 'low', high: 'xhigh' } } },
|
|
41
|
+
{ id: 'gpt-5.6-sol', alias: 'gpt56', contextWindow: 258400, capabilities: FULL, note: 'strong all-rounder', reasoning: { levels: { high: 'xhigh' } } },
|
|
42
|
+
{ id: 'gpt-5.6-terra', alias: 'terra', contextWindow: 258400, capabilities: FULL, note: 'balanced' },
|
|
43
|
+
{ id: 'gpt-5.6-luna', alias: 'luna', contextWindow: 258400, capabilities: FULL, note: 'fast and cheap — good for background work' },
|
|
44
|
+
{ id: 'gpt-5.5', alias: 'gpt55', contextWindow: 258400, capabilities: FULL, note: 'previous generation' },
|
|
45
|
+
],
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/** Default picks per job, in order of preference — the first alias that
|
|
49
|
+
* is configured wins. Chat wants the best model, the dream workers a
|
|
50
|
+
* cheap one (REM) or a careful one (Deep, Lucid). */
|
|
51
|
+
export const PREFERRED = {
|
|
52
|
+
chat: ['opus', 'fable', 'gpt56', 'astra', 'sonnet', 'terra'],
|
|
53
|
+
rem: ['haiku', 'luna', 'sonnet', 'terra'],
|
|
54
|
+
deep: ['opus', 'gpt56', 'sonnet', 'terra', 'fable', 'astra'],
|
|
55
|
+
} as const;
|
|
56
|
+
|
|
57
|
+
export function pickPreferred(job: keyof typeof PREFERRED, aliases: string[]): string | undefined {
|
|
58
|
+
return PREFERRED[job].find((a) => aliases.includes(a)) ?? aliases[0];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** `qwen3:32b-instruct` → `qwen3-32b-instruct` — a nickname that is safe
|
|
62
|
+
* as an alias and unique among `taken`. */
|
|
63
|
+
export function aliasFor(modelId: string, taken: string[]): string {
|
|
64
|
+
const base = (modelId.split('/').pop() ?? modelId)
|
|
65
|
+
.toLowerCase()
|
|
66
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
67
|
+
.replace(/^-+|-+$/g, '')
|
|
68
|
+
.slice(0, 24) || 'model';
|
|
69
|
+
if (!taken.includes(base)) return base;
|
|
70
|
+
for (let i = 2; ; i++) if (!taken.includes(`${base}-${i}`)) return `${base}-${i}`;
|
|
71
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// Plain line-based questions for the setup assistant. No TUI framework:
|
|
2
|
+
// it has to work over ssh, inside `curl … | bash` (stdin re-attached to
|
|
3
|
+
// /dev/tty) and with answers piped in from a script.
|
|
4
|
+
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { readFileSync } from 'node:fs';
|
|
7
|
+
import { createInterface } from 'node:readline';
|
|
8
|
+
|
|
9
|
+
const tty = process.stdout.isTTY === true;
|
|
10
|
+
const c = (code: string) => (s: string): string => (tty ? `\x1b[${code}m${s}\x1b[0m` : s);
|
|
11
|
+
export const bold = c('1');
|
|
12
|
+
export const dim = c('2');
|
|
13
|
+
export const green = c('32');
|
|
14
|
+
export const yellow = c('33');
|
|
15
|
+
export const red = c('31');
|
|
16
|
+
export const cyan = c('36');
|
|
17
|
+
|
|
18
|
+
export function say(text = ''): void {
|
|
19
|
+
process.stdout.write(`${text}\n`);
|
|
20
|
+
}
|
|
21
|
+
export function ok(text: string): void {
|
|
22
|
+
say(` ${green('✓')} ${text}`);
|
|
23
|
+
}
|
|
24
|
+
export function warn(text: string): void {
|
|
25
|
+
say(` ${yellow('!')} ${text}`);
|
|
26
|
+
}
|
|
27
|
+
export function fail(text: string): void {
|
|
28
|
+
say(` ${red('✗')} ${text}`);
|
|
29
|
+
}
|
|
30
|
+
export function heading(title: string): void {
|
|
31
|
+
say();
|
|
32
|
+
say(bold(`── ${title} ${'─'.repeat(Math.max(3, 66 - title.length))}`));
|
|
33
|
+
}
|
|
34
|
+
/** Indented explanatory paragraph. The common indentation of the
|
|
35
|
+
* source lines is removed, deeper indentation (lists) is kept. */
|
|
36
|
+
export function explain(text: string): void {
|
|
37
|
+
const lines = text.replace(/^\n+|\s+$/g, '').split('\n');
|
|
38
|
+
const indents = lines.slice(1).filter((l) => l.trim()).map((l) => l.match(/^ */)![0].length);
|
|
39
|
+
const cut = indents.length ? Math.min(...indents) : 0;
|
|
40
|
+
lines.forEach((l, i) => say(` ${dim(i === 0 ? l.trim() : l.slice(Math.min(cut, l.match(/^ */)![0].length)))}`));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface Choice<T> {
|
|
44
|
+
label: string;
|
|
45
|
+
value: T;
|
|
46
|
+
hint?: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export class Prompter {
|
|
50
|
+
/** Piped stdin is read once, up front — a readline interface that is
|
|
51
|
+
* closed between questions would throw away buffered lines. */
|
|
52
|
+
private scripted: string[] | null = null;
|
|
53
|
+
|
|
54
|
+
constructor() {
|
|
55
|
+
if (process.stdin.isTTY !== true) {
|
|
56
|
+
let text = '';
|
|
57
|
+
try {
|
|
58
|
+
text = readFileSync(0, 'utf8');
|
|
59
|
+
} catch {
|
|
60
|
+
/* no stdin at all */
|
|
61
|
+
}
|
|
62
|
+
this.scripted = text.split('\n');
|
|
63
|
+
if (this.scripted.at(-1) === '') this.scripted.pop();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
get interactive(): boolean {
|
|
68
|
+
return this.scripted === null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
private line(promptText: string): Promise<string> {
|
|
72
|
+
if (this.scripted) {
|
|
73
|
+
const answer = this.scripted.shift() ?? '';
|
|
74
|
+
process.stdout.write(`${promptText}${answer}\n`);
|
|
75
|
+
return Promise.resolve(answer);
|
|
76
|
+
}
|
|
77
|
+
return new Promise((resolve) => {
|
|
78
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
79
|
+
let answered = false;
|
|
80
|
+
rl.question(promptText, (a) => {
|
|
81
|
+
answered = true;
|
|
82
|
+
rl.close();
|
|
83
|
+
resolve(a);
|
|
84
|
+
});
|
|
85
|
+
// Ctrl-D: take the default instead of hanging.
|
|
86
|
+
rl.on('close', () => { if (!answered) resolve(''); });
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async ask(question: string, def?: string): Promise<string> {
|
|
91
|
+
const suffix = def !== undefined && def !== '' ? ` ${dim(`[${def}]`)}` : '';
|
|
92
|
+
const a = (await this.line(` ${question}${suffix}: `)).trim();
|
|
93
|
+
return a === '' ? (def ?? '') : a;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Ask until `check` returns null (= fine) — it returns the complaint otherwise. */
|
|
97
|
+
async askValid(question: string, def: string | undefined, check: (v: string) => string | null): Promise<string> {
|
|
98
|
+
for (let i = 0; ; i++) {
|
|
99
|
+
const v = await this.ask(question, def);
|
|
100
|
+
const problem = check(v);
|
|
101
|
+
if (problem === null) return v;
|
|
102
|
+
warn(problem);
|
|
103
|
+
if (!this.interactive && i >= 2) throw new Error(`no valid answer for: ${question}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async confirm(question: string, def = true): Promise<boolean> {
|
|
108
|
+
const a = (await this.line(` ${question} ${dim(def ? '[Y/n]' : '[y/N]')} `)).trim().toLowerCase();
|
|
109
|
+
if (a === '') return def;
|
|
110
|
+
return ['y', 'yes', 'j', 'ja'].includes(a);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async choose<T>(question: string, choices: Array<Choice<T>>, defIndex = 0): Promise<T> {
|
|
114
|
+
say(` ${question}`);
|
|
115
|
+
choices.forEach((ch, i) => say(` ${cyan(String(i + 1))}. ${ch.label}${ch.hint ? dim(` — ${ch.hint}`) : ''}`));
|
|
116
|
+
const v = await this.askValid('Choose', String(defIndex + 1), (s) => {
|
|
117
|
+
const n = Number(s);
|
|
118
|
+
return Number.isInteger(n) && n >= 1 && n <= choices.length ? null : `a number from 1 to ${choices.length}, please`;
|
|
119
|
+
});
|
|
120
|
+
return choices[Number(v) - 1]!.value;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Several of a list: "1,3", "all" or "none". */
|
|
124
|
+
async chooseMany<T>(question: string, choices: Array<Choice<T>>, defIndexes: number[]): Promise<T[]> {
|
|
125
|
+
say(` ${question}`);
|
|
126
|
+
choices.forEach((ch, i) => say(` ${cyan(String(i + 1))}. ${ch.label}${ch.hint ? dim(` — ${ch.hint}`) : ''}`));
|
|
127
|
+
const def = defIndexes.length ? defIndexes.map((i) => i + 1).join(',') : 'none';
|
|
128
|
+
const parse = (s: string): number[] | null => {
|
|
129
|
+
const t = s.trim().toLowerCase();
|
|
130
|
+
if (t === 'none' || t === '-') return [];
|
|
131
|
+
if (t === 'all') return choices.map((_, i) => i);
|
|
132
|
+
const nums = t.split(/[\s,]+/).filter(Boolean).map(Number);
|
|
133
|
+
if (nums.length === 0 || nums.some((n) => !Number.isInteger(n) || n < 1 || n > choices.length)) return null;
|
|
134
|
+
return [...new Set(nums.map((n) => n - 1))];
|
|
135
|
+
};
|
|
136
|
+
const v = await this.askValid('Choose (e.g. 1,3 — or all / none)', def, (s) => (parse(s) ? null : `numbers from 1 to ${choices.length}, separated by commas`));
|
|
137
|
+
return parse(v)!.map((i) => choices[i]!.value);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async pause(text = 'Press Enter to continue'): Promise<void> {
|
|
141
|
+
await this.line(` ${dim(text)} `);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Give the terminal to another program (a login flow, sudo, …). */
|
|
145
|
+
handOver(cmd: string, args: string[], env?: NodeJS.ProcessEnv): number {
|
|
146
|
+
const r = spawnSync(cmd, args, { stdio: 'inherit', env: env ?? process.env });
|
|
147
|
+
if (r.error) {
|
|
148
|
+
fail(`could not run ${cmd}: ${r.error.message}`);
|
|
149
|
+
return 127;
|
|
150
|
+
}
|
|
151
|
+
return r.status ?? 1;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Run quietly, capture output. */
|
|
156
|
+
export function capture(cmd: string, args: string[], timeoutMs = 30_000): { code: number; stdout: string; stderr: string } {
|
|
157
|
+
const r = spawnSync(cmd, args, { encoding: 'utf8', timeout: timeoutMs });
|
|
158
|
+
return { code: r.error ? 127 : (r.status ?? 1), stdout: r.stdout ?? '', stderr: r.stderr ?? (r.error?.message ?? '') };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function onPath(cmd: string): boolean {
|
|
162
|
+
return capture('sh', ['-c', `command -v ${cmd}`]).code === 0;
|
|
163
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// What the setup assistant needs to know about Tailscale on this host.
|
|
2
|
+
|
|
3
|
+
import { capture } from './prompt.ts';
|
|
4
|
+
|
|
5
|
+
export interface TailscaleState {
|
|
6
|
+
installed: boolean;
|
|
7
|
+
/** Logged in and connected. */
|
|
8
|
+
running: boolean;
|
|
9
|
+
/** `host.tailnet.ts.net`, no trailing dot. */
|
|
10
|
+
dnsName: string | null;
|
|
11
|
+
/** HTTPS certificates are switched on for the tailnet. */
|
|
12
|
+
certsEnabled: boolean;
|
|
13
|
+
backendState: string | null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function parseTailscaleStatus(json: string): Omit<TailscaleState, 'installed'> {
|
|
17
|
+
let j: { BackendState?: string; Self?: { DNSName?: string }; CertDomains?: string[] | null };
|
|
18
|
+
try {
|
|
19
|
+
j = JSON.parse(json);
|
|
20
|
+
} catch {
|
|
21
|
+
return { running: false, dnsName: null, certsEnabled: false, backendState: null };
|
|
22
|
+
}
|
|
23
|
+
const dnsName = (j.Self?.DNSName ?? '').replace(/\.$/, '') || null;
|
|
24
|
+
const certDomains = j.CertDomains ?? [];
|
|
25
|
+
return {
|
|
26
|
+
running: j.BackendState === 'Running',
|
|
27
|
+
dnsName,
|
|
28
|
+
// MagicDNS off → no DNSName; HTTPS off → CertDomains empty.
|
|
29
|
+
certsEnabled: dnsName !== null && certDomains.includes(dnsName),
|
|
30
|
+
backendState: j.BackendState ?? null,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function tailscaleState(): TailscaleState {
|
|
35
|
+
const r = capture('tailscale', ['status', '--json'], 15_000);
|
|
36
|
+
if (r.code === 127) return { installed: false, running: false, dnsName: null, certsEnabled: false, backendState: null };
|
|
37
|
+
return { installed: true, ...parseTailscaleStatus(r.stdout) };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** `tailscale cert` refused because this user may not talk to the
|
|
41
|
+
* daemon — cured by `sudo tailscale set --operator=<user>`. */
|
|
42
|
+
export function isOperatorError(stderr: string): boolean {
|
|
43
|
+
return /access denied|must be root|operator|permission denied/i.test(stderr);
|
|
44
|
+
}
|